public PolicyPublished Deserialise(XElement policyPublished)
        {
            if (policyPublished.Name != "policy_published")
            {
                throw new ArgumentException("Root element must be policy_published");
            }

            string domain = policyPublished.Single("domain").Value;

            if (!_domainValidator.IsValidDomain(domain))
            {
                throw new ArgumentException("Invalid domain");
            }

            //nullable this deviates from spec
            Alignment adkimCandidate;
            Alignment?adkim = Enum.TryParse(policyPublished.SingleOrDefault("adkim")?.Value, true, out adkimCandidate) ? adkimCandidate : (Alignment?)null;

            //nullable this deviates from spec
            Alignment aspfCandidate;
            Alignment?aspf = Enum.TryParse(policyPublished.SingleOrDefault("aspf")?.Value, true, out aspfCandidate) ? aspfCandidate : (Alignment?)null;

            Disposition p = (Disposition)Enum.Parse(typeof(Disposition), policyPublished.Single("p").Value, true);

            //nullable this deviates from spec
            Disposition spCandidate;
            Disposition?sp = Enum.TryParse(policyPublished.SingleOrDefault("sp")?.Value, true, out spCandidate) ? spCandidate : (Disposition?)null;

            //nullable this deviates from spec
            int pctCandidate;
            int?pct = int.TryParse(policyPublished.SingleOrDefault("pct")?.Value, out pctCandidate) ? pctCandidate : (int?)null;

            return(new PolicyPublished(domain, adkim, aspf, p, sp, pct));
        }
Exemplo n.º 2
0
        public void TestSerialization_Dispatched()
        {
            Disposition expectedDisposition = new Disposition(MDNStandard.NotificationType.Dispatched);

            Message             source              = this.CreateSourceMessage();
            Notification        notification        = this.CreateDispatchedNotification();
            NotificationMessage notificationMessage = source.CreateNotificationMessage(new MailAddress(source.FromValue), notification);

            var path = Path.GetTempFileName();

            try
            {
                notificationMessage.Save(path);
                Message loadedMessage = Message.Load(File.ReadAllText(path));
                Assert.True(loadedMessage.IsMDN());
                Assert.Equal(notificationMessage.ParsedContentType.MediaType, loadedMessage.ParsedContentType.MediaType);
                Assert.Equal(notificationMessage.SubjectValue, loadedMessage.SubjectValue);
                Assert.True(loadedMessage.HasHeader(MimeStandard.VersionHeader));
                Assert.True(loadedMessage.HasHeader(MailStandard.Headers.Date));
                Assert.True(loadedMessage.Headers.Count(x => (MimeStandard.Equals(x.Name, MimeStandard.VersionHeader))) == 1);
                var mdn = MDNParser.Parse(loadedMessage);
                VerifyEqual(expectedDisposition, mdn.Disposition);
            }
            finally
            {
                File.Delete(path);
            }
        }
Exemplo n.º 3
0
        public async Task RunAsync(IBankDbContext context, NewCustomerCommandModel model)
        {
            var foundCustomer = context.Customers.SingleOrDefault(c => c.CustomerId == model.CustomerId);

            if (foundCustomer == null)
            {
                var customer = NewCustomer(model);
                await context.Customers.AddAsync(customer);

                await context.SaveChangesAsync(new System.Threading.CancellationToken());

                Account account = new Account()
                {
                    Balance   = 0,
                    Created   = DateTime.Now,
                    Frequency = "Monthly"
                };
                await context.Accounts.AddAsync(account);

                await context.SaveChangesAsync(new System.Threading.CancellationToken());

                Disposition disposition = new Disposition()
                {
                    Account  = account,
                    Customer = customer,
                    Type     = "Owner"
                };
                await context.Dispositions.AddAsync(disposition);
            }
            else
            {
                EditCustomer(foundCustomer, model);
            }
            await context.SaveChangesAsync(new System.Threading.CancellationToken());
        }
Exemplo n.º 4
0
 void VerifyEqual(Disposition x, Disposition y)
 {
     Assert.Equal(x.TriggerType, y.TriggerType);
     Assert.Equal(x.SendType, y.SendType);
     Assert.Equal(x.Notification, y.Notification);
     Assert.Equal(x.IsError, y.IsError);
 }
Exemplo n.º 5
0
        internal override List <GameObject> Execute(BehaviorUpdateContext context)
        {
            var debrisObject = context.GameContext.GameObjects.Add("GenericDebris", context.GameObject.Owner);

            debrisObject.Transform.Translation = context.GameObject.Transform.Translation + Offset;
            debrisObject.Transform.Rotation    = context.GameObject.Transform.Rotation;

            // Model
            var w3dDebrisDraw = (W3dDebrisDraw)debrisObject.DrawModules[0];
            // TODO
            //var modelName = ModelNames[context.GameContext.Random.Next(ModelNames.Length)];
            var modelName = ModelNames[0];

            w3dDebrisDraw.SetModelName(modelName);

            // Physics
            var physicsBehavior = debrisObject.FindBehavior <PhysicsBehavior>();

            physicsBehavior.Mass = Mass;

            if (Disposition.Get(ObjectDisposition.SendItFlying))
            {
                physicsBehavior.AddForce(
                    new Vector3(
                        ((float)context.GameContext.Random.NextDouble() - 0.5f) * DispositionIntensity * 200,
                        ((float)context.GameContext.Random.NextDouble() - 0.5f) * DispositionIntensity * 200,
                        DispositionIntensity * 200));
            }

            // TODO: Count, Disposition, DispositionIntensity

            return(new List <GameObject> {
                debrisObject
            });
        }
Exemplo n.º 6
0
        public async Task <Disposition> GetSingleCustomerId(int customerId)
        {
            string url = Constants.urlDisposition + "/customer/" + customerId;

            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await _user.GetToken());
                    HttpResponseMessage respsone = await client.GetAsync(url);

                    respsone.EnsureSuccessStatusCode();

                    var json = await respsone.Content.ReadAsStringAsync();

                    Disposition disposition = JsonConvert.DeserializeObject <Disposition>(json);

                    return(disposition);
                }
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Exemplo n.º 7
0
        /// <inheritdoc />
        public virtual ErrorCode Disconnect(Disposition disposition)
        {
            var ret = Primitives.Api.SCardDisconnect(_card, disposition);

            _card = IntPtr.Zero;
            return(ret);
        }
Exemplo n.º 8
0
 /// <inheritdoc />
 public void ReadXml(XmlReader reader)
 {
     Initialization = (Disposition)Enum.Parse(typeof(Disposition), reader.GetAttribute("initialization"));
     reader.ReadStartElement();
     Protocol = (Protocol)Enum.Parse(typeof(Protocol), reader.ReadContentAsString());
     reader.ReadEndElement();
 }
 void Disconnect(IntPtr card, Disposition disconection)
 {
     if (card != IntPtr.Zero)
     {
         NativeMethods.SCardDisconnect(card, (uint)disconection);
     }
 }
Exemplo n.º 10
0
        /// <summary>
        /// Get the Name for the Enum Value
        /// </summary>
        /// <returns></returns>
        public string GetSerializedDisposition()
        {
            Type      t  = Disposition.GetType();
            FieldInfo fi = t.GetField(Disposition.ToString());

            return(EnumSerilizedNameAttribute.GetValue(fi));
        }
Exemplo n.º 11
0
        /// <inheritdoc />
        public ErrorCode Disconnect(Disposition disposition)
        {
            switch (InteractiveController.Mode)
            {
            case InteractiveMode.Replay:
                var nextAction = InteractiveController.ActionsList[InteractiveController.ActionsListId] as DisconnectAction;

                if (nextAction == null || nextAction.Disposition != disposition)
                {
                    return(ErrorCode.UnsupportedFeature);
                }

                // Seek id to next action and check limits
                if (++InteractiveController.ActionsListId == InteractiveController.ActionsList.Count)
                {
                    InteractiveController.Mode = InteractiveMode.Transparent;
                }

                return(ErrorCode.Success);

            default:
                var ret = stack.RequestLayer(this, SearchMode.Next).Disconnect(disposition);

                if (InteractiveController.Mode == InteractiveMode.Record)
                {
                    InteractiveController.ActionsList.Add(new DisconnectAction(disposition));
                }

                return(ret);
            }
        }
Exemplo n.º 12
0
        public DataCollectionFilter(
            SqlInt32 filterId,
            string instance,
            SqlString filterName,
            SqlString description,
            SqlString createdBy,
            SqlDateTime creationTime,
            SqlString lastModifiedBy,
            SqlDateTime lastModificationTime
            )
        {
            Debug.Assert(!filterId.IsNull);
            Debug.Assert(!string.IsNullOrEmpty(instance));
            Debug.Assert(!filterName.IsNull);

            m_Disposition          = Disposition.Unchanged;
            m_FilterId             = filterId.IsNull ? Constants.InvalidId : filterId.Value;
            m_Instance             = instance;
            m_FilterName           = filterName.IsNull ? string.Empty : filterName.Value;
            m_Description          = description.IsNull ? string.Empty : description.Value;
            m_CreatedBy            = createdBy.IsNull ? string.Empty : createdBy.Value;
            m_CreationTime         = creationTime.IsNull ? DateTime.Now : creationTime.Value;
            m_LastModifiedBy       = lastModifiedBy.IsNull ? string.Empty : lastModifiedBy.Value;
            m_LastModificationTime = lastModificationTime.IsNull ? DateTime.Now : lastModificationTime.Value;
        }
        public async Task <EntityId> Handle(CreateDispositionCommand request, CancellationToken cancellationToken)
        {
            EntityId entity = new EntityId();

            if (request.Disposition.CustomerId > 0 &&
                request.Disposition.AccountId > 0 &&
                request.Disposition.Type != null)
            {
                Disposition disposition = new Disposition
                {
                    CustomerId = request.Disposition.CustomerId,
                    AccountId  = request.Disposition.AccountId,
                    Type       = request.Disposition.Type
                };

                int dispositionId = await _repository.Create(disposition);

                entity = new EntityId(dispositionId);
                return(entity);
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 14
0
        public async Task <Unit> Handle(AddExistingAccountCommand request, CancellationToken cancellationToken)
        {
            var account = await _context.Accounts.SingleOrDefaultAsync(a => a.AccountId == request.AccountId);

            if (account == null)
            {
                throw new AccountNotFoundException(request.AccountId);
            }
            else
            {
                var customer = await _context.Customers.SingleOrDefaultAsync(c => c.CustomerId == request.CustomerId);

                var disp = new Disposition
                {
                    Customer = customer,
                    Account  = account,
                    Type     = "Disponent"
                };

                _context.Dispositions.Add(disp);

                if (await _context.SaveChangesAsync(cancellationToken) == 1)
                {
                    return(Unit.Value);
                }
                else
                {
                    throw new ErrorSavingToDatabaseException();
                }
            }
        }
Exemplo n.º 15
0
 //Constructeur pour les portes logiques (le nobre de sorties est fixee a 1)
 public Outils(int nb_entrees, string etiquette, List <ClasseEntree> liste_entrees, Disposition dispo)
 {
     this.disposition   = dispo;
     this.nb_entrees    = nb_entrees;
     this.etiquette     = etiquette;
     this.liste_entrees = liste_entrees;
 }
Exemplo n.º 16
0
        public DispoModule(IDispoRepository _repo)
            : base("/dispo")
        {
            // var _repo = new DispoRepository(_dbConn);

            Get("/", args =>
            {
                return(_repo.GetAll());
            });

            Get("Id={id}", args =>
            {
                return(_repo.Get(args.id));
            });

            Post("/Name={name}&Desc={description}", args =>
            {
                var posted         = new Disposition();
                posted.Name        = args.Name;
                posted.Description = args.Description;
                posted.Timestamp   = DateTime.Now;
                _repo.Add(posted);

                return(posted);
            });

            Delete("Id={id}", args =>
            {
                _repo.Remove(args.id);
                return($"{args.id} Removed");
            });
        }
Exemplo n.º 17
0
            public static void Log(object source, bool send, Performative command)
            {
                AmqpDebugImpl instance = AmqpDebugImpl.GetInstance(source);
                ulong         code     = command.DescriptorCode;
                uint          p1       = 0;
                uint          p2       = 0;

                if (code == Transfer.Code)
                {
                    Transfer transfer = (Transfer)command;
                    p1 = transfer.DeliveryId ?? 0;
                    p2 = transfer.Settled() ? 1u : 0u;
                }
                else if (code == Disposition.Code)
                {
                    Disposition disp = (Disposition)command;
                    p1 = disp.First ?? 0;
                    p2 = disp.Last ?? p1;
                }
                else if (code == Flow.Code)
                {
                    Flow flow = (Flow)command;
                    p1 = flow.IncomingWindow ?? 0;
                    p2 = flow.NextIncomingId ?? 0;
                    if (flow.Handle.HasValue)
                    {
                        instance.LogInternal(send, code, flow.DeliveryCount.Value, flow.LinkCredit.Value);
                    }
                }

                instance.LogInternal(send, code, p1, p2);
            }
Exemplo n.º 18
0
        private void ExtractParamsFromMultiPartFormData(Part part)
        {
            Disposition disp = part.ContentDisposition;

            if (disp == null)
            {
                throw new ArgumentException("incorrect use of this function: " +
                                            "input part.ContentDisposition is null");
            }

            if (disp.Value.Equals("form-data", StringComparison.CurrentCultureIgnoreCase))
            {
                string filename = disp.Parameters["filename"];

                if (filename != null)
                {
                    var file = new UploadedFile(filename, part.Bytes,
                                                part.Headers["Content-Type"]);
                    Files.Add(file);
                }
                else
                {
                    string name = disp.Parameters["name"];
                    Parameters.Add(name, part.Text);
                }
            }
        }
Exemplo n.º 19
0
 public InputOutput(int ID, Disposition disposi)
 {
     InitializeComponent();
     this.ID                = ID;
     this.dispo             = disposi;
     this.MouseDoubleClick += MouseClick;
 }
Exemplo n.º 20
0
            public void OnReceiveDisposition(Disposition disposition)
            {
                SequenceNumber first = disposition.First.Value;
                SequenceNumber last  = disposition.Last ?? first;

                this.session.diagnostics.SetLastDisposition(last.Value);
                bool settled = disposition.Settled();

                for (SequenceNumber i = first; ; i.Increment())
                {
                    Delivery delivery = this.GetDelivery(i);
                    if (delivery != null && delivery.Link != null)
                    {
                        delivery.Settled = settled;
                        delivery.State   = disposition.State;
                        delivery.Link.OnDisposeDelivery(delivery);
                    }

                    if (i == last)
                    {
                        break;
                    }
                }

                if (settled)
                {
                    this.Settle();
                }
            }
Exemplo n.º 21
0
        /// <inheritdoc />
        public ErrorCode Reconnect(ShareMode shareMode, Protocol preferedProtocol, Disposition initialization)
        {
            switch (InteractiveController.Mode)
            {
            case InteractiveMode.Replay:
                var nextAction = InteractiveController.ActionsList[InteractiveController.ActionsListId] as ReconnectAction;

                if (nextAction == null || nextAction.Initialization != initialization)
                {
                    return(ErrorCode.UnsupportedFeature);
                }

                // Retrieve protocol to send
                protocol = nextAction.Protocol;
                // Seek id to next action and check limits
                if (++InteractiveController.ActionsListId == InteractiveController.ActionsList.Count)
                {
                    InteractiveController.Mode = InteractiveMode.Transparent;
                }

                return(ErrorCode.Success);

            default:

                var ret = stack.RequestLayer(this, SearchMode.Next).Reconnect(shareMode, preferedProtocol, initialization);

                if (InteractiveController.Mode == InteractiveMode.Record)
                {
                    InteractiveController.ActionsList.Add(new ReconnectAction(Protocol, initialization));
                }

                return(ret);
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// Produces a report of this job for the console.
        /// </summary>
        public override string ToString()
        {
            var report = new StringBuilder();

            report.AppendLine(ConsoleFormat.DoubleLine);
            report.AppendLine($"JOB {Disposition.ToString().ToUpper()}");
            report.AppendLine(ConsoleFormat.DoubleLine);
            report.AppendLine();
            report.AppendLine($"{Items.Count()} item{ConsoleFormat.AsPlural(Items.Count())} {(TotalItemCount.HasValue ? "of " + TotalItemCount + " processed" : "processed")}");
            report.AppendLine();
            report.AppendLine(ConsoleFormat.AsColumns(20, nameof(InitializeAsync), InitializeAsync.IsSuccessful ? "Successful" : "Unsuccessful"));
            report.AppendLine(ConsoleFormat.AsColumns(20, nameof(GetItemsAsync), GetItemsAsync.IsSuccessful ? "Successful" : "Unsuccessful"));
            if (!Count?.IsSuccessful ?? false)
            {
                report.AppendLine(ConsoleFormat.AsColumns(20, nameof(Count), Count.IsSuccessful ? "Successful" : "Unsuccessful"));
            }
            if (!GetEnumerator?.IsSuccessful ?? false)
            {
                report.AppendLine(ConsoleFormat.AsColumns(20, nameof(GetEnumerator), GetEnumerator.IsSuccessful ? "Successful" : "Unsuccessful"));
            }
            report.AppendLine(ConsoleFormat.AsColumns(20, "ProcessAsync", FailedItemCount == 0 ? "Successful" : "Unsuccessful"));
            report.AppendLine(ConsoleFormat.AsColumns(20, nameof(FinalizeAsync), FinalizeAsync.IsSuccessful ? "Successful" : "Unsuccessful"));
            report.AppendLine();

            foreach (var summary in Categories)
            {
                report.AppendLine(ConsoleFormat.AsColumns(20, $"{summary.Count} item{ConsoleFormat.AsPlural(Items.Count())}", summary.IsSuccessful ? "Successful" : "Unsuccessful", summary.Category));
            }

            report.AppendLine();

            if (FailedItemsThatThrewExceptions.Count() > 0 || Methods.Values.Any(m => !m.IsSuccessful))
            {
                report.AppendLine(ConsoleFormat.DoubleLine);
                report.AppendLine("UNHANDLED EXCEPTIONS");
                report.AppendLine(ConsoleFormat.DoubleLine);
                report.AppendLine();

                foreach (var method in Methods.Values.Where(m => !m.IsSuccessful))
                {
                    report.AppendLine(ConsoleFormat.SingleLine);
                    report.AppendLine(method.Method.ToString());
                    report.AppendLine(ConsoleFormat.SingleLine);
                    report.AppendLine(method.Exception.ToString());
                    report.AppendLine();
                }

                foreach (var failure in FailedItemsThatThrewExceptions.Take(10))
                {
                    report.AppendLine(ConsoleFormat.SingleLine);
                    report.AppendLine(failure.Id ?? "Unknown");
                    report.AppendLine(ConsoleFormat.SingleLine);
                    report.AppendLine((failure.ProcessAsync.Exception ?? failure.EnumeratorCurrent.Exception ?? failure.EnumeratorMoveNext.Exception).ToString());
                    report.AppendLine();
                }
            }

            return(report.ToString());
        }
Exemplo n.º 23
0
 public static bool Batchable(this Disposition disposition)
 {
     if (!disposition.Batchable.HasValue)
     {
         return(false);
     }
     return(disposition.Batchable.Value);
 }
Exemplo n.º 24
0
 public static bool Settled(this Disposition disposition)
 {
     if (!disposition.Settled.HasValue)
     {
         return(false);
     }
     return(disposition.Settled.Value);
 }
Exemplo n.º 25
0
        private Task Completed(object output, Disposition disposition, DateTime completedAt)
        {
            Output      = output;
            Disposition = disposition;
            CompletedAt = completedAt;

            return(Task.CompletedTask);
        }
Exemplo n.º 26
0
 public void SetDisposition(Faction other, Disposition disposition)
 {
     if (disposition == Disposition.Self)
     {
         return;
     }
     dispositions[other.index] = disposition;
 }
Exemplo n.º 27
0
        public async Task <int> Create(Disposition disposition)
        {
            await _context.Set <Disposition>().AddAsync(disposition);

            await _context.SaveChangesAsync();

            return(disposition.DispositionId);
        }
Exemplo n.º 28
0
 public InputOutput(String etiq, int ID, Disposition disposi)
 {
     InitializeComponent();
     this.etiquette         = etiq;
     this.ID                = ID;
     this.dispo             = disposi;
     this.MouseDoubleClick += MouseClick;
 }
Exemplo n.º 29
0
 /// <summary>
 /// Initializes a new <see cref="ResultLog"/>.
 /// </summary>
 public ResultLog(IEnumerable <ItemResult> items, Disposition disposition, int?totalItemCount, Dictionary <JobMethod, MethodOutcome> methods, object output)
 {
     this.items     = new ConcurrentBag <ItemResult>(items ?? new ItemResult[0]);
     Disposition    = disposition;
     TotalItemCount = totalItemCount;
     Methods        = methods;
     Output         = output;
 }
        public void LoadDispostionCodes(string interactionID)
        {
            try
            {
                if (_chatDataContext.LoadDispositionCodes != null && _chatDataContext.LoadSubDispositionCodes != null)
                {
                    _chatDataContext.dicCMEObjects.Clear();
                    _chatDataContext.dicCMEObjects.Add("chat.disposition.codes", _chatDataContext.LoadDispositionCodes);
                    _chatDataContext.dicCMEObjects.Add("chat.subdisposition.codes", _chatDataContext.LoadSubDispositionCodes);
                    if (ConfigContainer.Instance().AllKeys.Contains("interaction.enable.multi-dispositioncode") && (((string)ConfigContainer.Instance().GetValue("interaction.enable.multi-dispositioncode")).ToLower().Equals("true")))
                    {
                        _chatDataContext.dicCMEObjects.Add("enable.multidisposition.enabled", true);
                    }
                    else
                    {
                        _chatDataContext.dicCMEObjects.Add("enable.multidisposition.enabled", false);
                    }
                    _chatDataContext.dicCMEObjects.Add("DispositionCodeKey", _chatDataContext.DisPositionKeyName);
                    if (ConfigContainer.Instance().AllKeys.Contains("interaction.disposition-object-name"))
                    {
                        _chatDataContext.dicCMEObjects.Add("DispositionName", (string)ConfigContainer.Instance().GetValue("interaction.disposition-object-name"));
                    }
                    else
                    {
                        _chatDataContext.dicCMEObjects.Add("DispositionName", string.Empty);
                    }
                    Pointel.Interactions.DispositionCodes.InteractionHandler.Listener _dispositionCodeListener = new Pointel.Interactions.DispositionCodes.InteractionHandler.Listener();
                    _dispositionCodeListener.NotifyCMEObjects(_chatDataContext.dicCMEObjects);
                    DispositionData disData = new DispositionData()
                    {
                        InteractionID = interactionID
                    };
                    _dispositionUC = _dispositionCodeListener.CreateUserControl();
                    _chatDataContext.DispositionObjCollection = new KeyValuePair <string, object>("DispositionObj", _dispositionUC);
                    stpDispCodelist.Children.Clear();
                    _dispositionUC.NotifyDispositionCodeEvent += new Pointel.Interactions.DispositionCodes.UserControls.Disposition.NotifyDispositionCode(NotifyDispositionCodeEvent);
                    _dispositionUC.Dispositions(Pointel.Interactions.IPlugins.MediaTypes.Chat, disData);

                    if (_dispositionUC != null)
                    {
                        if (!_dispositionUserControls.ContainsKey(interactionID))
                        {
                            _dispositionUserControls.Add(interactionID, _dispositionUC);
                        }
                        else
                        {
                            _dispositionUserControls[interactionID] = _dispositionUC;
                        }
                        stpDispCodelist.Children.Add(_dispositionUC);
                    }
                    isFirstTimeCall = false;
                }
            }
            catch (Exception generalException)
            {
                _logger.Error("Error Occurred as LoadDispostionCodes() :" + generalException.Message);
            }
        }
Exemplo n.º 31
0
        public static int NumberOfDisposition(User aUser, Disposition aDisposition)
        {
            int myTotalFromIssues = (from i in aUser.IssueDispositions
                                     where i.Disposition == (int)aDisposition
                                     select i).Count<IssueDisposition>();

            int myTotalFromIssueReplys = (from ir in aUser.IssueReplyDispositions
                                          where ir.Disposition == (int)aDisposition
                                          select ir).Count<IssueReplyDisposition>();

            return myTotalFromIssues + myTotalFromIssueReplys;
        }
        public IEnumerable<IssueWithDispositionModel> GetMostPopularIssues(Disposition aDisposition)
        {
            IEnumerable<Issue> myIssues = GetOrderedIssues();
            IEnumerable<int> myIssueIds = (from i in myIssues
                                           select i.Id).ToList<int>();
            IEnumerable<IssueDisposition> myIssueDispositions = (from d in theEntities.IssueDispositions
                                                                 where myIssueIds.Contains(d.IssueId)
                                                                 select d).ToList<IssueDisposition>();
            IEnumerable<IssueReply> myIssueReplys = GetOrderedIssueReplys();

            return Helpers.CalculatedWithWeights(myIssues.ToList(), myIssueReplys.ToList(), myIssueDispositions.ToList(), aDisposition);
        }
        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="mimeEntry"></param>
        /// <param name="mime"></param>
        public MimeEntry(byte[] mimeEntry,MimeParser mime)
        {
            m_Headers         = ParseHeaders(mimeEntry);
            m_ConentType      = ParseContentType(m_Headers);

            // != multipart content (must be nested)
            if(m_ConentType.ToLower().IndexOf("multipart") == -1){
                m_CharSet         = ParseCharSet(m_Headers);
                m_ContentEncoding = ParseEncoding(m_Headers);
                m_FileName        = ParseFileName(m_Headers);
                m_Disposition     = ParseContentDisposition(m_Headers);

                m_Data = ParseData(System.Text.Encoding.Default.GetString(mimeEntry).Substring(m_Headers.Length + 2)); // 2-<CRLF>
            }
            else{ // Get nested entries
                string boundaryID = mime.ParseBoundaryID(m_Headers);
                m_Entries = mime.ParseEntries(new MemoryStream(mimeEntry),m_Headers.Length,boundaryID);
            }
        }
Exemplo n.º 34
0
		static extern int RegCreateKeyEx (UIntPtr hKey, string subKey, uint reserved, string @class, uint options,
			uint samDesired, IntPtr lpSecurityAttributes, out UIntPtr phkResult, out Disposition lpdwDisposition);
Exemplo n.º 35
0
        protected virtual void ParseBody()
        {
            string strFullConentType	= _headers["Content-Type"];
            if(strFullConentType==null)
                strFullConentType="";

            //string strContentTypeValue	= null;

            Hashtable	parametrs;
            MimeEntry.ParseHeader(strFullConentType, out _contentType, out parametrs);

            // Step 2. Parse Messagy Body [1/23/2004]
            if(!_contentType.StartsWith("multipart/"))
            {
                _charSet         = (string)parametrs["charset"] ;

                if(_charSet==null)
                    _charSet = Encoding.Default.HeaderName;

                string ContentEncoding = _headers["Content-Transfer-Encoding"];

                if(ContentEncoding==null)
                    ContentEncoding = "8bit";

                string strDisposition     = _headers["Content-Disposition"];

                if(strDisposition!=null)
                {
                    Hashtable	DispositionParameters;
                    string		DispositionType;
                    MimeEntry.ParseHeader(strDisposition, out DispositionType, out DispositionParameters);

                    DispositionType = DispositionType.ToLower();

                    if(DispositionType=="attachment")
                        this._disposition = Disposition.Attachment;
                    else if(DispositionType=="inline")
                        this._disposition = Disposition.Inline;

                    _fileName = (string)DispositionParameters["filename"];
                    if(_fileName!=null)
                        _fileName = Rfc822HeaderCollection.DeocodeHeaderValue(_fileName);
                }

                //string BodyString = Encoding.Default.GetString(this._BinaryData.GetBuffer(),this._BodyOffset,(int)(this._BinaryData.Length  - this._BodyOffset));
                Encoding encoding = null;
                try
                {
                    encoding = Encoding.GetEncoding(CharSet);
                }
                catch
                {
                    encoding = Encoding.Default;
                }

                string BodyString = encoding.GetString(this._BinaryData.GetBuffer(),this._BodyOffset,(int)(this._BinaryData.Length  - this._BodyOffset));

                //string BodyString = Encoding.ASCII.GetString(this._BinaryData.GetBuffer(),this._BodyOffset,(int)(this._BinaryData.Length  - this._BodyOffset));
                //string BodyString2 = Encoding.UTF8.GetString(this._BinaryData.GetBuffer(),this._BodyOffset,(int)(this._BinaryData.Length  - this._BodyOffset));

                switch(ContentEncoding.ToLower())
                {
                    case "quoted-printable":
                        _body = encoding.GetBytes(MimeEntry.QDecode(encoding,BodyString));
                        break;
                    case "7bit":
                        //_body = Encoding.ASCII.GetBytes(BodyString);
                        _body = encoding.GetBytes(BodyString);
                        break;
                    default:
                    case "8bit":
                        _body = encoding.GetBytes(BodyString);
                        break;
                    case "base64":
                        BodyString = BodyString.Trim();

                        if(BodyString.Length>0 )
                        {
                            int base64FixCount = 0;

                            // Fix If Base 64 is broken
                            while (true)
                            {
                                try
                                {
                                    _body = Convert.FromBase64String(BodyString);
                                    break;
                                }
                                catch (System.FormatException)
                                {
                                    // Remove not supported chars
                                    if (base64FixCount == 0)
                                        BodyString = Regex.Replace(BodyString, "[^a-zA-Z0-9+/=]+", string.Empty);
                                    else if (base64FixCount == 1)
                                        BodyString += "=";
                                    else
                                        BodyString = BodyString.Substring(0, BodyString.Length - 1);

                                    if (BodyString.Length == 0 || base64FixCount == 25) // Max 25 Attempts to fix chars
                                    {
                                        _body = new byte[] { };
                                        break;
                                    }

                                    base64FixCount++;
                                }
                            }
                        }
                        else
                            _body = new byte[]{};
                        break;
                    case "binary":
                        _body = encoding.GetBytes(BodyString);
                        break;
                    //default:
                    //    throw new Pop3ServerIncorectEMailFormatException("Not supported content-encoding " + ContentEncoding + " !");
                }
            }
            else
            {
                DataParseStatus parseStatus = _mimeEntries.ParseMimeEntries(_BinaryData.GetBuffer(),(int)_BinaryData.Length,ref _BodyOffset,this.Headers);
            }
        }
Exemplo n.º 36
0
 internal void NotifyOfDisposition(Delivery delivery, Disposition disposition)
 {
     try
     {
         // TODO: notify application of change in application state
     }
     catch (AmqpException amqpException)
     {
         trace.Error(amqpException);
         DetachLink(amqpException.Error, destoryLink: true);
     }
     catch (Exception fatalException)
     {
         trace.Fatal(fatalException, "Ending Session due to fatal exception.");
         var error = new Error()
         {
             Condition = ErrorCode.InternalError,
             Description = "Ending Session due to fatal exception: " + fatalException.Message,
         };
         DetachLink(error, destoryLink: true);
     }
 }
Exemplo n.º 37
0
 public void SetDisposition(FactionId other, Disposition disposition)
 {
     switch (disposition) {
         case Disposition.Friendly:
             SetFactionFriendly(other);
             break;
         case Disposition.Hostile:
             SetFactionHostile(other);
             break;
         case Disposition.Neutral:
             SetFactionNeutral(other);
             break;
     }
 }
Exemplo n.º 38
0
        public void Can_Encode_and_Decode_Skipping_Null_Values()
        {
            var buffer = new ByteBuffer(1024, false);

            var value = new Disposition();
            value.First = (uint)randNum.Next();
            value.Settled = randNum.Next(1, 101) % 2 == 0 ? true : false;
            value.Role = randNum.Next(1, 101) % 2 == 0 ? true : false;
            value.State = randNum.Next(1, 101) % 2 == 0 ? (DeliveryState)new Accepted() : (DeliveryState)new Rejected();

            AmqpCodec.EncodeObject(buffer, value);

            var decodedValue = AmqpCodec.DecodeObject<Disposition>(buffer);

            Assert.AreEqual(value.First, decodedValue.First);
            Assert.AreEqual(value.Last, decodedValue.Last);
            Assert.AreEqual(value.Settled, decodedValue.Settled);
            Assert.AreEqual(value.Role, decodedValue.Role);
            Assert.AreEqual(value.State.Descriptor, decodedValue.State.Descriptor);
        }
Exemplo n.º 39
0
        /// <summary>
        /// Close the log and sound off according to how the test ended.
        /// </summary>
        /// <param name="action">The disposition of the test</param>
        public void close(Disposition action)
        {
            if (!s_isClosed)
            {
                Sound snd = new Sound();
                if (action == Disposition.Pass) {
                    snd.Frequency = 800;
                    snd.Duration = 500;
                }
                else if (action == Disposition.Fail) {
                    snd.Frequency = 300;
                    snd.Duration = 1000;
                }
                else { // Hung
                    snd.Frequency = 500;
                    snd.Duration = 200;
                }

                snd.Execute(); // a tone indicating disposition

                try
                {
                    m_sw.WriteLine(@"</gtdLog>");
                    m_sw.Close();
                }
                catch (Exception e)
                {
                    Console.Out.WriteLine("Log failed: " + e.Message);
                    action = Disposition.Hung;
                }
                s_isClosed = true;
                m_init = false;
            }
        }
Exemplo n.º 40
0
        /// <summary>
        /// Returns ArrayList of DateTime objects 
        /// (fromDate, toDate, eventStartDate - in UTC format)
        /// (return dates in UTC too, but without time part. 
        ///		To get the real Start DateTime you need to add recurrence StartTime to the returned dates)
        /// </summary>
        public static ArrayList GetRecurDates(DateTime fromDate, DateTime toDate, int startTime, DateTime eventStartDate, Recurrence recurrence, int maxCount, Disposition disp)
        {
            ArrayList list = new ArrayList();
            DateTime addDate;
            bool add;
            bool WeekDaysCalculated = false;
            int count = 0;
            // ѕереводим fromDate и toDate из UTC во временную зону рекурсии
            fromDate = DBCommon.GetLocalDate(recurrence.TimeZoneId, fromDate);
            toDate = DBCommon.GetLocalDate(recurrence.TimeZoneId, toDate);
            eventStartDate = DBCommon.GetLocalDate(recurrence.TimeZoneId, eventStartDate);

            DateTime startDate = recurrence.StartDate.Date;
            DateTime finishDate = recurrence.FinishDate.Date;
            DateTime curDate = startDate;

            if (recurrence.EndAfter == 0 && finishDate < toDate)
                toDate = finishDate;

            while (curDate <= toDate.AddDays(1))	// O.R.: добавл¤ем один день, чтобы не потер¤ть данные за счЄт разницы временных зон рекурсии и пользовател¤
            {
                // O.R.: if curDate is not appropriate - skip
                if (curDate.AddMinutes(startTime) < eventStartDate)
                {
                    curDate = curDate.AddDays(1);
                    continue;
                }

                add = false;
                addDate = curDate;

                if (recurrence.Pattern == RecurPattern.Daily && recurrence.SubPattern == RecurSubPattern.SubPattern1)
                {
                    // Repeat on every Nth day.
                    TimeSpan span = curDate - startDate;
                    if (span.Days % recurrence.Frequency == 0)
                    {
                        add = true;
                        curDate = curDate.AddDays(recurrence.Frequency);
                    }
                }
                else if (recurrence.Pattern == RecurPattern.Daily && recurrence.SubPattern == RecurSubPattern.SubPattern2)
                {
                    // Repeat on every Nth weekday.
                    if (WeekDaysCalculated)
                    {
                        add = true;
                        curDate = AddWeekDays(curDate, recurrence.Frequency);
                    }
                    else
                    {
                        int weekDaysElapsed = GetElapsedWeekDays(startDate, curDate);
                        if (weekDaysElapsed % recurrence.Frequency == 0 && GetFirstWeekDay(startDate) <= curDate)
                        {
                            WeekDaysCalculated = true;
                            add = true;
                            curDate = AddWeekDays(curDate, recurrence.Frequency);
                        }
                    }
                }
                else if (recurrence.Pattern == RecurPattern.Weekly)
                {
                    // Repeat on every selected day of Nth week.
                    BitDayOfWeek bdow = GetBitDayOfWeek(curDate.DayOfWeek);
                    if ((byte)BitDayOfWeek.Unknown != ((byte)bdow & recurrence.WeekDays))
                    {
                        int week = GetRelativeWeekNumber(startDate, curDate);
                        if ((double)week % recurrence.Frequency == 0)
                        {
                            add = true;
                            curDate = curDate.AddDays(1);
                        }
                    }
                }
                else if (recurrence.Pattern == RecurPattern.Monthly && recurrence.SubPattern == RecurSubPattern.SubPattern1)
                {
                    // Repeat on selected day of every Nth month.
                    if (curDate.Day == recurrence.DayOfMonth)
                    {
                        int month = GetRelativeMonthNumber(startDate, curDate);
                        if ((double)month % recurrence.Frequency == 0)
                        {
                            add = true;
                            curDate = curDate.AddMonths(recurrence.Frequency);
                        }
                    }
                }
                else if (recurrence.Pattern == RecurPattern.Monthly && recurrence.SubPattern == RecurSubPattern.SubPattern2)
                {
                    // Repeat on selected week and day of week of every Nth month.
                    if (curDate.DayOfWeek == GetDayOfWeekByBit((BitDayOfWeek)recurrence.WeekDays))
                    {
                        WeekNumber week = GetWeekNumber(curDate);
                        if ((week & ~WeekNumber.Last) == recurrence.RecurWeekNumber || (week & WeekNumber.Last) == recurrence.RecurWeekNumber)
                        {
                            int month = GetRelativeMonthNumber(startDate, curDate);
                            if ((double)month % recurrence.Frequency == 0)
                            {
                                add = true;
                                curDate = curDate.AddMonths(recurrence.Frequency).Subtract(new TimeSpan(7, 0, 0, 0));
                            }
                        }
                    }
                }
                else if (recurrence.Pattern == RecurPattern.Yearly && recurrence.SubPattern == RecurSubPattern.SubPattern1)
                {
                    // Repeat on selected day and month of every year.
                    if (curDate.Month == recurrence.MonthNumber && curDate.Day == recurrence.DayOfMonth)
                    {
                        add = true;
                        curDate = curDate.AddYears(1);
                    }
                }
                else if (recurrence.Pattern == RecurPattern.Yearly && recurrence.SubPattern == RecurSubPattern.SubPattern2)
                {
                    // Repeat on selected month, week and day of week of every year.
                    if (curDate.Month == recurrence.MonthNumber && curDate.DayOfWeek == GetDayOfWeekByBit((BitDayOfWeek)recurrence.WeekDays))
                    {
                        WeekNumber week = GetWeekNumber(curDate);
                        if ((week & ~WeekNumber.Last) == recurrence.RecurWeekNumber || (week & WeekNumber.Last) == recurrence.RecurWeekNumber)
                        {
                            add = true;
                            curDate = curDate.AddYears(1).Subtract(new TimeSpan(7, 0, 0, 0));
                        }
                    }
                }

                if (add && addDate >= fromDate.Date && addDate <= toDate.Date.AddDays(1))
                {
                    list.Add(DBCommon.GetUTCDate(recurrence.TimeZoneId, addDate));	// to UTC

                    if (maxCount > 0 && disp == Disposition.First && list.Count >= maxCount)
                        break;

                    if (maxCount > 0 && disp == Disposition.Last && list.Count > maxCount)
                        list.RemoveAt(0);
                }

                if (add)
                {
                    count++;
                    if (recurrence.EndAfter > 0 && count >= recurrence.EndAfter)
                        break;
                }
                else
                    curDate = curDate.AddDays(1);
            }

            return list;
        }
Exemplo n.º 41
0
 /// <summary>
 /// Initializes a new instance of the VerbSyncWorker class.
 /// </summary>
 /// <param name="workingDirectory">
 /// The private working directory for this worker to work in.
 /// </param>
 /// <param name="result">The Disposition to return on complete.</param>
 public VerbSyncWorker(WorkingDirectory workingDirectory, Disposition result)
 {
     this.workingDirectory = workingDirectory;
     this.result = result;
 }
        public ActionResult Disposition(int id, int issueId, Disposition disposition, SiteSection section, int sourceId)
        {
            if (!IsLoggedIn()) {
                return RedirectToLogin();
            }
            User aUser = GetUserInformaton();
            try {
                bool myResult = theIssueReplyService.AddIssueReplyStance(aUser, id, (int)disposition);
                if (!myResult) {
                    return SendToErrorPage("You can only provide a disposition towards a person's reply to an issue once.");
                }
                TempData["Message"] += MessageHelper.SuccessMessage(DISPOSITION_SUCCESS);
            } catch (Exception e) {
                LogError(e, DISPOSITION_ERROR);
                TempData["Message"] += MessageHelper.ErrorMessage(DISPOSITION_ERROR);
                return SendToErrorPage(DISPOSITION_ERROR);
            }

            if (section == SiteSection.Profile) {
                return RedirectToAction("Show", "Profile", new { id = sourceId });
            } else if (section == SiteSection.MyProfile) {
                return RedirectToAction("Show", "Profile");
            } else if (section == SiteSection.IssueActivity) {
                return RedirectToAction("IssueActivity", "Profile", new { id = sourceId });
            } else if (section == SiteSection.MyIssueActivity) {
                return RedirectToAction("IssueActivity", "Profile");
            } else if (section == SiteSection.IssueReply) {
                return RedirectToAction("Details", new { id = sourceId });
            } else {
                return RedirectToAction("RedirectToDetails", "Issue", new { id = issueId });
            }
        }
Exemplo n.º 43
0
        private void InterceptDispositionFrame(Disposition disposition)
        {
            if (!State.CanReceiveFrames())
                throw new AmqpException(ErrorCode.IllegalState, $"Received Disposition frame but session state is {State.ToString()}.");
            if (State == SessionStateEnum.DISCARDING)
                return;

            if (disposition.Role == true)
            {
                // from the RECEIVER
                throw new NotImplementedException();
            }
            else
            {
                // from the SENDER
                // We typically get a Disposition when the Receiver Link (our side)
                // sends back an unsettled Disposition in a terminal state.
                if (!disposition.Last.HasValue)
                    disposition.Last = disposition.First;
                for (uint deliveryHandle = disposition.First; deliveryHandle <= disposition.Last; deliveryHandle++)
                {
                    var delivery = incomingUnsettledMap.Find(d => d.DeliveryId == deliveryHandle);
                    delivery.Settled = disposition.Settled;
                    delivery.State = disposition.State;

                    var link = delivery.Link;
                    if (link.State == LinkStateEnum.DESTROYED)
                        throw new AmqpException(ErrorCode.ErrantLink, "If any input (other than a detach) related to the endpoint either via the input handle or delivery-ids be received, the session MUST be terminated with an errant-link session-error.");
                    link.NotifyOfDisposition(delivery, disposition);

                    if (disposition.Settled)
                        incomingUnsettledMap.Remove(delivery);
                }
            }
        }
Exemplo n.º 44
0
 private static int GetTotalStance(Issue anIssue, Disposition aStance)
 {
     return (from s in anIssue.IssueDispositions
             where s.Disposition == (int)aStance
             select s).Count<IssueDisposition>();
 }
Exemplo n.º 45
0
 public static extern SafeFileHandle CreateFile(string lpFileName, Rights dwDesiredAccess, Share dwShareMode, IntPtr lpSecurityAttributes, Disposition dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);
            public static IEnumerable<IssueWithDispositionModel> CalculatedWithWeights(List<Issue> anIssues,
                List<IssueReply> anIssueReplys,
                List<IssueDisposition> anIssueDispositions,
                Disposition aDisposition)
            {
                List<WeightModelIssue> myWeightModel = (from i in anIssues
                                                   let d = anIssueDispositions
                                                   .Where(d2 => d2.Issue.Id == i.Id)
                                                   .Where(d2 => d2.Disposition == (int)aDisposition)
                                                   .ToList<IssueDisposition>()
                                                   let ir = anIssueReplys
                                                   .Where(ir2 => ir2.Deleted == false)
                                                   .Where(ir2 => ir2.Issue.Id == i.Id)
                                                   .Where(ir2 => ir2.Disposition == (int)aDisposition)
                                                   .ToList<IssueReply>()
                                                   where i.Deleted == false
                                                   && (d.Count > 0 || ir.Count > 0)
                                                   select new WeightModelIssue {
                                                       Issue = i,
                                                       WeightedAverage = (d.Count * ISSUE_DISPOSITION_WEIGHT) + (ir.Count * ISSUE_REPLY_WEIGHT)
                                                   }).OrderByDescending(b2 => b2.WeightedAverage).ToList<WeightModelIssue>();

                return (from b in myWeightModel
                        select new IssueWithDispositionModel(b.Issue) {
                            HasDisposition = true
                        }).ToList<IssueWithDispositionModel>();
            }
Exemplo n.º 47
0
 internal static extern int SCardDisconnect(IntPtr card, Disposition disposition);
Exemplo n.º 48
0
 public void SendDeliveryDisposition(bool role, Delivery delivery, DeliveryState state, bool settled)
 {
     if (delivery != null)
     {
         var disposition = new Disposition()
         {
             Role = role,
             First = delivery.DeliveryId,
             Settled = settled,
             State = state,
         };
         if (settled)
         {
             incomingWindow++;
         }
         this.SendFrame(disposition);
     }
 }