Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Brendan Rice 538 posts 1102 karma points
    Feb 01, 2011 @ 15:21
    Brendan Rice
    0

    AbstractDataEditor strange behaviour

    I have the requirement to build a custom DataType that integrates into a 3rd party api. I have managed to get the data back from the API I require but am getting strange behaviour with the AbstractDataEditor when it tries to save data.

    I profiled the SQL database to see what is happening and managed to track down the error to SQL statement below:

    exec sp_executesql N'update cmsPropertyData set dataNtext = @value where id = 0',N'@value nvarchar(72)',@value=N'<Survey><survey id="454169" text="Test Survey" javascript="" /></Survey>'

    You can see that the id = 0 which will never cause a row to be updated.

     

    I have included the code for my DataType below:

    Any help with this would be really appreciated.

     

    using System;
    using System.Collections.Generic;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Xml;
    using Amaze.Umbraco.SurveyGizmo.Control;
    using Amaze.Umbraco.SurveyGizmo.Model;
    using System.Configuration;
    using System.Net;
    using System.Xml.Linq;
    using System.Web.Caching;
    using System.Linq;
    using Amaze.Umbraco.SurveyGizmo.Data;

    namespace Amaze.Umbraco.SurveyGizmo.CustomDataEditor
    {
        //using custom prevalue editor
        public class SelectSurveyDataType: umbraco.cms.businesslogic.datatype.AbstractDataEditor
        {
            private AmazeDropDownList _control = new AmazeDropDownList();
            private umbraco.interfaces.IData _data;
            
            public XmlDocument _xml { get; set; }
            
            public override Guid Id
            {
                get
                {
                    return new Guid("255CBF42-6CBD-40AB-A9FA-C77836039FF0");
                }
            }

            public override string DataTypeName
            {
                get
                {
                    return "SelectSurvey (without data editor settings)";
                }
            }

            public SelectSurveyDataType(): base()
            {
                base.RenderControl = _control;
                _control.Init += new EventHandler(m_control_Init);
                base.DataEditorControl.OnSave += new umbraco.cms.businesslogic.datatype.AbstractDataEditorControl.SaveEventHandler(DataEditorControl_OnSave);
            }

            void DataEditorControl_OnSave(EventArgs e)
            {
                Save();
            }

            public void m_control_Init(object sender, EventArgs e)
            {
                IList<Survey> surveys = GetSurveys();
                CacheSurveys(surveys);

                _control.BindToProperties<Survey>(surveys, x => x.Title, x => x.Id);
                            
                // set the value of the control
                if (_data != null && _data.Value != null)
                {
                    _xml = new XmlDocument();
                    
                    _xml.LoadXml(_data.Value.ToString());

                    _control.SelectedValue = GetSelectedValue();
                }
                else
                {
                    _xml = CreateBaseXmlDocument();
                }            
            }

            /// <summary>
            /// Gets the data.
            /// </summary>
            /// <value>The data.</value>
            public override umbraco.interfaces.IData Data
            {
                get
                {
                    if (_data == null)
                    {
                        _data = new SelectSurveyData(this);
                    }
                        
                    return _data;
                }
            }

            private string GetSelectedValue()
            {
                XDocument doc = XDocument.Parse(_xml.OuterXml);

                try
                {
                    return doc.Root.Elements().First().Attribute("id").Value;
                }
                catch (Exception)
                {
                    return null;
                }            
            }

            private IList<Survey> GetSurveys()
            {
                // build URL up at runtime
                string developerKey = ConfigurationManager.AppSettings["SurveyGizmoDeveloperKey"];
                string userKey = ConfigurationManager.AppSettings["SurveyGizmoUserKey"];
                string url = String.Format(ConfigurationManager.AppSettings["SurveyGizmoApiUrl"], developerKey, userKey, "sgGetSurveyList");

                WebRequest request = WebRequest.Create(url);
                IList<Survey> surveys = null;

                try
                {
                    WebResponse response = request.GetResponse();
                    System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
                    XDocument xmlDoc = new XDocument();
                    xmlDoc = XDocument.Parse(sr.ReadToEnd());

                    string status = xmlDoc.Root.Element("status").Value;

                    if (status == "success")
                    {
                        var surveysQuery = from xmlSurvey in xmlDoc.Root.Descendants("survey")
                                           select new Survey
                                           {
                                               CountAbandoned = (int)xmlSurvey.Element("count_abandoned"),
                                               CountComplete = (int)xmlSurvey.Element("count_abandoned"),
                                               CountInProgress = (int)xmlSurvey.Element("count_abandoned"),
                                               CountOverflow = (int)xmlSurvey.Element("count_abandoned"),
                                               CountPartial = (int)xmlSurvey.Element("count_abandoned"),
                                               DateCreated = (string)xmlSurvey.Element("date_created"),
                                               DateLastActivity = (string)xmlSurvey.Element("date_lastactivity"),
                                               DateModified = (string)xmlSurvey.Element("date_modified"),
                                               Id = (string)xmlSurvey.Element("id"),
                                               JavascriptEmbedingCode = (string)xmlSurvey.Element("js_embedingcode"),
                                               LinkEdit = (string)xmlSurvey.Element("link_edit"),
                                               LinkPreview = (string)xmlSurvey.Element("link_preview"),
                                               LinkReporting = (string)xmlSurvey.Element("link_reporting"),
                                               PublishLink = (string)xmlSurvey.Element("publish_link"),
                                               ResponseChart = (string)xmlSurvey.Element("response_chart"),
                                               Status = (string)xmlSurvey.Element("status"),
                                               SurveyType = (string)xmlSurvey.Element("survey_type"),
                                               Team = (string)xmlSurvey.Element("team"),
                                               Title = (string)xmlSurvey.Element("title"),
                                               UserCreated = (string)xmlSurvey.Element("user_created"),
                                               UserEmail = (string)xmlSurvey.Element("user_email"),
                                               Version = (string)xmlSurvey.Element("version")
                                           };

                        surveys = surveysQuery.ToList();
                    }

                }
                catch (WebException)
                {
                    // handle if necessary    
                }

                return surveys;
            }

            private void CacheSurveys(IList<Survey> surveys)
            {
                // insert a value into cache that will serve
                // as the cache key
                HttpRuntime.Cache["Surveys"] = surveys;

                // create an array of cache keys
                string[] keys = new String[1];
                keys[0] = "CacheKey";

                CacheDependency dep = new CacheDependency(null, keys);

                // insert an item into cache with a dependency on
                // the above CacheDependency
                HttpRuntime.Cache.Insert("Key", "Value", dep);
            }
            /// <summary>
            /// Creates the base XML document.
            /// </summary>
            /// <returns></returns>
            private XmlDocument CreateBaseXmlDocument()
            {
                XmlDocument doc = new XmlDocument();
                XmlNode root = doc.CreateElement("Survey");
                doc.AppendChild(root);
                return doc;
            }

            private void Save()
            {
                XmlDocument doc = CreateBaseXmlDocument();
                XmlNode root = doc.DocumentElement;

                XmlNode newNode = doc.CreateElement("survey");

                XmlNode idAttribute = doc.CreateNode(XmlNodeType.Attribute, "id", null);
                idAttribute.Value = this._control.SelectedValue;
                newNode.Attributes.SetNamedItem(idAttribute);

                XmlNode textAttribute = doc.CreateNode(XmlNodeType.Attribute, "text", null);
                textAttribute.Value = this._control.SelectedItem.Text;
                newNode.Attributes.SetNamedItem(textAttribute);

                XmlNode javascriptAttribute = doc.CreateNode(XmlNodeType.Attribute, "javascript", null);
                javascriptAttribute.Value = GetJavascriptEmbedCode(this._control.SelectedValue);
                newNode.Attributes.SetNamedItem(javascriptAttribute);

                root.AppendChild(newNode);

                this._data.Value = doc.InnerXml;

                base.Data.Value = this._data.Value;
            }

            private string GetJavascriptEmbedCode(string surveyId)
            {
                IEnumerable<Survey> surveys = (IEnumerable<Survey>)HttpRuntime.Cache["Surveys"];

                Survey selectedSurvey = (from Survey s in surveys
                                         where s.Id == surveyId
                                         select s).FirstOrDefault();

                string javascript = null;

                if(selectedSurvey != null)
                {
                    javascript = selectedSurvey.JavascriptEmbedingCode.Replace(":www", ":&#x2F;&#x2F;www");
                }            

                return javascript;
            }
            
        }
    }

     

     

     

  • Brendan Rice 538 posts 1102 karma points
    Feb 01, 2011 @ 16:02
    Brendan Rice
    0

    I think this is related to the override of the Data property casuing things to go a bit off.

  • This forum is in read-only mode while we transition to the new forum.

    You can continue this topic on the new forum by tapping the "Continue discussion" link below.

Please Sign in or register to post replies