Example #1
0
        public override void TriggerCreating(DbxObject newobj, string type, Dictionary<string, object> properties, BlobDetails blob, string srcuid)
        {
            if (type == "child") {
                // Set last report date
                newobj.Set(new Dictionary<string, object>() {
                    { "lastProgressReport", DateTime.UtcNow.ToString("o") },
                    { "subscriptionStartDate", DateTime.UtcNow.ToString("o") },
                    { "subscriptionEndDate", DateTime.UtcNow.AddMonths(+1).ToString("o") }
                }, "system");
            }

            if (type == "report") {
                // Load user
                DbxObject user;
                string userAname = "";
                string userUid = "";
                if (properties.ContainsKey("user") && !string.IsNullOrEmpty((string)properties["user"])) {
                    user = instance.Uid((string)properties["user"]);
                    userAname = (string)user.GetProp("aname", "system");
                    userUid = user.Uid;
                }

                // Create state file
                var path = Path.GetTempPath() + Path.GetRandomFileName();
                Directory.CreateDirectory(path);
                var pageStateFile = path + "\\pageState.html_";
                Util.PutContents(pageStateFile, (string)properties["pageState"]);

                // Compose email
                var message = SendGrid.GetInstance();
                message.AddTo("*****@*****.**");
                message.From = new MailAddress("*****@*****.**", "KidsPB Contact");
                message.Html = "" +
                    "<p><strong>Type: </strong> " + Util.EncodeHTML((string)properties["type"]) + "</p>" +
                    "<p><strong>User: </strong> " + Util.EncodeHTML(userAname) + " [" + userUid + "] (" + Util.EncodeHTML((string)properties["email"]) + ")</p>" +
                    "<p><strong>Message: </strong> " + Util.EncodeHTML((string)properties["message"]) + "</p>" +
                    "<p><strong>Log: </strong><br /><pre>" + Util.EncodeHTML((string)properties["log"]) + "</pre></p>" +
                    "";
                message.Subject = "Contact from '" + userAname + "'";
                message.AddAttachment(pageStateFile);
                message.DisableFooter();
                message.DisableTemplate();
                var emailtransport = SendGridMail.Transport.Web.GetInstance(new NetworkCredential(GridMailUsername, GridMailPassword));
                emailtransport.Deliver(message);
            }

            if (type == "post") {
                // Focus
                string PostFocus;
                if (null == properties["focus"]) {
                    PostFocus = "Personal Best";
                } else {
                    var Focus = instance.Uid((string)properties["focus"]);
                    PostFocus = Util.EncodeHTML((string)Focus.GetProp("title", "system"));
                }

                // Aname
                var PostAname = Util.EncodeHTML((string)instance.Uid((string)properties["member"]).GetProp("aname", "system"));

                // Message
                var PostMessage = Util.EncodeHTML((string)properties["message"]);

                // Date
                var PostDate = DateTime.Parse((string)properties["date"], null, System.Globalization.DateTimeStyles.RoundtripKind);

                var Message = "<p>Post by " +
                    "<strong>" + PostAname + "</strong> on <em>" + PostFocus + "<br />" +
                    "\"" + PostMessage + "\"" +
                    "<br /><em>" + PostDate.ToString("m") + "</em>" +
                    "</p>" +
                    "<p>Reply to this email and it will be added as a comment.</p>";

                // Find allowed members (leave empty if unrestricted)
                var allowedmembers = null == properties["focus"] ? new HashSet<object>() : instance.Index.GetProperty((string)properties["focus"], "members");

                // Load child
                var child = instance.Uid((string)properties["child"]);

                // Iterate all members of the community
                foreach (var muid in instance.Index.UidsMatching("member", Locate.GenerateSimple("child", properties["child"]))) {
                    // If restricting is active for the focus, skip non-included members
                    if (allowedmembers.Count > 0 && !allowedmembers.Contains(muid)) continue;

                    // Get user UID, skip if no UID available (non-invited member)
                    var userprop = instance.Index.GetProperty(muid, "user");
                    if (userprop.Count == 0) continue;
                    var uuid = (string)userprop.Pop();

                    // Skip user if no longer exists
                    if (!instance.Index.ContainsUid(uuid)) continue;

                    // Skip user if they don't want messages
                    if ((int)instance.Index.GetProperty(uuid, "emailFrequency").Pop() < 0) continue;

                    // Skip if this is the posting user
                    if (uuid == srcuid) continue;

                    // Add message to queue
                    instance.Create("mailqueue", "system", new Dictionary<string, object>(){
                        {"user", uuid},
                        {"email", UidToEmail(newobj.Uid)},
                        {"subject", "Re: " + PostFocus + " ("+child.GetProp("aname", "system")+"\'s Community)"},
                        {"type", "newpost"},
                        {"message", Message}
                    });

                }
            }

            if (type == "comment") {
                var Post = instance.Uid((string)properties["post"]);

                // Focus
                string PostFocus;
                DbxObject Focus = null;
                if (null == Post.GetProp("focus", "system")) {
                    PostFocus = "Personal Best";
                } else {
                    Focus = instance.Uid((string)Post.GetProp("focus", "system"));
                    PostFocus = Util.EncodeHTML((string)Focus.GetProp("title", "system"));
                }

                // Aname
                var PostAname = Util.EncodeHTML((string)instance.Uid((string)properties["member"]).GetProp("aname", "system"));

                // Message
                var PostMessage = Util.EncodeHTML((string)properties["message"]);

                // Date
                var PostDate = DateTime.Parse((string)properties["date"], null, System.Globalization.DateTimeStyles.RoundtripKind);

                var Message = "<p>Comment by " +
                "<strong>" + PostAname + "</strong> on <em>" + PostFocus + "<br />" +
                "\"" + PostMessage + "\"" +
                "<br /><em>" + PostDate.ToString("m") + "</em>" +
                "</p>";

                // Find allowed members
                var allowedmembers = null == Focus ? new ArrayList() : (ArrayList)Focus.GetProp("members", "system");

                // Load child
                var child = instance.Uid((string)Post.GetProp("child", "system"));

                // Iterate all members of the community
                foreach (var muid in instance.Index.UidsMatching("member", Locate.GenerateSimple("child", Post.GetProp("child", "system")))) {
                    // If restricting is active for the focus, skip non-included members
                    if (allowedmembers.Count > 0 && !allowedmembers.Contains(muid)) continue;

                    // Get user UID, skip if no UID available (non-invited member)
                    var userprop = instance.Index.GetProperty(muid, "user");
                    if (userprop.Count == 0) continue;
                    var uuid = (string)userprop.Pop();

                    // Skip user if no longer exists
                    if (!instance.Index.ContainsUid(uuid)) continue;

                    // Skip user if they don't want messages
                    if ((int)instance.Index.GetProperty(uuid, "emailFrequency").Pop() < 0) continue;

                    // Skip if this is the posting user
                    if (uuid == srcuid) continue;

                    // Add message to queue
                    instance.Create("mailqueue", "system", new Dictionary<string, object>(){
                        {"user", uuid},
                        {"email", UidToEmail(Post.Uid)},
                        {"subject", "Re: Comment ("+child.GetProp("aname", "system")+"\'s Community)"},
                        {"type", "newcomment"},
                        {"message", Message}
                    });
                }
            }

            if (type == "library") {
                MemoryStream outstream;
                BlobDetails newblob;
                DbxObject page;
                string icon = null;

                // Prepare properties
                var pageprops = new Dictionary<string, object>();
                pageprops["library"] = newobj.Uid;

                // Determine input type
                switch (blob.ContentType) {
                    case "application/pdf":
                        // Render to multiple images

                        // Load the PDF file.
                        using (var file = PDFFile.Open(blob.Stream)) {
                            file.SerialNumber = "PDFVW4WIN-RQF7C-87MFM-4BR91-5A1AO-B683E";
                            for (int i = 0; i < file.PageCount; i++) {
                                // Get image as stream
                                outstream = new MemoryStream();
                                file.GetPageImage(i, 150).Save(outstream, System.Drawing.Imaging.ImageFormat.Jpeg);

                                // Prepare blob details
                                newblob = new BlobDetails(outstream, "page" + (i + 1) + ".jpg", "image/jpeg", outstream.Length);

                                // Prepare properties
                                pageprops["page"] = ((int)i + 1);

                                // Create instance
                                outstream.Position = 0;
                                page = instance.Create("libraryPage", srcuid, pageprops, newblob);

                                // Note icon (first page)
                                if (null == icon) icon = page.Uid;
                            }
                        }

                        break;
                    case "image/jpeg":
                        // Create instance
                        pageprops["page"] = 1;
                        page = instance.Create("libraryPage", srcuid, pageprops, blob);

                        // Note icon
                        icon = page.Uid;

                        break;
                    case "image/png":
                        // Convert to bitmap
                        var bitmap = new Bitmap(blob.Stream);

                        // Convert to PNG in stream
                        outstream = new MemoryStream();
                        bitmap.Save(outstream, System.Drawing.Imaging.ImageFormat.Jpeg);
                        outstream.Position = 0;

                        // Prepare blob details
                        newblob = new BlobDetails(outstream, "page1.jpg", "image/jpeg", outstream.Length);

                        // Create instance
                        pageprops["page"] = 1;
                        page = instance.Create("libraryPage", srcuid, pageprops, newblob);

                        // Note icon
                        icon = page.Uid;

                        break;
                    default:
                        throw new Exception("Should never happen - schema error allowed bad condition?");

                }

                // Seed skipped properties with defaults
                var baseprops = new Dictionary<string, object>();
                if (!properties.ContainsKey("title") || String.IsNullOrEmpty((string)properties["title"])) baseprops["title"] = blob.Filename.substr(0, 100);
                if (!properties.ContainsKey("details") || String.IsNullOrEmpty((string)properties["details"])) baseprops["details"] = "";
                if (!properties.ContainsKey("dateUploaded") || String.IsNullOrEmpty((string)properties["dateUploaded"])) baseprops["dateUploaded"] = DateTime.UtcNow.ToString("o");
                if (!properties.ContainsKey("dateRelevance") || String.IsNullOrEmpty((string)properties["dateRelevance"])) baseprops["dateRelevance"] = DateTime.UtcNow.ToString("o");
                if (!properties.ContainsKey("icon") || String.IsNullOrEmpty((string)properties["icon"])) baseprops["icon"] = icon;

                newobj.Set(baseprops, srcuid);
            }

            if (type == "progressReport") {
                // Find associated child
                var childobj = instance.Uid((string)properties["child"]).GetWritableInstance();

                // Update last report date
                childobj.Set(new Dictionary<string, object>() { { "lastProgressReport", DateTime.UtcNow.ToString("o") } }, "system");
            }
        }
Example #2
0
        public override void TriggerSet(DbxObject obj, string type, ref Dictionary<string, object> properties, string srcuid)
        {
            if (type == "testTrigger") {
                // Sum
                long a = properties.ContainsKey("a") ? Convert.ToInt64(properties["a"]) : 0;
                long b = properties.ContainsKey("b") ? Convert.ToInt64(properties["b"]) : 0;

                properties["sum"] = a + b;

                // Record count
                var objs = instance.LocateEq("testtrigger", new List<Locate>());
                properties["recordcount"] = objs.Count;
            }
        }
Example #3
0
        public override void TriggerCreating(DbxObject newobj, string type, Dictionary<string, object> properties, BlobDetails blob, string srcuid)
        {
            if (type == "report") {
                var user = instance.Uid((string)properties["src"]);

                var message = SendGrid.GetInstance();
                message.AddTo("*****@*****.**");
                message.From = new MailAddress("*****@*****.**", "Mission Platform Contact");
                message.Html = "<html>" +
                    "<p><strong>Type: </strong> " + Util.EncodeHTML((string)properties["type"]) + "</p>" +
                    "<p><strong>User: </strong> <a href=\"" + user.GetProp("fbLink", "system") + "\">" + Util.EncodeHTML((string)user.GetProp("aname", "system")) + "</a> (" + user.GetProp("email", "system") + ")</p>" +
                    "<p><strong>Message: </strong> " + Util.EncodeHTML((string)properties["message"]) +
                    "</html>";
                message.Subject = "Contact from '" + user.GetProp("aname", "system") + "'";
                var emailtransport = SendGridMail.Transport.Web.GetInstance(new NetworkCredential(GridMailUsername, GridMailPassword));
                emailtransport.Deliver(message);
            }

            if (type == "initiativeContact") {
                var initiative = instance.Uid((string)properties["initiative"]);
                var user = String.IsNullOrEmpty((string)properties["src"]) ? null : instance.Uid((string)properties["src"]);

                // Compose message text
                var messageText = new StringBuilder();
                if (null != user) messageText.AppendLine("<p><strong>User: </strong> <a href=\"" + user.GetProp("fbLink", "system") + "\">" + Util.EncodeHTML((string)user.GetProp("aname", "system")) + "</a> (Registered using " + user.GetProp("email", "system") + ")</p>");
                if (properties.ContainsKey("email")) messageText.AppendLine("<p><strong>Email: </strong> " + Util.EncodeHTML((string)properties["email"]) + "</p>");
                if (properties.ContainsKey("phone")) messageText.AppendLine("<p><strong>Phone: </strong> " + Util.EncodeHTML((string)properties["phone"]) + "</p>");
                messageText.AppendLine("<p><strong>Message: </strong> " + Util.EncodeHTML((string)properties["message"]) + "</p>");

                // Send email
                var message = SendGrid.GetInstance();
                message.AddTo((string)initiative.GetProp("email", "system"));
                message.AddBcc("*****@*****.**");
                message.From = new MailAddress("*****@*****.**", "Mission Platform Contact");
                message.Html = "<html>" + messageText + "</html>";
                message.Subject = "Initiative Enquiry";
                var emailtransport = SendGridMail.Transport.Web.GetInstance(new NetworkCredential(GridMailUsername, GridMailPassword));
                emailtransport.Deliver(message);
            }
        }
Example #4
0
 public override DbxObject ObjectOutput(DbxObject obj)
 {
     return obj;
 }
Example #5
0
        public override DbxObject ObjectOutput(DbxObject obj)
        {
            /*
            // Check if the object needs to be considered for archiving
            if (obj.Type == "initiative" && !((bool)obj.GetProp("archived", "system"))) {
                var archive = false;

                // Check if initiative is more than 90 days old
                if (obj.Serial < Util.DateToSerial(DateTime.UtcNow.AddDays(-90))) archive = true;

                // Check if it has reached its expiry date
                try {
                    var expiry = (string)obj.GetProp("expires", "system");
                    if (!String.IsNullOrWhiteSpace(expiry) && DateTime.UtcNow >= DateTime.Parse(expiry, null, System.Globalization.DateTimeStyles.RoundtripKind)) archive = true;
                } catch (Exception) { }

                // Archive it
                if (archive) {
                    // Upgrade to writable object
                    obj = obj.GetWritableInstance();

                    // Archive object
                    obj.Set(new Dictionary<string, object> { { "archived", true } }, "system");
                }
            }
             * */
            return obj;
        }
Example #6
0
 public abstract void TriggerSet(DbxObject obj, string type, ref Dictionary<string, object> properties, string srcuid);
Example #7
0
 public abstract void TriggerCreating(DbxObject newobj, string type, Dictionary<string, object> properties, BlobDetails blob, string srcuid);
Example #8
0
 public abstract DbxObject ObjectOutput(DbxObject obj);
Example #9
0
        public DbxObject Uid(string uid, bool nocache = false)
        {
            // Must be fast!

            // Check UID is valid
            if (!Index.ContainsUid(uid)) throw new ObjectNotExistException();

            // If we don't have it yet - load it from the database
            var retobj = (DbxObject)CacheObj["object-" + uid]; // Done like this to handle thread sync issues
            if (null == retobj || nocache) {
                lock (CacheObj) {
                    // Retrieve from database
                    var retry = new RetryPolicy<DbRetryStrategy>(3, new TimeSpan(0, 0, 1));
                    using (var cmd = ObjDb.Query("SELECT [oid],[uid],[type],[serial],[predecessor],[creator],[properties] FROM [obj] WHERE [uid]=@uid AND [oid] NOT IN (SELECT [predecessor] FROM [obj]) ORDER BY [oid] DESC")) { // Returns most recent view of objects
                        cmd.Bind("uid", uid);

                        // Load object
                        DbxObject obj;
                        using (var rdr = cmd.ExecuteReaderWithRetry(retry)) {
                            // Check record existed
                            if (!rdr.Read()) {
                                throw new ObjectNotExistException();
                            }

                            // Create object
                            obj = new DbxObject(this, (long)rdr["oid"], (string)rdr["uid"], (string)rdr["type"], (long)rdr["serial"], (long)rdr["predecessor"], (string)rdr["creator"], (string)rdr["properties"]);
                        }

                        // Add item to cache
                        var expires = new CacheItemPolicy();
                        expires.AbsoluteExpiration = DateTime.Now.AddMinutes(10);
                        CacheObj.Add(uid, obj, expires);

                        // Return object
                        return obj;
                    }
                }
            }

            // Return object
            return retobj;
        }