public void Context()
        {
            _email = MockRepository.GenerateMock<Email>();
            var emailParts = new EmailPart[0];
            _email.Stub(a => a.Id).Return(EmailId);
            _email.Stub(a => a.Parts).Return(emailParts);

            _recipientOne = RecipientBuilder.New.WithId(RecipientOneId).WithEmailAddress(RecipientOneEmailAddress).WithName(RecipientOneName).Build();
            _recipientTwo = RecipientBuilder.New.WithId(RecipientTwoId).WithEmailAddress(RecipientTwoEmailAddress).WithName(RecipientTwoName).Build();
            _email.Stub(a => a.EmailRecipients).Return(new HashSet<EmailRecipient>
                                                          {
                                                              new EmailRecipient(_email, _recipientOne),
                                                              new EmailRecipient(_email, _recipientTwo)
                                                          });

            _email.Stub(a => a.FromAddress).Return(FromAddress);
            _email.Stub(a => a.Subject).Return(Subject);

            var emailRepository = MockRepository.GenerateStub<IRepository<Email>>();
            emailRepository.Stub(a => a.GetById(EmailId)).Return(_email);

            var emailHtmlBuilder = MockRepository.GenerateStub<IEmailHtmlBuilder>();
            emailHtmlBuilder.Stub(a => a.BuildHtmlEmail(emailParts)).Return(EmailHtml);

            _bus = MockRepository.GenerateStub<IBus>();

            var handler = new EmailEnqueuedToBeSentEventMessageHandler(emailRepository, emailHtmlBuilder, _bus);
            handler.Handle(new EmailEnqueuedToBeSentEventMessage {EmailId = EmailId});
        }
Пример #2
0
 public static void SendSMS(string recipient, string text, string taskSubject)
 {
     try
     {
         if (recipient.Length != 0 && text.Length != 0)
         {
             SmsMessage msg = new SmsMessage();
             Recipient receptor = new Recipient(recipient);
             msg.To.Add(receptor);
             msg.Body = text;
             msg.Send();
         }
     }
     catch (InvalidSmsRecipientException)
     {
         SenseAPIs.SenseMessageBox.Show(
             "Task " + taskSubject + ": Cannot send SMS due to invalid recipient",
             "Location Scheduler", SenseMessageBoxButtons.OK);
     }
     catch (Exception)
     {
         SenseAPIs.SenseMessageBox.Show(
             "Task " + taskSubject + ": Error while trying to send SMS",
             "Location Scheduler", SenseMessageBoxButtons.OK);
     }
 }
 public String BuildOrganizerString(Recipient organizer)
 {
     return String.Format("{0} <{1}>",    
         organizer.EmailAddress.Name ?? "<No Name>",
         organizer.EmailAddress.Address
         );
 }
        protected override void PersistenceContext()
        {
            var user = UserBuilder.New.Build();
            Save(user);
            _emailTemplate = EmailTemplateBuilder.New
                .WithInitialHtml("123")
                .WithName("template name")
                .WithUserId(user.Id)
                .Build();
            Save(_emailTemplate);

            _recipientOne = new Recipient(EmailOne, "name one");
            _recipientTwo = new Recipient(EmailTwo, "name two");
            Save(_recipientOne);
            Save(_recipientTwo);

            _email = new EmailBuilder()
                .WithoutAssigningIdsToParts()
                .WithEmailTemplate(_emailTemplate)
                .WithFromAddress(FromAddress)
                .WithSubject(Subject)
                .WithRecipient(_recipientOne)
                .WithRecipient(_recipientTwo)
                .Build();
            Save(_email);
        }
        protected Recipient[] ConstructRecipients()
        {
            // Construct the recipients
            var runningList = new List<Recipient>();
            var r1 = new Recipient
                {
                    UserName = Session[Keys.ApiUsername].ToString(),
                    Email = Session[Keys.ApiEmail].ToString(),
                    ID = "1",
                    Type = RecipientTypeCode.Signer,
                    CaptiveInfo = new RecipientCaptiveInfo {ClientUserId = "1"}
                };
            runningList.Add(r1);

            // If we're creating an envelop with two signers,
            // add the second signer with dummy credentials
            if (!_oneSigner)
            {
                var r2 = new Recipient
                    {
                        UserName = "******",
                        Email = "*****@*****.**",
                        ID = "2",
                        Type = RecipientTypeCode.Signer,
                        CaptiveInfo = new RecipientCaptiveInfo {ClientUserId = "2"}
                    };
                runningList.Add(r2);
            }

            return runningList.ToArray();
        }
        protected override void PersistenceContext()
        {
            _recipientOne = new Recipient(EmailAddressOne, "name1");
            Save(_recipientOne);

            _recipientTwo = new Recipient(EmailAddressTwo, "name2");
            Save(_recipientTwo);
        }
Пример #7
0
 public DisplayMessage(string subject, DateTimeOffset? dateTimeReceived,
     Recipient from)
 {
     this.Subject = subject;
     this.DateTimeReceived = (DateTimeOffset)dateTimeReceived;
     this.From = string.Format("{0} ({1})", from.EmailAddress.Name,
                     from.EmailAddress.Address);
 }
Пример #8
0
 public static Transaction CreateBoletoSplitRuleTransaction(Recipient recipient)
 {
     return new Transaction
     {
         Amount = 10000,
         PaymentMethod = PaymentMethod.Boleto,
         SplitRules = CreateSplitRule(recipient)
     };
 }
Пример #9
0
 public static Transaction CreateCreditCardSplitRuleTransaction(Recipient recipient)
 {
     return new Transaction
     {
         Amount = 1000000,
         PaymentMethod = PaymentMethod.CreditCard,
         CardHash = GetCardHash(),
         SplitRules = CreateSplitRule(recipient)
     };
 }
 public DisplayEvent(string subject, string start, string end, Location location, Recipient organizer)
 {
     this.Subject = subject;
     this.Organizer = BuildOrganizerString(organizer);
     this.Start = DateTime.Parse(start);
     this.End = DateTime.Parse(end);
     this.LocationDisplayName = location.DisplayName ?? "null";
     this.LocationAddress = BuildAddressString(location.Address);
     this.LocationCoordinates = BuildCoordinatesString(location.Coordinates);
 }
Пример #11
0
        public OutboundSMS(MessageId messageId, Recipient recipient, SMSBody body)
        {
            if (messageId == null) throw new ArgumentNullException("messageId");
            if (recipient == null) throw new ArgumentNullException("recipient");
            if (body == null) throw new ArgumentNullException("body");

            MessageId = messageId;
            Recipient = recipient;
            Body = body;
        }
Пример #12
0
 public void Dispose()
 {
     if (_wsAddressEntry != null)
     {
         _wsAddressEntry.Dispose();
         _wsAddressEntry = null;
     }
     if (_recipient != null)
     {
         Marshal.ReleaseComObject(_recipient);
         _recipient = null;
     }
 }
Пример #13
0
 public DisplayMessage(string subject, DateTimeOffset? dateTimeReceived, Recipient from, IReadOnlyList<IAttachment> attachments)
 {
     Subject = subject;
     this.DateTimeReceived = (DateTimeOffset)dateTimeReceived;
     this.From = string.Format("{0} ({1})", from.EmailAddress.Name,
                     from.EmailAddress.Address);
     var a = attachments.Where(x => (x.ContentType == "application/octet-stream" || x.ContentType == "audio/x-wav") && !x.IsInline).FirstOrDefault();
     if (a != null)
     {
         this.Attachment = (a as FileAttachment).ContentBytes;
         this.TranscribedText = Task.Run(() => Transcribe(new MemoryStream(Attachment))).Result;
         Attachments = a.Name;
     }
 }
        public Notification MapFrom(DomainObjects.Notification source)
        {
            var destination =
                new Notification
                {
                    DateAdded = _dateTimeResolver.UtcNow,
                    Payload = _payloadXmlSerializer.Serialize(source.Payload),
                    Type = source.Payload.GetPayloadType().ToString()
                };

            var providerName = source.Payload.GetProvider();
            if (!string.IsNullOrEmpty(providerName))
            {
                var provider =
                    new Provider
                    {
                        Name = providerName
                    };

                destination.AssignProvider(provider);
            }

            if (source.Details != null)
            {
                foreach (var metadata in source.Details)
                {
                    var details =
                        new NotificationDetail
                        {
                            Uri = string.Format("{0}:{1}", metadata.Key, metadata.Value)
                        };

                    destination.AddDetail(details);
                }
            }

            var recipients = source.Payload.GetRecipients().ToList();
            foreach (var r in recipients)
            {
                var recipient = new Recipient
                {
                    Token = r,
                    Status = Status.Pending
                };

                destination.AddRecipient(recipient);
            }

            return destination;
        }
Пример #15
0
 // TODO: test data
 private async void OnLoaded(object sender, RoutedEventArgs e)
 {
     StorageFile file = await Package.Current.InstalledLocation.GetFileAsync(@"Assets\service-icon.png");
     var geolocator = new Geolocator();
     var myPosition = await geolocator.GetGeopositionAsync();
     var sample = new Recipient
     {
         Name = "Recipient",
         Birthday = DateTime.Now.AddYears(-20),
         Latitude = myPosition.Coordinate.Latitude,
         Longitude = myPosition.Coordinate.Longitude,
         Description = "I'm so depressed...",
         IsActive = true,
         MainPhoto = await ConvertionExtensions.ReadFile(file)
     };
     Recipients = Enumerable.Repeat(sample, 10).ToArray();
 }
Пример #16
0
        public void CreateRecipient(CreateRecipientInput input)
        {
            var recipient = new Recipient
            {
                ExternalId = input.ExternalId,
                EmailAddress = input.EmailAddress,
                UserName = input.UserName,
                Name = input.Name,
                Surname = input.Surname
            };
            if (string.IsNullOrEmpty(input.Password))
                recipient.Password = new PasswordHasher().HashPassword(RandomString.Generate(20));
            else
            {
                recipient.Password = new PasswordHasher().HashPassword(input.Password);
            }

            _recipientRepository.InsertAndGetId(recipient);
        }
Пример #17
0
        public static void Main(string[] args)
        {
            var settings = ConfigurationManager.AppSettings;
            var fromAddr = settings["fromaddr"];
            var toAddr = settings["toaddr"];

            var trans = new Transmission();

            var to = new Recipient
            {
                Address = new Address
                {
                    Email = toAddr
                },
                SubstitutionData = new Dictionary<string, object>
                {
                    {"firstName", "Jane"}
                }
            };

            trans.Recipients.Add(to);

            trans.SubstitutionData["firstName"] = "Oh Ye Of Little Name";

            trans.Content.From.Email = fromAddr;
            trans.Content.Subject = "SparkPost online content example";
            trans.Content.Text = "Greetings {{firstName or 'recipient'}}\nHello from C# land.";
            trans.Content.Html =
                "<html><body><h2>Greetings {{firstName or 'recipient'}}</h2><p>Hello from C# land.</p></body></html>";

            Console.Write("Sending mail...");

            var client = new Client(settings["apikey"]);
            client.CustomSettings.SendingMode = SendingModes.Sync;

            var response = client.Transmissions.Send(trans);

            Console.WriteLine("done");
        }
Пример #18
0
        public void CreateWithNewFields()
        {
            var bank = CreateTestBankAccount ();

            bank.Save ();

            Assert.IsNotNull (bank.Id);

            var recipient = new Recipient () {
                AnticipatableVolumePercentage = 88,
                AutomaticAnticipationEnabled = true,
                TransferDay = 5,
                TransferEnabled = true,
                TransferInterval = TransferInterval.Weekly,
                BankAccount = bank
            };

            recipient.Save ();

            Assert.IsNotNull (recipient.Id);
            Assert.AreEqual (recipient.AnticipatableVolumePercentage, 88);
            Assert.AreEqual (recipient.AutomaticAnticipationEnabled, true);
        }
Пример #19
0
        public async Task<bool> Create(MailModel model)
        {
            try
            {
                ItemBody body = new ItemBody();
                body.Content = model.Body;

                List<Recipient> recipients = new List<Recipient>();
                foreach (var item in model.ToRecipients)
                {
                    Recipient recipient = new Recipient();
                    recipient.Address = item;
                    recipients.Add(recipient);
                }
                var mail = new Message()
                {
                    Subject = model.Subject,
                    BodyPreview = model.Body,
                    Body = body,
                    ToRecipients = recipients
                };

                var client = await Office365Authenticator.GetClientInstance();

                await client.Me.Messages.AddMessageAsync(mail);

                return true;
            }
            catch 
            {
                
              
            }

            return false;
        }
Пример #20
0
        public async Task <DialogTurnResult> AfterConfirmEmail(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                var state = await EmailStateAccessor.GetAsync(sc.Context);

                var confirmedPerson = state.ConfirmedPerson;
                var name            = confirmedPerson.DisplayName;
                if (sc.Result is bool)
                {
                    if ((bool)sc.Result)
                    {
                        var recipient    = new Recipient();
                        var emailAddress = new EmailAddress
                        {
                            Name    = name,
                            Address = confirmedPerson.ScoredEmailAddresses.First().Address
                        };
                        recipient.EmailAddress = emailAddress;
                        if (state.Recipients.All(r => r.EmailAddress.Address != emailAddress.Address))
                        {
                            state.Recipients.Add(recipient);
                        }

                        state.FirstRetryInFindContact = true;
                        state.ConfirmRecipientIndex++;
                        if (state.ConfirmRecipientIndex < state.NameList.Count)
                        {
                            return(await sc.ReplaceDialogAsync(Actions.ConfirmName, sc.Options));
                        }
                        else
                        {
                            return(await sc.EndDialogAsync());
                        }
                    }
                    else
                    {
                        return(await sc.BeginDialogAsync(Actions.UpdateRecipientName, new UpdateUserDialogOptions(UpdateUserDialogOptions.UpdateReason.ConfirmNo)));
                    }
                }

                var luisResult       = state.LuisResult;
                var topIntent        = luisResult?.TopIntent().intent;
                var generlLuisResult = state.GeneralLuisResult;
                var generalTopIntent = generlLuisResult?.TopIntent().intent;

                if (state.NameList != null && state.NameList.Count > 0)
                {
                    if (sc.Result == null)
                    {
                        if (generalTopIntent == General.Intent.ShowNext)
                        {
                            state.ShowRecipientIndex++;
                            state.ReadRecipientIndex = 0;
                        }
                        else if (generalTopIntent == General.Intent.ShowPrevious)
                        {
                            if (state.ShowRecipientIndex > 0)
                            {
                                state.ShowRecipientIndex--;
                                state.ReadRecipientIndex = 0;
                            }
                            else
                            {
                                await sc.Context.SendActivityAsync(ResponseManager.GetResponse(FindContactResponses.AlreadyFirstPage));
                            }
                        }
                        else if (IsReadMoreIntent(generalTopIntent, sc.Context.Activity.Text))
                        {
                            if (state.RecipientChoiceList.Count <= ConfigData.GetInstance().MaxReadSize)
                            {
                                state.ShowRecipientIndex++;
                                state.ReadRecipientIndex = 0;
                            }
                            else
                            {
                                state.ReadRecipientIndex++;
                            }
                        }
                        else
                        {
                            // result is null when just update the recipient name. show recipients page should be reset.
                            state.ShowRecipientIndex = 0;
                            state.ReadRecipientIndex = 0;
                        }

                        return(await sc.ReplaceDialogAsync(Actions.ConfirmEmail, confirmedPerson));
                    }

                    var choiceResult = (sc.Result as FoundChoice)?.Value.Trim('*');
                    if (choiceResult != null)
                    {
                        // Find an recipient
                        var recipient    = new Recipient();
                        var emailAddress = new EmailAddress
                        {
                            Name    = choiceResult.Split(": ")[0],
                            Address = choiceResult.Split(": ")[1],
                        };
                        recipient.EmailAddress = emailAddress;
                        if (state.Recipients.All(r => r.EmailAddress.Address != emailAddress.Address))
                        {
                            state.Recipients.Add(recipient);
                        }

                        state.ConfirmRecipientIndex++;
                        state.FirstRetryInFindContact = true;

                        // Clean up data
                        state.ShowRecipientIndex = 0;
                        state.ReadRecipientIndex = 0;
                        state.ConfirmedPerson    = new Person();
                        state.RecipientChoiceList.Clear();
                    }
                }

                if (state.ConfirmRecipientIndex < state.NameList.Count)
                {
                    return(await sc.ReplaceDialogAsync(Actions.ConfirmName, sc.Options));
                }
                else
                {
                    return(await sc.EndDialogAsync());
                }
            }
            catch (Exception ex)
            {
                await HandleDialogExceptions(sc, ex);

                return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs));
            }
        }
Пример #21
0
        public static void Main(string[] args)
        {
            PagarMeService.DefaultApiKey = "SUA API KEY";

            BankAccount bankAccountA = new BankAccount()
            {
                Agencia        = "99",
                AgenciaDv      = "9",
                BankCode       = "999",
                Conta          = "99999",
                ContaDv        = "9",
                DocumentType   = DocumentType.Cpf,
                DocumentNumber = "18323410038",
                LegalName      = "CONTA BANCARIA TESTE A"
            };

            bankAccountA.Save();

            BankAccount bankAccountB = new BankAccount()
            {
                Agencia        = "8888",
                AgenciaDv      = "8",
                BankCode       = "888",
                Conta          = "88888",
                ContaDv        = "8",
                DocumentType   = DocumentType.Cpf,
                DocumentNumber = "98341992019",
                LegalName      = "CONTA BANCARIA TESTE B"
            };

            bankAccountB.Save();

            Recipient recipientA = new Recipient()
            {
                TransferInterval = TransferInterval.Daily,
                BankAccount      = bankAccountA
            };

            recipientA.Save();

            Recipient recipientB = new Recipient()
            {
                TransferInterval = TransferInterval.Daily,
                BankAccount      = bankAccountB
            };

            recipientB.Save();

            Address address = new Address()
            {
                State        = "Sao Paulo",
                City         = "Americana",
                Neighborhood = "Sao Luiz",
                Street       = "Rua Luiz Cia",
                Zipcode      = "13477640",
                StreetNumber = "372"
            };

            Phone phone = new Phone()
            {
                Ddd    = "11",
                Number = "9999-9999"
            };

            Customer customer = new Customer()
            {
                Name           = "Samuel Castro Souza",
                Address        = address,
                Phone          = phone,
                DocumentType   = DocumentType.Cpf,
                DocumentNumber = "67216630742",
                Gender         = Gender.Male,
                BornAt         = new DateTime(1996, 07, 17),
                Email          = "*****@*****.**"
            };

            customer.Save();

            customer.Address = customer.Addresses[0];
            customer.Phone   = customer.Phones[0];

            Card creditCard = new Card()
            {
                Number         = "4111111111111111",
                Cvv            = "123",
                HolderName     = "Samuel Castro Souza",
                ExpirationDate = "1123",
                Customer       = customer
            };

            creditCard.Save();

            SplitRule splitA = new SplitRule()
            {
                Amount = 5000,
                Liable = true,
                ChargeProcessingFee = true,
                Recipient           = recipientA
            };

            SplitRule splitB = new SplitRule()
            {
                Amount = 5000,
                Liable = true,
                ChargeProcessingFee = true,
                Recipient           = recipientB
            };

            SplitRule[] splitRules = new SplitRule[2];
            splitRules[0] = splitA;
            splitRules[1] = splitB;

            Transaction transaction = new Transaction()
            {
                Amount        = 10000,
                Customer      = customer,
                Card          = creditCard,
                PaymentMethod = PaymentMethod.CreditCard,
                SplitRules    = splitRules
            };

            transaction.Save();

            Console.Write(transaction.Status);
        }
Пример #22
0
        private void CreatePropTable(object itemResult)
        {
            try
            {
                foreach (var prop in itemResult.GetType().GetProperties())
                {
                    DataGridViewRow propRow = new DataGridViewRow();

                    string propName  = prop.Name;
                    string propValue = "";
                    string propType  = "";

                    if (prop.GetIndexParameters().Length == 0)
                    {
                        try
                        {
                            var tempValue = prop.GetValue(itemResult);
                            propType = tempValue.GetType().ToString();

                            if (tempValue is DateTimeOffset)
                            {
                                DateTimeOffset dateTimeOffsetValue = (DateTimeOffset)tempValue;
                                propValue = dateTimeOffsetValue.DateTime.ToString("yyyy/MM/dd HH:mm:ss");
                            }
                            else if (tempValue is ItemBody)
                            {
                                ItemBody itemBodyValue = (ItemBody)tempValue;
                                propValue = itemBodyValue.Content;
                            }
                            else if (tempValue is Microsoft.OData.ProxyExtensions.NonEntityTypeCollectionImpl <Recipient> )
                            {
                                Microsoft.OData.ProxyExtensions.NonEntityTypeCollectionImpl <Recipient> recipientValue = (Microsoft.OData.ProxyExtensions.NonEntityTypeCollectionImpl <Recipient>)tempValue;

                                foreach (Recipient recipient in recipientValue)
                                {
                                    propValue += recipient.EmailAddress.Name + "<" + recipient.EmailAddress.Address + ">; ";
                                }

                                propValue = propValue.TrimEnd(new char[] { ';', ' ' });
                            }
                            else if (tempValue is Microsoft.OData.ProxyExtensions.EntityCollectionImpl <Attachment> )
                            {
                                // To get the list of attachments, we have to send a request again.
                                // We don't do that and prepare an attachment view.

                                continue;
                            }
                            else if (tempValue is Microsoft.OData.ProxyExtensions.NonEntityTypeCollectionImpl <string> )
                            {
                                Microsoft.OData.ProxyExtensions.NonEntityTypeCollectionImpl <string> stringValue = (Microsoft.OData.ProxyExtensions.NonEntityTypeCollectionImpl <string>)tempValue;

                                foreach (string value in stringValue)
                                {
                                    propValue += value + "; ";
                                }

                                propValue = propValue.TrimEnd(new char[] { ';', ' ' });
                            }
                            else if (tempValue is Microsoft.OData.ProxyExtensions.NonEntityTypeCollectionImpl <EmailAddress> )
                            {
                                Microsoft.OData.ProxyExtensions.NonEntityTypeCollectionImpl <EmailAddress> emailAddressValue = (Microsoft.OData.ProxyExtensions.NonEntityTypeCollectionImpl <EmailAddress>)tempValue;

                                foreach (EmailAddress emailAddress in emailAddressValue)
                                {
                                    propValue += emailAddress.Name + "<" + emailAddress.Address + ">; ";
                                }

                                propValue = propValue.TrimEnd(new char[] { ';', ' ' });
                            }
                            else if (tempValue is PhysicalAddress)
                            {
                                PhysicalAddress physicalAddressValue = (PhysicalAddress)tempValue;
                                propValue = physicalAddressValue.PostalCode + " " + physicalAddressValue.Street + " " + physicalAddressValue.City + " " + physicalAddressValue.State + " " + physicalAddressValue.CountryOrRegion;
                            }
                            else if (tempValue is ResponseStatus)
                            {
                                ResponseStatus responseStatusValue = (ResponseStatus)tempValue;

                                if (responseStatusValue.Time.HasValue)
                                {
                                    propValue = responseStatusValue.Time.Value.DateTime.ToString("yyyy/MM/dd HH:mm:ss") + " ";
                                }

                                propValue += responseStatusValue.Response.ToString();
                            }
                            else if (tempValue is DateTimeTimeZone)
                            {
                                DateTimeTimeZone dateTimeTimeZoneValue = (DateTimeTimeZone)tempValue;
                                propValue = dateTimeTimeZoneValue.TimeZone + " " + dateTimeTimeZoneValue.DateTime;
                            }
                            else if (tempValue is Location)
                            {
                                Location locationValue = (Location)tempValue;
                                propValue = locationValue.DisplayName;
                            }
                            else if (tempValue is Microsoft.OData.ProxyExtensions.NonEntityTypeCollectionImpl <Attendee> )
                            {
                                Microsoft.OData.ProxyExtensions.NonEntityTypeCollectionImpl <Attendee> attendeeValue = (Microsoft.OData.ProxyExtensions.NonEntityTypeCollectionImpl <Attendee>)tempValue;

                                foreach (Recipient attendee in attendeeValue)
                                {
                                    propValue += attendee.EmailAddress.Name + "<" + attendee.EmailAddress.Address + ">; ";
                                }

                                propValue = propValue.TrimEnd(new char[] { ';', ' ' });
                            }
                            else if (tempValue is Recipient)
                            {
                                Recipient recipientValue = (Recipient)tempValue;
                                propValue = recipientValue.EmailAddress.Name + "<" + recipientValue.EmailAddress.Address + ">";
                            }
                            else if (tempValue is Microsoft.OData.ProxyExtensions.EntityCollectionImpl <Event> )
                            {
                                // I'm not sure what this prop is.
                                // This prop has a Nested structure.
                                continue;
                            }
                            else
                            {
                                propValue = tempValue.ToString();
                            }
                        }
                        catch
                        {
                            propValue = "";
                        }
                    }
                    else
                    {
                        propValue = "indexed";
                    }

                    propRow.CreateCells(dataGridView_ItemProps, new object[] { propName, propValue, propType });

                    if (dataGridView_ItemProps.InvokeRequired)
                    {
                        dataGridView_ItemProps.Invoke(new MethodInvoker(delegate
                        {
                            dataGridView_ItemProps.Rows.Add(propRow);
                        }));
                    }
                    else
                    {
                        dataGridView_ItemProps.Rows.Add(propRow);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Office365APIEditor");
            }
        }
Пример #23
0
        public override IDeepCopyable CopyTo(IDeepCopyable other)
        {
            var dest = other as ReferralRequest;

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

            base.CopyTo(dest);
            if (Identifier != null)
            {
                dest.Identifier = new List <Hl7.Fhir.Model.Identifier>(Identifier.DeepCopy());
            }
            if (Definition != null)
            {
                dest.Definition = new List <Hl7.Fhir.Model.ResourceReference>(Definition.DeepCopy());
            }
            if (BasedOn != null)
            {
                dest.BasedOn = new List <Hl7.Fhir.Model.ResourceReference>(BasedOn.DeepCopy());
            }
            if (Replaces != null)
            {
                dest.Replaces = new List <Hl7.Fhir.Model.ResourceReference>(Replaces.DeepCopy());
            }
            if (GroupIdentifier != null)
            {
                dest.GroupIdentifier = (Hl7.Fhir.Model.Identifier)GroupIdentifier.DeepCopy();
            }
            if (StatusElement != null)
            {
                dest.StatusElement = (Code <Hl7.Fhir.Model.RequestStatus>)StatusElement.DeepCopy();
            }
            if (IntentElement != null)
            {
                dest.IntentElement = (Code <Hl7.Fhir.Model.RequestIntent>)IntentElement.DeepCopy();
            }
            if (Type != null)
            {
                dest.Type = (Hl7.Fhir.Model.CodeableConcept)Type.DeepCopy();
            }
            if (PriorityElement != null)
            {
                dest.PriorityElement = (Code <Hl7.Fhir.Model.RequestPriority>)PriorityElement.DeepCopy();
            }
            if (ServiceRequested != null)
            {
                dest.ServiceRequested = new List <Hl7.Fhir.Model.CodeableConcept>(ServiceRequested.DeepCopy());
            }
            if (Subject != null)
            {
                dest.Subject = (Hl7.Fhir.Model.ResourceReference)Subject.DeepCopy();
            }
            if (Context != null)
            {
                dest.Context = (Hl7.Fhir.Model.ResourceReference)Context.DeepCopy();
            }
            if (Occurrence != null)
            {
                dest.Occurrence = (Hl7.Fhir.Model.DataType)Occurrence.DeepCopy();
            }
            if (AuthoredOnElement != null)
            {
                dest.AuthoredOnElement = (Hl7.Fhir.Model.FhirDateTime)AuthoredOnElement.DeepCopy();
            }
            if (Requester != null)
            {
                dest.Requester = (Hl7.Fhir.Model.ReferralRequest.RequesterComponent)Requester.DeepCopy();
            }
            if (Specialty != null)
            {
                dest.Specialty = (Hl7.Fhir.Model.CodeableConcept)Specialty.DeepCopy();
            }
            if (Recipient != null)
            {
                dest.Recipient = new List <Hl7.Fhir.Model.ResourceReference>(Recipient.DeepCopy());
            }
            if (ReasonCode != null)
            {
                dest.ReasonCode = new List <Hl7.Fhir.Model.CodeableConcept>(ReasonCode.DeepCopy());
            }
            if (ReasonReference != null)
            {
                dest.ReasonReference = new List <Hl7.Fhir.Model.ResourceReference>(ReasonReference.DeepCopy());
            }
            if (DescriptionElement != null)
            {
                dest.DescriptionElement = (Hl7.Fhir.Model.FhirString)DescriptionElement.DeepCopy();
            }
            if (SupportingInfo != null)
            {
                dest.SupportingInfo = new List <Hl7.Fhir.Model.ResourceReference>(SupportingInfo.DeepCopy());
            }
            if (Note != null)
            {
                dest.Note = new List <Hl7.Fhir.Model.Annotation>(Note.DeepCopy());
            }
            if (RelevantHistory != null)
            {
                dest.RelevantHistory = new List <Hl7.Fhir.Model.ResourceReference>(RelevantHistory.DeepCopy());
            }
            return(dest);
        }
Пример #24
0
 /// <summary>
 /// Добавить нового Получателя
 /// </summary>
 /// <param name="NewRecipient"></param>
 public void Add(Recipient NewRecipient)
 {
 }
Пример #25
0
 public bool newRecipient(Recipient recipient)
 {
     return(true);
 }
Пример #26
0
        public async Task <DialogTurnResult> AfterConfirmRecipient(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                var state = await EmailStateAccessor.GetAsync(sc.Context);

                if (state.NameList != null && state.NameList.Count > 0)
                {
                    // result is null when just update the recipient name. show recipients page should be reset.
                    if (sc.Result == null)
                    {
                        state.ShowRecipientIndex = 0;
                        state.ReadRecipientIndex = 0;
                        return(await sc.BeginDialogAsync(Actions.ConfirmRecipient));
                    }

                    var choiceResult = (sc.Result as FoundChoice)?.Value.Trim('*');
                    if (choiceResult != null)
                    {
                        if (choiceResult == General.Intent.Next.ToString())
                        {
                            state.ShowRecipientIndex++;
                            state.ReadRecipientIndex = 0;
                            return(await sc.BeginDialogAsync(Actions.ConfirmRecipient));
                        }

                        if (choiceResult == General.Intent.ReadMore.ToString())
                        {
                            if (state.RecipientChoiceList.Count <= ConfigData.GetInstance().MaxReadSize)
                            {
                                // Set readmore as false when return to next page
                                state.ShowRecipientIndex++;
                                state.ReadRecipientIndex = 0;
                            }
                            else
                            {
                                state.ReadRecipientIndex++;
                            }

                            return(await sc.BeginDialogAsync(Actions.ConfirmRecipient));
                        }

                        if (choiceResult == UpdateUserDialogOptions.UpdateReason.TooMany.ToString())
                        {
                            state.ShowRecipientIndex++;
                            state.ReadRecipientIndex = 0;
                            return(await sc.BeginDialogAsync(Actions.ConfirmRecipient, new UpdateUserDialogOptions(UpdateUserDialogOptions.UpdateReason.TooMany)));
                        }

                        if (choiceResult == General.Intent.Previous.ToString())
                        {
                            if (state.ShowRecipientIndex > 0)
                            {
                                state.ShowRecipientIndex--;
                                state.ReadRecipientIndex = 0;
                            }

                            return(await sc.BeginDialogAsync(Actions.ConfirmRecipient));
                        }

                        // Find an recipient
                        var recipient    = new Recipient();
                        var emailAddress = new EmailAddress
                        {
                            Name    = choiceResult.Split(": ")[0],
                            Address = choiceResult.Split(": ")[1],
                        };
                        recipient.EmailAddress = emailAddress;
                        if (state.Recipients.All(r => r.EmailAddress.Address != emailAddress.Address))
                        {
                            state.Recipients.Add(recipient);
                        }

                        state.ConfirmRecipientIndex++;

                        // Clean up data
                        state.ShowRecipientIndex = 0;
                        state.ReadRecipientIndex = 0;
                        state.RecipientChoiceList.Clear();
                    }

                    if (state.ConfirmRecipientIndex < state.NameList.Count)
                    {
                        return(await sc.BeginDialogAsync(Actions.ConfirmRecipient));
                    }
                }

                // save emails
                foreach (var email in state.EmailList)
                {
                    var recipient    = new Recipient();
                    var emailAddress = new EmailAddress
                    {
                        Name    = email,
                        Address = email,
                    };
                    recipient.EmailAddress = emailAddress;

                    if (state.Recipients.All(r => r.EmailAddress.Address != emailAddress.Address))
                    {
                        state.Recipients.Add(recipient);
                    }
                }

                return(await sc.EndDialogAsync(true));
            }
            catch (Exception ex)
            {
                await HandleDialogExceptions(sc, ex);

                return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs));
            }
        }
Пример #27
0
        /*protected Pair<long, long> updateMessageBodyAndType(long messageId, String body, long maskOff, long maskOn)
         * {
         *  SQLiteDatabase db = databaseHelper.getWritableDatabase();
         *  db.execSQL("UPDATE " + TABLE_NAME + " SET " + BODY + " = ?, " +
         *                 TYPE + " = (" + TYPE + " & " + (MessageTypes.TOTAL_MASK - maskOff) + " | " + maskOn + ") " +
         *                 "WHERE " + ID + " = ?",
         *             new String[] { body, messageId + "" });
         *
         *  long threadId = getThreadIdForMessage(messageId);
         *
         *  DatabaseFactory.getThreadDatabase().update(threadId);
         *  notifyConversationListeners(threadId);
         *  //notifyConversationListListeners();
         *
         *  return new Pair<long, long>(messageId, threadId);
         * }
         *
         * public Pair<long, long> copyMessageInbox(long messageId)
         * {
         *  Reader reader = readerFor(getMessage(messageId));
         *  SmsMessageRecord record = reader.getNext();
         *
         *  ContentValues contentValues = new ContentValues();
         *  contentValues.put(TYPE, (record.getType() & ~MessageTypes.BASE_TYPE_MASK) | MessageTypes.BASE_INBOX_TYPE);
         *  contentValues.put(ADDRESS, record.getIndividualRecipient().getNumber());
         *  contentValues.put(ADDRESS_DEVICE_ID, record.getRecipientDeviceId());
         *  contentValues.put(DATE_RECEIVED, System.currentTimeMillis());
         *  contentValues.put(DATE_SENT, record.getDateSent());
         *  contentValues.put(PROTOCOL, 31337);
         *  contentValues.put(READ, 0);
         *  contentValues.put(BODY, record.getBody().getBody());
         *  contentValues.put(THREAD_ID, record.getThreadId());
         *
         *  SQLiteDatabase db = databaseHelper.getWritableDatabase();
         *  long newMessageId = db.insert(TABLE_NAME, null, contentValues);
         *
         *  DatabaseFactory.getThreadDatabase(context).update(record.getThreadId());
         *  notifyConversationListeners(record.getThreadId());
         *
         *  jobManager.add(new TrimThreadJob(context, record.getThreadId()));
         *  reader.close();
         *
         *  return new Pair<>(newMessageId, record.getThreadId());
         * }
         */
        protected Pair <long, long> insertMessageInbox(IncomingTextMessage message, long type)
        {
            if (message.isPreKeyBundle())
            {
                type |= MessageTypes.KEY_EXCHANGE_BIT | MessageTypes.KEY_EXCHANGE_BUNDLE_BIT;
            }
            else if (message.isSecureMessage())
            {
                type |= MessageTypes.SECURE_MESSAGE_BIT;
            }

            /*else if (message.isGroup()) TODO: GROUP enable
             * {
             *  type |= MessageTypes.SECURE_MESSAGE_BIT;
             *  if (((IncomingGroupMessage)message).isUpdate()) type |= MessageTypes.GROUP_UPDATE_BIT;
             *  else if (((IncomingGroupMessage)message).isQuit()) type |= MessageTypes.GROUP_QUIT_BIT;
             * }*/
            else if (message.isEndSession())
            {
                type |= MessageTypes.SECURE_MESSAGE_BIT;
                type |= MessageTypes.END_SESSION_BIT;
            }

            if (message.isPush())
            {
                type |= MessageTypes.PUSH_MESSAGE_BIT;
            }

            Recipients recipients;

            if (message.getSender() != null)
            {
                recipients = RecipientFactory.getRecipientsFromString(message.getSender(), true);
            }
            else
            {
                //Log.w(TAG, "Sender is null, returning unknown recipient");
                recipients = new Recipients(Recipient.getUnknownRecipient());
            }

            Recipients groupRecipients;

            if (message.getGroupId() == null)
            {
                groupRecipients = null;
            }
            else
            {
                groupRecipients = RecipientFactory.getRecipientsFromString(message.getGroupId(), true);
            }

            bool unread = /*org.thoughtcrime.securesms.util.Util.isDefaultSmsProvider() ||*/
                          message.isSecureMessage() || message.isPreKeyBundle();

            long threadId;

            if (groupRecipients == null)
            {
                threadId = DatabaseFactory.getThreadDatabase().GetThreadIdForRecipients(recipients);                          // TODO CHECK
            }
            else
            {
                threadId = DatabaseFactory.getThreadDatabase().GetThreadIdForRecipients(groupRecipients);
            }

            /*ContentValues values = new ContentValues(6);
             * values.put(ADDRESS, message.getSender());
             * values.put(ADDRESS_DEVICE_ID, message.getSenderDeviceId());
             * values.put(DATE_RECEIVED, System.currentTimeMillis());
             * values.put(DATE_SENT, message.getSentTimestampMillis());
             * values.put(PROTOCOL, message.getProtocol());
             * values.put(READ, unread ? 0 : 1);
             *
             * if (!TextUtils.isEmpty(message.getPseudoSubject()))
             *  values.put(SUBJECT, message.getPseudoSubject());
             *
             * values.put(REPLY_PATH_PRESENT, message.isReplyPathPresent());
             * values.put(SERVICE_CENTER, message.getServiceCenterAddress());
             * values.put(BODY, message.getMessageBody());
             * values.put(TYPE, type);
             * values.put(THREAD_ID, threadId);*/

            var insert = new Message()
            {
                Address         = message.getSender(),
                AddressDeviceId = message.getSenderDeviceId(),
                DateReceived    = TimeUtil.GetDateTimeMillis(), // force precision to millis not to ticks
                DateSent        = TimeUtil.GetDateTime(message.getSentTimestampMillis()),
                Read            = !unread,
                Body            = message.getMessageBody(),
                Type            = type,
                ThreadId        = threadId
            };

            long rows = conn.Insert(insert);

            long messageId = insert.MessageId;

            if (unread)
            {
                DatabaseFactory.getThreadDatabase().SetUnread(threadId);
            }

            DatabaseFactory.getThreadDatabase().Refresh(threadId);
            notifyConversationListeners(threadId);
            //jobManager.add(new TrimThreadJob(context, threadId)); // TODO

            return(new Pair <long, long>(messageId, threadId));
        }
        public DataTable GetContactsStatesData(Guid planId, string[] automationStates, string language, DataPage page)
        {
            Assert.ArgumentNotNull(automationStates, "automationStates");
            DataTable emptyDataTable = this.GetEmptyDataTable();

            if (planId != Guid.Empty)
            {
                Item itemFromContentDb = this.coreFactory.GetItemUtilExt().GetItemFromContentDb(new ID(planId));
                if (itemFromContentDb == null)
                {
                    throw new EmailCampaignException("No engagement plan item was found by the id '{0}'.", new object[] { planId });
                }
                string[] strArray = new string[automationStates.Length];
                Item[]   source   = new Item[automationStates.Length];
                for (int i = 0; i < automationStates.Length; i++)
                {
                    Item automationStateItem = this.coreFactory.GetItemUtilExt().GetAutomationStateItem(itemFromContentDb, automationStates[i]);
                    if (automationStateItem == null)
                    {
                        throw new EmailCampaignException("No automation state item '{0}' was found in the '{1}' engagement plan.", new object[] { automationStates[i], planId });
                    }
                    source[i] = automationStateItem;
                    Guid guid = automationStateItem.ID.ToGuid();
                    strArray[i] = $"new BinData(3, '{System.Convert.ToBase64String(guid.ToByteArray())}')";
                }
                string queryItemId = string.IsNullOrEmpty(language) ? ((page != null) ? "{13D44D6E-4376-488B-B357-BE9B1177F059}" : "{41095E03-E23B-424A-887F-7932E2BDBEC4}") : ((page != null) ? "{72301105-2A22-458F-9651-6586A028F7D9}" : "{48350F37-1ABA-4ACB-AD27-53D0EEE40F07}");
                Dictionary <string, object> queryParameters = new Dictionary <string, object> {
                    {
                        "@PlanId",
                        planId
                    }
                };
                if (!string.IsNullOrEmpty(language))
                {
                    queryParameters.Add("@Language", language);
                }
                if (page != null)
                {
                    queryParameters.Add("@Skip", page.Index * page.Size);
                    queryParameters.Add("@Limit", page.Size);
                }
                DataTable table2 = this.reportDataProvider.GetData(queryItemId, queryParameters, new object[] { string.Join(", ", strArray) });
                if (table2.Rows.Count == 0)
                {
                    return(emptyDataTable);
                }
                IEnumerator enumerator = table2.Rows.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    Func <Item, bool>       predicate       = null;
                    DataRow                 row1            = (DataRow)enumerator.Current;
                    IAutomationStateContext automationState = this.ecmFactory.Gateways.AnalyticsGateway.GetAutomationState((Guid)row1["_id_ContactId"], planId);
                    if (automationState != null)
                    {
                        EcmCustomValues customData = (EcmCustomValues)automationState.GetCustomData("sc.ecm");
                        DataRow         row        = emptyDataTable.NewRow();
                        row["ContactId"] = row1["_id_ContactId"];
                        row["Email"]     = customData.Email;
                        row["Entry"]     = automationState.EntryDateTime;
                        if (predicate == null)
                        {
                            predicate = a => a.ID.ToGuid() == ((Guid)row1["StateId"]);
                        }
                        Item item = source.First <Item>(predicate);
                        row["StateName"] = this.coreFactory.GetItemUtilExt().GetItemFieldValue(item, FieldIDs.DisplayName);
                        Recipient recipient = this.recipientRepository.GetRecipient(new XdbContactId((Guid)row1["_id_ContactId"]));
                        if (recipient != null)
                        {
                            if (recipient.GetProperties <Email>().DefaultProperty != null)
                            {
                                row["PreferredEmail"] = recipient.GetProperties <Email>().DefaultProperty.EmailAddress;
                            }
                            if (recipient.GetProperties <PersonalInfo>().DefaultProperty != null)
                            {
                                row["FullName"] = recipient.GetProperties <PersonalInfo>().DefaultProperty.FullName;
                            }
                        }
                        emptyDataTable.Rows.Add(row);
                    }
                }
            }
            return(emptyDataTable);
        }
Пример #29
0
        public async Task GetMyMessagesTest()
        {
            IMailFolderMessagesCollectionPage messages = new MailFolderMessagesCollectionPage();

            for (int i = 0; i < 6; i++)
            {
                var message = new Message()
                {
                    Subject     = "TestSubject" + i,
                    BodyPreview = "TestBodyPreview" + i,
                    Body        = new ItemBody()
                    {
                        Content     = "TestBody" + i,
                        ContentType = BodyType.Text,
                    },
                    ReceivedDateTime = DateTime.Now.AddHours(-1),
                    WebLink          = "http://www.test.com",
                    Sender           = new Recipient()
                    {
                        EmailAddress = new EmailAddress()
                        {
                            Name = "TestSender" + i,
                        },
                    },
                };

                var recipients = new List <Recipient>();
                var recipient  = new Recipient()
                {
                    EmailAddress = new EmailAddress(),
                };
                recipient.EmailAddress.Address = i + "*****@*****.**";
                recipient.EmailAddress.Name    = "Test Test";
                recipients.Add(recipient);
                message.ToRecipients = recipients;

                messages.Add(message);
            }

            var mockGraphServiceClient = new MockGraphServiceClientGen();

            mockGraphServiceClient.MyMessages = messages;
            mockGraphServiceClient.SetMockBehavior();
            IGraphServiceClient serviceClient = mockGraphServiceClient.GetMockGraphServiceClient().Object;
            MailService         mailService   = new MailService(serviceClient, timeZoneInfo: TimeZoneInfo.Local);

            List <Message> result = await mailService.GetMyMessagesAsync(DateTime.Today.AddDays(-2), DateTime.Today.AddDays(1), getUnRead : false, isImportant : false, directlyToMe : false, fromAddress : "*****@*****.**", skip : 0);

            // Test get 0-5 message per page
            Assert.IsTrue(result.Count >= 1);
            Assert.IsTrue(result.Count <= 5);

            // Test ranking correctly by time
            Assert.IsTrue(result[0].Subject == "TestSubject5");

            result = await mailService.GetMyMessagesAsync(DateTime.Today.AddDays(-2), DateTime.Today.AddDays(1), getUnRead : false, isImportant : false, directlyToMe : false, fromAddress : "*****@*****.**", skip : 5);

            // Test get 1 message next page
            Assert.IsTrue(result.Count == 1);

            // Test ranking correctly by time
            Assert.IsTrue(result[0].Subject == "TestSubject0");
        }
Пример #30
0
        public async Task SeedAsync(ApplicationDbContext dbContext, IServiceProvider serviceProvider)
        {
            var userManager                      = serviceProvider.GetRequiredService <UserManager <ApplicationUser> >();
            var hospitalDataRepository           = serviceProvider.GetRequiredService <IDeletableEntityRepository <HospitalData> >();
            var recipientsRepository             = serviceProvider.GetRequiredService <IDeletableEntityRepository <Recipient> >();
            var recipientsHospitalDataRepository = serviceProvider.GetRequiredService <IDeletableEntityRepository <RecipientHospitalData> >();
            var bloodBankRepository              = serviceProvider.GetRequiredService <IDeletableEntityRepository <BloodBank> >();
            var hospitalBloodBankRepository      = serviceProvider.GetRequiredService <IDeletableEntityRepository <HospitalDataBloodBank> >();
            var allUsers     = serviceProvider.GetService <IDeletableEntityRepository <ApplicationUser> >();
            var deletedUsers = allUsers
                               .AllAsNoTrackingWithDeleted()
                               .Where(u => u.IsDeleted == true)
                               .ToList();

            // Seeding hospitals and hospitalsData
            for (int i = 0; i < 6; i++)
            {
                var user = await userManager.FindByEmailAsync($"Hospital{i}@hospital.bg");

                if (user != null)
                {
                    return;
                }

                user = new ApplicationUser
                {
                    UserName       = $"Hospital{i}@hospital.bg",
                    Email          = $"Hospital{i}@hospital.bg",
                    EmailConfirmed = true,
                };

                if (deletedUsers.Any(u => u.Email == user.Email))
                {
                    return;
                }

                await userManager.CreateAsync(user, $"Hospital{i}@hospital.bg");

                await userManager.AddToRoleAsync(user, GlobalConstants.HospitaltRoleName);

                var hospitalData = new HospitalData
                {
                    ApplicationUserId = user.Id,
                    ApplicationUser   = user,
                    Name    = $"Hospital{i}",
                    Contact = new Contact
                    {
                        Email = user.Email,
                        Phone = $"0{i * 5}{i * 6}{i * 7}",
                    },
                    Location = new Location
                    {
                        Country           = "Bulgaria",
                        City              = $"City{i}",
                        AdressDescription = $"Street{i * 3}",
                    },
                };
                await hospitalDataRepository.AddAsync(hospitalData);

                var bloodBank = new BloodBank
                {
                    HospitalDataId = hospitalData.Id,
                };
                await bloodBankRepository.AddAsync(bloodBank);

                var hospitalBloodBank = new HospitalDataBloodBank
                {
                    HospitalId  = hospitalData.Id,
                    BloodBankId = bloodBank.Id,
                };
                await hospitalBloodBankRepository.AddAsync(hospitalBloodBank);

                // Seeding recipients in hospitals
                for (int j = 0; j < 3; j++)
                {
                    Random random    = new Random();
                    var    recipient = new Recipient
                    {
                        HospitalDataId     = hospitalData.Id,
                        FirstName          = $"Recipient{j}",
                        MiddleName         = $"Recipient{j}",
                        LastName           = $"Recipient{j}",
                        Age                = 20 + j,
                        NeededQuantity     = 500,
                        RecipientEmergency = (EmergencyStatus)random.Next(Enum.GetNames(typeof(EmergencyStatus)).Length),
                        BloodGroup         = (BloodGroup)random.Next(Enum.GetNames(typeof(BloodGroup)).Length),
                        RhesusFactor       = (RhesusFactor)random.Next(Enum.GetNames(typeof(RhesusFactor)).Length),
                    };

                    await recipientsRepository.AddAsync(recipient);

                    var recipientHospitalData = new RecipientHospitalData
                    {
                        HospitalDataId = hospitalData.Id,
                        RecipientId    = recipient.Id,
                    };

                    await recipientsHospitalDataRepository.AddAsync(recipientHospitalData);
                }
            }
        }
        private BuildCreateContractTransactionResponse BuildCreateTx(BuildCreateContractTransactionRequest request)
        {
            this.logger.LogTrace(request.ToString());

            AddressBalance addressBalance = this.walletManager.GetAddressBalance(request.Sender);

            if (addressBalance.AmountConfirmed == 0)
            {
                return(BuildCreateContractTransactionResponse.Failed($"The 'Sender' address you're trying to spend from doesn't have a confirmed balance. Current unconfirmed balance: {addressBalance.AmountUnconfirmed}. Please check the 'Sender' address."));
            }

            var selectedInputs = new List <OutPoint>();

            selectedInputs = this.walletManager.GetSpendableTransactionsInWallet(request.WalletName, MinConfirmationsAllChecks).Where(x => x.Address.Address == request.Sender).Select(x => x.ToOutPoint()).ToList();

            ulong gasPrice = ulong.Parse(request.GasPrice);
            ulong gasLimit = ulong.Parse(request.GasLimit);

            SmartContractCarrier carrier;

            if (request.Parameters != null && request.Parameters.Any())
            {
                carrier = SmartContractCarrier.CreateContract(ReflectionVirtualMachine.VmVersion, request.ContractCode.HexToByteArray(), gasPrice, new Gas(gasLimit), request.Parameters);
            }
            else
            {
                carrier = SmartContractCarrier.CreateContract(ReflectionVirtualMachine.VmVersion, request.ContractCode.HexToByteArray(), gasPrice, new Gas(gasLimit));
            }

            HdAddress senderAddress = null;

            if (!string.IsNullOrWhiteSpace(request.Sender))
            {
                Features.Wallet.Wallet wallet = this.walletManager.GetWallet(request.WalletName);
                HdAccount account             = wallet.GetAccountByCoinType(request.AccountName, this.coinType);
                senderAddress = account.GetCombinedAddresses().FirstOrDefault(x => x.Address == request.Sender);
            }

            ulong totalFee = (gasPrice * gasLimit) + Money.Parse(request.FeeAmount);
            var   walletAccountReference = new WalletAccountReference(request.WalletName, request.AccountName);
            var   recipient = new Recipient {
                Amount = request.Amount ?? "0", ScriptPubKey = new Script(carrier.Serialize())
            };
            var context = new TransactionBuildContext(this.network)
            {
                AccountReference = walletAccountReference,
                TransactionFee   = totalFee,
                ChangeAddress    = senderAddress,
                SelectedInputs   = selectedInputs,
                MinConfirmations = MinConfirmationsAllChecks,
                WalletPassword   = request.Password,
                Recipients       = new[] { recipient }.ToList()
            };

            try
            {
                Transaction transaction     = this.walletTransactionHandler.BuildTransaction(context);
                uint160     contractAddress = this.addressGenerator.GenerateAddress(transaction.GetHash(), 0);
                return(BuildCreateContractTransactionResponse.Succeeded(transaction, context.TransactionFee, contractAddress.ToAddress(this.network)));
            }
            catch (Exception exception)
            {
                return(BuildCreateContractTransactionResponse.Failed(exception.Message));
            }
        }
Пример #32
0
 private static bool EvalRecip(Recipient recip, ref Dictionary<string, Recipient> selections)
 {
     try
     {
         var ae = recip.AddressEntry;
         if (ae == null) return false;
         var smtp = ae.GetPrimarySMTP();
         if (string.IsNullOrEmpty(smtp) || selections.ContainsKey(smtp)) return false;
         selections.Add(smtp, recip);
         return true;
     }
     catch (Exception ex)
     {
         Logger.Verbose("", ex.Message);
     }
     return false;
 }
Пример #33
0
        public override int GetHashCode()
        {
            int hashCode = 1108362053;

            if (Recipient != null)
            {
                hashCode += Recipient.GetHashCode();
            }

            if (Carrier != null)
            {
                hashCode += Carrier.GetHashCode();
            }

            if (ShippingNote != null)
            {
                hashCode += ShippingNote.GetHashCode();
            }

            if (ShippingType != null)
            {
                hashCode += ShippingType.GetHashCode();
            }

            if (TrackingNumber != null)
            {
                hashCode += TrackingNumber.GetHashCode();
            }

            if (TrackingUrl != null)
            {
                hashCode += TrackingUrl.GetHashCode();
            }

            if (PlacedAt != null)
            {
                hashCode += PlacedAt.GetHashCode();
            }

            if (InProgressAt != null)
            {
                hashCode += InProgressAt.GetHashCode();
            }

            if (PackagedAt != null)
            {
                hashCode += PackagedAt.GetHashCode();
            }

            if (ExpectedShippedAt != null)
            {
                hashCode += ExpectedShippedAt.GetHashCode();
            }

            if (ShippedAt != null)
            {
                hashCode += ShippedAt.GetHashCode();
            }

            if (CanceledAt != null)
            {
                hashCode += CanceledAt.GetHashCode();
            }

            if (CancelReason != null)
            {
                hashCode += CancelReason.GetHashCode();
            }

            if (FailedAt != null)
            {
                hashCode += FailedAt.GetHashCode();
            }

            if (FailureReason != null)
            {
                hashCode += FailureReason.GetHashCode();
            }

            return(hashCode);
        }
Пример #34
0
 private void EditRecipientList(Recipient editedRecipient)
 {
     Recipients = new ObservableCollection <Recipient>(_recipientService.GetAll());
 }
Пример #35
0
 /// <summary>
 /// Правка информации
 /// </summary>
 /// <param name="Recipient"></param>
 public void Edit(Recipient Recipient)
 {
     //берем место хранения данных
     _Store.Edit(Recipient.Id, Recipient);
 }
 public void Init(Recipient recipient = null)
 {
     _recipient = recipient == null ? new Recipient() : recipient;
     RaiseAllPropertiesChanged();
 }
Пример #37
0
        public override IDeepCopyable CopyTo(IDeepCopyable other)
        {
            var dest = other as DocumentManifest;

            if (dest != null)
            {
                base.CopyTo(dest);
                if (MasterIdentifier != null)
                {
                    dest.MasterIdentifier = (Hl7.Fhir.Model.Identifier)MasterIdentifier.DeepCopy();
                }
                if (Identifier != null)
                {
                    dest.Identifier = new List <Hl7.Fhir.Model.Identifier>(Identifier.DeepCopy());
                }
                if (Subject != null)
                {
                    dest.Subject = (Hl7.Fhir.Model.ResourceReference)Subject.DeepCopy();
                }
                if (Recipient != null)
                {
                    dest.Recipient = new List <Hl7.Fhir.Model.ResourceReference>(Recipient.DeepCopy());
                }
                if (Type != null)
                {
                    dest.Type = (Hl7.Fhir.Model.CodeableConcept)Type.DeepCopy();
                }
                if (Author != null)
                {
                    dest.Author = new List <Hl7.Fhir.Model.ResourceReference>(Author.DeepCopy());
                }
                if (CreatedElement != null)
                {
                    dest.CreatedElement = (Hl7.Fhir.Model.FhirDateTime)CreatedElement.DeepCopy();
                }
                if (SourceElement != null)
                {
                    dest.SourceElement = (Hl7.Fhir.Model.FhirUri)SourceElement.DeepCopy();
                }
                if (StatusElement != null)
                {
                    dest.StatusElement = (Code <Hl7.Fhir.Model.DocumentReferenceStatus>)StatusElement.DeepCopy();
                }
                if (DescriptionElement != null)
                {
                    dest.DescriptionElement = (Hl7.Fhir.Model.FhirString)DescriptionElement.DeepCopy();
                }
                if (Content != null)
                {
                    dest.Content = new List <Hl7.Fhir.Model.DocumentManifest.DocumentManifestContentComponent>(Content.DeepCopy());
                }
                if (Related != null)
                {
                    dest.Related = new List <Hl7.Fhir.Model.DocumentManifest.DocumentManifestRelatedComponent>(Related.DeepCopy());
                }
                return(dest);
            }
            else
            {
                throw new ArgumentException("Can only copy to an object of the same type", "other");
            }
        }
Пример #38
0
        public NameSpace GetCurrentUser(NameSpace oNS)
        {
            //We only need the current user details when syncing meeting attendees.
            //If GAL had previously been detected as blocked, let's always try one attempt to see if it's been opened up
            if (!Settings.Instance.OutlookGalBlocked && !Settings.Instance.AddAttendees)
            {
                return(oNS);
            }

            Boolean releaseNamespace = (oNS == null);

            if (releaseNamespace)
            {
                oNS = oApp.GetNamespace("mapi");
            }

            Recipient currentUser = null;

            try {
                DateTime triggerOOMsecurity = DateTime.Now;
                try {
                    currentUser = oNS.CurrentUser;
                    if (!Forms.Main.Instance.IsHandleCreated && (DateTime.Now - triggerOOMsecurity).TotalSeconds > 1)
                    {
                        log.Warn(">1s delay possibly due to Outlook security popup.");
                        OutlookOgcs.Calendar.OOMsecurityInfo = true;
                    }
                } catch (System.Exception ex) {
                    OGCSexception.Analyse(ex);
                    if (Settings.Instance.OutlookGalBlocked)   //Fail fast
                    {
                        log.Debug("Corporate policy is still blocking access to GAL.");
                        return(oNS);
                    }
                    log.Warn("We seem to have a faux connection to Outlook! Forcing starting it with a system call :-/");
                    oNS = (NameSpace)OutlookOgcs.Calendar.ReleaseObject(oNS);
                    Disconnect();
                    OutlookOgcs.Calendar.AttachToOutlook(ref oApp, openOutlookOnFail: true, withSystemCall: true);
                    oNS = oApp.GetNamespace("mapi");

                    int maxDelay = 5;
                    int delay    = 1;
                    while (delay <= maxDelay)
                    {
                        log.Debug("Sleeping..." + delay + "/" + maxDelay);
                        System.Threading.Thread.Sleep(10000);
                        try {
                            currentUser = oNS.CurrentUser;
                            delay       = maxDelay;
                        } catch (System.Exception ex2) {
                            if (delay == maxDelay)
                            {
                                if (OGCSexception.GetErrorCode(ex2) == "0x80004004")   //E_ABORT
                                {
                                    log.Warn("Corporate policy or possibly anti-virus is blocking access to GAL.");
                                }
                                else
                                {
                                    OGCSexception.Analyse(ex2);
                                }
                                log.Warn("OGCS is unable to obtain CurrentUser from Outlook.");
                                Settings.Instance.OutlookGalBlocked = true;
                                return(oNS);
                            }
                            OGCSexception.Analyse(ex2);
                        }
                        delay++;
                    }
                }
                if (Settings.Instance.OutlookGalBlocked)
                {
                    log.Debug("GAL is no longer blocked!");
                }
                Settings.Instance.OutlookGalBlocked = false;
                currentUserSMTP = GetRecipientEmail(currentUser);
                currentUserName = currentUser.Name;
            } finally {
                currentUser = (Recipient)OutlookOgcs.Calendar.ReleaseObject(currentUser);
                if (releaseNamespace)
                {
                    oNS = (NameSpace)OutlookOgcs.Calendar.ReleaseObject(oNS);
                }
            }
            return(oNS);
        }
        async void SendMail(object sender, EventArgs e)
        {
            ShowProgress("Getting profile photo");

            try
            {
                // Upload the profile pic to OneDrive
                var photoStream = await GetUserPhoto();

                // Copy to memory stream
                MemoryStream memStream = new MemoryStream();
                photoStream.CopyTo(memStream);

                // Get the bytes
                var photoBytes = memStream.ToArray();

                UpdateProgress("Uploading photo to OneDrive");
                var uploadedPhoto = await App.GraphClient.Me.Drive.Root.ItemWithPath("ProfilePhoto.png")
                                    .Content.Request().PutAsync <DriveItem>(new MemoryStream(photoBytes));

                // Generate a sharing link
                UpdateProgress("Generating sharing link");
                var sharingLink = await App.GraphClient.Me.Drive.Items[uploadedPhoto.Id]
                                  .CreateLink("view", "organization").Request().PostAsync();

                // Create a recipient from the selected Person object
                var selectedRecipient = pickerRecipient.SelectedItem as Person;

                var recipient = new Recipient()
                {
                    EmailAddress = new EmailAddress()
                    {
                        Name    = selectedRecipient.DisplayName,
                        Address = selectedRecipient.ScoredEmailAddresses.FirstOrDefault().Address
                    }
                };

                // Create the email message
                var message = new Message()
                {
                    Subject      = "Check out my profile photo",
                    ToRecipients = new List <Recipient>()
                    {
                        recipient
                    },
                    Body = new ItemBody()
                    {
                        ContentType = BodyType.Html
                    },
                    Attachments = new MessageAttachmentsCollectionPage()
                };

                // Attach profile pic and add as inline
                message.Attachments.Add(new FileAttachment()
                {
                    ODataType    = "#microsoft.graph.fileAttachment",
                    ContentBytes = photoBytes,
                    ContentType  = "image/png",
                    Name         = "ProfilePhoto.png",
                    IsInline     = true
                });

                message.Body.Content = $@"<html><head>
<meta http-equiv='Content-Type' content='text/html; charset=us-ascii'>
</head>
<body style='font-family:calibri'>
  <h2>Hello, {selectedRecipient.GivenName}!</h2>
  <p>This is a message from the PhotoSender app.What do you think of my profile picture?</p>
  <img src=""cid:ProfilePhoto.png""></img>
  <p>You can also <a href=""{sharingLink.Link.WebUrl}"" >view it on my OneDrive</a>.</p>
</body></html>";

                UpdateProgress("Sending message");
                // Send the message
                await App.GraphClient.Me.SendMail(message, true).Request().PostAsync();

                await DisplayAlert("Success", "Message sent", "OK");
            }
            catch (ServiceException ex)
            {
                await DisplayAlert("A Graph error occurred", ex.Message, "Dismiss");
            }
            finally
            {
                HideProgress();
            }
        }
Пример #40
0
        public String GetRecipientEmail(Recipient recipient)
        {
            String  retEmail       = "";
            Boolean builtFakeEmail = false;

            log.Fine("Determining email of recipient: " + recipient.Name);
            AddressEntry addressEntry     = null;
            String       addressEntryType = "";

            try {
                try {
                    addressEntry = recipient.AddressEntry;
                } catch {
                    log.Warn("Can't resolve this recipient!");
                    addressEntry = null;
                }
                if (addressEntry == null)
                {
                    log.Warn("No AddressEntry exists!");
                    retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name, out builtFakeEmail);
                }
                else
                {
                    try {
                        addressEntryType = addressEntry.Type;
                    } catch {
                        log.Warn("Cannot access addressEntry.Type!");
                    }
                    log.Fine("AddressEntry Type: " + addressEntryType);
                    if (addressEntryType == "EX")   //Exchange
                    {
                        log.Fine("Address is from Exchange");
                        retEmail = ADX_GetSMTPAddress(addressEntry.Address);
                    }
                    else if (addressEntry.Type != null && addressEntry.Type.ToUpper() == "NOTES")
                    {
                        log.Fine("From Lotus Notes");
                        //Migrated contacts from notes, have weird "email addresses" eg: "James T. Kirk/US-Corp03/enterprise/US"
                        retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name, out builtFakeEmail);
                    }
                    else
                    {
                        log.Fine("Not from Exchange");
                        try {
                            if (string.IsNullOrEmpty(addressEntry.Address))
                            {
                                log.Warn("addressEntry.Address is empty.");
                                retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name, out builtFakeEmail);
                            }
                            else
                            {
                                retEmail = addressEntry.Address;
                            }
                        } catch (System.Exception ex) {
                            log.Error("Failed accessing addressEntry.Address");
                            log.Error(ex.Message);
                            retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name, out builtFakeEmail);
                        }
                    }
                }

                if (string.IsNullOrEmpty(retEmail) || retEmail == "Unknown")
                {
                    log.Error("Failed to get email address through Addin MAPI access!");
                    retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name, out builtFakeEmail);
                }

                if (retEmail != null && retEmail.IndexOf("<") > 0)
                {
                    retEmail = retEmail.Substring(retEmail.IndexOf("<") + 1);
                    retEmail = retEmail.TrimEnd(Convert.ToChar(">"));
                }
                log.Fine("Email address: " + retEmail, retEmail);
                if (!EmailAddress.IsValidEmail(retEmail) && !builtFakeEmail)
                {
                    retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name, out builtFakeEmail);
                    if (!EmailAddress.IsValidEmail(retEmail))
                    {
                        Forms.Main.Instance.Console.Update("Recipient \"" + recipient.Name + "\" with email address \"" + retEmail + "\" is invalid.", Console.Markup.error, notifyBubble: true);
                        Forms.Main.Instance.Console.Update("This must be manually resolved in order to sync this appointment.");
                        throw new ApplicationException("Invalid recipient email for \"" + recipient.Name + "\"");
                    }
                }
                return(retEmail);
            } finally {
                addressEntry = (AddressEntry)OutlookOgcs.Calendar.ReleaseObject(addressEntry);
            }
        }
Пример #41
0
 public static Model.Recipient MapToModel(this Recipient source) =>
 new Model.Recipient(
     source.Name,
     source.Email,
     source.Address.MapToModel());
Пример #42
0
 void Start()
 {
     //Busca recipiente
     recipient = GameObject.FindWithTag("Recipiente").GetComponent<Recipient>();
     //Busca temporizador
     timeControl = GetComponent<TimeControl> ();
     //Busca Janela
 }
        public String GetRecipientEmail(Recipient recipient) {
            String retEmail = "";
            log.Fine("Determining email of recipient: " + recipient.Name);
            try {
                AddressEntry addressEntry = recipient.AddressEntry;
            } catch {
                log.Warn("Can't resolve this recipient!");
                recipient.AddressEntry = null;
            }
            if (recipient.AddressEntry == null) {
                log.Warn("No AddressEntry exists!");
                retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name);
                EmailAddress.IsValidEmail(retEmail);
                return retEmail;
            }
            log.Fine("AddressEntry Type: " + recipient.AddressEntry.Type);
            if (recipient.AddressEntry.Type == "EX") { //Exchange
                log.Fine("Address is from Exchange");
                if (recipient.AddressEntry.AddressEntryUserType == OlAddressEntryUserType.olExchangeUserAddressEntry ||
                    recipient.AddressEntry.AddressEntryUserType == OlAddressEntryUserType.olExchangeRemoteUserAddressEntry) {
                    ExchangeUser eu = recipient.AddressEntry.GetExchangeUser();
                    if (eu != null && eu.PrimarySmtpAddress != null)
                        retEmail = eu.PrimarySmtpAddress;
                    else {
                        log.Warn("Exchange does not have an email for recipient: "+ recipient.Name);
                        try {
                            //Should I try PR_EMS_AB_PROXY_ADDRESSES next to cater for cached mode?
                            Microsoft.Office.Interop.Outlook.PropertyAccessor pa = recipient.PropertyAccessor;
                            retEmail = pa.GetProperty(OutlookNew.PR_SMTP_ADDRESS).ToString();
                            log.Debug("Retrieved from PropertyAccessor instead.");
                        } catch {
                            log.Warn("Also failed to retrieve email from PropertyAccessor.");
                            retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name);
                        }
                    }

                } else if (recipient.AddressEntry.AddressEntryUserType == OlAddressEntryUserType.olOutlookContactAddressEntry) {
                    log.Fine("This is an Outlook contact");
                    ContactItem contact = null;
                    try {
                        contact = recipient.AddressEntry.GetContact();
                    } catch {
                        log.Warn("Doesn't seem to be a valid contact object. Maybe this account is not longer in Exchange.");
                        retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name);
                    }
                    if (contact != null) {
                        if (contact.Email1AddressType == "EX") {
                            log.Fine("Address is from Exchange.");
                            log.Fine("Using PropertyAccessor to get email address.");
                            Microsoft.Office.Interop.Outlook.PropertyAccessor pa = contact.PropertyAccessor;
                            retEmail = pa.GetProperty(EMAIL1ADDRESS).ToString();
                        } else {
                            retEmail = contact.Email1Address;
                        }
                    }
                } else {
                    log.Fine("Exchange type: " + recipient.AddressEntry.AddressEntryUserType.ToString());
                    log.Fine("Using PropertyAccessor to get email address.");
                    Microsoft.Office.Interop.Outlook.PropertyAccessor pa = recipient.PropertyAccessor;
                    retEmail = pa.GetProperty(OutlookNew.PR_SMTP_ADDRESS).ToString();
                }

            } else if (recipient.AddressEntry.Type.ToUpper() == "NOTES") {
                log.Fine("From Lotus Notes");
                //Migrated contacts from notes, have weird "email addresses" eg: "James T. Kirk/US-Corp03/enterprise/US"
                retEmail = EmailAddress.BuildFakeEmailAddress(recipient.Name);

            } else {
                log.Fine("Not from Exchange");
                retEmail = recipient.AddressEntry.Address;
            }

            if (retEmail.IndexOf("<") > 0) {
                retEmail = retEmail.Substring(retEmail.IndexOf("<") + 1);
                retEmail = retEmail.TrimEnd(Convert.ToChar(">"));
            }
            log.Fine("Email address: " + retEmail);
            EmailAddress.IsValidEmail(retEmail);
            return retEmail;
        }
        public async Task ScheduleAndExecuteAsync_When_NotificationCreated_NotificationSent_Then_SuccessfulReturned(bool isErrorsCollectionNull)
        {
            // Arrange
            var mock      = new MockNotificationService();
            var recipient = new Recipient();
            var content   = new NotificationContent();

            var resolverResult = new ResolverResult()
            {
                ToAddress = "*****@*****.**"
            };

            var expectedAddedNotifications = new INotificationData[]
            {
                new MockNotificationData()
                {
                    TransportType = mock.MockNotificationTransporter.Object.TransporterType
                }
            };

            mock.SetupTransporters();
            mock.MockNotificationRecipientResolver.Setup(x => x.ResolveAsync(recipient, content, mock.MockNotificationTransporter.Object.TransporterType))
            .Returns(Task.FromResult <object>(resolverResult));


            mock.MockNotificationRepository.Setup(x => x.AddAsync(It.Is <IEnumerable <CreatableNotification> >((creatables) => creatables.Count() == 1 &&
                                                                                                               creatables.FirstOrDefault(item => item.TransportType == mock.MockNotificationTransporter.Object.TransporterType &&
                                                                                                                                         item.Recipients == resolverResult &&
                                                                                                                                         item.NotificationType == content.NotificationType &&
                                                                                                                                         item.Content == content) != null)))
            .Returns(Task.FromResult <IEnumerable <INotificationData> >(expectedAddedNotifications));

            mock.MockNotificationTransporter.Setup(x => x.SendAsync(expectedAddedNotifications[0].NotificationType,
                                                                    expectedAddedNotifications[0].Recipients,
                                                                    expectedAddedNotifications[0].Content))
            .Returns(Task.FromResult <IEnumerable <string> >(isErrorsCollectionNull ? null : new string[0]));

            // Act
            var result = await mock.Service.ScheduleAndExecuteAsync(content, recipient);

            // Assert
            Assert.Equal(NotifyStatus.Successful, result);

            mock.MockNotificationRepository.Verify(x => x.UpdateAsync(expectedAddedNotifications[0].Id,
                                                                      NotificationState.Processing,
                                                                      0,
                                                                      null,
                                                                      null),
                                                   Times.Once);

            mock.MockNotificationRepository.Verify(x => x.UpdateAsync(expectedAddedNotifications[0].Id,
                                                                      NotificationState.Successful,
                                                                      0,
                                                                      null,
                                                                      null),
                                                   Times.Once);


            mock.MockNotificationTransporter.Verify(x => x.SendAsync(expectedAddedNotifications[0].NotificationType,
                                                                     expectedAddedNotifications[0].Recipients,
                                                                     expectedAddedNotifications[0].Content),
                                                    Times.Once);
        }
Пример #45
0
        public void Send(MailMessage message)
        {
            if (!OutlookIsRunning)
            {
                LaunchOutlook();
            }
            Recipients oRecips = null;
            Recipient  oRecip  = null;
            MailItem   oMsg    = null;

            try
            {
                MyApp = new Application();

                oMsg = (MailItem)MyApp.CreateItem(OlItemType.olMailItem);

                oMsg.HTMLBody = message.Body;
                oMsg.Subject  = message.Subject;
                oRecips       = oMsg.Recipients;


                foreach (var email in message.To)
                {
                    oRecip = oRecips.Add(email.Address);
                }

                foreach (var email in message.CC)
                {
                    oMsg.CC += string.Concat(email, ";");
                }

                var filenames = Attach(message.Attachments, oMsg);
                oRecip?.Resolve();

                oMsg.Send();

                MapiNameSpace = MyApp.GetNamespace("MAPI");

                DeleteTempFiles(filenames);
                Thread.Sleep(5000);
            }
            finally
            {
                if (oRecip != null)
                {
                    Marshal.ReleaseComObject(oRecip);
                }
                if (oRecips != null)
                {
                    Marshal.ReleaseComObject(oRecips);
                }
                if (oMsg != null)
                {
                    Marshal.ReleaseComObject(oMsg);
                }
                if (MapiNameSpace != null)
                {
                    Marshal.ReleaseComObject(MapiNameSpace);
                }
                if (MyApp != null)
                {
                    Marshal.ReleaseComObject(MyApp);
                }
            }
        }
Пример #46
0
        public async Task <DialogTurnResult> ConfirmName(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                var state = await EmailStateAccessor.GetAsync(sc.Context);

                if (((state.NameList == null) || (state.NameList.Count == 0)) && state.EmailList.Count == 0)
                {
                    return(await sc.BeginDialogAsync(Actions.UpdateRecipientName, new UpdateUserDialogOptions(UpdateUserDialogOptions.UpdateReason.NotFound)));
                }

                var unionList = new List <Person>();

                if (state.FirstEnterFindContact || state.EmailList.Count > 0)
                {
                    state.FirstEnterFindContact = false;
                    if (state.NameList.Count > 1)
                    {
                        var nameString = await GetReadyToSendNameListStringAsync(sc);

                        await sc.Context.SendActivityAsync(ResponseManager.GetResponse(FindContactResponses.BeforeSendingMessage, new StringDictionary()
                        {
                            { "NameList", nameString }
                        }));
                    }
                }

                if (state.EmailList.Count > 0)
                {
                    foreach (var email in state.EmailList)
                    {
                        var recipient    = new Recipient();
                        var emailAddress = new EmailAddress
                        {
                            Name    = email,
                            Address = email,
                        };
                        recipient.EmailAddress = emailAddress;

                        if (state.Recipients.All(r => r.EmailAddress.Address != emailAddress.Address))
                        {
                            state.Recipients.Add(recipient);
                        }
                    }

                    state.EmailList.Clear();

                    if (state.NameList.Count > 0)
                    {
                        return(await sc.ReplaceDialogAsync(Actions.ConfirmName, sc.Options));
                    }
                    else
                    {
                        return(await sc.EndDialogAsync());
                    }
                }

                if (state.ConfirmRecipientIndex < state.NameList.Count)
                {
                    var currentRecipientName = state.NameList[state.ConfirmRecipientIndex];

                    var originPersonList = await GetPeopleWorkWithAsync(sc.Context, currentRecipientName);

                    var originContactList = await GetContactsAsync(sc.Context, currentRecipientName);

                    originPersonList.AddRange(originContactList);

                    var originUserList = new List <Person>();
                    try
                    {
                        originUserList = await GetUserAsync(sc.Context, currentRecipientName);
                    }
                    catch
                    {
                        // do nothing when get user failed. because can not use token to ensure user use a work account.
                    }

                    (var personList, var userList) = DisplayHelper.FormatRecipientList(originPersonList, originUserList);

                    // people you work with has the distinct email address has the highest priority
                    if (personList.Count == 1 && personList.First().ScoredEmailAddresses.Count() == 1 && personList.First().ScoredEmailAddresses != null && !string.IsNullOrEmpty(personList.First().ScoredEmailAddresses.First().Address))
                    {
                        state.ConfirmedPerson = personList.First();
                        return(await sc.ReplaceDialogAsync(Actions.ConfirmEmail, personList.First()));
                    }

                    personList.AddRange(userList);

                    foreach (var person in personList)
                    {
                        if (unionList.Find(p => p.DisplayName == person.DisplayName) == null)
                        {
                            var personWithSameName = personList.FindAll(p => p.DisplayName == person.DisplayName);
                            if (personWithSameName.Count == 1)
                            {
                                unionList.Add(personWithSameName.FirstOrDefault());
                            }
                            else
                            {
                                var unionPerson = personWithSameName.FirstOrDefault();
                                var emailList   = new List <ScoredEmailAddress>();
                                foreach (var sameNamePerson in personWithSameName)
                                {
                                    sameNamePerson.ScoredEmailAddresses.ToList().ForEach(e =>
                                    {
                                        if (e != null && !string.IsNullOrEmpty(e.Address))
                                        {
                                            emailList.Add(e);
                                        }
                                    });
                                }

                                unionPerson.ScoredEmailAddresses = emailList;
                                unionList.Add(unionPerson);
                            }
                        }
                    }
                }
                else
                {
                    return(await sc.EndDialogAsync());
                }

                unionList.RemoveAll(person => !person.ScoredEmailAddresses.ToList().Exists(email => email.Address != null));

                state.UnconfirmedPerson = unionList;

                if (unionList.Count == 0)
                {
                    return(await sc.BeginDialogAsync(Actions.UpdateRecipientName, new UpdateUserDialogOptions(UpdateUserDialogOptions.UpdateReason.NotFound)));
                }
                else if (unionList.Count == 1)
                {
                    state.ConfirmedPerson = unionList.First();
                    return(await sc.ReplaceDialogAsync(Actions.ConfirmEmail, unionList.First()));
                }
                else
                {
                    var nameString = string.Empty;
                    if (unionList.Count <= ConfigData.GetInstance().MaxDisplaySize)
                    {
                        return(await sc.PromptAsync(Actions.Choice, await GenerateOptionsForName(sc, unionList, sc.Context, true)));
                    }
                    else
                    {
                        return(await sc.PromptAsync(Actions.Choice, await GenerateOptionsForName(sc, unionList, sc.Context, false)));
                    }
                }
            }
            catch (SkillException skillEx)
            {
                await HandleDialogExceptions(sc, skillEx);

                return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs));
            }
            catch (Exception ex)
            {
                await HandleDialogExceptions(sc, ex);

                return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs));
            }
        }
Пример #47
0
 public static EventAttendee CreateAttendee(Recipient recipient)
 {
     EventAttendee ea = new EventAttendee();
     log.Fine("Creating attendee " + recipient.Name);
     ea.DisplayName = recipient.Name;
     ea.Email = OutlookCalendar.Instance.IOutlook.GetRecipientEmail(recipient);
     ea.Optional = (recipient.Type == (int)OlMeetingRecipientType.olOptional);
     //Readonly: ea.Organizer = (ai.Organizer == recipient.Name);
     switch (recipient.MeetingResponseStatus) {
         case OlResponseStatus.olResponseNone: ea.ResponseStatus = "needsAction"; break;
         case OlResponseStatus.olResponseAccepted: ea.ResponseStatus = "accepted"; break;
         case OlResponseStatus.olResponseDeclined: ea.ResponseStatus = "declined"; break;
         case OlResponseStatus.olResponseTentative: ea.ResponseStatus = "tentative"; break;
     }
     return ea;
 }
    protected void createEnvelope()
    {
        FileStream fs = null;

        try
        {
            String userName = ConfigurationManager.AppSettings["API.Email"];
            String password = ConfigurationManager.AppSettings["API.Password"];
            String integratorKey = ConfigurationManager.AppSettings["API.IntegratorKey"];


            String auth = "<DocuSignCredentials><Username>" + userName
                + "</Username><Password>" + password
                + "</Password><IntegratorKey>" + integratorKey
                + "</IntegratorKey></DocuSignCredentials>";
            ServiceReference1.DSAPIServiceSoapClient client = new ServiceReference1.DSAPIServiceSoapClient();

            using (OperationContextScope scope = new System.ServiceModel.OperationContextScope(client.InnerChannel))
            {
                HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty();
                httpRequestProperty.Headers.Add("X-DocuSign-Authentication", auth);
                OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;

                CompositeTemplate template = new CompositeTemplate();

                // Set up the envelope
                EnvelopeInformation envInfo = new EnvelopeInformation();
                envInfo.AutoNavigation = true;
                envInfo.AccountId = ConfigurationManager.AppSettings["API.AccountId"];
                envInfo.Subject = "Dynamic Fields Example";

                // Set up recipients 
                Recipient[] recipients;
                if (jointEmail.Value.Trim().Equals(""))
                {
                    recipients = new Recipient[1];
                }
                else
                {
                    recipients = new Recipient[2];
                }

                recipients[0] = new Recipient();
                recipients[0].ID = "1";
                recipients[0].Email = email.Value;
                recipients[0].Type = RecipientTypeCode.Signer;
                recipients[0].UserName = firstname.Value + " " + lastname.Value;
                recipients[0].CaptiveInfo = new RecipientCaptiveInfo();

                recipients[0].CaptiveInfo.ClientUserId = RandomizeClientUserID();
                recipients[0].RoutingOrder = 1;
                recipients[0].RoleName = "Signer1";

                // If there is a 2nd recipient, configure 
                if (!jointEmail.Value.Equals(""))
                {
                    recipients[1] = new Recipient();
                    recipients[1].ID = "2";
                    recipients[1].Email = jointEmail.Value;
                    recipients[1].Type = RecipientTypeCode.Signer;
                    recipients[1].UserName = jointFirstname.Value + " " + jointLastname.Value;
                    recipients[1].RoleName = "Signer2";
                    recipients[1].RoutingOrder = 1;
                }

                //Configure the inline templates 
                InlineTemplate inlineTemplate = new InlineTemplate();
                inlineTemplate.Sequence = "1";
                inlineTemplate.Envelope = new Envelope();
                inlineTemplate.Envelope.Recipients = recipients;
                inlineTemplate.Envelope.AccountId = ConfigurationManager.AppSettings["API.AccountId"];

                // Initialize tab properties 
                Tab tab = new Tab();
                tab.Type = TabTypeCode.SignHere;
                tab.XPosition = xPosition.Value;
                tab.YPosition = yPosition.Value;
                tab.TabLabel = tabName.Value;
                tab.RecipientID = "1";
                tab.DocumentID = "1";
                tab.Name = tabName.Value;
                tab.PageNumber = tabPage.Value;

                Tab tab2 = new Tab();
                tab2.Type = TabTypeCode.DateSigned;

                tab2.XPosition = xPosition2.Value;
                tab2.YPosition = yPosition2.Value;
                tab2.TabLabel = tabName2.Value;
                tab2.RecipientID = "1";
                tab2.DocumentID = "1";
                tab2.Name = tabName2.Value;
                tab2.PageNumber = tabPage2.Value;

                inlineTemplate.Envelope.Tabs = new Tab[] { tab, tab2 };

                template.InlineTemplates = new InlineTemplate[] { inlineTemplate };


                // Configure the document
                template.Document = new Document();
                template.Document.ID = "1";
                template.Document.Name = "Sample Document";
                BinaryReader binReader = null;
                String filename = uploadFile.Value;
                if (File.Exists(Server.MapPath("~/App_Data/" + filename)))
                {
                    fs = new FileStream(Server.MapPath("~/App_Data/" + filename), FileMode.Open);
                    binReader = new BinaryReader(fs);
                }
                byte[] PDF = binReader.ReadBytes(System.Convert.ToInt32(fs.Length));
                template.Document.PDFBytes = PDF;

                template.Document.TransformPdfFields = true;
                template.Document.FileExtension = "pdf";

                //Create envelope with all the composite template information 
                EnvelopeStatus status = client.CreateEnvelopeFromTemplatesAndForms(envInfo, new CompositeTemplate[] { template }, true);
                RequestRecipientTokenAuthenticationAssertion assert = new RequestRecipientTokenAuthenticationAssertion();
                assert.AssertionID = "12345";
                assert.AuthenticationInstant = DateTime.Now;
                assert.AuthenticationMethod = RequestRecipientTokenAuthenticationAssertionAuthenticationMethod.Password;
                assert.SecurityDomain = "www.magicparadigm.com";

                RequestRecipientTokenClientURLs clientURLs = new RequestRecipientTokenClientURLs();

                clientURLs.OnAccessCodeFailed = ConfigurationManager.AppSettings["RecipientTokenClientURLsPrefix"] + "?envelopeId=" + status.EnvelopeID + "&event=OnAccessCodeFailed";
                clientURLs.OnCancel = ConfigurationManager.AppSettings["RecipientTokenClientURLsPrefix"] + "?envelopeId=" + status.EnvelopeID + "&event=OnCancel";
                clientURLs.OnDecline = ConfigurationManager.AppSettings["RecipientTokenClientURLsPrefix"] + "?envelopeId=" + status.EnvelopeID + "&event=OnDecline";
                clientURLs.OnException = ConfigurationManager.AppSettings["RecipientTokenClientURLsPrefix"] + "?envelopeId=" + status.EnvelopeID + "&event=OnException";
                clientURLs.OnFaxPending = ConfigurationManager.AppSettings["RecipientTokenClientURLsPrefix"] + "?envelopeId=" + status.EnvelopeID + "&event=OnFaxPending";
                clientURLs.OnIdCheckFailed = ConfigurationManager.AppSettings["RecipientTokenClientURLsPrefix"] + "?envelopeId=" + status.EnvelopeID + "&event=OnIdCheckFailed";
                clientURLs.OnSessionTimeout = ConfigurationManager.AppSettings["RecipientTokenClientURLsPrefix"] + "?envelopeId=" + status.EnvelopeID + "&event=OnSessionTimeout";
                clientURLs.OnTTLExpired = ConfigurationManager.AppSettings["RecipientTokenClientURLsPrefix"] + "?envelopeId=" + status.EnvelopeID + "&event=OnTTLExpired";
                clientURLs.OnViewingComplete = ConfigurationManager.AppSettings["RecipientTokenClientURLsPrefix"] + "?envelopeId=" + status.EnvelopeID + "&event=OnViewingComplete";


                String url = Request.Url.AbsoluteUri;

                String recipientToken;

                clientURLs.OnSigningComplete = url.Substring(0, url.LastIndexOf("/")) + "/EmbeddedSigningComplete0.aspx?envelopeID=" + status.EnvelopeID;
                recipientToken = client.RequestRecipientToken(status.EnvelopeID, recipients[0].CaptiveInfo.ClientUserId, recipients[0].UserName, recipients[0].Email, assert, clientURLs);
                Session["envelopeID"] = status.EnvelopeID;
                if (!Request.Browser.Browser.Equals("InternetExplorer") && (!Request.Browser.Browser.Equals("Safari")))
                {
                    docusignFrame.Visible = true;
                    docusignFrame.Src = recipientToken;
                }
                else // Handle IE differently since it does not allow dynamic setting of the iFrame width and height
                {
                    docusignFrameIE.Visible = true;
                    docusignFrameIE.Src = recipientToken;
                }


            }
        }
        catch (Exception ex)
        {
            // Log4Net Piece
            log4net.ILog logger = log4net.LogManager.GetLogger(typeof(DynamicFields));
            logger.Info("\n----------------------------------------\n");
            logger.Error(ex.Message);
            logger.Error(ex.StackTrace);
            Response.Write(ex.Message);

        }
        finally
        {
            if (fs != null)
                fs.Close();
        }
    }
Пример #49
0
 public MAPIFolder GetSharedDefaultFolder(Recipient Recipient, OlDefaultFolders FolderType)
 {
     Utils.LogNotImplementedStackTrace();
     
     return _nameSpace.GetSharedDefaultFolder(Recipient, FolderType);
 }
        //TODO: test dat
        private async void OnLoaded(object sender, RoutedEventArgs e)
        {
            StorageFile file = await Package.Current.InstalledLocation.GetFileAsync(@"Assets\service-icon.png");
            var geolocator = new Geolocator();
            var myPosition = await geolocator.GetGeopositionAsync();
            var sample = new Recipient
            {
                Name = "Recipient",
                Birthday = DateTime.Now.AddYears(-20),
                Latitude = myPosition.Coordinate.Latitude,
                Longitude = myPosition.Coordinate.Longitude,
                Description = "I'm so depressed...",
                IsActive = true,
                MainPhoto = await ConvertionExtensions.ReadFile(file)
            };
            var bitmap = new BitmapImage();
            await bitmap.SetSourceAsync(await ConvertionExtensions.ConvertToInMemoryStream(sample.MainPhoto));
            var recipients = Enumerable.Repeat(sample, 10).Select(x => new RecipientListInfo
            {
                Age = AgeConverter.GetAge(x.Birthday),
                Id = x.Id,
                Image = bitmap,
                Name = x.Name,
                ShowRecipientCommand =
                    new DelegateCommand(_ => ((Frame) Window.Current.Content).Navigate(typeof (RecipientInfoPage)),
                        _ => Window.Current.Content is Frame)
            }).ToArray();

            var culture = CultureInfo.CurrentCulture;
            var firstDay = culture.DateTimeFormat.FirstDayOfWeek;
            var today = DateTime.Today;
            var startDate = today.AddDays(1 - today.Day);
            var days = culture.Calendar.GetDaysInMonth(startDate.Year, startDate.Month);
            while (startDate.DayOfWeek != firstDay)
                startDate = startDate.AddDays(-1);
            var endDate = today.AddDays(days - today.Day);
            while (endDate.DayOfWeek != firstDay)
                endDate = endDate.AddDays(1);

            CalendarDays = Enumerable.Range(0, (int) (endDate - startDate).TotalDays)
                .Select(x => startDate.AddDays(x))
                .Select(x => new CalendarDayInfo
                {
                    Date = x,
                    Recipients = recipients.ToArray(),
                    ShowDetailsCommand = new DelegateCommand<CalendarDayInfo>(ShowDayDetailsCommandHandler),
                    ElementWidth = _currentDayElementWidth
                })
                .Select((x, i) => new {Item = x, Index = i})
                .GroupBy(x => x.Index/7)
                .Select(x => x.Select(y => y.Item).ToList())
                .Cast<object>()
                .ToList();
        }
Пример #51
0
 public EmailBuilder WithRecipient(Recipient recipient)
 {
     _recipients.Add(recipient);
     return this;
 }
        public async Task ScheduleAndExecuteAsync_When_NotificationCreated_NotificationNotSent_Then_ScheduledReturned()
        {
            // Arrange
            var mock      = new MockNotificationService();
            var recipient = new Recipient();
            var content   = new NotificationContent();

            var resolverResult = new ResolverResult()
            {
                ToAddress = "*****@*****.**"
            };

            var expectedAddedNotifications = new INotificationData[]
            {
                new MockNotificationData()
                {
                    TransportType = mock.MockNotificationTransporter.Object.TransporterType
                }
            };

            mock.SetupTransporters();
            mock.MockNotificationRecipientResolver.Setup(x => x.ResolveAsync(recipient, content, mock.MockNotificationTransporter.Object.TransporterType))
            .Returns(Task.FromResult <object>(resolverResult));


            mock.MockNotificationRepository.Setup(x => x.AddAsync(It.Is <IEnumerable <CreatableNotification> >((creatables) => creatables.Count() == 1 &&
                                                                                                               creatables.FirstOrDefault(item => item.TransportType == mock.MockNotificationTransporter.Object.TransporterType &&
                                                                                                                                         item.Recipients == resolverResult &&
                                                                                                                                         item.NotificationType == content.NotificationType &&
                                                                                                                                         item.Content == content) != null)))
            .Returns(Task.FromResult <IEnumerable <INotificationData> >(expectedAddedNotifications));

            var expectedNextSchedule = DateTime.UtcNow.AddSeconds(60);

            mock.MockNotificationTransporter.Setup(x => x.SendAsync(expectedAddedNotifications[0].NotificationType,
                                                                    expectedAddedNotifications[0].Recipients,
                                                                    expectedAddedNotifications[0].Content))
            .Callback(() => throw new SystemException());

            // Act
            var result = await mock.Service.ScheduleAndExecuteAsync(content, recipient);

            // Assert
            Assert.Equal(NotifyStatus.Scheduled, result);

            mock.MockNotificationRepository.Verify(x => x.UpdateAsync(expectedAddedNotifications[0].Id,
                                                                      NotificationState.Processing,
                                                                      0,
                                                                      null,
                                                                      null),
                                                   Times.Once);

            mock.MockNotificationRepository.Verify(x => x.UpdateAsync(expectedAddedNotifications[0].Id,
                                                                      NotificationState.WaitingForRetry,
                                                                      1,
                                                                      It.IsAny <string>(),
                                                                      It.Is <DateTime>((value) => value >= expectedNextSchedule)),
                                                   Times.Once);


            mock.MockNotificationTransporter.Verify(x => x.SendAsync(expectedAddedNotifications[0].NotificationType,
                                                                     expectedAddedNotifications[0].Recipients,
                                                                     expectedAddedNotifications[0].Content),
                                                    Times.Once);
        }
Пример #53
0
        private static int ExpandDl(Recipient dl, ref Dictionary<string, Recipient> selections)
        {
            var invalid = 0;
            Outlook.AddressEntry ae = null;
            try
            {
                ae = dl.AddressEntry;
            }
            catch (Exception ex)
            {
                Logger.Warning("ExpandDl", string.Format("failed to retrieve AddressEntry for {0}: {1}",
                    dl.Name, ex.Message));
            }
            if (ae == null) return 1;
            if (ae.Members == null || ae.Members.Count == 0) return 0;
            foreach (Outlook.AddressEntry member in ae.Members)
            {
                switch (member.AddressEntryUserType)
                {
                    case OlAddressEntryUserType.olExchangeOrganizationAddressEntry:
                    case OlAddressEntryUserType.olExchangePublicFolderAddressEntry:
                    case OlAddressEntryUserType.olExchangeRemoteUserAddressEntry:
                    case OlAddressEntryUserType.olOtherAddressEntry:
                    case OlAddressEntryUserType.olLdapAddressEntry:
                    case OlAddressEntryUserType.olExchangeAgentAddressEntry: //might be query-dl
                        invalid++;
                        break;
                    case OlAddressEntryUserType.olExchangeUserAddressEntry:
                    case OlAddressEntryUserType.olSmtpAddressEntry:
                    case OlAddressEntryUserType.olOutlookContactAddressEntry:
                        var smtp = member.GetPrimarySMTP();
                        if (string.IsNullOrEmpty(smtp))
                        {
                            invalid++;
                        }
                        else if (!selections.ContainsKey(smtp))
                        {
                            var recip = GenerateRecip(smtp, dl.Type, dl.Session);
                            if (recip != null)
                                selections.Add(smtp, recip);
                        }
                        break;
                    case OlAddressEntryUserType.olExchangeDistributionListAddressEntry:
                    case OlAddressEntryUserType.olOutlookDistributionListAddressEntry:

                        var memberRecip = GenerateRecip(member.Address, dl.Type, dl.Session);
                        if (memberRecip != null)
                            invalid += ExpandDl(memberRecip, ref selections);
                        break;
                }
            }
            return invalid;
        }
Пример #54
0
        /// <summary>
        /// Estra gli utenti coinvolti nel processo che devono essere notificati
        /// </summary>
        /// <param name="typeEvent"></param>
        /// <param name="dateEvent"></param>
        /// <param name="idObject"></param>
        /// <returns></returns>
        public List <Recipient> GetRecipientsUserInProcess(string typeEvent, string dateEvent, string idObject)
        {
            List <Recipient> listRecipients = new List <Recipient>();

            try
            {
                DataSet           ds = new DataSet();
                DocsPaUtils.Query q;
                string            queryString           = string.Empty;
                string            tipoEvento            = Utils.GetTypeEvent(typeEvent);
                string            conditionNotification = string.Empty;
                string            statoPasso            = string.Empty;
                #region RUOLO TITOLARE
                //Notifica al titolare del passo;
                //La notifica viene inviata all'utente che ha effettuato l'operazione; se invece il passo è automatico invio a tutto il ruolo
                switch (tipoEvento)
                {
                case SupportStructures.EventType.TRONCAMENTO_PROCESSO:
                    q = DocsPaUtils.InitQuery.getInstance().getQuery("S_USERS_ROLE_HOLDER_IN_PROCESS_ACTIVE");
                    break;

                case SupportStructures.EventType.PROCESSO_FIRMA:
                    q = DocsPaUtils.InitQuery.getInstance().getQuery("S_USERS_ROLE_HOLDER_PASSO_IN_ERRORE");
                    if (typeEvent.Equals(SupportStructures.EventType.PROCESSO_FIRMA_ERRORE_PASSO_AUTOMATICO))
                    {
                        statoPasso = " AND PA.STATO_PASSO = 'LOOK'";
                    }
                    break;

                default:
                    q = DocsPaUtils.InitQuery.getInstance().getQuery("S_USERS_ROLE_HOLDER_IN_PROCESS");
                    break;
                }

                q.setParam("typeEvent", typeEvent.ToString());
                q.setParam("dateEvent", DocsPaDbManagement.Functions.Functions.ToDate(dateEvent));
                q.setParam("idObject", idObject.ToString());
                q.setParam("statoPasso", statoPasso);

                queryString = q.getSQL();
                if (this.ExecuteQuery(out ds, "Recipients", queryString))
                {
                    if (ds.Tables["Recipients"] != null && ds.Tables["Recipients"].Rows.Count > 0)
                    {
                        foreach (DataRow row in ds.Tables["Recipients"].Rows)
                        {
                            Recipient recipient = new Recipient(Utils.ConvertField(row["ID_GRUPPO"].ToString()),
                                                                Utils.ConvertField(row["ID_PEOPLE"].ToString()));
                            bool isPresent = (from r in listRecipients
                                              where r.ID_ROLE.Equals(recipient.ID_ROLE) && r.ID_USER.Equals(recipient.ID_USER)
                                              select r).FirstOrDefault() != null;
                            if (!isPresent)
                            {
                                listRecipients.Add(recipient);
                            }
                        }
                    }
                }
                #endregion

                #region RUOLO PROPONENTE
                //Estraggo il ruolo avviatore per la notifica
                switch (tipoEvento)
                {
                case SupportStructures.EventType.TRONCAMENTO_PROCESSO:
                    q = DocsPaUtils.InitQuery.getInstance().getQuery("S_USER_ROLE_PROPONENT_IN_PROCESS_ACTIVE");
                    break;

                case SupportStructures.EventType.PROCESSO_FIRMA:
                    q = DocsPaUtils.InitQuery.getInstance().getQuery("S_USER_ROLE_PROPONENT_IN_PROCESS_ACTIVE");
                    if (typeEvent.Equals(SupportStructures.EventType.PROCESSO_FIRMA_ERRORE_PASSO_AUTOMATICO))
                    {
                        conditionNotification = "AND NOTIFICA_ERRORE = '1'";
                    }
                    if (typeEvent.Equals(SupportStructures.EventType.PROCESSO_FIRMA_DESTINATARI_NON_INTEROP))
                    {
                        conditionNotification = "AND NOTIFICA_DEST_NON_INTEROP = '1'";
                    }
                    break;

                case SupportStructures.EventType.CONCLUSIONE_PROCESSO:
                    q = DocsPaUtils.InitQuery.getInstance().getQuery("S_USER_ROLE_PROPONENT_IN_PROCESS");
                    conditionNotification = " NOTIFICA_CONCLUSO = '1'";
                    break;

                case SupportStructures.EventType.INTERROTTO_PROCESSO:
                    q = DocsPaUtils.InitQuery.getInstance().getQuery("S_USER_ROLE_PROPONENT_IN_PROCESS");
                    conditionNotification = " NOTIFICA_INTERROTTO = '1'";
                    break;
                }
                q.setParam("conditionNotification", conditionNotification);
                q.setParam("dateEvent", DocsPaDbManagement.Functions.Functions.ToDate(dateEvent));
                q.setParam("idObject", idObject.ToString());
                queryString = q.getSQL();
                if (this.ExecuteQuery(out ds, "Recipients", q.getSQL()))
                {
                    if (ds.Tables["Recipients"] != null && ds.Tables["Recipients"].Rows.Count > 0)
                    {
                        foreach (DataRow row in ds.Tables["Recipients"].Rows)
                        {
                            Recipient recipient = new Recipient(Utils.ConvertField(row["ID_GRUPPO"].ToString()),
                                                                Utils.ConvertField(row["ID_PEOPLE"].ToString()));
                            bool isPresent = (from r in listRecipients
                                              where r.ID_ROLE.Equals(recipient.ID_ROLE) && r.ID_USER.Equals(recipient.ID_USER)
                                              select r).FirstOrDefault() != null;
                            if (!isPresent)
                            {
                                listRecipients.Add(recipient);
                            }
                        }
                    }
                }
                #endregion

                #region MONITORATORE
                conditionNotification = string.Empty;
                switch (tipoEvento)
                {
                case SupportStructures.EventType.PROCESSO_FIRMA:
                    if (typeEvent.Equals(SupportStructures.EventType.PROCESSO_FIRMA_ERRORE_PASSO_AUTOMATICO))
                    {
                        conditionNotification = " AND NOTIFICA_ERRORE = '1'";
                    }
                    if (typeEvent.Equals(SupportStructures.EventType.PROCESSO_FIRMA_DESTINATARI_NON_INTEROP))
                    {
                        conditionNotification = " AND NOTIFICA_DEST_NON_INTEROP = '1'";
                    }
                    break;

                case SupportStructures.EventType.CONCLUSIONE_PROCESSO:
                    conditionNotification = " AND NOTIFICA_CONCLUSO = '1'";
                    break;

                case SupportStructures.EventType.INTERROTTO_PROCESSO:
                    conditionNotification = " AND NOTIFICA_INTERROTTO = '1'";
                    break;
                }
                //Qualunque notifica va anche notificata al monitoratore del processo fatta eccezione di quella dei destinatari interoperanti
                q = DocsPaUtils.InitQuery.getInstance().getQuery("S_ROLE_MONITORATORE_PROCESS");
                q.setParam("dateEvent", DocsPaDbManagement.Functions.Functions.ToDate(dateEvent));
                q.setParam("idObject", idObject.ToString());
                q.setParam("conditionNotification", conditionNotification);
                queryString = q.getSQL();
                if (this.ExecuteQuery(out ds, "Recipients", q.getSQL()))
                {
                    if (ds.Tables["Recipients"] != null && ds.Tables["Recipients"].Rows.Count > 0)
                    {
                        foreach (DataRow row in ds.Tables["Recipients"].Rows)
                        {
                            Recipient recipient = new Recipient(Utils.ConvertField(row["ID_GRUPPO"].ToString()), Utils.ConvertField(row["ID_PEOPLE"].ToString()));
                            bool      isPresent = (from r in listRecipients
                                                   where r.ID_ROLE.Equals(recipient.ID_ROLE) && r.ID_USER.Equals(recipient.ID_USER)
                                                   select r).FirstOrDefault() != null;
                            if (!isPresent)
                            {
                                listRecipients.Add(recipient);
                            }
                        }
                    }
                }
                #endregion
            }
            catch (Exception exc)
            {
                // traccia l'eccezione nel file di log
                File.AppendAllText("C:\\ServiceNotification\\ErrorTrace.txt", "---------------------\nException in " +
                                   ConfigurationManager.AppSettings["name_service"] + "\n" +
                                   exc.StackTrace + "\n\n" + exc.Message + "\n---------------------\n\n");

                listRecipients = new List <Recipient>();
                throw exc;
            }

            return(listRecipients);
        }
        private Recipient[] ConstructRecipients()
        {
            // Construct the recipients
            var runningList = new List<Recipient>();

            for (int i = 1; i <= Request.Form.Count; i++)
            {
                if (null !=Request.Form[Keys.RecipientName + i])
                {
                    var r = new Recipient
                        {
                            UserName = Request.Form[Keys.RecipientName + i],
                            Email = Request.Form[Keys.RecipientEmail + i]
                        };

                    // Get and set the security settings
                    string security = Request.Form[Keys.RecipientSecurity + i];
                    if (null != security)
                    {
                        switch (security)
                        {
                            case "AccessCode":
                                r.AccessCode = Request.Form[Keys.RecipientSecuritySetting + i].ToString();
                                break;
                            case "PhoneAuthentication":
                                r.PhoneAuthentication = new RecipientPhoneAuthentication
                                    {
                                        RecipMayProvideNumber = true,
                                        RecipMayProvideNumberSpecified = true,
                                        RecordVoicePrint = true,
                                        RecordVoicePrintSpecified = true
                                    };
                                r.IDCheckConfigurationName = "Phone Auth $";
                                break;
                            case "IDCheck":
                                r.RequireIDLookup = true;
                                r.RequireIDLookupSpecified = true;
                                r.IDCheckConfigurationName = "ID Check $";
                                break;
                        }
                    }
                    r.ID = i.ToString();
                    r.Type = RecipientTypeCode.Signer;

                    if (null == Request.Form[Keys.RecipientInviteToggle + i])
                    {
                        // we want an embedded signer
                        r.CaptiveInfo = new RecipientCaptiveInfo {ClientUserId = i.ToString()};
                    }
                    runningList.Add(r);
                }
                else
                {
                    break;
                }
            }
            return runningList.ToArray();
        }
 public MAPIFolder GetSharedDefaultFolder(Recipient Recipient, OlDefaultFolders FolderType)
 {
     throw new NotImplementedException();
 }
            /// <summary>
            /// Processes sub storages on the specified storage to capture attachment and recipient data.
            /// </summary>
            /// <param name="storage">The storage to check for attachment and recipient data.</param>
            protected override void LoadStorage(NativeMethods.IStorage storage)
            {
                base.LoadStorage(storage);

                foreach (ComTypes.STATSTG storageStat in this.subStorageStatistics.Values)
                {
                    //element is a storage. get it and add its statistics object to the sub storage dictionary
                    NativeMethods.IStorage subStorage = this.storage.OpenStorage(storageStat.pwcsName, IntPtr.Zero, NativeMethods.STGM.READ | NativeMethods.STGM.SHARE_EXCLUSIVE, IntPtr.Zero, 0);

                    //run specific load method depending on sub storage name prefix
                    if (storageStat.pwcsName.StartsWith(OutlookStorage.RECIP_STORAGE_PREFIX))
                    {
                        Recipient recipient = new Recipient(new OutlookStorage(subStorage));
                        this.recipients.Add(recipient);
                    }
                    else if (storageStat.pwcsName.StartsWith(OutlookStorage.ATTACH_STORAGE_PREFIX))
                    {
                        this.LoadAttachmentStorage(subStorage);
                    }
                    else
                    {
                        //release sub storage
                        Marshal.ReleaseComObject(subStorage);
                    }
                }
            }
Пример #58
0
        public async Task <uint256> SendManyAsync(string fromAccount, string addressesJson, int minConf = 1, string comment = null, string subtractFeeFromJson = null, bool isReplaceable = false, int?confTarget = null, string estimateMode = "UNSET")
        {
            if (string.IsNullOrEmpty(addressesJson))
            {
                throw new RPCServerException(RPCErrorCode.RPC_INVALID_PARAMETER, "No valid output addresses specified.");
            }

            var addresses = new Dictionary <string, decimal>();

            try
            {
                // Outputs addresses are key-value pairs of address, amount. Translate to Receipient list.
                addresses = JsonConvert.DeserializeObject <Dictionary <string, decimal> >(addressesJson);
            }
            catch (JsonSerializationException ex)
            {
                throw new RPCServerException(RPCErrorCode.RPC_PARSE_ERROR, ex.Message);
            }

            if (addresses.Count == 0)
            {
                throw new RPCServerException(RPCErrorCode.RPC_INVALID_PARAMETER, "No valid output addresses specified.");
            }

            // Optional list of addresses to subtract fees from.
            IEnumerable <BitcoinAddress> subtractFeeFromAddresses = null;

            if (!string.IsNullOrEmpty(subtractFeeFromJson))
            {
                try
                {
                    subtractFeeFromAddresses = JsonConvert.DeserializeObject <List <string> >(subtractFeeFromJson).Select(i => BitcoinAddress.Create(i, this.FullNode.Network));
                }
                catch (JsonSerializationException ex)
                {
                    throw new RPCServerException(RPCErrorCode.RPC_PARSE_ERROR, ex.Message);
                }
            }

            var recipients = new List <Recipient>();

            foreach (var address in addresses)
            {
                // Check for duplicate recipients
                var recipientAddress = BitcoinAddress.Create(address.Key, this.FullNode.Network).ScriptPubKey;
                if (recipients.Any(r => r.ScriptPubKey == recipientAddress))
                {
                    throw new RPCServerException(RPCErrorCode.RPC_INVALID_PARAMETER, string.Format("Invalid parameter, duplicated address: {0}.", recipientAddress));
                }

                var recipient = new Recipient
                {
                    ScriptPubKey          = recipientAddress,
                    Amount                = Money.Coins(address.Value),
                    SubtractFeeFromAmount = subtractFeeFromAddresses == null ? false : subtractFeeFromAddresses.Contains(BitcoinAddress.Create(address.Key, this.FullNode.Network))
                };

                recipients.Add(recipient);
            }

            WalletAccountReference accountReference = this.GetWalletAccountReference();

            var context = new TransactionBuildContext(this.FullNode.Network)
            {
                AccountReference = accountReference,
                MinConfirmations = minConf,
                Shuffle          = true, // We shuffle transaction outputs by default as it's better for anonymity.
                Recipients       = recipients,
                CacheSecret      = false
            };

            // Set fee type for transaction build context.
            context.FeeType = FeeType.Medium;

            if (estimateMode.Equals("ECONOMICAL", StringComparison.InvariantCultureIgnoreCase))
            {
                context.FeeType = FeeType.Low;
            }
            else if (estimateMode.Equals("CONSERVATIVE", StringComparison.InvariantCultureIgnoreCase))
            {
                context.FeeType = FeeType.High;
            }

            try
            {
                // Log warnings for currently unsupported parameters.
                if (!string.IsNullOrEmpty(comment))
                {
                    this.logger.LogWarning("'comment' parameter is currently unsupported. Ignored.");
                }

                if (isReplaceable)
                {
                    this.logger.LogWarning("'replaceable' parameter is currently unsupported. Ignored.");
                }

                if (confTarget != null)
                {
                    this.logger.LogWarning("'conf_target' parameter is currently unsupported. Ignored.");
                }

                Transaction transaction = this.walletTransactionHandler.BuildTransaction(context);
                await this.broadcasterManager.BroadcastTransactionAsync(transaction);

                return(transaction.GetHash());
            }
            catch (SecurityException)
            {
                throw new RPCServerException(RPCErrorCode.RPC_WALLET_UNLOCK_NEEDED, "Wallet unlock needed");
            }
            catch (WalletException exception)
            {
                throw new RPCServerException(RPCErrorCode.RPC_WALLET_ERROR, exception.Message);
            }
            catch (NotImplementedException exception)
            {
                throw new RPCServerException(RPCErrorCode.RPC_MISC_ERROR, exception.Message);
            }
        }
Пример #59
0
        private Recipient[] ConstructRecipients()
        {
            // Construct the recipients
            var runningList = new List <Recipient>();

            for (int i = 1; i <= Request.Form.Count; i++)
            {
                if (null != Request.Form[Keys.RecipientName + i])
                {
                    var r = new Recipient
                    {
                        UserName = Request.Form[Keys.RecipientName + i],
                        Email    = Request.Form[Keys.RecipientEmail + i]
                    };

                    // Get and set the security settings
                    string security = Request.Form[Keys.RecipientSecurity + i];
                    if (null != security)
                    {
                        switch (security)
                        {
                        case "AccessCode":
                            r.AccessCode = Request.Form[Keys.RecipientSecuritySetting + i].ToString();
                            break;

                        case "PhoneAuthentication":
                            r.PhoneAuthentication = new RecipientPhoneAuthentication
                            {
                                RecipMayProvideNumber          = true,
                                RecipMayProvideNumberSpecified = true,
                                RecordVoicePrint          = true,
                                RecordVoicePrintSpecified = true
                            };
                            r.IDCheckConfigurationName = "Phone Auth $";
                            break;

                        case "IDCheck":
                            r.RequireIDLookup          = true;
                            r.RequireIDLookupSpecified = true;
                            r.IDCheckConfigurationName = "ID Check $";
                            break;
                        }
                    }
                    r.ID   = i.ToString();
                    r.Type = RecipientTypeCode.Signer;

                    if (null == Request.Form[Keys.RecipientInviteToggle + i])
                    {
                        // we want an embedded signer
                        r.CaptiveInfo = new RecipientCaptiveInfo {
                            ClientUserId = i.ToString()
                        };
                    }
                    runningList.Add(r);
                }
                else
                {
                    break;
                }
            }
            return(runningList.ToArray());
        }
Пример #60
0
 /// <summary>
 /// Asynchronously retrieve all permissions associated with the user calling this method.
 /// </summary>
 /// <returns>
 /// A queryable collection of <see cref="Permission"/> objects that provide detailed information
 /// regarding the granted access.
 /// </returns>
 /// <param name="recipient">The optional recipient of the permission.</param>
 /// <param name="millisecondTimeout">
 /// The timeout in milliseconds for downloading server changes. If the download times out, no error will be thrown
 /// and instead the latest local state will be returned. If set to 0, the latest state will be returned immediately.
 /// </param>
 /// <remarks>
 /// The collection is a live query, similar to what you would get by calling <see cref="Realm.All"/>, so the same
 /// features and limitations apply - you can query and subscribe for notifications, but you cannot pass it between
 /// threads.
 /// </remarks>
 public Task <IQueryable <Permission> > GetGrantedPermissionsAsync(Recipient recipient = Recipient.Any, int millisecondTimeout = 2000)
 {
     RealmPCLHelpers.ThrowProxyShouldNeverBeUsed();
     return(null);
 }