示例#1
0
        protected override Umbraco.Web.Models.Trees.TreeNodeCollection GetTreeNodes(string id, System.Net.Http.Formatting.FormDataCollection queryStrings)
        {
            //check if we're rendering the root node's children
            if (id == Constants.System.Root.ToInvariantString())
            {
                var ctrl  = new MCFlyApiController();
                var nodes = new TreeNodeCollection();

                foreach (var form    in ctrl.GetAll())
                {
                    var node = CreateTreeNode(
                        form.Id.ToString(),
                        "-1",
                        queryStrings,
                        form.Name,
                        "icon-plane",
                        false);

                    nodes.Add(node);
                }
                return(nodes);
            }

            //this tree doesn't suport rendering more than 1 level
            throw new NotSupportedException();
        }
        //[ValidateGoogleCaptcha]
        public ActionResult HandleAjaxForm(FormCollection frm)
        {
            var typeName = frm["FullName"];

            var form = new MCFlyApiController().GetByAlias(typeName);


            var type = UIOMatic.Helper.GetUIOMaticTypes().FirstOrDefault(x => x.FullName == typeName);

            var instance = Activator.CreateInstance(type);

            var dict = new Dictionary <string, object>();

            foreach (PropertyInfo prop in type.GetProperties())
            {
                if (prop.Name != "Id" && prop.Name != "Created" && prop.Name != "UmbracoPage" && prop.Name != "UmbracoMember")
                {
                    var fld = form.Fields.FirstOrDefault(x => x.Alias == prop.Name);

                    var val = fld.FieldType.Process(form, fld, !frm.AllKeys.Contains(prop.Name) ? null : frm[prop.Name], ControllerContext);

                    if (fld.FieldType.FrontEndRenderView == "CheckBox" && (bool)val == false)
                    {
                        ModelState.AddModelError(string.Empty, $"The field {0} is required");
                    }

                    if (val != null && val.ToString() != string.Empty)
                    {
                        prop.SetValue(instance, val);
                        dict.Add(prop.Name, val);
                    }
                }
                if (prop.Name == "Member")
                {
                    var memberShipHelper = new MembershipHelper(Umbraco.UmbracoContext);
                    var member           = Services.MemberService.GetById(memberShipHelper.GetCurrentMemberId());
                    if (memberShipHelper.IsLoggedIn())
                    {
                        prop.SetValue(instance, member.Name);
                        dict.Add("UmbracoMember", member.Name);
                    }
                    else
                    {
                        prop.SetValue(instance, "");
                        dict.Add("UmbracoMember", "");
                    }
                }
                if (prop.Name == "Created")
                {
                    prop.SetValue(instance, DateTime.Now);
                    dict.Add("Created", DateTime.Now);
                }
                if (prop.Name == "UmbracoPage")
                {
                    prop.SetValue(instance, frm["Umbraco.AssignedContentItem.Id"]);
                    dict.Add("UmbracoPage", frm["Umbraco.AssignedContentItem.Id"]);
                }
            }

            // Server Side Validation
            var context = new ValidationContext(instance, null, null);
            var results = new List <ValidationResult>();

            Validator.TryValidateObject(instance, context, results, true);

            if (results.Any())
            {
                foreach (var error in results)
                {
                    ModelState.AddModelError(error.MemberNames.FirstOrDefault(), error.ErrorMessage);
                }
            }

            if (!ModelState.IsValid)
            {
                return(Json(new { message = "Failure" }));
            }

            ////workaround for nullable string props
            foreach (PropertyInfo prop in type.GetProperties())
            {
                if (prop.Name != "Id" && prop.Name != "Created" && prop.Name != "UmbracoPage" && prop.Name != "UmbracoMember")
                {
                    if (string.IsNullOrEmpty(frm[prop.Name]) && prop.PropertyType == typeof(string))
                    {
                        var val = string.Empty;
                        if (prop.GetValue(instance) == null)
                        {
                            prop.SetValue(instance, val);
                            dict.Remove(prop.Name);
                            dict.Add(prop.Name, val);
                        }
                    }
                }
            }

            //Store Record to DB
            if (form.StoresData)
            {
                UIOMaticObjectService.Instance.Create(type, dict);
            }

            //Send Emails
            foreach (var email in form.Emails)
            {
                var mm = new MailMessage
                {
                    Body       = EmailRenderer.Render(email.Template, instance, form, email, Umbraco.TypedContent(frm["Umbraco.AssignedContentItem.Id"])),
                    IsBodyHtml = true,
                    Subject    = email.Subject ?? "New " + form.Name + " entry",
                    From       = new MailAddress(email.From)
                };

                mm.Headers.Add("X-Application", "Website");
                mm.Headers.Add("MIME-Version", "1.0");
                mm.Headers.Add("Content-Type", "text/html;charset=utf-8");
                mm.Headers.Add("Content-Transfer-Encoding", "base64");
                mm.SubjectEncoding = Encoding.UTF8;
                mm.HeadersEncoding = Encoding.UTF8;
                mm.BodyEncoding    = Encoding.UTF8;

                mm.To.Add(email.ToProperty != string.Empty
                    ? new MailAddress(type.GetProperty(email.ToProperty).GetValue(instance).ToString(), type.GetProperty(email.ToProperty).GetValue(instance).ToString(), Encoding.UTF8)
                    : new MailAddress(email.To, email.To, Encoding.UTF8));

                using (SmtpClient client = new SmtpClient())
                {
                    client.Send(mm);
                }
            }

            //Do more stuff
            if (!string.IsNullOrEmpty(form.WebHookUrl))
            {
                var client = new WebClient
                {
                    Encoding = Encoding.UTF8
                };
                client.Headers[HttpRequestHeader.ContentType] = "application/json";

                try
                {
                    var response = client.UploadString(form.WebHookUrl, "POST", JsonConvert.SerializeObject(dict));
                }

                catch (Exception ex)
                {
                    //log
                }
            }

            return(Json(new { Success = true }));
        }
示例#3
0
        public ActionResult HandleAjaxForm(FormCollection frm)
        {
            var typeName = frm["FullName"];

            var form = new MCFlyApiController().GetByAlias(typeName);


            var type = UIOMatic.Helper.GetUIOMaticTypes().FirstOrDefault(x => x.FullName == typeName);

            var instance = Activator.CreateInstance(type);

            var dict = new Dictionary <string, object>();

            foreach (PropertyInfo prop in type.GetProperties())
            {
                if (prop.Name != "Id" && prop.Name != "Created" && prop.Name != "UmbracoPage")
                {
                    var fld = form.Fields.FirstOrDefault(x => x.Alias == prop.Name);


                    var val = fld.FieldType.Process(form, fld, !frm.AllKeys.Contains(prop.Name) ? null : frm[prop.Name], ControllerContext);

                    if (val != null && val.ToString() != string.Empty)
                    {
                        prop.SetValue(instance, val);
                        dict.Add(prop.Name, val);
                    }
                }
                if (prop.Name == "Created")
                {
                    prop.SetValue(instance, DateTime.Now);
                    dict.Add("Created", DateTime.Now);
                }
                if (prop.Name == "UmbracoPage")
                {
                    prop.SetValue(instance, frm["Umbraco.AssignedContentItem.Id"]);
                    dict.Add("UmbracoPage", frm["Umbraco.AssignedContentItem.Id"]);
                }
            }

            //Server Side Validation
            //var context = new ValidationContext(instance, null, null);
            //var results = new List<ValidationResult>();

            //Validator.TryValidateObject(instance, context, results, true);

            //if (results.Any())
            //{
            //    foreach (var error in results)
            //    {

            //        ModelState.AddModelError(error.MemberNames.FirstOrDefault(), error.ErrorMessage);
            //    }

            //}

            //if (!ModelState.IsValid)
            //    return CurrentUmbracoPage();

            ////workaround for nullable string props
            foreach (PropertyInfo prop in type.GetProperties())
            {
                if (prop.Name != "Id" && prop.Name != "Created" && prop.Name != "UmbracoPage")
                {
                    if (string.IsNullOrEmpty(frm[prop.Name]) && prop.PropertyType == typeof(string))
                    {
                        var val = string.Empty;
                        if (prop.GetValue(instance) == null)
                        {
                            prop.SetValue(instance, val);
                            dict.Remove(prop.Name);
                            dict.Add(prop.Name, val);
                        }
                    }
                }
            }

            //Store Record to DB
            if (form.StoresData)
            {
                UIOMaticObjectService.Instance.Create(type, dict);
            }

            //Send Emails
            foreach (var email in form.Emails)
            {
                var mm = new MailMessage
                {
                    Body       = EmailRenderer.Render(email.Template, instance, form, email, Umbraco.TypedContent(frm["Umbraco.AssignedContentItem.Id"])),
                    IsBodyHtml = true,
                    Subject    = email.Subject ?? "New " + form.Name + " entry",
                    From       = new MailAddress(email.From)
                };

                mm.To.Add(email.ToProperty != string.Empty ? new MailAddress(type.GetProperty(email.ToProperty).GetValue(instance).ToString()) : new MailAddress(email.To));

                new SmtpClient().Send(mm);
            }

            //Do more stuff
            if (!string.IsNullOrEmpty(form.WebHookUrl))
            {
                var client = new WebClient
                {
                    Encoding = Encoding.UTF8
                };
                client.Headers[HttpRequestHeader.ContentType] = "application/json";

                try
                {
                    var response = client.UploadString(form.WebHookUrl, "POST", JsonConvert.SerializeObject(dict));
                }

                catch (Exception ex)
                {
                    //log
                }
            }

            return(Json(new
            {
                Success = true,
            }));
        }
示例#4
0
文件: Events.cs 项目: laniatech/MCFly
        protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
        {
            MCFly.Core.Helper.EnsureMCFlyFieldTypes();

            var ctx = applicationContext.DatabaseContext;
            var db  = new DatabaseSchemaHelper(ctx.Database, applicationContext.ProfilingLogger.Logger, ctx.SqlSyntax);

            if (!db.TableExist("MCFlyForms"))
            {
                db.CreateTable <Form>(true);
            }

            if (!db.TableExist("MCFlyFields"))
            {
                db.CreateTable <Field>(true);
            }

            if (!db.TableExist("MCFlyFieldOptions"))
            {
                db.CreateTable <MCFly.Core.FieldOption>(true);
            }

            if (!db.TableExist("MCFlyEmails"))
            {
                db.CreateTable <MCFly.Core.Email>(true);
            }



            if (!db.TableExist("MCFlyFlags"))
            {
                db.CreateTable <MCFly.Core.Flag>(true);
            }

            var ctrl = new MCFlyApiController();

            foreach (var form in ctrl.GetAll())
            {
                var  completeForm = ctrl.GetById(form.Id);
                Type type         = MyTypeBuilder.CreateNewObject(completeForm);


                var flagExist = ctx.Database.Fetch <MCFly.Core.Flag>(new Sql().Select("*").From("MCFlyFlags").Where <MCFly.Core.Flag>(x => x.FormId == form.Id)).Any();

                if (!db.TableExist(completeForm.Alias) || flagExist)
                {
                    db.CreateTable(true, type);

                    ctx.Database.Execute(new Sql("Delete From [MCFlyFlags] Where [FormId] = @0", form.Id));
                }
            }


            //MyTypeBuilder.BuildingCustomValidationAttributes += MyTypeBuilder_Building;
            var targetDbVersion  = new SemVersion(1, 0, 0); // Update this whenever a migration change is made
            var currentDbVersion = new SemVersion(0, 0, 0);

            var migrations      = ApplicationContext.Current.Services.MigrationEntryService.GetAll("MCFly");
            var latestMigration = migrations.OrderByDescending(x => x.Version).FirstOrDefault();

            if (latestMigration != null)
            {
                currentDbVersion = latestMigration.Version;
            }

            if (targetDbVersion == currentDbVersion)
            {
                return;
            }

            var migrationsRunner = new MigrationRunner(
                ApplicationContext.Current.Services.MigrationEntryService,
                ApplicationContext.Current.ProfilingLogger.Logger,
                currentDbVersion,
                targetDbVersion,
                "MCFly");

            try
            {
                migrationsRunner.Execute(UmbracoContext.Current.Application.DatabaseContext.Database);
            }
            catch (Exception e)
            {
                LogHelper.Error <Events>("Error running MCFly migrations", e);
            }
        }