Beispiel #1
0
        public async Task <ActionResult> TimeOut(string id)
        {
            var context = new SphDataContext();
            var user    = await context.LoadOneAsync <Pengguna>(x => x.MyKad == User.Identity.Name);

            var sesi = await context.LoadOneAsync <SesiUjian>(x => x.Id == id);

            var name    = user == null ? "" : user.Nama;
            var setting = (await context.LoadOneAsync <PercubaanSesi>(x => x.MyKad == User.Identity.Name && x.SesiUjianId == id))
                          ?? new PercubaanSesi
            {
                No           = Guid.NewGuid().ToString(),
                MyKad        = User.Identity.Name,
                SesiUjianId  = id,
                Bilangan     = 0,
                NamaUjian    = sesi.NamaUjian,
                Program      = sesi.NamaProgram,
                NamaPengguna = name,
                Tarikh       = DateTime.Now,
                Id           = Guid.NewGuid().ToString()
            };


            setting.Bilangan += 1;
            using (var session = context.OpenSession())
            {
                session.Attach(setting);
                await session.SubmitChanges();
            }


            return(Json(setting));
        }
        public async Task <IHttpActionResult> AddContactToGroup(string id, string group)
        {
            var repos   = ObjectBuilder.GetObject <IRepository <AddressBook> >();
            var context = new SphDataContext();

            var contact = await repos.LoadOneAsync(id);

            if (null == contact)
            {
                return(NotFound($"Contact with Id {id} is not found"));
            }
            if (contact.Groups.Contains(group))
            {
                return(Ok(new { message = $"{contact.CompanyName} is already in {group}" }));
            }

            contact.Groups.Add(group);
            using (var session = context.OpenSession())
            {
                session.Attach(contact);
                await session.SubmitChanges("AddGroup", new Dictionary <string, object> {
                    { "username", User.Identity.Name }
                });
            }
            // wait until the worker process it
            await Task.Delay(1000);

            return(Ok(new { message = $"{contact.CompanyName} has been added to {group}" }));
        }
Beispiel #3
0
        public async Task <ActionResult> UpdateUser(UserProfile profile)
        {
            var context     = new SphDataContext();
            var userprofile = await context.LoadOneAsync <UserProfile>(p => p.UserName == User.Identity.Name)
                              ?? new UserProfile();

            userprofile.UserName    = User.Identity.Name;
            userprofile.Email       = profile.Email;
            userprofile.Telephone   = profile.Telephone;
            userprofile.FullName    = profile.FullName;
            userprofile.StartModule = profile.StartModule;
            userprofile.Language    = profile.Language;

            if (userprofile.IsNewItem)
            {
                userprofile.Id = userprofile.UserName.ToIdFormat();
            }

            using (var session = context.OpenSession())
            {
                session.Attach(userprofile);
                await session.SubmitChanges();
            }
            this.Response.ContentType = "application/json; charset=utf-8";
            return(Content(JsonConvert.SerializeObject(userprofile)));
        }
        public async Task RunAsync(Pickup pickup)
        {
            //pickup_event_new
            var pickupToEnttAcceptanceMap = new Integrations.Transforms.RtsPickupToEnttPlatformAcceptance();
            var acceptanceList            = new List <EnttAcceptance>();
            var parentRow = await pickupToEnttAcceptanceMap.TransformAsync(pickup);

            parentRow.IsParent = true;

            acceptanceList.Add(parentRow);

            if (null != pickup.BabyConsignment)
            {
                var      consignmentBabies = pickup.BabyConsignment.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                string[] babiesWeight      = { };
                if (!string.IsNullOrEmpty(pickup.BabyWeigth))
                {
                    babiesWeight = pickup.BabyWeigth.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                }
                var babiesHeight = pickup.BabyHeigth.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                var babiesWidth  = pickup.BabyWidth.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                var babiesLength = pickup.BabyLength.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                var index        = 0;

                foreach (var babyConsignmentNo in consignmentBabies)
                {
                    var consignmentChildRow = parentRow.Clone();
                    consignmentChildRow.Id            = Guid.NewGuid().ToString();
                    consignmentChildRow.Parent        = parentRow.ConsignmentNo;
                    consignmentChildRow.IsParent      = false;
                    consignmentChildRow.ConsignmentNo = babyConsignmentNo;
                    if (babiesWeight.Length == consignmentBabies.Length)
                    {
                        consignmentChildRow.Weight = GetDoubleValue(babiesWeight[index]);
                    }
                    else
                    {
                        consignmentChildRow.Weight = 0;
                    }
                    consignmentChildRow.Height = GetDoubleValue(babiesHeight[index]);
                    consignmentChildRow.Length = GetDoubleValue(babiesLength[index]);
                    consignmentChildRow.Width  = GetDoubleValue(babiesWidth[index]);

                    acceptanceList.Add(consignmentChildRow);
                    index++;
                }
            }

            //
            foreach (var item in acceptanceList)
            {
                var context = new SphDataContext();
                using (var session = context.OpenSession())
                {
                    session.Attach(item);
                    await session.SubmitChanges();
                }
            }
        }
        private static async Task SaveSetting(Setting setting, string operation)
        {
            var context = new SphDataContext();

            using (var session = context.OpenSession())
            {
                session.Attach(setting);
                await session.SubmitChanges(operation);
            }
        }
        private static async Task SaveEstRegistration(EstRegistration EstRegistration)
        {
            var context = new SphDataContext();

            using (var session = context.OpenSession())
            {
                session.Attach(EstRegistration);
                await session.SubmitChanges("Default");
            }
        }
Beispiel #7
0
        private static async Task SaveConsigmentRequest(ConsigmentRequest item)
        {
            var context = new SphDataContext();

            using (var session = context.OpenSession())
            {
                session.Attach(item);
                await session.SubmitChanges("Default");
            }
        }
Beispiel #8
0
        public async Task <ActionResult> PsRequestPrepaid(string id)
        {
            var context          = new SphDataContext();
            LoadData <Wallet> lo = await GetWallet(id);

            if (null == lo.Source)
            {
                Response.StatusCode = (int)HttpStatusCode.NotFound;
                return(Json(new { success = false, status = "ERROR", message = $"Cannot find WalletCode with Id: {id}." }, JsonRequestBehavior.AllowGet));
            }

            var generalLedger = new GeneralLedger();

            generalLedger.Id = Guid.NewGuid().ToString();

            var     wallet     = lo.Source;
            decimal noGstPrice = 0;
            decimal gstPrice   = 0;
            decimal totalPrice = 0;

            noGstPrice = Convert.ToDecimal(wallet.TotalValue);
            gstPrice   = noGstPrice * Convert.ToDecimal(0.06);
            totalPrice = noGstPrice + gstPrice;

            // required by payment gateway
            var model = new PaymentSwitchRequestModel();

            model.TransactionId     = GenerateCustomRefNo(generalLedger);
            model.TransactionAmount = noGstPrice;
            model.TransactionGST    = gstPrice;
            model.PurchaseDate      = DateTime.Now;
            model.Description       = $"{m_applicationName} purchase topup by {User.Identity.Name} for RM{totalPrice} with Id: ({wallet.WalletCode})";
            model.CallbackUrl       = $"{m_baseUrl}/ost-payment/ps-response-prepaid";

            //insert empty transaction into GL with reference no and type
            generalLedger.ReferenceNo = model.TransactionId;
            generalLedger.Type        = "Prepaid";
            using (var session = context.OpenSession())
            {
                session.Attach(generalLedger);
                await session.SubmitChanges("Default");
            }

            var rijndaelKey   = new RijndaelEnhanced(m_paymentGatewayEncryptionKey);
            var dataToEncrypt = string.Format("{0}|{1}|{2}|{3}|{4}", model.TransactionId, model.TransactionAmount, model.TransactionGST, model.PurchaseDate.ToString("MM/dd/yyyy hh:mm:ss"), model.Description);

            if (!string.IsNullOrEmpty(model.CallbackUrl))
            {
                dataToEncrypt += "|" + model.CallbackUrl;
            }
            var encryptedData = rijndaelKey.Encrypt(dataToEncrypt);

            Response.StatusCode = (int)HttpStatusCode.OK;
            return(Json(new { success = true, status = "OK", id = m_paymentGatewayApplicationId, data = encryptedData, url = $"{m_paymentGatewayBaseUrl}/pay" }, JsonRequestBehavior.AllowGet));
        }
Beispiel #9
0
        private static async Task SaveChanges(SphDataContext context, ConsigmentRequest consignmentRequestPickup, ConsigmentRequest consignmentRequestCart)
        {
            Console.WriteLine($"Consignment Request Pickup Number: {consignmentRequestPickup.Pickup.Number}");
            Console.WriteLine($"======================");
            var countPickup = 0;

            foreach (var itemConsignments in consignmentRequestPickup.Consignments)
            {
                Console.WriteLine($"{countPickup += 1}. {itemConsignments.ConNote}");
            }

            Console.WriteLine($"Consignment Request Cart Reference No: {consignmentRequestCart.ReferenceNo}");
            Console.WriteLine($"======================");
            var countCart = 0;

            foreach (var itemConsignments in consignmentRequestCart.Consignments)
            {
                Console.WriteLine($"{countCart += 1}. {itemConsignments.ConNote}");
            }

            using (var session = context.OpenSession())
            {
                session.Attach(consignmentRequestPickup);
                session.Attach(consignmentRequestCart);
                await session.SubmitChanges("Default");
            }

            if (consignmentRequestCart.Consignments.Count == 0)
            {
                //Empty Cart
                consignmentRequestCart.Pickup                 = new Bespoke.Ost.ConsigmentRequests.Domain.Pickup();
                consignmentRequestCart.Payment                = new Bespoke.Ost.ConsigmentRequests.Domain.Payment();
                consignmentRequestCart.ReferenceNo            = Guid.NewGuid().ToString();
                consignmentRequestCart.GenerateConnoteCounter = 0;
                using (var session = context.OpenSession())
                {
                    session.Attach(consignmentRequestCart);
                    await session.SubmitChanges("Default");
                }
                Console.WriteLine($"Cart Emptied");
            }
        }
Beispiel #10
0
        public async Task <ActionResult> ChangePassword(ChangePaswordModel model)
        {
            var userName = User.Identity.Name;

            if (!Membership.ValidateUser(userName, model.OldPassword))
            {
                return(Json(new { success = false, status = "PASSWORD_INCORRECT", message = "Your old password is incorrect", user = userName }));
            }
            if (model.Password != model.ConfirmPassword)
            {
                return(Json(new { success = false, status = "PASSWORD_DOESNOT_MATCH", message = "Your password is not the same" }));
            }


            var user = Membership.GetUser(userName);

            if (null == user)
            {
                throw new Exception("Cannot find user");
            }

            try
            {
                var valid = user.ChangePassword(model.OldPassword, model.Password);
                if (!valid)
                {
                    return(Json(new { success = false, status = "ERROR_CHANGING_PASSWORD", message = "There's an error changing your password" }));
                }
            }
            catch (Exception ex)
            {
                return(Json(new { success = false, status = "EXCEPTION_CHANGING_PASSWORD", message = ex.Message }));
            }

            var context = new SphDataContext();
            var profile = await context.LoadOneAsync <UserProfile>(u => u.UserName == User.Identity.Name);

            profile.HasChangedDefaultPassword = true;

            using (var session = context.OpenSession())
            {
                session.Attach(profile);
                await session.SubmitChanges("Change password");
            }

            if (Request.ContentType.Contains("application/json"))
            {
                this.Response.ContentType = "application/json; charset=utf-8";
                return(Content(JsonConvert.SerializeObject(new { success = true, status = "OK" })));
            }

            return(Redirect("/"));
        }
Beispiel #11
0
        //exec:6527072e-1302-4de8-cdbe-52968cfea0a4
        public async Task <ActivityExecutionResult> CreateProfileAndMembershipAsync()
        {
            var result = new ActivityExecutionResult {
                Status = ActivityExecutionStatus.Success
            };
            var item = this;

            var context     = new SphDataContext();
            var designation = await context.LoadOneAsync <Designation>(d => d.Name == "Responden");

            var roles   = designation.RoleCollection.ToArray();
            var profile = new UserProfile
            {
                Id          = this.Pengguna.Id,
                UserName    = this.Pengguna.MyKad,
                Email       = this.Pengguna.Emel,
                FullName    = this.Pengguna.Nama,
                Designation = "Responden",
                HasChangedDefaultPassword = false,
                RoleTypes   = string.Join(",", roles),
                StartModule = "responden-home",
                Language    = "en-US"
            };

            Console.WriteLine("done mapping user profile");

            var exist            = System.Web.Security.Membership.GetUser(profile.UserName);
            var existUserByEmail = System.Web.Security.Membership.GetUserNameByEmail(profile.Email);


            if ((null == exist) || (null == existUserByEmail))
            {
                this.Password = System.Web.Security.Membership.GeneratePassword(6, 0);

                System.Web.Security.Membership.CreateUser(profile.UserName, this.Password, profile.Email);
                System.Web.Security.Roles.AddUserToRoles(profile.UserName, roles);

                Console.WriteLine("insert into user profile");
                using (var session = context.OpenSession())
                {
                    session.Attach(profile);
                    await session.SubmitChanges();
                }

                //IsCreated = true;
            }

            result.NextActivities = new[] { "41cddfd4-0781-44b1-db25-cbef78c61352" };


            return(result);
        }
        private async Task DeleteEstRegistration(string id)
        {
            var             context = new SphDataContext();
            EstRegistration item    = await GetEstRegistrationAsync(id);

            Console.WriteLine($"Preparing to delete EstRegistration with Id: {item.Id}");
            Console.WriteLine($"===============================================");

            using (var session = context.OpenSession())
            {
                session.Delete(item);
                await session.SubmitChanges("Default");
            }
        }
        private static async Task SetVerifyEmailFlag(string username)
        {
            var context     = new SphDataContext();
            var userProfile = await context.LoadOneAsync <UserProfile>(p => p.UserName == username);

            if (!userProfile.HasChangedDefaultPassword)
            {
                userProfile.HasChangedDefaultPassword = true;
                using (var session = context.OpenSession())
                {
                    session.Attach(userProfile);
                    await session.SubmitChanges();
                }
            }
        }
        public async Task RunAsync(MailItem item)
        {
            var ipsExportMap = new Integrations.Transforms.IpsExportToEnttAcceptance();
            var acceptance   = await ipsExportMap.TransformAsync(item);

            var tn030 = item.FromIPS.IPSEvent.Single(m => m.TNCd == "TN030");

            acceptance.DateTime = tn030.Date.Value;

            var context = new SphDataContext();

            using (var session = context.OpenSession())
            {
                session.Attach(acceptance);
                await session.SubmitChanges();
            }
        }
    private static async Task <UserProfile> CreateProfile(Profile profile, Designation designation)
    {
        if (null == profile)
        {
            throw new ArgumentNullException(nameof(profile));
        }
        if (null == designation)
        {
            throw new ArgumentNullException(nameof(designation));
        }
        if (string.IsNullOrWhiteSpace(designation.Name))
        {
            throw new ArgumentNullException(nameof(designation), "Designation Name cannot be null, empty or whitespace");
        }
        if (string.IsNullOrWhiteSpace(profile.UserName))
        {
            throw new ArgumentNullException(nameof(profile), "Profile UserName cannot be null, empty or whitespace");
        }

        var context = new SphDataContext();
        var usp     = await context.LoadOneAsync <UserProfile>(p => p.UserName == profile.UserName) ?? new UserProfile();

        usp.UserName    = profile.UserName;
        usp.FullName    = profile.FullName;
        usp.Designation = profile.Designation;
        usp.Department  = profile.Department;
        usp.Mobile      = profile.Mobile;
        usp.Telephone   = profile.Telephone;
        usp.Email       = profile.Email;
        usp.RoleTypes   = string.Join(",", profile.Roles);
        usp.StartModule = designation.StartModule;
        if (usp.IsNewItem)
        {
            usp.Id = profile.UserName.ToIdFormat();
        }

        using (var session = context.OpenSession())
        {
            session.Attach(usp);
            await session.SubmitChanges();
        }

        return(usp);
    }
    public async Task <ActionResult> RemoveUser(string user)
    {
        var context = new SphDataContext();
        var profile = await context.LoadOneAsync <UserProfile>(x => x.UserName == user);

        if (null != profile)
        {
            using (var session = context.OpenSession())
            {
                session.Delete(profile);
                await session.SubmitChanges("Remove");
            }
        }
        var member = Membership.GetUser(user);

        if (null != member)
        {
            Membership.DeleteUser(user, true);
        }
        return(Content("{success : true, status : \"OK\"}", "application/json"));
    }
Beispiel #17
0
        public async Task <ActionResult> ForgotPassword(string email)
        {
            var username = Membership.GetUserNameByEmail(email);

            if (string.IsNullOrWhiteSpace(username))
            {
                return(Json(new { sucess = false, status = "Cannot find any user with email  " + email }));
            }
            var setting = new Setting {
                UserName = email, Key = "ForgotPassword", Value = DateTime.Now.ToString("s"), Id = Strings.GenerateId()
            };
            var context = new SphDataContext();

            using (var session = context.OpenSession())
            {
                session.Attach(setting);
                await session.SubmitChanges("ForgotPassword");
            }
            using (var smtp = new SmtpClient())
            {
                var mail = new MailMessage(ConfigurationManager.FromEmailAddress, email)
                {
                    Subject    = ConfigurationManager.ApplicationFullName + " Forgot password ",
                    Body       = $@"Salam Sejahtera,

Anda memohon untuk membuat pertukaran kata laluan melalui alamat ini, klik di pautan dibawah untuk meneruskan pertukaran kata laluan anda
{ConfigurationManager.BaseUrl}/jpa-account/reset-password/{setting.Id}


Emel ini di jana oleh komputer.",
                    IsBodyHtml = false
                };
                await smtp.SendMailAsync(mail);
            }
            return(Json(new { sucess = true, status = "ok" }));
        }
Beispiel #18
0
        //exec:659b3c30-7a39-488e-da26-56b627c6050b
        public async Task <ActivityExecutionResult> Email2Async()
        {
            var result = new ActivityExecutionResult {
                Status = ActivityExecutionStatus.Success
            };
            var act = this.GetActivity <NotificationActivity>("659b3c30-7a39-488e-da26-56b627c6050b");

            result.NextActivities = new[] { "56dd17a3-d01d-44d6-a2c1-d1fb0587655e" };

            var @from = await this.TransformFromEmail2Async(act.From);

            var to = await this.TransformToEmail2Async(act.To);

            var subject = await this.TransformSubjectEmail2Async(act.Subject);

            var body = await this.TransformBodyEmail2Async(act.Body);

            var cc = await this.TransformBodyEmail2Async(act.Cc);

            var bcc = await this.TransformBodyEmail2Async(act.Bcc);

            var client = new System.Net.Mail.SmtpClient();
            var mm     = new System.Net.Mail.MailMessage();

            mm.Subject = subject;
            mm.Body    = body;
            mm.From    = new System.Net.Mail.MailAddress(@from);
            mm.To.Add(to);
            if (!string.IsNullOrWhiteSpace(cc))
            {
                mm.CC.Add(cc);
            }
            if (!string.IsNullOrWhiteSpace(bcc))
            {
                mm.Bcc.Add(bcc);
            }
            await client.SendMailAsync(mm).ConfigureAwait(false);


            var context = new SphDataContext();

            foreach (var et in to.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            {
                var et1  = et;
                var user = await context.LoadOneAsync <UserProfile>(u => u.Email == et1);

                if (null == user)
                {
                    continue;
                }
                var message = new Message
                {
                    Subject  = subject,
                    UserName = user.UserName,
                    Body     = body,
                    Id       = Strings.GenerateId()
                };
                using (var session = context.OpenSession())
                {
                    session.Attach(message);
                    await session.SubmitChanges("Email 2").ConfigureAwait(false);
                }
            }


            return(result);
        }
Beispiel #19
0
        public async Task <ActionResult> ResetPassword(ResetPaswordModel model)
        {
            var context = new SphDataContext();
            var key     = await context.LoadOneAsync <Setting>(x => x.Id == model.Id);

            if (null == key)
            {
                return(HttpNotFound("Cannot find any password reset key " + model.Id));
            }

            var username = Membership.GetUserNameByEmail(model.Email);

            if (model.Password != model.ConfirmPassword)
            {
                return(Json(new { success = false, status = "PASSWORD_DOESNOT_MATCH", message = "Kata laluan anda tidak sama" }));
            }
            if (string.IsNullOrWhiteSpace(username))
            {
                return(HttpNotFound("Cannot find any user registered with " + model.Email));
            }

            var user = Membership.GetUser(username);

            if (null == user)
            {
                throw new Exception("Cannot find any user with email " + model.Email);
            }


            var ok = AdminController.CheckPasswordComplexity(Membership.Provider, model.Password);

            if (!ok)
            {
                return(Json(new { success = false, status = "PASSWORD_COMPLEXITY", message = "Kata laluan anda tidak mengikut kesesuaian yang ditetapkan" }));
            }

            var temp = user.ResetPassword();

            user.ChangePassword(temp, model.Password);

            var profile = await context.LoadOneAsync <UserProfile>(u => u.UserName == username)
                          ?? new UserProfile
            {
                UserName = username,
                Email    = model.Email,
                HasChangedDefaultPassword = true,
                Id          = username,
                StartModule = ""
            };

            profile.HasChangedDefaultPassword = true;

            using (var session = context.OpenSession())
            {
                session.Attach(profile);
                await session.SubmitChanges("Change password");
            }

            if (Request.ContentType.Contains("application/json"))
            {
                this.Response.ContentType = "application/json; charset=utf-8";
                return(Content(JsonConvert.SerializeObject(new { success = true, status = "OK" })));
            }

            return(Redirect("/"));
        }
Beispiel #20
0
        public async Task <ActionResult> ProcessFile(string id, string permohonanId)
        {
            if (string.IsNullOrEmpty(id))
            {
                return(Json(new { success = false, messge = "Store Id is not provided for the excel file" }));
            }
            var context = new SphDataContext();
            var store   = ObjectBuilder.GetObject <IBinaryStore>();
            var doc     = await store.GetContentAsync(id);

            var temp = Path.GetTempFileName() + ".xlsx";

            System.IO.File.WriteAllBytes(temp, doc.Content);

            var file  = new FileInfo(temp);
            var excel = new ExcelPackage(file);
            var ws    = excel.Workbook.Worksheets["Pelajar"];

            if (null == ws)
            {
                throw new ArgumentException("Cannot open Worksheet Pelajar in " + doc.FileName);
            }


            var permohonan = await context.LoadOneAsync <Permohonan>(x => x.Id == permohonanId);

            if (null == permohonan)
            {
                return(HttpNotFound("Cannot find any Permohonan with Id=" + permohonanId));
            }

            var senaraiDaftar = new List <PendaftaranProgram>();
            var row           = 2;
            var name          = ws.Cells["A" + row].GetValue <string>();
            var mykad         = ws.Cells["B" + row].GetValue <string>();
            var hasRow        = !string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(mykad);

            var    duplicateEmails = new List <string>();
            string warning         = "";

            while (hasRow)
            {
                var student = new Pengguna
                {
                    Id          = mykad,
                    Nama        = name,
                    MyKad       = mykad,
                    Jantina     = ws.Cells["C" + row].GetValue <string>(),
                    Warganegara = "Malaysia",
                    Umur        = 0,
                    Emel        = ws.Cells["G" + row].GetValue <string>(),
                    Emel2       = null,
                    Pekerjaan   = "Pelajar",
                    Pelajar     = new Pelajar
                    {
                        BidangPengajian = ws.Cells["D" + row].GetValue <string>(),
                        Tempat          = ws.Cells["F" + row].GetValue <string>(),
                        TahapPendidikan = ws.Cells["E" + row].GetValue <string>()
                    },
                    IsResponden = true
                };

                var emailExist = await context.GetAnyAsync <Pengguna>(x => x.MyKad == student.MyKad);

                if (!emailExist)
                {
                    var email = Membership.FindUsersByEmail(student.Emel);
                    if (email.Count > 0)
                    {
                        duplicateEmails.Add(student.Emel);
                    }
                }

                var did    = Guid.NewGuid().ToString();
                var daftar = new PendaftaranProgram
                {
                    NamaProgram   = permohonan.NamaProgram,
                    MyKad         = student.MyKad,
                    TarikhDaftar  = DateTime.Now,
                    NamaPengguna  = student.Nama,
                    NoPermohonan  = permohonan.PermohonanNo,
                    PendaftaranNo = did,
                    PermohonanId  = permohonanId,
                    Id            = did,
                    WebId         = did
                };

                //increment
                row++;
                name   = ws.Cells["A" + row].GetValue <string>();
                mykad  = ws.Cells["B" + row].GetValue <string>();
                hasRow = !string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(mykad);

                if (row - 2 > permohonan.BilRespondan)
                {
                    warning = $"Fail Excel ini mengandungi lebih dari bilangan responden yang dibenarkan : {permohonan.BilRespondan}";
                    break;
                }

                var daftarExist = await context.GetAnyAsync <PendaftaranProgram>(x => x.MyKad == student.MyKad && x.NoPermohonan == permohonan.PermohonanNo);

                if (!daftarExist)
                {
                    senaraiDaftar.Add(daftar);
                }
                using (var session = context.OpenSession())
                {
                    if (!emailExist)
                    {
                        session.Attach(student);
                    }
                    if (!daftarExist)
                    {
                        session.Attach(daftar);
                    }
                    if (!daftarExist || !emailExist)
                    {
                        await session.SubmitChanges("TambahResponden");
                    }
                }
            }

            // TODO : verify the user name and email for each record


            return(Json(new { success = true, warning, list = senaraiDaftar, duplicateEmails, status = "OK" }));
        }
        public async Task <IHttpActionResult> ImportContacts(string storeId)
        {
            var errors  = new List <object>();
            var context = new SphDataContext();

            var store = ObjectBuilder.GetObject <IBinaryStore>();
            var doc   = await store.GetContentAsync(storeId);

            if (null == doc)
            {
                return(Ok(new { success = false, status = $"Cannot find file in {storeId}." }));
            }

            var ext = Path.GetExtension(doc.FileName).ToLower();

            if (ext != ".xlsx")
            {
                return(Ok(new { success = false, status = "Invalid file format. Only *.xlsx file is supported." }));
            }

            var temp = Path.GetTempFileName() + ".xlsx";

            System.IO.File.WriteAllBytes(temp, doc.Content);

            var file  = new FileInfo(temp);
            var excel = new ExcelPackage(file);
            var ws    = excel.Workbook.Worksheets["Addresses"];

            if (null == ws)
            {
                return(Ok(new { success = false, status = $"Cannot open Worksheet Addresses in {doc.FileName}." }));
            }

            var row = 2;
            var countAddedAddressBook = 0;
            var name     = ws.Cells[$"A{row}"].GetValue <string>();
            var email    = ws.Cells[$"B{row}"].GetValue <string>();
            var postcode = ws.Cells[$"L{row}"].GetValue <string>();
            var hasRow   = !string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(email) && !string.IsNullOrEmpty(postcode);

            while (hasRow)
            {
                var contact = new AddressBook();
                contact.Id                                          = Guid.NewGuid().ToString();
                contact.ReferenceNo                                 = email;
                contact.CompanyName                                 = ws.Cells[$"M{row}"].GetValue <string>();
                contact.ContactPerson                               = name;
                contact.ContactInformation.Email                    = email;
                contact.ContactInformation.ContactNumber            = ws.Cells[$"C{row}"].GetValue <string>();
                contact.ContactInformation.AlternativeContactNumber = ws.Cells[$"D{row}"].GetValue <string>();
                contact.Address.Address1                            = ws.Cells[$"E{row}"].GetValue <string>();
                contact.Address.Address2                            = ws.Cells[$"F{row}"].GetValue <string>();
                contact.Address.Address3                            = ws.Cells[$"G{row}"].GetValue <string>();
                contact.Address.Address4                            = ws.Cells[$"H{row}"].GetValue <string>();
                contact.Address.City                                = ws.Cells[$"I{row}"].GetValue <string>();
                contact.Address.State                               = ws.Cells[$"J{row}"].GetValue <string>();
                contact.Address.Country                             = ws.Cells[$"K{row}"].GetValue <string>();
                contact.Address.Postcode                            = postcode;
                contact.UserId                                      = User.Identity.Name;

                row++;
                name     = ws.Cells[$"A{row}"].GetValue <string>();
                email    = ws.Cells[$"B{row}"].GetValue <string>();
                postcode = ws.Cells[$"L{row}"].GetValue <string>();
                hasRow   = !string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(email) && !string.IsNullOrEmpty(postcode);

                try
                {
                    using (var session = context.OpenSession())
                    {
                        session.Attach(contact);
                        await session.SubmitChanges("ImportContacts", new Dictionary <string, object> {
                            { "username", User.Identity.Name }
                        });
                    }
                }
                catch (Exception e)
                {
                    errors.Add(new { message = e.Message, contact = contact });
                }

                countAddedAddressBook += 1;
            }

            await store.DeleteAsync(storeId);

            if (errors.Count > 0)
            {
                return(Ok(new { success = false, status = "Some errors happened." }));
            }

            // wait until the worker process it
            await Task.Delay(1500);

            return(Ok(new { success = true, status = $"{countAddedAddressBook} contact(s) added." }));
        }
        public async Task <IHttpActionResult> ChangeGroupName(string group, string newName)
        {
            var       list  = new List <string>();
            var       rows  = int.MaxValue;
            var       page  = 0;
            const int size  = 50;
            var       repos = ObjectBuilder.GetObject <IReadonlyRepository <AddressBook> >();
            var       query = $@"{{
   ""query"": {{
      ""bool"": {{
         ""must"": [
            {{
               ""term"": {{
                  ""CreatedBy"": {{
                     ""value"": ""{User.Identity.Name}""
                  }}
               }}
            }},            
            {{
               ""term"": {{
                  ""Groups"": {{
                     ""value"": ""{group}""
                  }}
               }}
            }}
         ]
      }}
   }},
   ""fields"": []
}}";

            while (list.Count < rows)
            {
                page++;

                var queryString = $"from={size * (page - 1)}&size={size}";

                var response = await repos.SearchAsync(query, queryString);

                var json      = JObject.Parse(response);
                var addresses = from f in json.SelectToken("$.hits.hits")
                                select f.SelectToken("_id").Value <string>();

                list.AddRange(addresses);
                rows = json.SelectToken("$.hits.total").Value <int>();
            }

            var sql     = ObjectBuilder.GetObject <IRepository <AddressBook> >();
            var context = new SphDataContext();

            foreach (var id in list)
            {
                var contact = await sql.LoadOneAsync(id);

                // TODO : removeAll, doesn seem to work
                contact.Groups.RemoveAll(x => x.Equals(group, StringComparison.InvariantCultureIgnoreCase));
                var nn = contact.Groups.Any(x => x.Equals(newName, StringComparison.InvariantCultureIgnoreCase));
                if (!nn)
                {
                    contact.Groups.Add(newName);
                }

                using (var session = context.OpenSession())
                {
                    session.Attach(contact);
                    await session.SubmitChanges("RenameGroup", new Dictionary <string, object> {
                        { "username", User.Identity.Name }
                    });
                }
            }
            // wait a little until it's processed , max 10 seconds
            for (var i = 0; i < 100; i++)
            {
                await Task.Delay(100);

                var response = await repos.SearchAsync(query, "from=0&size=1");

                var json = JObject.Parse(response);
                rows = json.SelectToken("$.hits.total").Value <int>();
                if (rows == 0)
                {
                    break;
                }
            }

            return(Ok(new { message = $"{group} has been renamed to {newName}, there are {list.Count} changes made" }));
        }
        public async Task <ActionResult> SocialMediaHandle(OstSocialModel model)
        {
            if (string.IsNullOrEmpty(model.Email))
            {
                Response.StatusCode = (int)HttpStatusCode.Accepted;
                return(Json(new { success = false, status = "ERROR", message = "Email cannot be set to null or empty." }));
            }
            if (string.IsNullOrEmpty(model.Name))
            {
                Response.StatusCode = (int)HttpStatusCode.Accepted;
                return(Json(new { success = false, status = "ERROR", message = "Name cannot be set to null or empty." }));
            }
            if (string.IsNullOrEmpty(model.Id))
            {
                Response.StatusCode = (int)HttpStatusCode.Accepted;
                return(Json(new { success = false, status = "ERROR", message = "Id cannot be set to null or empty." }));
            }

            if (!string.IsNullOrEmpty(model.IdToken))
            {
                // TODO: Verify the integrity of the ID token
                // Phase 2
                if (model.Brand.Equals("facebook"))
                {
                }
                if (model.Brand.Equals("google"))
                {
                }
            }

            var username = Membership.GetUserNameByEmail(model.Email);

            if (null == username)
            {
                //register
                string strippedName = new string(model.Name.ToCharArray()
                                                 .Where(c => !char.IsWhiteSpace(c))
                                                 .ToArray()).ToLower();
                Random rnd         = new Random();
                int    rndTail     = rnd.Next(1000, 10000);
                var    newUserName = strippedName + rndTail.ToString();
                string password    = Membership.GeneratePassword(8, 1);

                var registerModel = new OstRegisterModel
                {
                    UserName        = newUserName,
                    FullName        = model.Name,
                    Email           = model.Email,
                    Password        = password,
                    ConfirmPassword = password,
                    Designation     = "No contract customer"
                };
                var result = await CreateAccount(registerModel);

                if (!result.Success)
                {
                    Response.StatusCode = (int)HttpStatusCode.Accepted;
                    return(Json(new { success = result.Success, status = "ERROR", message = result.Status }));
                }

                var emailModel = new OstCreateEmailModel
                {
                    UserEmail    = registerModel.Email,
                    UserName     = registerModel.UserName,
                    EmailSubject = "Verify your email address",
                    EmailBody    = $"To finish setting up this {ConfigurationManager.ApplicationFullName} account, we just need to make sure this email address is yours."
                };
                await SendVerificationEmail(emailModel);

                //create user details
                var context    = new SphDataContext();
                var userDetail = new Bespoke.Ost.UserDetails.Domain.UserDetail();
                var guid       = Guid.NewGuid().ToString();
                userDetail.Id     = guid;
                userDetail.UserId = registerModel.UserName;
                userDetail.Profile.ContactPerson            = registerModel.FullName;
                userDetail.ProfilePictureUrl                = model.PictureUrl;
                userDetail.Profile.ContactInformation.Email = registerModel.Email;
                userDetail.Profile.Address.Country          = "MY";
                using (var session = context.OpenSession())
                {
                    session.Attach(userDetail);
                    await session.SubmitChanges("Default");
                }

                Response.StatusCode = (int)HttpStatusCode.OK;
                return(Json(new { success = true, status = "OK", message = $"User {registerModel.UserName} with email {registerModel.Email} has been registered." }));
            }
            else
            {
                //login
                var logger   = ObjectBuilder.GetObject <ILogger>();
                var identity = new ClaimsIdentity(ConfigurationManager.ApplicationName + "Cookie");
                identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, username));
                identity.AddClaim(new Claim(ClaimTypes.Name, username));
                var roles = Roles.GetRolesForUser(username).Select(x => new Claim(ClaimTypes.Role, x));
                identity.AddClaims(roles);


                var context = new SphDataContext();
                var profile = await context.LoadOneAsync <UserProfile>(u => u.UserName == username);

                await logger.LogAsync(new LogEntry { Log = EventLog.Security });

                if (null != profile)
                {
                    // user email address verification pending
                    if (!profile.HasChangedDefaultPassword)
                    {
                        Response.StatusCode = (int)HttpStatusCode.Accepted;
                        return(Json(new { success = false, status = "ERROR", message = "Email verification pending. Please check your inbox for a verification email. You will be allowed to sign in after verification is complete." }));
                    }

                    var claims = profile.GetClaims();
                    identity.AddClaims(claims);

                    var designation = context.LoadOneFromSources <Designation>(x => x.Name == profile.Designation);
                    if (null != designation && designation.EnforceStartModule)
                    {
                        profile.StartModule = designation.StartModule;
                    }

                    HttpContext.GetOwinContext().Authentication.SignIn(identity);

                    Response.StatusCode = (int)HttpStatusCode.OK;
                    return(Json(new { success = true, status = "OK", message = $"User {profile.UserName} with email {profile.Email} has been authenticated." }));
                }
                HttpContext.GetOwinContext().Authentication.SignIn(identity);

                Response.StatusCode = (int)HttpStatusCode.OK;
                return(Json(new { success = true, status = "OK", message = $"User {profile.UserName} with email {profile.Email} has been authenticated." }));
            }
        }
        public async Task <ActionResult> FirstTimeLogin(int step, EstUserInputModel model)
        {
            var pointingUrl  = $"/api/est-registration/" + model.AccountNo;
            var outputString = await m_baseUrlClient.GetAsync(pointingUrl);

            var output       = string.Empty;
            var errorMessage = "Please go to the nearest Pusat Pos Laju (PPL) to reactivate your account.";

            if (outputString.IsSuccessStatusCode)
            {
                output = await outputString.Content.ReadAsStringAsync();

                var item         = JsonConvert.DeserializeObject <EstRegisterModel>(output);
                var encodedEmail = Convert.ToBase64String(Encoding.UTF8.GetBytes(item.EmailAddress));
                if (step == 1)
                {
                    if (model.AccountNo == item.AccountNo)
                    {
                        if (item.AccountStatus == 0)
                        {
                            if (item.EmailAddress != null)
                            {
                                if (IsValidEmail(item.EmailAddress))
                                {
                                    return(RedirectToAction("first-time-login/step/2", "ost-account", new { accNo = item.AccountNo, email = encodedEmail }));
                                }
                                else
                                {
                                    return(RedirectToAction("first-time-login/step/1", "ost-account", new { success = false, status = $"Your registered email address is invalid. {errorMessage}", accNo = item.AccountNo, email = encodedEmail }));
                                }
                            }
                            else
                            {
                                return(RedirectToAction("first-time-login/step/1", "ost-account", new { success = false, status = $"Your registered email address is invalid. {errorMessage}", accNo = item.AccountNo, email = encodedEmail }));
                            }
                        }
                        else if (item.AccountStatus == 1)
                        {
                            return(RedirectToAction("first-time-login/step/1", "ost-account", new { success = false, status = $"Your account has been blocked. {errorMessage}", accNo = item.AccountNo, email = encodedEmail }));
                        }
                        else
                        {
                            return(RedirectToAction("first-time-login/step/1", "ost-account", new { success = false, status = $"Your account has been terminated. {errorMessage}", accNo = item.AccountNo, email = encodedEmail }));
                        }
                    }
                    else
                    {
                        return(RedirectToAction("first-time-login/step/1", "ost-account", new { success = false, status = $"Your account number is invalid. {errorMessage}", accNo = item.AccountNo, email = encodedEmail }));
                    }
                }
                else if (step == 2)
                {
                    if (IsValidEmail(model.EmailAddress) && IsValidEmail(item.EmailAddress))
                    {
                        if ((model.EmailAddress != item.EmailAddress) ||
                            (model.AccountNo != item.AccountNo))
                        {
                            return(RedirectToAction("first-time-login/step/2", "ost-account", new { success = false, status = $"Your email address cannot be verified. {errorMessage}", accNo = item.AccountNo, email = encodedEmail }));
                        }
                    }
                    else
                    {
                        return(RedirectToAction("first-time-login/step/1", "ost-account", new { success = false, status = $"Your registered email address is invalid. {errorMessage}", accNo = item.AccountNo, email = encodedEmail }));
                    }

                    //register customer as Ezisend user; designation - "Contract customer"
                    string password      = Membership.GeneratePassword(8, 1);
                    var    registerModel = new OstRegisterModel
                    {
                        UserName        = model.AccountNo,
                        FullName        = item.CustomerName,
                        Password        = password,
                        ConfirmPassword = password,
                        Email           = model.EmailAddress,
                        Designation     = "Contract customer"
                    };
                    var result = await CreateAccount(registerModel);

                    if (!result.Success)
                    {
                        return(RedirectToAction("first-time-login/step/1", "ost-account", new { success = result.Success, status = result.Status, accNo = item.AccountNo, email = encodedEmail }));
                    }

                    var emailModel = new OstCreateEmailModel
                    {
                        UserEmail    = registerModel.Email,
                        UserName     = registerModel.UserName,
                        EmailSubject = "Create your password",
                        EmailBody    = $"Thank you for registering as a Pos Laju Business Customer user at {ConfigurationManager.ApplicationFullName}. To complete your account registration, you must create a new password.",
                    };
                    await SendForgotPasswordEmail(emailModel);

                    //create user details
                    var context    = new SphDataContext();
                    var userDetail = new Bespoke.Ost.UserDetails.Domain.UserDetail();
                    var guid       = Guid.NewGuid().ToString();
                    userDetail.Id     = guid;
                    userDetail.UserId = registerModel.UserName;
                    userDetail.Profile.CompanyName                                 = item.CompanyName;
                    userDetail.Profile.ContactPerson                               = item.CustomerName;
                    userDetail.ProfilePictureUrl                                   = "/assets/admin/pages/img/avatars/user_default.png";
                    userDetail.Profile.ContactInformation.Email                    = registerModel.Email;
                    userDetail.Profile.ContactInformation.ContactNumber            = item.ContactNo;
                    userDetail.Profile.ContactInformation.AlternativeContactNumber = item.AltContactNo;

                    userDetail.Profile.Address.Address1 = item.Address.Address1;
                    userDetail.Profile.Address.Address2 = item.Address.Address2;
                    userDetail.Profile.Address.Address3 = item.Address.Address3;
                    userDetail.Profile.Address.Address4 = $"{item.Address.Address4} {item.Address.Address5}";
                    userDetail.Profile.Address.City     = item.Address.City;
                    userDetail.Profile.Address.State    = item.Address.State;
                    userDetail.Profile.Address.Country  = "MY"; //item.Address.Country;
                    userDetail.Profile.Address.Postcode = item.Address.Postcode;

                    userDetail.PickupAddress.Address.Address1 = item.PickupAddress.Address1;
                    userDetail.PickupAddress.Address.Address2 = item.PickupAddress.Address2;
                    userDetail.PickupAddress.Address.Address3 = item.PickupAddress.Address3;
                    userDetail.PickupAddress.Address.Address4 = $"{item.PickupAddress.Address4} {item.PickupAddress.Address5}";
                    userDetail.PickupAddress.Address.City     = item.PickupAddress.City;
                    userDetail.PickupAddress.Address.State    = item.PickupAddress.State;
                    userDetail.PickupAddress.Address.Country  = "MY"; //item.PickupAddress.Country;
                    userDetail.PickupAddress.Address.Postcode = item.PickupAddress.Postcode;

                    userDetail.BillingAddress.Address.Address1 = item.BillingAddress.Address1;
                    userDetail.BillingAddress.Address.Address2 = item.BillingAddress.Address2;
                    userDetail.BillingAddress.Address.Address3 = item.BillingAddress.Address3;
                    userDetail.BillingAddress.Address.Address4 = $"{item.BillingAddress.Address4} {item.BillingAddress.Address5}";
                    userDetail.BillingAddress.Address.City     = item.BillingAddress.City;
                    userDetail.BillingAddress.Address.State    = item.BillingAddress.State;
                    userDetail.BillingAddress.Address.Country  = "MY"; //item.BillingAddress.Country;
                    userDetail.BillingAddress.Address.Postcode = item.BillingAddress.Postcode;

                    using (var session = context.OpenSession())
                    {
                        session.Attach(userDetail);
                        await session.SubmitChanges("Default");
                    }

                    return(RedirectToAction("success", "ost-account", new { success = true, status = "OK", operation = "register" }));
                }
            }
            else
            {
                return(RedirectToAction("first-time-login/step/1", "ost-account", new { success = false, status = $"Account number {model.AccountNo} is not exist. {errorMessage}" }));
            }
            return(RedirectToAction("first-time-login/step/1", "ost-account"));
        }
Beispiel #25
0
        public async Task <ActionResult> PsResponsePrepaid()
        {
            var context = new SphDataContext();
            //TODO: Clean-up unused GLs
            //1. get all GLs owned by current user with (Type == "Prepaid") AND (UserId == null)
            //2. delete all found GLs

            var encryptedData = Request.Form["data"];

            if (string.IsNullOrEmpty(encryptedData))
            {
                return(Redirect($"{m_baseUrl}/ost#wallet-list-all"));
            }

            var rijndaelKey   = new RijndaelEnhanced(m_paymentGatewayEncryptionKey);
            var decryptedData = rijndaelKey.Decrypt(encryptedData);

            var decryptedDataArr = decryptedData.Split(new char[] { '|' });

            var model = new PaymentSwitchResponseModel();

            model.TransactionId     = decryptedDataArr[0];
            model.TransactionAmount = decryptedDataArr[1];
            model.TransactionGST    = decryptedDataArr[2];
            model.ServiceFee        = decryptedDataArr[3];
            model.ServiceGST        = decryptedDataArr[4];
            model.TotalAmount       = decryptedDataArr[5];
            model.Status            = decryptedDataArr[6];
            model.ErrorMessage      = decryptedDataArr[7];
            Console.WriteLine(model.ErrorMessage);

            //get wallet to determine wallet Id as GL correspondingId
            LoadData <Wallet> loWallet = await GetWalletByTotalValue(model.TransactionAmount);

            if (null == loWallet.Source)
            {
                Response.StatusCode = (int)HttpStatusCode.NotFound;
                return(Json(new { success = false, status = "ERROR", message = $"Cannot find TransactionAmount with Id: {model.TransactionAmount}." }, JsonRequestBehavior.AllowGet));
            }
            var wallet = loWallet.Source;

            //get userdetail to update AccountBalance
            LoadData <UserDetail> loUserDetail = await GetUserDetail(User.Identity.Name);

            if (null == loUserDetail.Source)
            {
                Response.StatusCode = (int)HttpStatusCode.NotFound;
                return(Json(new { success = false, status = "ERROR", message = $"Cannot find UserId with Id: {User.Identity.Name}." }, JsonRequestBehavior.AllowGet));
            }
            var userDetail = loUserDetail.Source;

            //verify reference no from GL (get by reference no)
            LoadData <GeneralLedger> loGeneralLedger = await GetGeneralLedger(model.TransactionId);

            if (null == loGeneralLedger.Source)
            {
                Response.StatusCode = (int)HttpStatusCode.NotFound;
                return(Json(new { success = false, status = "ERROR", message = $"Cannot find ReferenceNo with Id: {model.TransactionId}." }, JsonRequestBehavior.AllowGet));
            }
            var generalLedger = loGeneralLedger.Source;

            if (model.Status.Equals("1"))
            {
                //update GeneralLedger
                generalLedger.ReferenceNo     = model.TransactionId;
                generalLedger.UserId          = User.Identity.Name;
                generalLedger.Type            = "Prepaid";
                generalLedger.CorrespondingId = wallet.Id;
                generalLedger.Description     = $"{m_applicationName} purchase topup by {User.Identity.Name} for RM{model.TransactionAmount}";
                generalLedger.Amount          = Convert.ToDecimal(model.TransactionAmount);
                generalLedger.ExistingAmount  = Convert.ToDecimal(userDetail.AccountBalance);
                generalLedger.NewAmount       = Convert.ToDecimal(model.TransactionAmount) + Convert.ToDecimal(userDetail.AccountBalance);

                //update UserDetail
                userDetail.AccountBalance = generalLedger.NewAmount;

                using (var session = context.OpenSession())
                {
                    session.Attach(generalLedger);
                    session.Attach(userDetail);
                    await session.SubmitChanges("Default");
                }
                await Task.Delay(1500);

                return(Redirect($"{m_baseUrl}/ost#wallet-history"));
            }
            else
            {
                //fall through
            }

            await Task.Delay(1500);

            return(Redirect($"{m_baseUrl}/ost#wallet-list-all"));
        }
Beispiel #26
0
        //exec:41cddfd4-0781-44b1-db25-cbef78c61352
        public async Task <ActivityExecutionResult> EmailPenggunaAsync()
        {
            var result = new ActivityExecutionResult {
                Status = ActivityExecutionStatus.Success
            };
            var act = this.GetActivity <NotificationActivity>("41cddfd4-0781-44b1-db25-cbef78c61352");

            result.NextActivities = new[] { "e3dc1536-e258-4a73-fb1d-7b59f8fabc35" };

            var @from = await this.TransformFromEmailPenggunaAsync(act.From);

            var to = await this.TransformToEmailPenggunaAsync(act.To);

            var subject = await this.TransformSubjectEmailPenggunaAsync(act.Subject);

            var body = await this.TransformBodyEmailPenggunaAsync(act.Body);

            var cc = await this.TransformBodyEmailPenggunaAsync(act.Cc);

            var bcc = await this.TransformBodyEmailPenggunaAsync(act.Bcc);

            var client = new System.Net.Mail.SmtpClient();
            var mm     = new System.Net.Mail.MailMessage();

            mm.Subject = subject;
            mm.Body    = body;
            mm.From    = new System.Net.Mail.MailAddress(@from);
            mm.To.Add(to);
            if (!string.IsNullOrWhiteSpace(cc))
            {
                mm.CC.Add(cc);
            }
            if (!string.IsNullOrWhiteSpace(bcc))
            {
                mm.Bcc.Add(bcc);
            }
            await client.SendMailAsync(mm).ConfigureAwait(false);


            var context = new SphDataContext();

            foreach (var et in to.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            {
                var et1  = et;
                var user = await context.LoadOneAsync <UserProfile>(u => u.Email == et1);

                if (null == user)
                {
                    continue;
                }
                var message = new Message
                {
                    Subject  = subject,
                    UserName = user.UserName,
                    Body     = body,
                    Id       = Strings.GenerateId()
                };
                using (var session = context.OpenSession())
                {
                    session.Attach(message);
                    await session.SubmitChanges("Email Pengguna").ConfigureAwait(false);
                }
            }


            return(result);
        }