Inheritance: MonoBehaviour
        /// <summary>
        ///     Constructor taking the path to the configuration file. 
        ///     Starts the lidgren server to start listening for connections, and 
        ///     initializes all data structres and such.
        /// </summary>
        /// <param name="configpath"></param>
        public RegionServer(string configpath)
        {
            //Load this region server's junk from xml
            XmlSerializer deserializer = new XmlSerializer(typeof(RegionConfig));
            RegionConfig regionconfig = (RegionConfig)deserializer.Deserialize(XmlReader.Create(configpath));

            //Create the server
            var config = new NetPeerConfiguration(regionconfig.ServerName);
            config.Port = regionconfig.ServerPort;
            LidgrenServer = new NetServer(config);
            LidgrenServer.Start();

            //Initizlie our data structures
            Characters = new Dictionary<Guid, Character>();
            UserIdToMasterServer = new Dictionary<Guid, NetConnection>();
            TeleportEnters = new List<TeleportEnter>(regionconfig.TeleportEnters);
            TeleportExits = new List<TeleportExit>(regionconfig.TeleportExits);
            ItemSpawns = new List<ItemSpawn>(regionconfig.ItemSpawns);
            ItemSpawnIdGenerator = new UniqueId();
            ItemSpawnsWaitingForSpawn = new Dictionary<ItemSpawn, DateTime>();

            foreach(ItemSpawn spawn in ItemSpawns)
                ItemSpawnIdGenerator.RegisterId(spawn.Id);

            RegionId = regionconfig.RegionId;
        }
 public ChangeEvent(ChangeType type, UniqueId beforeId, UniqueId afterId, Instant versionInstant)
 {
     _type = type;
     _beforeId = beforeId;
     _afterId = afterId;
     _versionInstant = versionInstant;
 }
 protected ManageableSecurity(string name, string securityType, UniqueId uniqueId, ExternalIdBundle identifiers)
 {
     _name = name;
     _securityType = string.Intern(securityType); // Should be a small static set
     _uniqueId = uniqueId;
     _identifiers = identifiers;
 }
 internal PortfolioNode(UniqueId uniqueId, string name, IList<PortfolioNode> subNodes, IList<IPosition> positions)
 {
     _uniqueId = uniqueId;
     _name = name;
     _subNodes = subNodes;
     _positions = positions;
 }
 public SimplePosition(UniqueId identifier, decimal quantity, ExternalIdBundle securityKey, IList<ITrade> trades)
 {
     _securityKey = securityKey;
     _trades = trades;
     _identifier = identifier;
     _quantity = quantity;
 }
		/// <summary>
		/// Attempts to parse an atom token as a set of UIDs.
		/// </summary>
		/// <returns><c>true</c> if the UIDs were successfully parsed, otherwise <c>false</c>.</returns>
		/// <param name="atom">The atom string.</param>
		/// <param name="uids">The UIDs.</param>
		public static bool TryParseUidSet (string atom, out UniqueId[] uids)
		{
			var ranges = atom.Split (new [] { ',' }, StringSplitOptions.RemoveEmptyEntries);
			var list = new List<UniqueId> ();

			uids = null;

			for (int i = 0; i < ranges.Length; i++) {
				var minmax = ranges[i].Split (':');
				uint min;

				if (!uint.TryParse (minmax[0], out min) || min == 0)
					return false;

				if (minmax.Length == 2) {
					uint max;

					if (!uint.TryParse (minmax[1], out max) || max == 0)
						return false;

					for (uint uid = min; uid <= max; uid++)
						list.Add (new UniqueId (uid));
				} else if (minmax.Length == 1) {
					list.Add (new UniqueId (min));
				} else {
					return false;
				}
			}

			uids = list.ToArray ();

			return true;
		}
 /// <summary>
 /// Initializes a new instance of the <see cref="StartRecording"/> class.
 /// </summary>
 /// <param name="id">The id.</param>
 /// <param name="path">FreeSwitch relative path (directory + filename).</param>
 public StartRecording(UniqueId id, string path)
 {
     if (id == null) throw new ArgumentNullException("id");
     if (path == null) throw new ArgumentNullException("path");
     _id = id;
     _path = path;
     RecordingLimit = TimeSpan.MinValue;
 }
Exemple #8
0
		/// <summary>
		/// Initializes a new instance of the <see cref="T:MailKit.Search.UidSearchQuery"/> class.
		/// </summary>
		/// <remarks>
		/// Creates a new unique identifier-based search query.
		/// </remarks>
		/// <param name="uid">The unique identifier to match against.</param>
		/// <exception cref="System.ArgumentException">
		/// <paramref name="uid"/> is an invalid unique identifier.
		/// </exception>
		public UidSearchQuery (UniqueId uid) : base (SearchTerm.Uid)
		{
			if (!uid.IsValid)
				throw new ArgumentException ("Cannot search for an invalid unique identifier.", nameof (uid));

			Uids = new UniqueIdSet (SortOrder.Ascending);
			Uids.Add (uid);
		}
 public SimpleTrade(UniqueId uniqueId, DateTimeOffset tradeDate, ExternalIdBundle securityKey, CounterpartyImpl counterparty, decimal quantity)
 {
     _uniqueId = uniqueId;
     _quantity = quantity;
     _securityKey = securityKey;
     _counterparty = counterparty;
     _tradeDate = tradeDate;
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="Deflect"/> class.
        /// </summary>
        /// <param name="id">Channel id</param>
        /// <param name="address">Sip address to deflect to</param>
        public Deflect(UniqueId id, SipAddress address)
        {
            if (id == null) throw new ArgumentNullException("id");
            if (address == null) throw new ArgumentNullException("address");

            _id = id;
            _address = address;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="SetVariable"/> class.
 /// </summary>
 /// <param name="id">Channel id.</param>
 /// <param name="name">Variable name as declared by FreeSWITCH.</param>
 /// <param name="value">Variable value, <see cref="string.Empty"/> if you which to unset it.</param>
 public SetVariable(UniqueId id, string name, string value)
 {
     if (id == null) throw new ArgumentNullException("id");
     if (name == null) throw new ArgumentNullException("name");
     if (value == null) throw new ArgumentNullException("value");
     _channelId = id;
     _name = name;
     _value = value;
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="Sleep"/> class.
        /// </summary>
        /// <param name="id">Channel id.</param>
        /// <param name="duration">The duration.</param>
        public Sleep(UniqueId id, TimeSpan duration)
        {
            if (id == null) throw new ArgumentNullException("id");
            if (_duration == TimeSpan.MinValue)
                throw new ArgumentException("Duration must be larger than 0 ms.", "duration");

            _id = id;
            _duration = duration;
        }
 public YieldCurveDefinitionDocument Get(UniqueId uniqueId)
 {
     var resp = _restTarget.Resolve("definitions", uniqueId.ToString()).Get<YieldCurveDefinitionDocument>();
     if (resp == null || resp.UniqueId == null || resp.YieldCurveDefinition == null)
     {
         throw new ArgumentException("Not found", "uniqueId");
     }
     return resp;
 }
Exemple #14
0
 protected InMemoryViewResultModelBase(UniqueId viewProcessId, UniqueId viewCycleId, DateTimeOffset inputDataTimestamp, DateTimeOffset resultTimestamp, IDictionary<string, ViewCalculationResultModel> configurationMap, TimeSpan calculationDuration)
 {
     _viewProcessId = viewProcessId;
     _viewCycleId = viewCycleId;
     _inputDataTimestamp = inputDataTimestamp;
     _resultTimestamp = resultTimestamp;
     _configurationMap = configurationMap;
     _calculationDuration = calculationDuration;
 }
 public PortfolioDocument Get(UniqueId uniqueId)
 {
     ArgumentChecker.NotNull(uniqueId, "uniqueId");
     var resp = _restTarget.Resolve("portfolios").Resolve(uniqueId.ObjectID.ToString()).Get<PortfolioDocument>();
     if (resp == null || resp.UniqueId == null || resp.Portfolio == null)
     {
         throw new ArgumentException("Not found", "uniqueId");
     }
     return resp;
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="SendMsg"/> class.
        /// </summary>
        /// <param name="id">Channel UUID.</param>
        /// <param name="callCommand">The call command.</param>
        protected SendMsg(UniqueId id, string callCommand)
        {
            if (id == null)
                throw new ArgumentNullException("id");
            if (string.IsNullOrEmpty(callCommand))
                throw new ArgumentNullException("callCommand");

            _callCommand = callCommand;
            _id = id;
        }
Exemple #17
0
 public BondSecurity(string name, string securityType, UniqueId uniqueId, ExternalIdBundle identifiers,
                     string issuerName, string issuerType, string issuerDomicile, string market, string currency // ... you get the idea, I'm not going to write all of these out
     )
     : base(name, securityType, uniqueId, identifiers)
 {
     _issuerName = issuerName;
     _issuerType = issuerType;
     _issuerDomicile = issuerDomicile;
     _market = market;
     _currency = currency;
 }
		public void TestFormattingNonSequentialUids ()
		{
			UniqueId[] uids = new UniqueId[] {
				new UniqueId (1), new UniqueId (3), new UniqueId (5),
				new UniqueId (7), new UniqueId (9)
			};
			string expect = "1,3,5,7,9";
			string actual;

			actual = ImapUtils.FormatUidSet (uids);
			Assert.AreEqual (expect, actual, "Formatting a non-sequential list of uids.");
		}
Exemple #19
0
        internal PixelShader(SlimDX.Direct3D11.PixelShader pixelShader)
        {
            #if ASSERT
            if (pixelShader == null)
            {
                throw new ArgumentNullException("pixelShader");
            }
            #endif

            resourceOwner = false;
            this.pixelShader = pixelShader;
            uniqueId = new UniqueId<PixelShader>();
        }
Exemple #20
0
        internal RenderTarget(SlimDX.Direct3D11.RenderTargetView renderTargetView)
        {
            #if ASSERT
            if (renderTargetView == null)
            {
                throw new ArgumentNullException("renderTargetView");
            }
            #endif

            this.renderTargetView = renderTargetView;
            resourceOwner = false;
            uniqueId = new UniqueId<RenderTarget>();
        }
        public IAvailableOutputs GetPortfolioOutputs(UniqueId portfolioId, string timeStamp = "now")
        {
            ArgumentChecker.NotNull(portfolioId, "portfolioId");
            ArgumentChecker.NotNull(timeStamp, "timeStamp");

            RestTarget target = _restTarget.Resolve("portfolio").Resolve(timeStamp);
            if (_maxNodes > 0)
                target = target.Resolve("nodes", _maxNodes.ToString());
            if (_maxPositions > 0)
                target = target.Resolve("positions", _maxPositions.ToString());
            target = target.Resolve(portfolioId.ToString());
            return target.Get<IAvailableOutputs>();
        }
		public void TestFormattingSimpleUidRange ()
		{
			UniqueId[] uids = new UniqueId[] {
				new UniqueId (1), new UniqueId (2), new UniqueId (3),
				new UniqueId (4), new UniqueId (5), new UniqueId (6),
				new UniqueId (7), new UniqueId (8), new UniqueId (9)
			};
			string expect = "1:9";
			string actual;

			actual = ImapUtils.FormatUidSet (uids);
			Assert.AreEqual (expect, actual, "Formatting a simple range of uids failed.");
		}
 public ISecurity GetSecurity(UniqueId uid)
 {
     if (uid.IsLatest)
     {
         var securityDocument = _restTarget.Resolve("securities", uid.ToString()).Get<SecurityDocument>();
         return securityDocument.Security;
     }
     else
     {
         var securityDocument = _restTarget.Resolve("securities", uid.ObjectID.ToString(), "versions", uid.Version).Get<SecurityDocument>();
         return securityDocument.Security;
     }
 }
Exemple #24
0
        internal Texture2d(SlimDX.Direct3D11.Device device, string fileName)
        {
            #if ASSERT
            if (device == null)
            {
                throw new ArgumentNullException("device");
            }
            #endif

            texture2d = SlimDX.Direct3D11.Texture2D.FromFile(device, fileName);
            shaderResourceView = new SlimDX.Direct3D11.ShaderResourceView(device, texture2d);
            uniqueId = new UniqueId<Texture2d>();
        }
		public void TestFormattingComplexSetOfUids ()
		{
			UniqueId[] uids = new UniqueId[] {
				new UniqueId (1), new UniqueId (2), new UniqueId (3),
				new UniqueId (5), new UniqueId (6), new UniqueId (9),
				new UniqueId (10), new UniqueId (11), new UniqueId (12),
				new UniqueId (15), new UniqueId (19), new UniqueId (20)
			};
			string expect = "1:3,5:6,9:12,15,19:20";
			string actual;

			actual = ImapUtils.FormatUidSet (uids);
			Assert.AreEqual (expect, actual, "Formatting a complex list of uids.");
		}
Exemple #26
0
        public async Task<MimeMessage> GetMessage(UniqueId uid)
        {
            _idleTimer.Stop();
            await StopIdle();

            try
            {
                return await ImapClient.Inbox.GetMessageAsync(uid, Util.GetCancellationToken(120000));
            }
            finally
            {
                _idleTimer.Start();
            }
        }
Exemple #27
0
 public ViewDefinition(string name, ResultModelDefinition resultModelDefinition = null, UniqueId portfolioIdentifier = null, UserPrincipal user = null, Currency defaultCurrency = null, TimeSpan? minDeltaCalcPeriod = null, TimeSpan? maxDeltaCalcPeriod = null, TimeSpan? minFullCalcPeriod = null, TimeSpan? maxFullCalcPeriod = null, Dictionary<string, ViewCalculationConfiguration> calculationConfigurationsByName = null, UniqueId uniqueID = null)
 {
     _name = name;
     _uniqueID = uniqueID;
     _portfolioIdentifier = portfolioIdentifier;
     _user = user ?? UserPrincipal.DefaultUser;
     _resultModelDefinition = resultModelDefinition ?? new ResultModelDefinition();
     _defaultCurrency = defaultCurrency;
     _minDeltaCalcPeriod = minDeltaCalcPeriod;
     _maxDeltaCalcPeriod = maxDeltaCalcPeriod;
     _minFullCalcPeriod = minFullCalcPeriod;
     _maxFullCalcPeriod = maxFullCalcPeriod;
     _calculationConfigurationsByName = calculationConfigurationsByName ?? new Dictionary<string, ViewCalculationConfiguration>();
 }
Exemple #28
0
        private static UniqueId LoadLink(XmlNode inputNode, out string linkId)
        {
            linkId = inputNode.GetXmlNodeValue("@A");
            if (string.IsNullOrEmpty(linkId))
                return null;

            var linkValue = inputNode.GetXmlNodeValue("@B");
            if (string.IsNullOrEmpty(linkValue))
                return null;

            var uniqueId = new UniqueId
            {
                Id = linkValue,
                Source = inputNode.GetXmlNodeValue("@C")
            };

            return uniqueId;
        }
Exemple #29
0
        internal PixelShader(SlimDX.Direct3D11.Device device, SlimDX.D3DCompiler.ShaderBytecode pixelShaderCode)
        {
            #if ASSERT
            if (device == null)
            {
                throw new ArgumentNullException("device");
            }

            if (pixelShaderCode == null)
            {
                throw new ArgumentNullException("pixelShaderCode");
            }
            #endif

            resourceOwner = true;
            pixelShader = new SlimDX.Direct3D11.PixelShader(device, pixelShaderCode);
            uniqueId = new UniqueId<PixelShader>();
        }
Exemple #30
0
        internal RenderTarget(SlimDX.Direct3D11.Device device, SlimDX.Direct3D11.Resource resource)
        {
            #if ASSERT
            if (device == null)
            {
                throw new ArgumentNullException("device");
            }

            if (resource == null)
            {
                throw new ArgumentNullException("resource");
            }
            #endif

            renderTargetView = new SlimDX.Direct3D11.RenderTargetView(device, resource);
            resourceOwner = true;
            uniqueId = new UniqueId<RenderTarget>();
        }
Exemple #31
0
 public bool Matches(UniqueId contextId, UniqueId generation)
 {
     return(contextId == _contextId && generation == _generation);
 }
Exemple #32
0
            /// <summary>
            /// Async Pattern. Callback of BeginProcessMessage method.
            /// </summary>
            /// <param name="state">state object</param>
            private void InternalBeginAddResponse(object state)
            {
                Message responseMessage = null;
                Tuple <ConcurrentQueue <Message>, AzureStorageClient> messageClient = null;

                try
                {
                    foreach (Tuple <ConcurrentQueue <Message>, AzureStorageClient> responseMessageClient in this.responseMessageClients.Values)
                    {
                        if (!responseMessageClient.Item1.TryDequeue(out responseMessage))
                        {
                            BrokerTracing.TraceInfo(
                                SoaHelper.CreateTraceMessage(
                                    "MessageSender.Worker",
                                    "InternalBeginAddResponse",
                                    "Local response cache is empty."));
                        }
                        else
                        {
                            messageClient = responseMessageClient;
                            break;
                        }
                    }
                }
                catch (Exception e)
                {
                    BrokerTracing.TraceError(
                        SoaHelper.CreateTraceMessage(
                            "MessageSender.Worker",
                            "InternalBeginAddResponse",
                            string.Format("Failed to get response from local cache, {0}", e)));
                }

                if (responseMessage == null)
                {
                    this.TriggerTimer();

                    return;
                }

                BrokerTracing.TraceInfo(
                    SoaHelper.CreateTraceMessage(
                        "MessageSender.Worker",
                        "InternalBeginAddResponse",
                        "Retrieved message from local response cache."));

                try
                {
                    UniqueId messageId = SoaHelper.GetMessageId(responseMessage);

                    if (messageId == null)
                    {
                        messageId = new UniqueId();
                    }

                    ReliableQueueClient.ReliableState reliableState = new ReliableQueueClient.ReliableState(responseMessage, messageClient, messageId);

                    this.waitHandler.Reset();

                    byte[] messageData;

                    using (responseMessage)
                    {
                        messageData = AzureQueueMessageItem.Serialize(responseMessage);
                    }

                    messageClient.Item2.BeginAddMessage(messageData, messageId, this.AddMessageCallback, reliableState);
                }
                catch (Exception e)
                {
                    this.waitHandler.Set();

                    BrokerTracing.TraceError(
                        SoaHelper.CreateTraceMessage(
                            "MessageSender.Worker",
                            "InternalBeginAddResponse",
                            "Failed to add response message, {0}", e));

                    this.TriggerTimer();
                }
            }
        /// <summary>
        /// 根据邮件Id获取邮件内容,并下载附件
        /// </summary>
        /// <param name="EmailIds"></param>
        /// <param name="saveFilePath"></param>
        /// <param name=""></param>
        /// <param name="IsSetFlag"></param>
        /// <param name="IsdownloadFile">是否下载邮件内文件</param>
        /// <returns></returns>
        public ReceiveMailBodyModel ReceiveMail(UniqueId mailId, string saveFilePath = null, bool IsSetFlag = false)
        {
            ReceiveMailBodyModel resInfo = null;

            //如果没有邮件,则返回
            if (mailId == null)
            {
                return(resInfo);
            }
            TryExFunc(() =>
            {
                resInfo               = new ReceiveMailBodyModel();
                var mail              = _client.Inbox.GetMessage(mailId);
                resInfo.MailUniqueId  = mailId.Id;
                resInfo.MailMessage   = mail;
                resInfo.MailTime      = mail.Date.DateTime;
                resInfo.mailMessageId = mail.MessageId;
                var FromAddress       = (MailboxAddress)mail.From[0];
                resInfo.SenderAddress = FromAddress.Address;
                resInfo.Sender        = FromAddress.Name;
                resInfo.HtmlBody      = mail.HtmlBody; //Html内容
                resInfo.TextBody      = mail.TextBody; //Text内容
                if (mail.To != null && mail.To.Count > 0)
                {
                    foreach (var t in mail.To)
                    {
                        if (t.Name != "undisclosed-recipients")
                        {
                            var ToAddress = (MailboxAddress)t;
                            resInfo.Recipients.Add(new RecipientsModel
                            {
                                ReceiveMail = ToAddress.Address,
                                ReceiveName = ToAddress.Name
                            });
                        }
                    }
                }
                resInfo.Subject = mail.Subject;
                if (mail.Cc != null && mail.Cc.Count > 0)//获取抄送人
                {
                    resInfo.Cc = new List <RecipientsModel>();
                    foreach (var cc in mail.Cc)
                    {
                        if (cc.Name != "undisclosed-recipients")
                        {
                            var ccAddress = (MailboxAddress)cc;
                            resInfo.Recipients.Add(new RecipientsModel
                            {
                                ReceiveMail = ccAddress.Address,
                                ReceiveName = ccAddress.Name
                            });
                        }
                    }
                }
                if (mail.Bcc != null && mail.Bcc.Count > 0)//获取密送人
                {
                    resInfo.Bcc = new List <RecipientsModel>();
                    foreach (var Bcc in mail.Bcc)
                    {
                        if (Bcc.Name != "undisclosed-recipients")
                        {
                            var BccAddress = (MailboxAddress)Bcc;
                            resInfo.Recipients.Add(new RecipientsModel
                            {
                                ReceiveMail = BccAddress.Address,
                                ReceiveName = BccAddress.Name
                            });
                        }
                    }
                }
                if (!string.IsNullOrEmpty(saveFilePath))
                {
                    resInfo.MailImg   = SaveMailImg(mail, saveFilePath, mail.MessageId);
                    resInfo.MailFiles = SaveMailFile(mail, saveFilePath, mail.MessageId);
                }
                if (IsSetFlag)
                {
                    SetMailSeen(mailId);
                }
            }, $"邮件获取错误,真实邮件Id:[{mailId.Id}]");
            return(resInfo);
        }
        public override IDeepCopyable CopyTo(IDeepCopyable other)
        {
            var dest = other as NamingSystem;

            if (dest == null)
            {
                throw new ArgumentException("Can only copy to an object of the same type", "other");
            }

            base.CopyTo(dest);
            if (NameElement != null)
            {
                dest.NameElement = (Hl7.Fhir.Model.FhirString)NameElement.DeepCopy();
            }
            if (StatusElement != null)
            {
                dest.StatusElement = (Code <Hl7.Fhir.Model.PublicationStatus>)StatusElement.DeepCopy();
            }
            if (KindElement != null)
            {
                dest.KindElement = (Code <Hl7.Fhir.Model.NamingSystem.NamingSystemType>)KindElement.DeepCopy();
            }
            if (DateElement != null)
            {
                dest.DateElement = (Hl7.Fhir.Model.FhirDateTime)DateElement.DeepCopy();
            }
            if (PublisherElement != null)
            {
                dest.PublisherElement = (Hl7.Fhir.Model.FhirString)PublisherElement.DeepCopy();
            }
            if (Contact != null)
            {
                dest.Contact = new List <Hl7.Fhir.Model.ContactDetail>(Contact.DeepCopy());
            }
            if (ResponsibleElement != null)
            {
                dest.ResponsibleElement = (Hl7.Fhir.Model.FhirString)ResponsibleElement.DeepCopy();
            }
            if (Type != null)
            {
                dest.Type = (Hl7.Fhir.Model.CodeableConcept)Type.DeepCopy();
            }
            if (Description != null)
            {
                dest.Description = (Hl7.Fhir.Model.Markdown)Description.DeepCopy();
            }
            if (UseContext != null)
            {
                dest.UseContext = new List <Hl7.Fhir.Model.UsageContext>(UseContext.DeepCopy());
            }
            if (Jurisdiction != null)
            {
                dest.Jurisdiction = new List <Hl7.Fhir.Model.CodeableConcept>(Jurisdiction.DeepCopy());
            }
            if (UsageElement != null)
            {
                dest.UsageElement = (Hl7.Fhir.Model.FhirString)UsageElement.DeepCopy();
            }
            if (UniqueId != null)
            {
                dest.UniqueId = new List <Hl7.Fhir.Model.NamingSystem.UniqueIdComponent>(UniqueId.DeepCopy());
            }
            if (ReplacedBy != null)
            {
                dest.ReplacedBy = (Hl7.Fhir.Model.ResourceReference)ReplacedBy.DeepCopy();
            }
            return(dest);
        }
 public abstract void RemoveAll(string endpointId, UniqueId contextId);
        private void AddUniqueIdAssemblyAttribute(AssemblyDefinition assembly)
        {
            var module         = assembly.MainModule;
            var attribType     = typeof(Recorder.InstrumentationUniqueIdAttribute);
            var attribTypeRef  = module.ImportReference(attribType);
            var attrib         = assembly.CustomAttributes.FirstOrDefault(a => a.AttributeType == attribTypeRef);
            var attribArgument = new CustomAttributeArgument(module.ImportReference(typeof(string)), UniqueId.ToString());

            if (attrib == null)
            {
                var constructor = attribType.GetConstructors()[0];
                attrib = new CustomAttribute(module.ImportReference(constructor));
                attrib.ConstructorArguments.Add(attribArgument);
                assembly.CustomAttributes.Add(attrib);
            }
            else
            {
                attrib.ConstructorArguments[0] = attribArgument;
            }
        }
        private IQ SetRoster(XmppStream stream, IQ iq, XmppHandlerContext context)
        {
            var answer = new IQ(IqType.result);

            answer.Id   = iq.Id;
            answer.To   = iq.From;
            answer.From = iq.To;

            iq.Id = UniqueId.CreateNewId();
            var            roster = (Roster)iq.Query;
            UserRosterItem item   = null;

            try
            {
                var rosterItems = roster.GetRoster();
                if (rosterItems.Length != 1)
                {
                    throw new JabberException(ErrorCode.BadRequest);
                }

                var rosterItem = rosterItems[0];
                item = UserRosterItem.FromRosterItem(rosterItem);

                if (rosterItem.Subscription == SubscriptionType.remove)
                {
                    context.StorageManager.RosterStorage.RemoveRosterItem(iq.From, item.Jid);

                    //Send presences
                    var unsubscribe = new Presence()
                    {
                        Type = PresenceType.unsubscribe, To = item.Jid, From = iq.From
                    };
                    var unsubscribed = new Presence()
                    {
                        Type = PresenceType.unsubscribed, To = item.Jid, From = iq.From
                    };
                    var unavailable = new Presence()
                    {
                        Type = PresenceType.unavailable, To = item.Jid, From = iq.From
                    };

                    bool sended = false;
                    foreach (var session in context.SessionManager.GetBareJidSessions(item.Jid))
                    {
                        if (session.RosterRequested)
                        {
                            context.Sender.SendTo(session, unsubscribe);
                            context.Sender.SendTo(session, unsubscribed);
                            sended = true;
                        }
                        context.Sender.SendTo(session, unavailable);
                    }
                    if (!sended)
                    {
                        context.StorageManager.OfflineStorage.SaveOfflinePresence(unsubscribe);
                        context.StorageManager.OfflineStorage.SaveOfflinePresence(unsubscribed);
                    }
                }
                else
                {
                    item = context.StorageManager.RosterStorage.SaveRosterItem(iq.From, item);
                    roster.RemoveAllChildNodes();
                    roster.AddRosterItem(item.ToRosterItem());
                }
                //send all available user's resources
                context.Sender.Broadcast(context.SessionManager.GetBareJidSessions(iq.From), iq);
            }
            catch (System.Exception)
            {
                roster.RemoveAllChildNodes();
                item = context.StorageManager.RosterStorage.GetRosterItem(iq.From, item.Jid);
                if (item != null)
                {
                    roster.AddRosterItem(item.ToRosterItem());
                    context.Sender.Broadcast(context.SessionManager.GetBareJidSessions(iq.From), iq);
                }
                throw;
            }

            return(answer);
        }
 /// <summary>
 /// 标记邮件已读
 /// </summary>
 public void SetMailSeen(UniqueId mailId)
 {
     //将此邮件标记已为已读邮件
     _client.Inbox.SetFlags(mailId, MessageFlags.Seen, true);
 }
Exemple #39
0
 public void Disabled(UniqueId id)
 {
     GetEntById(id).Enabled = false;
 }
 /// <summary>
 /// Initializes a new instance of the ReliableState class.
 /// </summary>
 /// <param name="state">state object</param>
 /// <param name="messageId">wcf message Id</param>
 public ReliableState(object state, Tuple <ConcurrentQueue <Message>, AzureStorageClient> messageClient, UniqueId messageId)
 {
     this.State         = state;
     this.MessageId     = messageId;
     this.MessageClient = messageClient;
 }
 public SessionSecurityTokenCacheKey(string endpointId, UniqueId contextId, UniqueId keyGeneration)
 {
     EndpointId    = endpointId;
     ContextId     = contextId;
     KeyGeneration = keyGeneration;
 }
        private async ValueTask <Maybe <ITransportChannel> > TryCreateChannelSafeAsync(UniqueId channelId)
        {
            TransportChannel channel;

            lock (_channels)
            {
                if (_sendCompletion.IsEntered)
                {
                    return(Nothing.Instance);
                }
                _log.Trace("Creating new channel by local request: {0}", channelId);
                channel = new TransportChannel(Id, channelId, _transportSendProcessor.Out, _headerFactory);
                _channels[channel.Id] = channel;
                channel.Completion.ContinueWithSynchronously((Action <Task, object>)OnChannelCompleted, channel).IgnoreAwait(_log);
            }
            await channel.Initialized.ConfigureAwait(false);

            return(channel);
        }
Exemple #43
0
 public MailPreview(String mailObject, List <Address> listFrom, String date, UniqueId index)
     : this(mailObject, listFrom, date)
 {
     this.uniqueId = index;
 }
Exemple #44
0
 protected override void Cleanup()
 {
     ApplicationId         = default;
     ApplicationInstanceId = default;
 }
Exemple #45
0
 public void Enable(UniqueId id)
 {
     GetEntById(id).Enabled = true;
 }
Exemple #46
0
 protected SecurityContextSecurityToken IssueSecurityContextToken(UniqueId contextId, string id, byte[] key, DateTime tokenEffectiveTime, DateTime tokenExpirationTime, UniqueId keyGeneration, DateTime keyEffectiveTime, DateTime keyExpirationTime, ReadOnlyCollection <IAuthorizationPolicy> authorizationPolicies, bool isCookieMode)
 {
     base.CommunicationObject.ThrowIfClosedOrNotOpen();
     if ((this.securityStateEncoder == null) && isCookieMode)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SctCookieNotSupported")));
     }
     return(new SecurityContextSecurityToken(contextId, id, key, tokenEffectiveTime, tokenExpirationTime, authorizationPolicies, isCookieMode, isCookieMode ? this.cookieSerializer.CreateCookieFromSecurityContext(contextId, id, key, tokenEffectiveTime, tokenExpirationTime, keyGeneration, keyEffectiveTime, keyExpirationTime, authorizationPolicies) : null, keyGeneration, keyEffectiveTime, keyExpirationTime));
 }
Exemple #47
0
 public SecurityContextKeyIdentifierClause(UniqueId contextId, UniqueId generation)
     : this(contextId, generation, null, 0)
 {
 }
Exemple #48
0
 public bool IsEnabled(UniqueId id)
 {
     return(GetEntById(id).Enabled);
 }
Exemple #49
0
 public void Remove(UniqueId uniqueId)
 {
     _restTarget.Resolve("snapshots").Resolve(uniqueId.ObjectID.ToString()).Delete();
 }
 internal static void RepositoryUpdated(this ILogger <ObjectRepositoryContainer> logger, UniqueId id, ObjectId commitId) =>
 _repositoryUpdated(logger, id, commitId, null);
Exemple #51
0
 public SecurityContextKeyIdentifierClause(UniqueId contextId)
     : this(contextId, null)
 {
 }
        public static SecurityContextSecurityToken ResolveCookie(byte [] bytes, byte [] cookie)
        {
            string   id           = null;
            UniqueId context      = null;
            DateTime validFrom    = DateTime.MinValue,
                     validTo      = DateTime.MaxValue,
                     keyEffective = DateTime.MinValue,
                     keyExpired   = DateTime.MaxValue;

            byte []               key    = null;
            X509Certificate2      cert   = null;
            X500DistinguishedName issuer = null;

            XmlDictionary dic = new XmlDictionary();

            for (int i = 0; i < 30; i++)
            {
                dic.Add("n" + i);
            }
            // FIXME: create proper quotas
            XmlDictionaryReaderQuotas quotas =
                new XmlDictionaryReaderQuotas();
            XmlDictionaryReader cr = XmlDictionaryReader.CreateBinaryReader(bytes, 0, bytes.Length, dic, quotas);

            cr.MoveToContent();              // -> n1
            cr.ReadStartElement("n0", String.Empty);
            do
            {
                cr.MoveToContent();
                if (cr.NodeType == XmlNodeType.EndElement)
                {
                    break;
                }
                if (cr.NodeType != XmlNodeType.Element)
                {
                    throw new Exception("Unxpected non-element content:" + cr.NodeType);
                }

                switch (cr.Name)
                {
                case "n1":
                    // FIXME: some integer here
                    int n1 = cr.ReadElementContentAsInt();
                    if (n1 != 1)
                    {
                        throw new Exception("INTERNAL ERROR: there was unexpected n2 content: " + n1);
                    }
                    break;

                case "n2":
                    context = cr.ReadElementContentAsUniqueId();
                    break;

                case "n3":
                    id = cr.ReadElementContentAsString();
                    break;

                case "n4":
                    key = cr.ReadElementContentAsBase64();
                    break;

                case "n7":
                    validFrom = new DateTime(cr.ReadElementContentAsLong());
                    break;

                case "n8":
                    validTo = new DateTime(cr.ReadElementContentAsLong());
                    break;

                case "n10":
                    keyEffective = new DateTime(cr.ReadElementContentAsLong());
                    break;

                case "n11":
                    keyExpired = new DateTime(cr.ReadElementContentAsLong());
                    break;

                case "n13":
                    // <n18>X509Certificate</n18>
                    cr.Read();
                    cr.MoveToContent();
                    cert = new X509Certificate2(cr.ReadElementContentAsBase64());
                    cr.ReadEndElement();
                    break;

                case "n15":
                    // <n16><n24 n25="IssuerName" /></n16>
                    cr.Read();
                    cr.ReadStartElement("n16", String.Empty);
                    issuer = new X500DistinguishedName(cr.GetAttribute("n25"));
                    bool empty = cr.IsEmptyElement;
                    cr.ReadStartElement("n24", String.Empty);
                    if (!empty)
                    {
                        cr.ReadEndElement();                  // n24
                    }
                    cr.ReadEndElement();                      // n16
                    cr.ReadEndElement();                      // n15
                    break;

                default:
                    throw new Exception("INTERNAL ERROR: there was an unhandled element: " + cr.Name);
                }
            } while (true);

            SecurityContextSecurityToken sct = new SecurityContextSecurityToken(
                context, id, key, validFrom, validTo,
                null, keyEffective, keyExpired, null);

            sct.Cookie = cookie;
            return(sct);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="MailKit.ModSeqChangedEventArgs"/> class.
 /// </summary>
 /// <remarks>
 /// Creates a new <see cref="ModSeqChangedEventArgs"/>.
 /// </remarks>
 /// <param name="index">The message index.</param>
 /// <param name="uid">The unique id of the message.</param>
 /// <param name="modseq">The modification sequence value.</param>
 public ModSeqChangedEventArgs(int index, UniqueId uid, ulong modseq) : base(index)
 {
     ModSeq   = modseq;
     UniqueId = uid;
 }
Exemple #54
0
 private Entity GetEntById(UniqueId id)
 {
     return(globalEnts.Find(x => x.Id == id));
 }
 public abstract IEnumerable <SessionSecurityToken> GetAll(string endpointId, UniqueId contextId);
Exemple #56
0
 internal SequenceFaultedTraceRecord(UniqueId id, string reason) : base(id)
 {
     this.reason = reason;
 }
Exemple #57
0
 internal Key(UniqueId messageId, Type stateType)
 {
     MessageId = messageId;
     StateType = stateType;
 }
Exemple #58
0
        public void WriteValue_UniqueId_IdNull()
        {
            UniqueId value = null;

            writer.WriteValue(value);
        }
        private Challenge GetChallenge(string domain)
        {
            var challenge = new Challenge();

            challenge.TextBase64 = string.Format("realm=\"{0}\",nonce=\"{1}\",qop=\"auth\",charset=utf-8,algorithm=md5-sess", domain, UniqueId.CreateNewId());
            return(challenge);
        }
Exemple #60
0
 protected SecurityContextSecurityToken IssueSecurityContextToken(UniqueId contextId, string id, byte[] key, DateTime tokenEffectiveTime, DateTime tokenExpirationTime, ReadOnlyCollection <IAuthorizationPolicy> authorizationPolicies, bool isCookieMode)
 {
     return(this.IssueSecurityContextToken(contextId, id, key, tokenEffectiveTime, tokenExpirationTime, null, tokenEffectiveTime, tokenExpirationTime, authorizationPolicies, isCookieMode));
 }