예제 #1
0
        public Response <MentorshipVM> SetContactDetails([FromBody] ContactUpdate ContactUpdate)
        {
            var service = new Services.Relationships.MentorshipService(Context, CurrentUser);

            LogService.Write("Save Contact Details", String.Format("User:{0};Mentorship:{1}", ContactUpdate.UserId, ContactUpdate.MentorshipId));
            return(new Response <MentorshipVM>(service.SetContactDetails(ContactUpdate)));
        }
예제 #2
0
        public MentorshipVM SetContactDetails(ContactUpdate contactDetails)
        {
            if (contactDetails.UserId == this.Actor.UserId || this.Actor.Roles.Contains("Admin"))
            {
                var dbMentorship = this.mainContext.Mentorships.Where(m => m.MentorshipId == contactDetails.MentorshipId).FirstOrDefault();

                if (
                    dbMentorship != null &&
                    (
                        dbMentorship.LearnerUserId == contactDetails.UserId ||
                        dbMentorship.MentorUserId == contactDetails.UserId
                    )
                    )
                {
                    if (dbMentorship.LearnerUserId == contactDetails.UserId)
                    {
                        dbMentorship.LearnerContact = contactDetails.ContactDetails;
                    }
                    else if (dbMentorship.MentorUserId == contactDetails.UserId)
                    {
                        dbMentorship.MentorContact = contactDetails.ContactDetails;
                    }

                    this.mainContext.Mentorships.Update(dbMentorship);
                    this.mainContext.SaveChanges();
                }
            }

            return(GetMentorship(contactDetails.MentorshipId));
        }
예제 #3
0
        protected static ContactUpdate getExisitingCustomerContactDetails(String CustID)
        {
            var obj = new ContactUpdate();

            String strCompanyName = "";
            String CustomerName   = "";

            String CustomerShipAddressLine1 = "";
            String CustomerShipCity         = "";
            String CustomerShipPostcode     = "";
            String CustomerShipState        = "";

            String CustomerContactNumber = "";
            String CustomerEmail         = "";


            using (SqlConnection conn = new SqlConnection())
            {
                conn.ConnectionString = ConfigurationManager.ConnectionStrings["ConnStringDeltoneCRM"].ConnectionString;
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.CommandText = "SELECT CT.*, CP.CompanyName FROM dbo.Contacts CT, dbo.Companies CP WHERE CT.CompanyID = CP.CompanyID AND CP.CompanyID = " + CustID;
                    cmd.Connection  = conn;
                    conn.Open();

                    using (SqlDataReader sdr = cmd.ExecuteReader())
                    {
                        while (sdr.Read())
                        {
                            strCompanyName = sdr["CompanyName"].ToString();
                            CustomerName   = sdr["FirstName"].ToString();
                            var lastName = sdr["LastName"].ToString();


                            CustomerShipAddressLine1 = sdr["STREET_AddressLine1"].ToString();
                            CustomerShipCity         = sdr["STREET_City"].ToString();
                            CustomerShipPostcode     = sdr["STREET_PostalCode"].ToString();
                            CustomerShipState        = sdr["STREET_Region"].ToString();

                            CustomerContactNumber = sdr["DEFAULT_AreaCode"].ToString() + ' ' + sdr["DEFAULT_Number"].ToString();
                            CustomerEmail         = sdr["Email"].ToString();
                            obj.CompanyName       = strCompanyName;
                            obj.ComId             = Convert.ToInt32(CustID);
                            obj.Address1          = CustomerShipAddressLine1;
                            obj.City          = CustomerShipCity;
                            obj.Email         = CustomerEmail;
                            obj.FirstName     = CustomerName;
                            obj.LastName      = lastName;
                            obj.AreaCode      = sdr["DEFAULT_AreaCode"].ToString();
                            obj.DefaultNumber = sdr["DEFAULT_Number"].ToString();
                            obj.Phone         = sdr["MOBILE_Number"].ToString();
                            obj.PostCode      = CustomerShipPostcode;
                            obj.State         = CustomerShipState;
                        }
                    }
                }
            }

            return(obj);
        }
예제 #4
0
        public async Task <IActionResult> UpdateContact([FromRoute] Guid contactId, [FromBody] ContactUpdate contactUpdate)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            contactUpdate.Id            = contactId;
            contactUpdate.UpdatedUserId = _claimsUser.UserId;

            var updateResult = await _contactService.UpdateContact(contactUpdate);

            if (updateResult.IsBadRequest)
            {
                return(BadRequest(updateResult.ErrorMessage));
            }
            else if (updateResult.Data.Value)
            {
                return(Ok());
            }
            else //if (!deleteResult.Data.Value)
            {
                return(NotFound());
            }
        }
예제 #5
0
        private static void UpdateCom_Contacts(ContactUpdate obj)
        {
            using (SqlConnection conn = new SqlConnection())
            {
                conn.ConnectionString = ConfigurationManager.ConnectionStrings["ConnStringDeltoneCRM"].ConnectionString;
                using (SqlCommand cmd = new SqlCommand())
                {
                    var strSqlContactStmt = @"UPDATE Contacts SET FirstName=@FirstName, LastName=@LastName , AlteredBy=@AlteredBy ,
                                              STREET_AddressLine1=@STREET_AddressLine1, STREET_City=@STREET_City,DEFAULT_Number=@DEFAULT_Number,DEFAULT_AreaCode=@DEFAULT_AreaCode ,MOBILE_Number=@Mobile_Number , Email=@Email ,
                                             STREET_PostalCode=@STREET_PostalCode, STREET_Region=@STREET_Region,AlteredDateTime=CURRENT_TIMESTAMP 
                                                WHERE CompanyID=@ContactID";

                    cmd.Connection = conn;
                    conn.Open();
                    cmd.CommandText = strSqlContactStmt;
                    cmd.Parameters.Add("@FirstName", SqlDbType.VarChar).Value            = obj.FirstName;
                    cmd.Parameters.Add("@LastName", SqlDbType.VarChar).Value             = obj.LastName;
                    cmd.Parameters.Add("@AlteredBy", SqlDbType.NVarChar).Value           = HttpContext.Current.Session["LoggedUser"].ToString();
                    cmd.Parameters.Add("@STREET_AddressLine1", SqlDbType.NVarChar).Value = obj.Address1;
                    cmd.Parameters.Add("@STREET_City", SqlDbType.NVarChar).Value         = obj.City;
                    cmd.Parameters.Add("@STREET_PostalCode", SqlDbType.NVarChar).Value   = obj.PostCode;
                    cmd.Parameters.Add("@STREET_Region", SqlDbType.NVarChar).Value       = obj.State;
                    cmd.Parameters.Add("@Mobile_Number", SqlDbType.NVarChar).Value       = obj.Phone;
                    cmd.Parameters.Add("@DEFAULT_AreaCode", SqlDbType.NVarChar).Value    = obj.AreaCode;
                    cmd.Parameters.Add("@DEFAULT_Number", SqlDbType.NVarChar).Value      = obj.DefaultNumber;
                    cmd.Parameters.Add("@Email", SqlDbType.NVarChar).Value = obj.Email;
                    cmd.Parameters.Add("@ContactID", SqlDbType.Int).Value  = obj.ComId;

                    cmd.ExecuteNonQuery();

                    conn.Close();
                }
            }
        }
예제 #6
0
        private async void Button_Clicked(object sender, EventArgs e)
        {
            var cnt = BindingContext as contact;

            if (cnt.FirstName == null)
            {
                await DisplayAlert("Alert", "Firstname should not be empty", "ok");

                return;
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(cnt.Id.ToString()))
                {
                    //await DisplayAlert("Alert", cnt.FirstName, "ok");
                    cnt.Id = 1;
                    ContactAdded?.Invoke(this, cnt);
                    await Navigation.PopModalAsync();
                }
                else
                {
                    //await DisplayAlert("new", cnt.FirstName, "ok");

                    ContactUpdate?.Invoke(this, cnt);
                    await Navigation.PopModalAsync();
                }
            }
        }
        public static MappingResult Map(Dictionary <string, string> messageHeaders, byte[] crmRawMessage)
        {
            // Deserialize CRM message into RemoteExecutionContext
            var stream = new MemoryStream(crmRawMessage);
            var remoteExecutionContext = (RemoteExecutionContext) new DataContractJsonSerializer(typeof(RemoteExecutionContext)).ReadObject(stream);

            //Get the Entity and Action from the header in the raw CRM message from Azure.
            var entityName   = messageHeaders["http://schemas.microsoft.com/xrm/2011/Claims/EntityLogicalName"];
            var entityAction = messageHeaders["http://schemas.microsoft.com/xrm/2011/Claims/RequestName"];

            var mapperTypeName = entityName.ToLower() + entityAction.ToLower();

            IMessage targetMessage;

            switch (mapperTypeName)
            {
            case "contactcreate":
                targetMessage = new ContactCreate(remoteExecutionContext);
                break;

            case "contactupdate":
                targetMessage = new ContactUpdate(remoteExecutionContext);
                break;

            default:
                //if we don't have a mapper, throw this exception.  It is configured as non-recoverable in the adapter endpoint and won't trigger retry.
                throw new MapperNotFoundException($"A mapping class is not configured for the entity {entityName} and action {entityAction}.");
            }

            // serialize the message
            var serializedObject = JsonConvert.SerializeObject(targetMessage);
            var bytes            = System.Text.Encoding.UTF8.GetBytes(serializedObject);

            return(new MappingResult(bytes, targetMessage.GetType().FullName));
        }
예제 #8
0
    public ContactItem(ContactUpdate.Types.Client client)
    {
      InitializeComponent();
      this.m_clientContact = new Contact(client.ClientId);
      this.m_clientContact.onDataUpdate += this.OnDataUpdated;

      this.m_clientContact.SetUsername(client.Name, client.Surname);
      this.m_clientContact.Status = client.Online;
    }
예제 #9
0
        public IActionResult Update(ContactUpdate contactUpdate)
        {
            var result = _contactUpdateService.Update(contactUpdate);

            if (result.Success)
            {
                return(Ok(result));
            }
            return(BadRequest(result));
        }
예제 #10
0
 public IActionResult UpdateContact(ContactUpdate Contact)
 {
     try
     {
         return(new JsonResult(ContactBAL.UpdateContact(Contact)));
     }
     catch (Exception ex)
     {
         return(StatusCode(StatusCodes.Status500InternalServerError, "Failed to update Contact"));
     }
 }
예제 #11
0
        public static bool IsValidNumber(ContactUpdate instance, string number)
        {
            if (string.IsNullOrWhiteSpace(number))
            {
                return(true);
            }

            var  pn = number.Trim().Replace(" ", "").Replace("-", "");
            long nu;

            return(long.TryParse(pn, out nu));
        }
예제 #12
0
        public async Task <Result> UpdateAsync(Guid id, ContactUpdate contact)
        {
            var result = await Task.Run(() =>
            {
                var result          = new Result();
                var existed_contact = _contactRepository.Get(id);
                if (existed_contact == null)
                {
                    result.IsError   = true;
                    result.Message   = "Contact does not exist for give Id";
                    result.StatuCode = 400;
                }
                else
                {
                    var c = contact.GetContact();

                    var title = _titleRepository.Find(new TitleExistSpecification(contact.Title).SpecExpression()).FirstOrDefault();

                    if (title == null)
                    {
                        var titles       = _titleRepository.GetAll();
                        result.Message   = $"Provided title is not supported: Supported titles: {string.Join(", ", titles)}";
                        result.StatuCode = 400;
                    }
                    else
                    {
                        // c.Title = title;
                        c.TitleId = title.Id;
                        c.Id      = id;
                        try
                        {
                            _contactRepository.Update(id, c);
                        }
                        catch (CrmException ex)
                        {
                            result.IsError   = true;
                            result.Message   = ex.Message;
                            result.StatuCode = 400;
                        }
                        catch (Exception)
                        {
                            throw;
                        }
                    }
                }

                return(result);
            });

            return(result);
        }
예제 #13
0
        public static bool OnePhoneNumberIsRequired(ContactUpdate contact, string number)
        {
            var mpn = contact.MobileNumber;
            var pn  = contact.PhoneNumber;

            var isEmpty = !string.IsNullOrWhiteSpace(mpn);

            if (!isEmpty)
            {
                isEmpty = !string.IsNullOrWhiteSpace(pn);
            }

            return(!string.IsNullOrWhiteSpace(mpn) || !string.IsNullOrWhiteSpace(pn));
        }
예제 #14
0
 public void UpdateTransaction(TaskCard taskCard)
 {
     contactUpdate = new FinancialPlanner.Common.JSONSerialization().DeserializeFromString <ContactUpdate>(taskCard.TaskTransactionType.ToString());
     DataBase.DBService.ExecuteCommandString(string.Format(UPDATE_CONTACT,
                                                           taskCard.Id,
                                                           contactUpdate.Arn,
                                                           contactUpdate.Cid,
                                                           contactUpdate.MemberName,
                                                           contactUpdate.Amc,
                                                           contactUpdate.FolioNumber,
                                                           contactUpdate.NewEmailId,
                                                           contactUpdate.NewMobileNo,
                                                           contactUpdate.ModeOfExecution,
                                                           taskCard.Id), true);
 }
예제 #15
0
        public Contact UpdateContact(ContactUpdate contact)
        {
            using (SqlConnection connection = new SqlConnection(DefaultConnection))
            {
                DynamicParameters p = new DynamicParameters();
                p.Add("businessid", contact.BusinessID);
                p.Add("customerid", contact.CustomerID);
                p.Add("fullname", contact.FullName);
                p.Add("email", contact.Email);
                p.Add("title", contact.Title);
                p.Add("updatedby", contact.UpdatedBy);
                Contact result = connection.Query <Contact>("spUpdateContact", p, commandType: CommandType.StoredProcedure).Single();

                return(result);
            }
        }
예제 #16
0
        private ContactUpdate converToBankchangeRequest(DataRow dr)
        {
            ContactUpdate contactUpdate = new ContactUpdate();

            contactUpdate.Id              = dr.Field <int>("ID");
            contactUpdate.TaskId          = dr.Field <int>("TaskId");
            contactUpdate.Cid             = dr.Field <int>("CID");
            contactUpdate.Arn             = dr.Field <int>("ARN");
            contactUpdate.MemberName      = dr.Field <string>("MemberName");
            contactUpdate.Amc             = dr.Field <int>("AMC");
            contactUpdate.FolioNumber     = dr.Field <string>("FolioNumber");
            contactUpdate.NewEmailId      = dr.Field <string>("NewEmailId");
            contactUpdate.NewMobileNo     = dr.Field <string>("NewMobileNo");
            contactUpdate.ModeOfExecution = dr.Field <string>("ModeOfExecution");
            return(contactUpdate);
        }
예제 #17
0
        public void TestContactUpdateCommandNominetPrivacyOn()
        {
            string expected = File.ReadAllText("ContactUpdateCommandNominetPrivacyOn.xml");//set a new file

            ContactChange contactChange = new ContactChange();

            contactChange.DiscloseFlag = false;
            contactChange.DiscloseMask = ~Contact.DiscloseFlags.OrganizationInt & ~Contact.DiscloseFlags.AddressInt;

            var command = new ContactUpdate("CONTACT-1234");

            command.ContactChange = contactChange;

            command.TransactionId = "ABC-12345";
            command.Password      = "******";
            Assert.AreEqual(expected, command.ToXml().InnerXml);
        }
예제 #18
0
        public void GetXmlTest()
        {
            string expected = @"<?xml version=""1.0"" encoding=""utf-8""?>
<function controlid=""unittest"">
    <update>
        <CONTACT>
            <CONTACTNAME>hello</CONTACTNAME>
        </CONTACT>
    </update>
</function>";

            ContactUpdate record = new ContactUpdate("unittest")
            {
                ContactName = "hello"
            };

            this.CompareXml(expected, record);
        }
예제 #19
0
        public void FuryContactUpdateWithPrivacy()
        {
            string expected = File.ReadAllText("FuryContactUpdateCommand.xml");

            var command = new ContactUpdate("agreed2");

            //change contact email and language
            var contactChange = new ContactChange();

            contactChange.Email = "*****@*****.**";

            command.ContactChange = contactChange;

            command.Extensions.Add(new FuryContactUpdateExtension("en", "fr"));

            var xml = command.ToXml().InnerXml;

            Assert.AreEqual(expected, xml);
        }
예제 #20
0
        public async Task <IActionResult> Put(Guid id, [FromBody] ContactUpdate contact)
        {
            try
            {
                var result = await _contactService.UpdateAsync(id, contact);

                if (result.IsError)
                {
                    result.StatuCode = 400;
                    return(BadRequest(result));
                }
                return(Ok(result));
            }
            catch (CrmException ex)
            {
                _logger.LogError(ex, "Error has encounterd");
                return(StatusCode(500));
            }// general exception should be handled by ExceptionMiddleware
        }
예제 #21
0
        public ActionResult ShowUser(ContactUpdate update)
        {
            User       user          = new User();
            var        error_message = new object();
            JsonResult json          = new JsonResult();

            if (string.IsNullOrWhiteSpace(update.contactUpdateHidden))
            {
                error_message = "error, could not update click";
                return(Json(error_message, "application/json; charset=utf-8", Encoding.UTF8, JsonRequestBehavior.DenyGet));
            }

            var id = Guid.Parse(update.contactUpdateHidden);

            using (var api = new HttpClient())
            {
                api.BaseAddress = new Uri("https://localhost:44343/api/user/");
                api.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var get_user = api.PostAsJsonAsync <Guid>("show/id", id);
                get_user.Wait();
                var result = get_user.Result;
                if (result.StatusCode == HttpStatusCode.OK)
                {
                    var s = result.Content.ReadAsAsync <User>();
                    s.Wait();
                    user = s.Result;
                }
                else if (result.StatusCode == HttpStatusCode.NotFound)
                {
                    var s = result.Content.ReadAsAsync <User>();
                    s.Wait();
                    user = s.Result;
                }
            }

            error_message        = user;
            json.Data            = error_message;
            json.ContentEncoding = Encoding.UTF8;
            json.ContentType     = "application/json; charset=utf-8";
            json.MaxJsonLength   = int.MaxValue;
            return(json);
        }
예제 #22
0
        private async void Button_Clicked(object sender, EventArgs e)
        {
            var contact = BindingContext as ContactEj;

            if (String.IsNullOrWhiteSpace(contact.FirstName))
            {
                await DisplayAlert("Error", "Por favor ingrese el nombre.", "OK");

                return;
            }

            if (contact.Id > 0)
            {
                ContactUpdate.Invoke(this, contact);
            }
            else
            {
                ContactAdded.Invoke(this, contact);
            }
        }
예제 #23
0
        async private void saveBtn_Clicked(object sender, EventArgs e)
        {
            var contact = BindingContext as Contact;

            if (string.IsNullOrEmpty(contact.FirstName) && string.IsNullOrEmpty(contact.LastName))
            {
                await DisplayAlert("Validation failed", "Please enter the name", "OK");
            }
            else
            {
                if (contact.Id == null)
                {
                    ContactAdd?.Invoke(this, contact);
                }
                else
                {
                    ContactUpdate?.Invoke(this, contact);
                }
                await Navigation.PopAsync();
            }
        }
예제 #24
0
        public static bool IsCheckLength(ContactUpdate contact, string number)
        {
            // not empty
            var mpn = !string.IsNullOrWhiteSpace(contact.MobileNumber);
            var pn  = !string.IsNullOrWhiteSpace(contact.PhoneNumber);

            // if phone number or mobile number is not empty
            var isOk = OnePhoneNumberIsRequired(contact, number);

            if (isOk && mpn)
            {
                isOk = contact.MobileNumber.Length >= 7 && contact.MobileNumber.Length <= 16;
            }

            if (isOk && pn)
            {
                isOk = contact.PhoneNumber.Length >= 7 && contact.PhoneNumber.Length <= 16;
            }

            return(isOk);
        }
예제 #25
0
        public object GetTransaction(int id)
        {
            try
            {
                Logger.LogInfo("Get: Bank change request transaction process start");
                contactUpdate = new ContactUpdate();

                DataTable dtAppConfig = DataBase.DBService.ExecuteCommand(string.Format(SELECT_BY_ID, id));
                foreach (DataRow dr in dtAppConfig.Rows)
                {
                    contactUpdate = converToBankchangeRequest(dr);
                }
                Logger.LogInfo("Get: Bank change request transaction process completed.");
                return(contactUpdate);
            }
            catch (Exception ex)
            {
                StackTrace st = new StackTrace();
                StackFrame sf = st.GetFrame(0);
                MethodBase currentMethodName = sf.GetMethod();
                LogDebug(currentMethodName.Name, ex);
                return(null);
            }
        }
예제 #26
0
        public Contact Update(string id, ContactUpdate contact)
        {
            if (contact == null)
            {
                throw new ArgumentNullException(nameof(contact));
            }
            if (contact == null)
            {
                throw new ArgumentNullException(nameof(contact));
            }

            ClientResponse <Contact> result = null;
            String body = Serialize <ContactUpdate>(contact);

            if (string.IsNullOrEmpty(id))
            {
                result = Post <Contact>(body);
            }
            else
            {
                result = Put <Contact>(body, resource: CONTACTS_RESOURCE + Path.DirectorySeparatorChar + id);
            }
            return(result.Result);
        }
예제 #27
0
        public void GetXmlTest()
        {
            string expected = @"<?xml version=""1.0"" encoding=""utf-8""?>
<function controlid=""unittest"">
    <update>
        <CONTACT>
            <CONTACTNAME>hello</CONTACTNAME>
        </CONTACT>
    </update>
</function>";

            Stream            stream      = new MemoryStream();
            XmlWriterSettings xmlSettings = new XmlWriterSettings();

            xmlSettings.Encoding    = Encoding.UTF8;
            xmlSettings.Indent      = true;
            xmlSettings.IndentChars = "    ";

            IaXmlWriter xml = new IaXmlWriter(stream, xmlSettings);

            ContactUpdate record = new ContactUpdate("unittest");

            record.ContactName = "hello";

            record.WriteXml(ref xml);

            xml.Flush();
            stream.Position = 0;
            StreamReader reader = new StreamReader(stream);

            Diff xmlDiff = DiffBuilder.Compare(expected).WithTest(reader.ReadToEnd())
                           .WithDifferenceEvaluator(DifferenceEvaluators.Default)
                           .Build();

            Assert.IsFalse(xmlDiff.HasDifferences(), xmlDiff.ToString());
        }
예제 #28
0
 public IResult Update(ContactUpdate contactUpdate)
 {
     _contactUpdateDal.Update(contactUpdate);
     return(new SuccessResult());
 }
예제 #29
0
        public void TestContactUpdateCommandNominetPrivacyOn()
        {
            string expected = File.ReadAllText("ContactUpdateCommandNominetPrivacyOn.xml");//set a new file

            ContactChange contactChange = new ContactChange();
            contactChange.DiscloseFlag = false;
            contactChange.DiscloseMask = ~Contact.DiscloseFlags.OrganizationInt & ~Contact.DiscloseFlags.AddressInt;

            var command = new ContactUpdate("CONTACT-1234");
            command.ContactChange = contactChange;

            command.TransactionId = "ABC-12345";
            command.Password = "******";
            Assert.AreEqual(expected, command.ToXml().InnerXml);
        }
예제 #30
0
 public static void UpdateContact(ContactUpdate obj)
 {
     UpdateCom_Contacts(obj);
 }
예제 #31
0
        private void CiraTecnicalTest()
        {
            var tcpTransport = new TcpTransport("epp.test.cira.ca", 700, new X509Certificate("cert.pfx", "password"), true);

            var service = new Service(tcpTransport);

            //1. SSL connection establishment
            Console.WriteLine("TEST: 1");
            service.Connect();

            //2. EPP <login> command with your ‘a’ account
            Console.WriteLine("TEST: 2");
            var logingCmd = new Login("username", "password");

            var response = service.Execute(logingCmd);

            PrintResponse(response);

            //3. Using the correct EPP call, get the latest CIRA Registrant Agreement
            Console.WriteLine("TEST: 3");
            var agreementCmd = new GetAgreement();

            var getAgreementResponse = service.Execute(agreementCmd);

            var agreementVersion = getAgreementResponse.AgreementVersion;
            var agreementText = getAgreementResponse.Agreement;
            var agreementLanguage = getAgreementResponse.Language;

            PrintResponse(response);
            Console.WriteLine("Agreement Version:{0}", agreementVersion);
            /*
             4. Create a Registrant contact using: 
                -the same ID as your Registrar Number prefixed with the word ‘rant’ (e.g. rant75)
                -CPR category CCT
                -Full postal information, phone number, fax number, and email address
                -Agreed to latest CIRA Registrant Agreement version
             */
            Console.WriteLine("TEST: 4");
            var registrantContact = new Contact("rant" + registrarNumber,
                "Registrant Step Four", "Example Inc.",
                "Toronto", "301 La Fanfan Ave.", "ON", "M5V 3T1", "CA",
                "*****@*****.**",
                new Telephone { Value = "+1.6478913606", Extension = "333" },
                new Telephone { Value = "+1.6478913607" });


            var registrantContactCmd = new CiraContactCreate(registrantContact);

            registrantContactCmd.CprCategory = CiraCprCategories.CCT;
            registrantContactCmd.AgreementVersion = agreementVersion;
            registrantContactCmd.AggreementValue = "Y";
            registrantContactCmd.Language = "en";
            registrantContactCmd.OriginatingIpAddress = "127.0.0.1";
            registrantContactCmd.CreatedByResellerId = registrarNumber;

            var response1 = service.Execute(registrantContactCmd);

            PrintResponse(response1);

            /*
             5. Create an administrative contact
             -the same ID as your Registrar Number prefixed with the word ‘admin’ (e.g. admin75)
             -using all mandatory elements required for a Canadian administrative contact
             -omit CPR category (he have not agreed to the CIRA agreement)
            */
            Console.WriteLine("TEST: 5");
            var adminContact = new Contact("admin" + registrarNumber,
               "Administrative Step Five", "Example Inc.",
               "Toronto", "301 La Fanfan Ave.", "ON", "M5V 3T1", "CA",
               "*****@*****.**",
               new Telephone { Value = "+1.6478913606", Extension = "333" },
               new Telephone { Value = "+1.6478913607" });

            var adminContactCmd = new CiraContactCreate(adminContact);

            adminContactCmd.CprCategory = null;
            adminContactCmd.AgreementVersion = null;
            adminContactCmd.AggreementValue = null;
            adminContactCmd.Language = "en";
            adminContactCmd.OriginatingIpAddress = "127.0.0.1";
            adminContactCmd.CreatedByResellerId = registrarNumber;

            const string adminContactId = "admin" + registrarNumber;

            var loginresponse = service.Execute(adminContactCmd);

            PrintResponse(loginresponse);

            //6. Get information for the contact created in operation #4
            Console.WriteLine("TEST: 6");
            var getContactInfo = new ContactInfo(registrantContact.Id);

            var contactInfoResponse = service.Execute(getContactInfo);

            PrintResponse(contactInfoResponse);

            //7. Do a Registrant transfer for domain <registrar number>-3.ca to the Registrant created in operation #4
            Console.WriteLine("TEST: 7");

            //NOTE: registrant transfers are domain updates

            var registrantTransferCmd = new DomainUpdate(registrarNumber + "-3.ca");
            //var registrantTransferCmd = new DomainUpdate("3406310-4.ca");

            var domainChange = new DomainChange { RegistrantContactId = registrantContact.Id };

            registrantTransferCmd.DomainChange = domainChange;

            var response2 = service.Execute(registrantTransferCmd);

            PrintResponse(response2);

            //8. Update the contact created in operation #4 to no longer have a fax number
            Console.WriteLine("TEST: 8");
            var contactUpdateCmd = new ContactUpdate(registrantContact.Id);

            var contactChange = new ContactChange(registrantContact);

            contactChange.Fax = new Telephone("", "");

            contactUpdateCmd.ContactChange = contactChange;

            //NOTE:the docs say that the cpr category is update for domain contact
            //but they show a sample of a contact update request that does not include the extension
            //NOTE: Organization cannot be entered when CPR Category indicates a non individual - see documentation
            contactUpdateCmd.Extensions.Add(new CiraContactUpdateExtension { CprCategory = CiraCprCategories.CCT });

            var response3 = service.Execute(contactUpdateCmd);

            PrintResponse(response3);

            //8.1 Get contact info and check the fax number dissapeared
            var contactInfoCmd1 = new ContactInfo(registrantContact.Id);

            var contactInfoResponse1 = service.Execute(contactInfoCmd1);

            PrintResponse(contactInfoResponse1);

            //9. Do a domain:check on <registrar number>a.ca
            Console.WriteLine("TEST: 9");
            const string domainStep10 = registrarNumber + "a.ca";

            var domainCheckCmd = new DomainCheck(domainStep10);

            var response4 = service.Execute(domainCheckCmd);

            PrintResponse(response4);

            /*
             10. Create a domain using:
             -a domain name set to <registrar number>a.ca
             -a Registrant who is a Permanent Resident
             -the same administrative contact as the Registrant
             -0 hosts
             -the minimum registration period
            */
            Console.WriteLine("TEST: 10");
            //NOTE: CPR categories CCT and RES where merged into CCR

            //BUG: the registrant needs to be a Permanent Resident
            //TODO: create a new contact that is a permanent resident
            //10.1 
            var registrantContact10 = new Contact("ten" + registrarNumber,
               "Registrant Step Ten", "Example Inc.",
               "Toronto", "301 La Fanfan Ave.", "ON", "M5V 3T1", "CA",
               "*****@*****.**",
               new Telephone { Value = "+1.6478913606", Extension = "333" },
               new Telephone { Value = "+1.6478913607" });


            registrantContactCmd = new CiraContactCreate(registrantContact10);
            registrantContactCmd.CprCategory = CiraCprCategories.RES;
            registrantContactCmd.AgreementVersion = agreementVersion;
            registrantContactCmd.AggreementValue = "Y";
            registrantContactCmd.OriginatingIpAddress = "127.0.0.1";
            registrantContactCmd.Language = "en";
            registrantContactCmd.CreatedByResellerId = registrarNumber;

            //ContactCreate.MakeContact(registrantContact10,  agreementVersion, "Y", "127.0.0.1", "en", registrarNumber);

            var response5 = service.Execute(registrantContactCmd);

            PrintResponse(response5);

            //10.2
            var domainCreateCmd = new DomainCreate(domainStep10, registrantContact10.Id);

            domainCreateCmd.DomainContacts.Add(new DomainContact(registrantContact10.Id, "admin"));

            //NOTE: password is compulsory
            domainCreateCmd.Password = "******";

            var response6 = service.Execute(domainCreateCmd);

            PrintResponse(response6);

            /*11. Do a host:check on hosts <registrar number>.example.com and <registrar number>.example.net*/
            Console.WriteLine("TEST: 11");
            var hostCheckCmd = new HostCheck(new List<string> { registrarNumber + ".example.com", registrarNumber + ".example.net" });

            var response7 = service.Execute(hostCheckCmd);

            PrintResponse(response7);

            /*
             12. Create 2 hosts with the following name formats:
             <registrar number>.example.com
             <registrar number>.example.net
             */
            Console.WriteLine("TEST: 12");
            //CIRA only creates a host at a time

            //12.1
            var hostCreateCmd = new HostCreate(new Host(registrarNumber + ".example.com"));

            var response8 = service.Execute(hostCreateCmd);

            PrintResponse(response8);

            //12.2
            hostCreateCmd = new HostCreate(new Host(registrarNumber + ".example.net"));

            var response9 = service.Execute(hostCreateCmd);

            PrintResponse(response9);

            /*
             13. Create a domain using:
             -a domain name set to <registrar number>b.ca
             -the pre-populated contact id <registrar number> as the administrative contact
             -a Registrant who is a Corporation
             -2 hosts created in operation #12 <- the nameservers
             -a maximum registration period (10 years)
             */
            Console.WriteLine("TEST: 13");
            //13.1 - Create a corporation

            //If it is a corporation you can not provide company name
            var corporation = new Contact("corp" + registrarNumber, "Acme Corp.", null, "Toronto",
                                          "some where 22", "ON", "M6G2L1", "CA", "*****@*****.**",
                                          new Telephone("+1.1234567890", null), new Telephone("+1.1234567890", null));

            //var createCorporationContactCmd = ContactCreate.MakeContact(corporation, CiraCprCategories.CCO, agreementVersion, "Y", "127.0.0.1", "en", registrarNumber);

            var createCorporationContactCmd = new CiraContactCreate(corporation);
            createCorporationContactCmd.CprCategory = CiraCprCategories.CCO;
            createCorporationContactCmd.AgreementVersion = agreementVersion;
            createCorporationContactCmd.AggreementValue = "Y";
            createCorporationContactCmd.OriginatingIpAddress = "127.0.0.1";
            createCorporationContactCmd.Language = "en";
            createCorporationContactCmd.CreatedByResellerId = registrarNumber;

            var response10 = service.Execute(createCorporationContactCmd);

            PrintResponse(response10);

            /* var domainUpdateCmd = new DomainUpdate(registrarNumber + "-10.ca");

             domainUpdateCmd.ToRemove.Status.Add(new Status("", "serverDeleteProhibited"));

             response = service.Execute(domainUpdateCmd);

             PrintResponse(response);*/

            //13.2 - Create the domain

            //var createDomainCmd = new DomainCreate(registrarNumber + "b.ca", corporation.Id);
            var createDomainCmd = new DomainCreate(registrarNumber + "b.ca", "corp" + registrarNumber);

            createDomainCmd.Period = new DomainPeriod(10, "y");

            //NOTE:The administrative or technical contact must be an Individual
            //BUG: admin contact needs be the prepopulated 3406310
            createDomainCmd.DomainContacts.Add(new DomainContact(registrarNumber, "admin"));

            //NOTE:Create the host on the Registry system before you assign it to a domain
            createDomainCmd.NameServers.Add(registrarNumber + ".example.com");
            createDomainCmd.NameServers.Add(registrarNumber + ".example.net");

            createDomainCmd.Password = "******";

            var response11 = service.Execute(createDomainCmd);

            PrintResponse(response11);

            /*
             14. Create a domain using: 
             - a domain name set to <registrar number>c.ca
             - a Registrant who is an Association
             - the administrative contact set to the contact created in operation #5
             - maximum number of technical contacts assigned to it (max is 3)
            - 0 hosts
            - a 2-year term
             */
            Console.WriteLine("TEST: 14");
            var association = new Contact("assoc" + registrarNumber, "Beer Producers Association", null, "Toronto",
                                          "some where 22", "ON", "M6G2L1", "CA", "*****@*****.**",
                                          new Telephone("+1.1234567890", null), new Telephone("+1.1234567890", null));

            //var createAssociationContactCmd = ContactCreate.MakeContact(association, CiraCprCategories.ASS, agreementVersion, "Y", "127.0.0.1", "en", registrarNumber);

            var createAssociationContactCmd = new CiraContactCreate(association);
            createAssociationContactCmd.CprCategory = CiraCprCategories.ASS;
            createAssociationContactCmd.AgreementVersion = agreementVersion;
            createAssociationContactCmd.AggreementValue = "Y";
            createAssociationContactCmd.OriginatingIpAddress = "127.0.0.1";
            createAssociationContactCmd.Language = "en";
            createAssociationContactCmd.CreatedByResellerId = registrarNumber;

            var response12 = service.Execute(createAssociationContactCmd);

            PrintResponse(response12);

            //tech1
            var tech1 = new Contact("tech1" + registrarNumber, "Technician #1", "Beer Producers Association", "Toronto",
                                          "some where 22", "ON", "M6G2L1", "CA", "*****@*****.**",
                                          new Telephone("+1.1234567890", null), new Telephone("+1.1234567890", null));

            //var createTech1ContactCmd = ContactCreate.MakeContact(tech1, CiraCprCategories.CCT, agreementVersion, "Y", "127.0.0.1", "en", registrarNumber);

            var createTech1ContactCmd = new CiraContactCreate(tech1);
            createTech1ContactCmd.CprCategory = CiraCprCategories.CCT;
            createTech1ContactCmd.AgreementVersion = agreementVersion;
            createTech1ContactCmd.AggreementValue = "Y";
            createTech1ContactCmd.OriginatingIpAddress = "127.0.0.1";
            createTech1ContactCmd.Language = "en";
            createTech1ContactCmd.CreatedByResellerId = registrarNumber;

            var response13 = service.Execute(createTech1ContactCmd);

            PrintResponse(response13);

            //tech2
            var tech2 = new Contact("tech2" + registrarNumber, "Technician #2", "Beer Producers Association", "Toronto",
                                          "some where 22", "ON", "M6G2L1", "CA", "*****@*****.**",
                                          new Telephone("+1.1234567890", null), new Telephone("+1.1234567890", null));

            //var createTech2ContactCmd = ContactCreate.MakeContact(tech2, CiraCprCategories.CCT, agreementVersion, "Y", "127.0.0.1", "en", registrarNumber);

            var createTech2ContactCmd = new CiraContactCreate(tech2);
            createTech2ContactCmd.CprCategory = CiraCprCategories.CCT;
            createTech2ContactCmd.AgreementVersion = agreementVersion;
            createTech2ContactCmd.AggreementValue = "Y";
            createTech2ContactCmd.OriginatingIpAddress = "127.0.0.1";
            createTech2ContactCmd.Language = "en";
            createTech2ContactCmd.CreatedByResellerId = registrarNumber;

            var response14 = service.Execute(createTech2ContactCmd);

            PrintResponse(response14);

            //tech1
            var tech3 = new Contact("tech3" + registrarNumber, "Technician #3", "Beer Producers Association", "Toronto",
                                          "some where 22", "ON", "M6G2L1", "CA", "*****@*****.**",
                                          new Telephone("+1.1234567890", null), new Telephone("+1.1234567890", null));

            //var createTech3ContactCmd = ContactCreate.MakeContact(tech3, CiraCprCategories.CCT, agreementVersion, "Y", "127.0.0.1", "en", registrarNumber);

            var createTech3ContactCmd = new CiraContactCreate(tech3);
            createTech3ContactCmd.CprCategory = CiraCprCategories.CCT;
            createTech3ContactCmd.AgreementVersion = agreementVersion;
            createTech3ContactCmd.AggreementValue = "Y";
            createTech3ContactCmd.OriginatingIpAddress = "127.0.0.1";
            createTech3ContactCmd.Language = "en";
            createTech3ContactCmd.CreatedByResellerId = registrarNumber;


            var response15 = service.Execute(createTech3ContactCmd);

            PrintResponse(response15);

            const string step14domain = registrarNumber + "c.ca";

            createDomainCmd = new DomainCreate(step14domain, association.Id);

            createDomainCmd.Period = new DomainPeriod(2, "y");

            createDomainCmd.DomainContacts.Add(new DomainContact(adminContactId, "admin"));

            createDomainCmd.DomainContacts.Add(new DomainContact(tech1.Id, "tech"));
            createDomainCmd.DomainContacts.Add(new DomainContact(tech2.Id, "tech"));
            createDomainCmd.DomainContacts.Add(new DomainContact(tech3.Id, "tech"));

            createDomainCmd.Password = "******";

            var response16 = service.Execute(createDomainCmd);

            PrintResponse(response16);

            /*
             15. Do a host:check for a host which the dot-ca domain name is registered
            */
            Console.WriteLine("TEST: 15");
            hostCheckCmd = new HostCheck("any." + registrarNumber + "b.ca");

            var response17 = service.Execute(hostCheckCmd);

            PrintResponse(response17);

            /*
             16. Create 2 subordinate hosts for the domain created in operation #14:
              - with format ns1.<domain> and ns2.<domain>
              - with IPv4 address information
            */
            Console.WriteLine("TEST: 16");
            var host1 = new Host("ns1." + step14domain);
            host1.Addresses.Add(new HostAddress("127.0.0.1", "v4"));
            var host2 = new Host("ns2." + step14domain);
            host2.Addresses.Add(new HostAddress("127.0.0.2", "v4"));

            var createHostCmd = new HostCreate(host1);

            var response18 = service.Execute(createHostCmd);

            PrintResponse(response18);

            createHostCmd = new HostCreate(host2);

            response18 = service.Execute(createHostCmd);

            PrintResponse(response18);

            /*
             17. Using the correct EPP call, get information on a host
            */
            Console.WriteLine("TEST: 17");
            var hostInfoCmd = new HostInfo(host1.HostName);

            var response19 = service.Execute(hostInfoCmd);

            PrintResponse(response19);

            /*18. Update the domain created in operation #14 such that the hosts created in operation #16 are delegated to the domain explicitly*/
            Console.WriteLine("TEST: 18");
            var domainUpdateCmd = new DomainUpdate(step14domain);

            //NOTE: Nameservers need different IP addresses
            domainUpdateCmd.ToAdd.NameServers = new List<string> { host1.HostName, host2.HostName };

            var response20 = service.Execute(domainUpdateCmd);

            PrintResponse(response20);

            //19. Update host ns1.<domain> created in operation #16 such that an IPv6 address is added
            Console.WriteLine("TEST: 19");
            var hostUpdateCmd = new HostUpdate(host1.HostName);

            var eppHostUpdateAddRemove = new EppHostUpdateAddRemove();

            eppHostUpdateAddRemove.Adresses = new List<HostAddress> { new HostAddress("1080:0:0:0:8:800:2004:17A", "v6") };

            hostUpdateCmd.ToAdd = eppHostUpdateAddRemove;

            var response21 = service.Execute(hostUpdateCmd);
            PrintResponse(response21);

            //20. Update host ns1.<domain> created in operation #16 such that an IPv4 address is removed
            Console.WriteLine("TEST: 20");
            hostUpdateCmd = new HostUpdate(host1.HostName);

            eppHostUpdateAddRemove = new EppHostUpdateAddRemove();

            eppHostUpdateAddRemove.Adresses = new List<HostAddress> { new HostAddress("127.0.0.1", "v4") };

            hostUpdateCmd.ToRemove = eppHostUpdateAddRemove;

            var response22 = service.Execute(hostUpdateCmd);
            PrintResponse(response22);

            //21. Update the status of ns1.<domain> such that it can no longer be updated
            Console.WriteLine("TEST: 21");
            hostUpdateCmd = new HostUpdate(host1.HostName);

            eppHostUpdateAddRemove = new EppHostUpdateAddRemove();

            eppHostUpdateAddRemove.Status = new List<Status> { new Status("", "clientUpdateProhibited") };

            hostUpdateCmd.ToAdd = eppHostUpdateAddRemove;

            response22 = service.Execute(hostUpdateCmd);
            PrintResponse(response22);

            //22. Using the correct EPP call, get information on a domain name without using WHOIS
            Console.WriteLine("TEST: 22");

            //const string domainStep10 = registrarNumber + "a.ca";

            var domainInfoCmd = new DomainInfo(domainStep10);
            var domainInfo = service.Execute(domainInfoCmd);

            PrintResponse(domainInfo);

            //23. Renew the domain created in operation #10 such that the domain’s total length of term becomes 3 years
            Console.WriteLine("TEST: 23");
            var renewCmd = new DomainRenew(domainStep10, domainInfo.Domain.ExDate, new DomainPeriod(2, "y"));

            var response23 = service.Execute(renewCmd);
            PrintResponse(response23);

            /*
             24. Do a Registrar transfer:
             - Domain name <registrar number>X2-1.ca, from your ‘e’ Registrar account 
             - Have the system auto-generate the contacts so that their information is identical to the contacts in the ‘e’ account
             */
            Console.WriteLine("TEST: 24");

            var transferCmd = new CiraDomainTransfer(registrarNumber + "X2-1.ca", null, null, new List<string>());
            //var transferCmd = new DomainTransfer("3406310x2-5.ca", null, null, new List<string>());

            transferCmd.Password = "******";
            var response24 = service.Execute(transferCmd);

            PrintResponse(response24);

            /*25. Do a Registrar transfer:
              - Domain name, <registrar number>X2-2.ca, from your ‘e’ Registrar account
              - Specify the same Registrant, administrative, and technical contacts used for the domain created in operation #14
             */
            Console.WriteLine("TEST: 25");

            //BUG: did not use all the technical contacts.

            transferCmd = new CiraDomainTransfer(registrarNumber + "X2-2.ca", association.Id, adminContactId, new List<string> { tech1.Id, tech2.Id, tech3.Id });
            //transferCmd = new DomainTransfer("3406310x2-10.ca", association.Id, adminContactId, new List<string> { tech1.Id, tech2.Id, tech3.Id });

            //Password is mandatory
            //TODO: find it in the control panel
            transferCmd.Password = "******";
            response24 = service.Execute(transferCmd);

            PrintResponse(response24);

            /*
             26. Do an update to the domain created in operation #14 to change the administrative contact to the pre-populated contact whose id is of format <registrar number>
             */
            Console.WriteLine("TEST: 26");
            domainUpdateCmd = new DomainUpdate(step14domain);

            //remove the previous admin
            domainUpdateCmd.ToRemove.DomainContacts.Add(new DomainContact(adminContactId, "admin"));

            domainUpdateCmd.ToAdd.DomainContacts.Add(new DomainContact(registrarNumber, "admin"));

            var response25 = service.Execute(domainUpdateCmd);

            PrintResponse(response25);

            /*27. Do an update to the status of the domain created in operation #14 such that it cannot be deleted*/
            Console.WriteLine("TEST: 27");
            domainUpdateCmd = new DomainUpdate(step14domain);

            domainUpdateCmd.ToAdd.Status.Add(new Status("", "clientDeleteProhibited"));

            var response26 = service.Execute(domainUpdateCmd);

            PrintResponse(response26);

            /*28. Do an update to the email address of the pre-populated contact whose id is of format <registrar number> to "*****@*****.**" */
            Console.WriteLine("TEST: 28");
            //28.1 get the contact
            //var contactInfoCmd = new ContactInfo("rant" + registrarNumber);
            var contactInfoCmd = new ContactInfo(registrarNumber);

            contactInfoResponse = service.Execute(contactInfoCmd);

            PrintResponse(contactInfoResponse);

            if (contactInfoResponse.Contact != null)
            {

                //28.2 update the email address

                //ASSERT: contactInfoResponse.Contact != null
                contactUpdateCmd = new ContactUpdate(contactInfoResponse.Contact.Id);

                var contactchage = new ContactChange(contactInfoResponse.Contact);

                contactchage.Email = "*****@*****.**";

                contactUpdateCmd.ContactChange = contactchage;

                //the extensions are compulsory
                contactUpdateCmd.Extensions.Add(new CiraContactUpdateExtension { CprCategory = contactInfoResponse.Contact.CprCategory });

                var response27 = service.Execute(contactUpdateCmd);

                PrintResponse(response27);


            }
            else
            {
                Console.WriteLine("Error: contact does not exist?");
            }


            /*
                 29. Do an update to the privacy status for Registrant contact created in operation #4 to now show full detail
            */
            Console.WriteLine("TEST: 29");
            contactUpdateCmd = new ContactUpdate("rant" + registrarNumber);

            //Invalid WHOIS display setting - valid values are PRIVATE or FULL
            contactUpdateCmd.Extensions.Add(new CiraContactUpdateExtension { WhoisDisplaySetting = "FULL" });

            var response28 = service.Execute(contactUpdateCmd);

            PrintResponse(response28);


            /*30. Delete the domain <registrar number>-10.ca*/
            Console.WriteLine("TEST: 30");
            //NOTE:check this domain status

            var deleteDomainCmd = new DomainDelete(registrarNumber + "-10.ca");
            //var deleteDomainCmd = new DomainDelete(registrarNumber + "-9.ca");

            var response29 = service.Execute(deleteDomainCmd);
            PrintResponse(response29);

            /*31. EPP <logout> command*/
            Console.WriteLine("TEST:31");
            var logOutCmd = new Logout();

            service.Execute(logOutCmd);

            /*32. Disconnect SSL connection*/
            Console.WriteLine("TEST: 32");
            service.Disconnect();

            /*33. SSL connection establishment*/
            Console.WriteLine("TEST: 33");
            service.Connect();

            /*34. EPP <login> command with your ‘e’ account*/
            Console.WriteLine("TEST: 34");
            logingCmd = new Login("username", "password");

            response = service.Execute(logingCmd);

            PrintResponse(response);

            /*35. Acknowledge all poll messages*/
            Console.WriteLine("TEST: 35");
            var thereAreMessages = true;

            while (thereAreMessages)
            {
                //request
                var poll = new Poll { Type = PollType.Request };

                var pollResponse = (PollResponse)service.Execute(poll);

                PrintResponse(pollResponse);

                if (!String.IsNullOrEmpty(pollResponse.Id))
                {
                    //acknowledge
                    poll = new Poll { Type = PollType.Acknowledge, MessageId = pollResponse.Id };

                    pollResponse = (PollResponse)service.Execute(poll);

                    PrintResponse(pollResponse);
                }

                Console.WriteLine("Messages left in the queue:" + pollResponse.Count);

                thereAreMessages = pollResponse.Count != 0;
            }

            /*36. EPP <logout> command*/
            Console.WriteLine("TEST: 36");
            logOutCmd = new Logout();

            service.Execute(logOutCmd);


        }
예제 #32
0
    private void ClientDisconnectHandler(NetworkClient senderClient)
    {
      this.m_connectedClients.Remove(senderClient);
      Debug.Log("Current connected clients Count={0}.", this.m_connectedClients.Count);

      ContactUpdate removeUpdate = new ContactUpdate();
      removeUpdate.Remove.Add(senderClient.ClientId);

      foreach (NetworkClient connectedClient in this.m_connectedClients) {
        Debug.Log("Sending UpdateContact to remove Client from ClientId={0}.", connectedClient.ClientId);
        connectedClient.SendMessage(MessageType.ContactUpdate, removeUpdate);
      }
    }
예제 #33
0
        /// <summary>
        /// Synchronizes a set of employees using a connected IntacctClient
        /// </summary>
        /// <param name="client">The Client to sync to</param>
        /// <param name="orgemployees">Customer Data to Send</param>
        private async Task SyncOrgEmployees(OnlineClient client, IEnumerable <IntacctEmployee> orgemployees, PerformContext context)
        {
            IDictionary <string, string> employeemap = await GetEmployeeIds(client, context);

            IList <string> contactNames = await GetContacts(client, context);

            // Filter Existing Out
            if (SyncOnlyNew)
            {
                context.WriteLine("Filtering out Existing Employees");
                orgemployees = orgemployees.Where(c => !contactNames.Contains(IntacctCleanString(c.EMPLOYEENAME))).ToArray();
            }

            // Send in batches of Employees
            int sent  = 0;
            int total = orgemployees.Count();

            while (sent < total)
            {
                // What's in this batch
                var batchData = orgemployees.Skip(sent).Take(50).ToList();
                context.WriteLine("Preparing Batch of 50 ({0} - {1} of {2})", sent, sent + batchData.Count, total);
                sent += batchData.Count;

                // Create the Batch for Intacct
                List <IFunction> batchFunctions = new List <IFunction>();
                foreach (var employee in batchData)
                {
                    // Process the Contact First
                    if (contactNames.Contains(IntacctCleanString(employee.EMPLOYEENAME)))
                    {
                        // Update the Contact
                        ContactUpdate update = new ContactUpdate
                        {
                            PrintAs             = employee.EMPLOYEENAME,
                            ContactName         = IntacctCleanString(employee.EMPLOYEENAME),
                            FirstName           = employee.FIRSTNAME,
                            LastName            = employee.LASTNAME,
                            Active              = employee.EMPLOYEEACTIVE == "active",
                            PrimaryPhoneNo      = employee.PHONE,
                            PrimaryEmailAddress = employee.EMAIL
                        };
                        batchFunctions.Add(update);
                    }
                    else
                    {
                        // Create the Contact
                        ContactCreate create = new ContactCreate
                        {
                            PrintAs             = employee.EMPLOYEENAME,
                            ContactName         = IntacctCleanString(employee.EMPLOYEENAME),
                            FirstName           = employee.FIRSTNAME,
                            LastName            = employee.LASTNAME,
                            Active              = employee.EMPLOYEEACTIVE == "active",
                            PrimaryPhoneNo      = employee.PHONE,
                            PrimaryEmailAddress = employee.EMAIL
                        };
                        batchFunctions.Add(create);
                        // Add to our List, so we don't update duplicates
                        contactNames.Add(employee.EMPLOYEENAME);
                    }

                    // Process the Employee Now
                    if (employeemap.ContainsKey(employee.EMPLOYEEID))
                    {
                        // Update the Employee
                        EmployeeUpdate update = new EmployeeUpdate
                        {
                            EmployeeId   = employee.EMPLOYEEID,
                            ContactName  = IntacctCleanString(employee.EMPLOYEENAME),
                            DepartmentId = employee.DEPARTMENTID,
                            LocationId   = employee.LOCATIONID,
                            Active       = employee.EMPLOYEEACTIVE == "active",
                            StartDate    = employee.EMPLOYEESTART,
                            EndDate      = employee.EMPLOYEETERMINATION.ToIntacctDate()
                        };
                        if (!String.IsNullOrWhiteSpace(employee.PE_STAFF_CODE))
                        {
                            update.CustomFields.Add("PE_STAFF_CODE", employee.PE_STAFF_CODE);
                        }
                        update.CustomFields.Add("RECORDNO", employeemap[employee.EMPLOYEEID]);
                        batchFunctions.Add(update);
                    }
                    else
                    {
                        // Create the Employee
                        EmployeeCreate create = new EmployeeCreate
                        {
                            EmployeeId   = employee.EMPLOYEEID,
                            ContactName  = IntacctCleanString(employee.EMPLOYEENAME),
                            DepartmentId = employee.DEPARTMENTID,
                            LocationId   = employee.LOCATIONID,
                            Active       = employee.EMPLOYEEACTIVE == "active",
                            StartDate    = employee.EMPLOYEESTART,
                            EndDate      = employee.EMPLOYEETERMINATION.ToIntacctDate()
                        };
                        if (!String.IsNullOrWhiteSpace(employee.PE_STAFF_CODE))
                        {
                            create.CustomFields.Add("PE_STAFF_CODE", employee.PE_STAFF_CODE);
                        }
                        batchFunctions.Add(create);
                    }
                }

                // Send the Batch to Intacct
                context.WriteLine("Sending Batch to Intacct");
                var response = await client.ExecuteBatch(batchFunctions);

                context.WriteLine("Inspecting Response from Intacct");
                foreach (var result in response.Results)
                {
                    if (result.Errors != null)
                    {
                        context.SetTextColor(ConsoleTextColor.Red);
                        context.WriteLine("==================================");
                        foreach (var err in result.Errors)
                        {
                            context.WriteLine(err);
                        }
                        context.WriteLine("==================================");
                        context.WriteLine();
                        Console.ResetColor();
                    }
                }
            }
        }
예제 #34
0
 public void CreateClient(ContactUpdate.Types.Client client)
 {
   Debug.Log("Creating clientId={0} Name={1} Surname={2}.", client.ClientId, client.Name, client.Surname);
   this.spContacts.Dispatcher.Invoke(() => {
     UI.ContactItem createdContact = new UI.ContactItem(client);
     createdContact.onContactItemButtonClick += this.m_clientButtonHandler;
     this.spContacts.Children.Add(createdContact);
   });
 }
예제 #35
0
 /// <summary>
 /// PUT api/Contacts/{id}
 /// Update contact.
 /// </summary>
 public async Task <Contact> UpdateAsync(int contactId, ContactUpdate model)
 {
     return(await PutAsync <Contact, ContactUpdate>(ResourceUrl + "/" + contactId, model));
 }
예제 #36
0
    private void ServerMessageReceived(NetworkClient senderClient, int messageType, ByteString messageContent)
    {
      Debug.Log("Server message Type={0} Size={1}.", messageType, messageContent.Length);

      switch (messageType) {
        /* Handshake request. */
        case MessageType.ClientHandshakeRequest: {
            HandshakeRequest request = HandshakeRequest.Parser.ParseFrom(messageContent);
            senderClient.UpdatePublicKey(request.Key);

            PublicKey serverPublic = this.ServerKey;
            if (serverPublic == null) {
              Debug.Error("Server public key is invalid.");
              return;
            }

            HandshakeResponse response = new HandshakeResponse();
            response.Key = serverPublic;
            senderClient.SendMessage(MessageType.ClientHandshakeResponse, response);
          }
          break;

        /* Authorization request. */
        case MessageType.AuthorizationRequest: {
            AuthorizationRequest request = AuthorizationRequest.Parser.ParseFrom(messageContent);
            senderClient.Profile.UpdateProfile(request);

            AuthorizationResponse response = new AuthorizationResponse();
            response.ServerName = this.m_serverConfig.ServerName;
            senderClient.SendMessage(MessageType.AuthorizationResponse, response);

            Task.Run(() => {
              ContactUpdate contactUpdate = new ContactUpdate();
              contactUpdate.Add.Add(senderClient.ContactClient);

              foreach (NetworkClient connectedClient in this.m_connectedClients) {
                if (connectedClient.ClientId == senderClient.ClientId) continue;

                Debug.Log("Sending contact update to ClientId={0}.", connectedClient.ClientId);
                connectedClient.SendMessage(MessageType.ContactUpdate, contactUpdate);
              }
            });
          }
          break;

        /* Contact list update. */
        case MessageType.ContactUpdateRequest: {
            ContactUpdateRequest request = ContactUpdateRequest.Parser.ParseFrom(messageContent);
            ContactUpdate contactUpdate = new ContactUpdate();

            List<long> clientList = request.Clients.ToList();
            foreach (NetworkClient connectedClient in this.m_connectedClients) {
              // if (connectedClient.ClientId == senderClient.ClientId) continue;
              if (!connectedClient.Profile.Valid) continue;

              if (clientList.Contains(connectedClient.ClientId)) {
                Debug.Log("Client {0} has got ClientId={1}.", senderClient.ClientId, connectedClient.ClientId);
                clientList.Remove(connectedClient.ClientId);
              }
              else {
                Debug.Log("Client {0} requires ClientId={1}.", senderClient.ClientId, connectedClient.ClientId);
                contactUpdate.Add.Add(connectedClient.ContactClient);
              }
            }

            Debug.Log("Trash clients count={0}.", clientList.Count);
            if (clientList.Count > 0) {
              contactUpdate.Remove.Add(clientList);
            }
            senderClient.SendMessage(MessageType.ContactUpdate, contactUpdate);
          }
          break;

        case MessageType.ContactUpdateChangeRequest: {
            ContactUpdateChangeRequest clientRequestedChange = ContactUpdateChangeRequest.Parser.ParseFrom(messageContent);
            var senderProfile = senderClient.Profile;

            if (senderProfile.Name != clientRequestedChange.Name || senderProfile.Surname != clientRequestedChange.Surname) {
              Debug.Log("Updating client data. This is not implemented on the client side. ;)");
            }
            else if(senderProfile.Status != clientRequestedChange.Online) {
              senderProfile.Status = clientRequestedChange.Online;

              ContactUpdateStatus statusUpdate = new ContactUpdateStatus();
              statusUpdate.Online = clientRequestedChange.Online;
              statusUpdate.ClientId = senderClient.ClientId;

              foreach (NetworkClient connectedClient in this.m_connectedClients) {
                // if (connectedClient.ClientId == senderClient.ClientId) continue;

                Debug.Log("Sending status update to ClientId={0}.", connectedClient.ClientId);
                connectedClient.SendMessage(MessageType.ContactUpdateStatus, statusUpdate);
              }
            }
          }
          break;

        /* Client Public Key request. */
        case MessageType.MessageClientPublicRequest: {
            MessageRequestClientPublic requestMessage = MessageRequestClientPublic.Parser.ParseFrom(messageContent);
            PublicKey responseKey = null;

            foreach (NetworkClient connectedClient in this.m_connectedClients) {
              if (connectedClient.ClientId == requestMessage.ClientId) {
                responseKey = connectedClient.ClientPublic;
              }
            }

            if (responseKey != null) {
              MessageResponseClientPublic responseMessage = new MessageResponseClientPublic();
              responseMessage.ClientId = requestMessage.ClientId;
              responseMessage.Key = responseKey;

              senderClient.SendMessage(MessageType.MessageClientPublicResponse, responseMessage);
            }
            else 
              Debug.Warn("ClientId={0} has invalid public key.");
          }
          break;
      }
    }
 /// <summary>
 /// Update the organization's contact.
 /// </summary>
 /// <param name="guid">The guid of the contact to update</param>
 /// <param name="updatedModel">The updated contact</param>
 public Task UpdateAsync(Guid guid, ContactUpdate updatedModel)
 {
     if (updatedModel == null) throw new ArgumentNullException("updatedModel");
     return PutAsyncWithGuid<EmptyDineroResult>(guid, updatedModel);
 }
 /// <summary>
 /// Update the organization's contact.
 /// </summary>
 /// <param name="guid">The guid of the contact to update</param>
 /// <param name="updatedModel">The updated contact</param>
 public void Update(Guid guid, ContactUpdate updatedModel)
 {
     TaskHelper.ExecuteSync(() => UpdateAsync(guid, updatedModel));
 }
        private static async Task UpdateContact(Dinero dinero, Contact contact)
        {
            var model = new ContactUpdate()
            {
                ExternalReference = contact.ExternalReference +"TestRef updated",
                Name = contact.Name +" Updated",
                CountryKey = "SE"
            };

            await dinero.Contacts.UpdateAsync(contact.ContactGuid, model);
            Console.WriteLine("Contact updated.");
        }