Exemple #1
0
        public void Add(ProjectExceptionArgs Args)
        {
            Initialize();

            XmlElement newElm = clsXmErrors.CreateElement("error");

            clsXmErrors.DocumentElement.AppendChild(newElm);

            newElm.SetAttribute("severity", Args.Severity.ToString());
            newElm.SetAttribute("log", Args.Log.ToString());

            if (Args.SourceClass != null)
            {
                newElm.SetAttribute("sourceclass", Args.SourceClass);
            }

            if (Args.SourceMethod != null)
            {
                newElm.SetAttribute("sourcemethod", Args.SourceMethod);
            }

            if (Args.SourceSnippet != null)
            {
                newElm.SetAttribute("sourcesnippet", Args.SourceSnippet);
            }

            if (Args.Message != null)
            {
                newElm.InnerText = Args.Message;
            }
        }
        public void Add(ProjectExceptionArgs Args)
        {
            Initialize();

            XmlElement newElm = clsXmErrors.CreateElement("error");
            clsXmErrors.DocumentElement.AppendChild(newElm);

            newElm.SetAttribute("severity", Args.Severity.ToString());
            newElm.SetAttribute("log", Args.Log.ToString());

            if (Args.SourceClass != null)
                newElm.SetAttribute("sourceclass", Args.SourceClass);

            if (Args.SourceMethod != null)
                newElm.SetAttribute("sourcemethod", Args.SourceMethod);

            if (Args.SourceSnippet != null)
                newElm.SetAttribute("sourcesnippet", Args.SourceSnippet);

            if (Args.Message != null)
                newElm.InnerText = Args.Message;
        }
Exemple #3
0
 public ProjectException(ProjectExceptionArgs Args, Exception inner) : base(Args.Message, inner)
 {
     _args = Args;
 }
Exemple #4
0
 public ProjectException(string Message, Exception inner) : base(Message, inner)
 {
     _args = new ProjectExceptionArgs(Message);
 }
Exemple #5
0
 public ProjectException(ProjectExceptionArgs Args) : base(Args.Message)
 {
     _args = Args;
 }
Exemple #6
0
        public virtual void ProcessTemplate()
        {
            if (_xslt == null)
            {
                ProjectExceptionArgs args = new ProjectExceptionArgs("XSL Not Set, ProcessTemplate aborted", "WebTemplater", "ProcessTemplate", null, SeverityLevel.Critical, LogLevel.Event);
                throw new ProjectException(args);
            }

            //initialize xslt global param vars
            string doc_folder = httpC.Request.Path;

            //strip application name
            doc_folder = doc_folder.Substring(0,doc_folder.LastIndexOf("/") + 1);

            //Current Page - DOC_ACTION
            _args.AddParam("DOC_ACTION", "", httpC.Request.Path);

            //Current Folder - DOC_FOLDER
            _args.AddParam("DOC_FOLDER", "", doc_folder);

            using (_writer = new StringWriter())
            {
                //_xslt.Transform(_xml.CreateNavigator(),_args, _writer);
                _xslt.xslTransformer(_xml.CreateNavigator(), _args);
                _xslt.XMLObjectSource = _xml;
                _writer.Write(_xslt.ResultText);
            }
        }
Exemple #7
0
        private void BuildResults(SqlDataReader dr, int subqueryIndex = 0)
        {
            // paging
            switch (_pagingDirection)
            {
                case DatabaseQueryPagingDirection.Top:
                    _currentPage = 1;
                    break;
                case DatabaseQueryPagingDirection.Next:
                    _currentPage++;
                    break;
                case DatabaseQueryPagingDirection.Previous:
                    _currentPage--;
                    if (_currentPage < 1)
                        _currentPage = 1;
                    break;
            }

            int startread = (_currentPage * _pagingLimit) - _pagingLimit;
            int endread = startread + _pagingLimit;

            //build result node
            MemoryStream stream = new MemoryStream();
            XmlTextWriter w = new XmlTextWriter(stream, Encoding.UTF8);

            XmlNodeList fieldNodes;

            // begin writing the xml result
            w.WriteStartElement("result");

            try
            {

                //field values for results
                if(subqueryIndex > 0)
                    fieldNodes = _querynode.SelectNodes(String.Format(@"subquery[{0}]/fields/field", subqueryIndex));
                else
                    fieldNodes = _querynode.SelectNodes(@"fields/field");

                //add rows to result node
                long currentrow = 0;

                _resultPages = getNewResultPages(_querynode);
                int pagecount = 1;
                int inpagecount = 0;
                while (dr.Read())
                {
                    bool flginpage = false;

                    if ((currentrow >= (startread) && currentrow < endread) || _pagingLimit == -1)
                        flginpage = true;

                    #region in page write results
                    if (flginpage)
                    {
                        w.WriteStartElement("row");

                        // if we come accross Json fields, they are translated to Xml and added as child to row node
                        // keep track of them and add them after all attributes have been processed
                        List<string> innerXml = new List<string>();

                        //attributes (fields)
                        if (fieldNodes.Count > 0)
                        {
                            foreach (XmlElement m in fieldNodes)
                            {
                                try
                                {
                                    // validate json type
                                    if (m.GetAttribute("type") == "json")
                                    {
                                        try
                                        {

                                            var val = dr[m.GetAttribute("name")].ToString();
                                            string json = null;
                                            if (string.IsNullOrEmpty(val))
                                            {
                                                json = "{}";
                                            }
                                            else
                                            {
                                                var jsoObj = Newtonsoft.Json.Linq.JObject.Parse(val);
                                                json = val;
                                            }
                                            w.WriteAttributeString(m.GetAttribute("name").ToString(), json);
                                        }
                                        catch (IndexOutOfRangeException handled)
                                        {
                                            throw handled;
                                        }
                                        catch (Exception unhandled)
                                        {
                                            w.WriteAttributeString(m.GetAttribute("name").ToString(), "{\"error\":\"" + unhandled.Message + "\"}");
                                        }
                                    }
                                    else
                                    {
                                        string val = null;
                                        if(!(m.HasAttribute("encode") || m.HasAttribute("regx")))
                                            val = dr[m.GetAttribute("name")].ToString().Trim();

                                        if (m.HasAttribute("encode"))
                                        {
                                            val = System.Web.HttpUtility.UrlEncode(dr[m.GetAttribute("encode")].ToString().TrimEnd()).Replace("+", "%20"); ;
                                        }
                                        if (m.HasAttribute("regx") && m.HasAttribute("replace") && m.HasAttribute("field"))
                                        {
                                            val = dr[m.GetAttribute("field")].ToString().Trim();
                                            val = Regex.Replace(val, m.GetAttribute("regex").ToString(), m.GetAttribute("replace").ToString());
                                        }
                                        w.WriteAttributeString(m.GetAttribute("name").ToString(), String.IsNullOrEmpty(val) ? "" : val.ToString().Trim());
                                    }

                                    if (m.GetAttribute("type") == "json")
                                    {
                                        string xml = null;
                                        try
                                        {

                                            var details = dr[m.GetAttribute("name")].ToString();

                                            // try to parse it

                                            string jsonDetails = String.Format("{{\"{0}\":{1}}}", m.GetAttribute("name"), details);
                                            xml = JsonConvert.DeserializeXmlNode(jsonDetails).OuterXml;
                                            if (xml.StartsWith("<?"))
                                                xml = xml.Substring(xml.IndexOf("?>") + 2);
                                        }
                                        catch (JsonReaderException) { }
                                        catch (JsonSerializationException) { }
                                        finally
                                        {
                                            if(xml != null)
                                                innerXml.Add(xml);
                                        }
                                    }
                                }
                                catch (IndexOutOfRangeException handled)
                                {
                                    w.WriteAttributeString(m.GetAttribute("name").ToString(), "#field not found#");
                                }
                            }
                        }
                        else
                        {
                            for (int i = 0; i < dr.FieldCount; i++)
                            {
                                w.WriteAttributeString(dr.GetName(i), dr[i].ToString().Trim());
                            }
                        }

                        // add inner xml
                        foreach (String s in innerXml)
                            w.WriteRaw(s);

                        w.WriteEndElement();
                    }
                    #endregion

                    _rowsaffected = (Int32)currentrow++;
                    inpagecount++;
                    if (inpagecount >= _pagingLimit)
                    {
                        _resultPages.Add(new ResultPaging(pagecount++, inpagecount));
                        inpagecount = 0;
                    }

                }

                // get last result for _resultPage
                if (inpagecount > 0)
                    _resultPages.Add(new ResultPaging(pagecount++, inpagecount));

                _results = true;

                // reset a couple of paging items
                _currentPage = 1;
                _pagingDirection = DatabaseQueryPagingDirection.None;
            }
            catch (IndexOutOfRangeException ie)
            {
                string errmsg = string.Format("One or more invalid Field or Parameters for QueryName: {0}", _querynode.Attributes["name"].InnerText);
                ProjectExceptionArgs args = new ProjectExceptionArgs(errmsg, "Database.cs", "BuildResults", null, SeverityLevel.Fatal, LogLevel.Event);
                throw new ProjectException(args, ie);
            }
            catch (SqlException se)
            {
                string errmsg = string.Format("ExecuteReader Error For QueryName: {0}", _querynode.Attributes["name"].InnerText);
                ProjectExceptionArgs args = new ProjectExceptionArgs(errmsg, "Database.cs", "BuildResults", null, SeverityLevel.Fatal, LogLevel.Event);
                throw new ProjectException(args, se);
            }

            //end result node
            w.WriteEndElement();
            w.Flush();

            // include sub results (StoredProcedure returns more than one Result Set)
            while (dr.NextResult())
            {
                subqueryIndex++;
                BuildResults(dr, subqueryIndex);
            }

            //add stream xml to return xml
            XmlDocument xmStreamObj = new XmlDocument();
            stream.Seek(0, SeekOrigin.Begin);
            xmStreamObj.Load(stream);

            //import result xml to original xml obj
            XmlNode import = _xmresult.ImportNode(xmStreamObj.DocumentElement, true);
            XmlNode elm;
            if (subqueryIndex > 0 && _xmresult.SelectSingleNode("results/subquery") == null)
                elm = _xmresult.SelectSingleNode("results").AppendChild(_xmresult.CreateElement("subquery"));
            else
                elm = _xmresult.SelectSingleNode("results");

            elm.AppendChild(import);
        }
Exemple #8
0
        private void AddParameter(string name, object value, string valueType, string inout, int size)
        {
            _command.CommandType = CommandType.StoredProcedure;
            SqlParameter parameter = null;
            ProjectExceptionArgs args = null;

            switch (valueType)
            {
                case ("int"):
                    parameter = _command.Parameters.Add(name, SqlDbType.Int);
                    try
                    {
                        parameter.Value = Convert.ToInt32(value);
                    }
                    catch (FormatException)
                    {
                        args = new ProjectExceptionArgs(
                           String.Format("Invalid parameter value for: {0} - expecting valid number", name),SeverityLevel.Format);
                        _handler.Add(args);
                    }
                    break;
                case ("date"):
                    parameter = _command.Parameters.Add(name, SqlDbType.DateTime);
                    try
                    {
                        parameter.Value = Convert.ToDateTime(value);
                    }
                    catch (FormatException)
                    {
                        args = new ProjectExceptionArgs(
                           String.Format("Invalid parameter value for: {0} - expecting a valid Date", name), SeverityLevel.Format);
                        _handler.Add(args);
                    }
                    break;
                case ("varchar"):
                    parameter = _command.Parameters.Add(name, SqlDbType.VarChar);
                    try
                    {
                        parameter.Value = Convert.ToString(value);
                        parameter.Size = (size <= 0) ? (-1) : size;
                    }
                    catch (FormatException)
                    {
                        args = new ProjectExceptionArgs(
                           String.Format("Invalid parameter value for: {0} - expecting a valid String", name), SeverityLevel.Format);
                        _handler.Add(args);
                    }
                    break;
                case ("text"):
                default:
                    try
                    {
                        if (size <= 0)
                        {
                            parameter = _command.Parameters.Add(name, SqlDbType.VarChar);
                            parameter.Size = -1;
                        }
                        else
                        {
                            parameter = _command.Parameters.Add(name, SqlDbType.Text);
                            parameter.Size = (size <= 0) ? (-1) : size;
                        }
                        parameter.Value = Convert.ToString(value);
                    }
                    catch (InvalidCastException)
                    {
                        args = new ProjectExceptionArgs(
                           String.Format("Invalid parameter value for: {0} - expecting a valid String", name), SeverityLevel.Format);
                        _handler.Add(args);
                    }
                    break;
            }

            // parameter direction
            if (inout == "inout")
                parameter.Direction = ParameterDirection.InputOutput;
            if (inout == "out")
                parameter.Direction = ParameterDirection.Output;
        }
Exemple #9
0
        public void Query(XmlNode Query)
        {
            XmlElement elm = null;

            string _commandtext = null;
            string xpath = null;
            InitializeCommand();

            _querynode = Query;

            if (_database.State != ConnectionState.Open)
                _database.Open();

            try
            {

                // command type
                xpath = "command/type";
                elm = (XmlElement)Query.SelectSingleNode(xpath);
                switch (elm.InnerText)
                {
                    case "StoredProcedure":
                        _command.Parameters.Clear();
                        _command.CommandType = CommandType.StoredProcedure;
                        break;
                    case "Select":
                    case "SQL":
                        _command.CommandType = CommandType.Text;
                        break;
                }

                // command text
                switch (_command.CommandType)
                {
                    case (CommandType.Text):
                        xpath = "command/text";
                        elm = (XmlElement)Query.SelectSingleNode(xpath);
                        _commandtext = Regex.Replace(elm.InnerText, @"^[ \t]+", "", RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace);
                        _commandtext = Regex.Replace(_commandtext, @"(\r\n)", " ", RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace);
                        break;
                    default:
                        xpath = "command/name";
                        elm = (XmlElement)Query.SelectSingleNode(xpath);
                        _commandtext = elm.InnerText;
                        _command.Parameters.Clear();
                        break;
                }

                // command parameters - in only
                xpath = "parameters/parameter[not(@inout='out')]";
                XmlNodeList nodes = Query.SelectNodes(xpath);
                foreach (XmlNode node in nodes)
                {
                    // validate input
                    if (validInput(node))
                    {

                        if (_command.CommandType == CommandType.Text)
                        {
                            string replaceparam = "[" + node.Attributes["name"].Value + "]";
                            _commandtext = _commandtext.Replace(replaceparam, node.InnerText);
                        }
                        else
                        {
                            elm = (XmlElement)node;
                            if (!elm.IsEmpty)
                            {
                                int size = 0;
                                if (!String.IsNullOrEmpty(elm.GetAttribute("size")))
                                    size = Convert.ToInt32(elm.GetAttribute("size"));

                                AddParameter(elm.GetAttribute("name"), elm.InnerText, elm.GetAttribute("type"), elm.GetAttribute("inout"), size);
                            }
                        }

                    }
                }

                // did all input values validate?
                if (!_isValid)
                    throw new ProjectException("Invalid Formatting Exception", _handler);

                // command parameters - output only (are required)
                xpath = "parameters/parameter[@inout='out']";
                nodes = Query.SelectNodes(xpath);
                foreach (XmlNode node in nodes)
                {
                    if (_command.CommandType == CommandType.Text)
                    {
                        string replaceparam = "[" + node.Attributes["name"].Value + "]";
                        _commandtext.Replace(replaceparam, node.InnerText);
                    }
                    else
                    {
                        elm = (XmlElement)node;
                        int size = 0;
                        if (!String.IsNullOrEmpty(elm.GetAttribute("size")))
                            size = Convert.ToInt32(elm.GetAttribute("size"));

                        AddParameter(elm.GetAttribute("name"), elm.InnerText, elm.GetAttribute("type"), elm.GetAttribute("inout"), size);
                    }

                }

                _command.CommandText = _commandtext;

                // prepare result xml document
                XmlNode importnode;
                XmlNode newElm;
                _xmresult = new XmlDocument();
                _xmresult.LoadXml("<results><schema/></results>");
                _xmresult.DocumentElement.SetAttribute("name", Query.Attributes["name"].Value);
                if(!String.IsNullOrEmpty(_sqlProjName))
                    _xmresult.DocumentElement.SetAttribute("ProjectSqlFile", _sqlProjName);
                importnode = _xmresult.ImportNode(Query, true);
                _xmresult.SelectSingleNode("results/schema").AppendChild(importnode);

                // execute query
                Int64 rows = 0;
                xpath = "command/action";
                elm = (XmlElement)Query.SelectSingleNode(xpath);

                if (_database.WithTransaction)
                    _command.Transaction = _database.Transaction;

                switch (elm.InnerText)
                {
                    case ("Scalar"):
                        rows = Convert.ToInt64(_command.ExecuteScalar());
                        _rowsaffected = Convert.ToInt32(rows);

                        // set result in xml
                        elm = (XmlElement)_xmresult.SelectSingleNode("results");
                        newElm = _xmresult.CreateElement("result");
                        newElm.InnerText = Convert.ToString(_rowsaffected);
                        elm.AppendChild(newElm);

                        break;
                    case ("Result"):
                        SqlDataReader dr = null;
                        try
                        {
                            BuildResults(dr = _command.ExecuteReader());
                        }
                        finally
                        {
                            if (dr != null)
                                dr.Close();
                        }

                        break;
                    case ("NonQuery"):
                    default:
                        rows = _command.ExecuteNonQuery();
                        _rowsaffected = Convert.ToInt32(rows);

                        // set result in xml
                        elm = (XmlElement)_xmresult.SelectSingleNode("results");
                        newElm = _xmresult.CreateElement("result");
                        newElm.InnerText = Convert.ToString(_rowsaffected);
                        elm.AppendChild(newElm);

                        break;
                }

                // set output parameter results on result xml document
                xpath = "results/schema/query/parameters/parameter[@inout='out' or @inout='inout']";
                nodes = _xmresult.SelectNodes(xpath);
                foreach (XmlNode node in nodes)
                {
                    node.InnerText = _command.Parameters[node.Attributes["name"].InnerText].Value.ToString();
                }
            }
            catch (SqlException handledSql)
            {
                if (handledSql.Message.Contains(" duplicate key "))
                {
                    if (QuiteUniqueConstraints == false)
                        throw handledSql;
                }
                else
                    throw handledSql;
            }
            catch (Exception unhandled)
            {
                ProjectExceptionArgs args = new ProjectExceptionArgs("Sorry, we handled an exception.  The problem has been sent to MSO Admin", "mso.Utility.DB.DatabaseQuery", "Query " + _commandtext, null, SeverityLevel.Critical, LogLevel.Event);
                throw new ProjectException(args, unhandled);
            }
        }
Exemple #10
0
        private bool validInput(XmlNode node)
        {
            bool result = true;
            bool required = false;

            XmlElement m = (XmlElement)node;

            // exceptions - no regular expression check
            if (m.GetAttribute("validation") == "")
                return (true);

            // for each validation scenario in validations (space delimited list
            string[] aValid = m.GetAttribute("validation").Split(' ');
            List<string> validations = new List<string>(aValid);
            string srequired = validations.Find(delegate(String s) { return s == "required"; });
            bool isrequired = Convert.ToBoolean(String.IsNullOrEmpty(srequired) ? false : srequired.Equals("true") || srequired.Equals("True"));

            foreach (string validation in validations)
            {
                if (validation.StartsWith("regx:"))
                {
                    if (!m.IsEmpty || !string.IsNullOrEmpty(m.InnerText))
                    {
                        //load validation xml obj library
                        if (_xmRegX == null)
                            throw new Exception("RegX input validation fails, RegX library not loaded");

                        // TODO: pass back friendly title for item
                        if (!validInputTestRegX(m.InnerText, validation.Split(':')[1]))
                        {
                            if (!isrequired && m.InnerText.Length == 0)
                                result = true;
                            else
                            {
                                result = false;
                                ProjectExceptionArgs args = new ProjectExceptionArgs(String.Format("Invalid Format for item: {0}", String.IsNullOrEmpty(m.GetAttribute("title")) ? m.GetAttribute("name") : m.GetAttribute("title")), SeverityLevel.Format);
                                _handler.Add(args);
                            }
                        }
                    }
                }
                else
                {
                    switch (validation)
                    {
                        case "required":
                            // expecting a value for innertext
                            required = true;
                            if (m.IsEmpty)
                            {
                                result = false;
                                ProjectExceptionArgs args = new ProjectExceptionArgs(String.Format("A value is required: {0}", String.IsNullOrEmpty(m.GetAttribute("title")) ? m.GetAttribute("name") : m.GetAttribute("title")), SeverityLevel.Format);
                                _handler.Add(args);
                            }
                            break;
                    }

                }

            }

            // test the object type for consistency with object value
            if (required && result)
                switch (m.GetAttribute("type"))
                {
                    case "int":
                        if (!(validInputTestNumber(m.InnerText)))
                        {
                            result = false;
                            ProjectExceptionArgs args = new ProjectExceptionArgs(String.Format("Format Exception, expecting a valid number for: {0}", String.IsNullOrEmpty(m.GetAttribute("title")) ? m.GetAttribute("name") : m.GetAttribute("title")), SeverityLevel.Format);
                            _handler.Add(args);
                        }
                        break;
                    case "text":
                    case "varchar":
                        if (!(validInputTestCharacters(m.InnerText, m.GetAttribute("size"))))
                        {
                            result = false;
                            ProjectExceptionArgs args = new ProjectExceptionArgs(String.Format("Format Exception, too many characters for: {0}, expecting: {1}", String.IsNullOrEmpty(m.GetAttribute("title")) ? m.GetAttribute("name") : m.GetAttribute("title"), m.GetAttribute("size")), SeverityLevel.Format);
                            _handler.Add(args);
                        }
                        break;
                    case "date":
                        // expecting a value that can parse as a date
                        if (!(validInputTestDate(m.InnerText)))
                        {
                            result = false;
                            ProjectExceptionArgs args = new ProjectExceptionArgs(String.Format("Format Exception, expecting a valid date for: {0}", String.IsNullOrEmpty(m.GetAttribute("title")) ? m.GetAttribute("name") : m.GetAttribute("title"), m.GetAttribute("size")), SeverityLevel.Format);
                            _handler.Add(args);
                        }
                        break;
                }

            return result;
        }
Exemple #11
0
        private void _Transform()
        {
            try
            {

                //validate before we get started
                if (classXSLObjectSource == "")
                {
                    ProjectExceptionArgs args = new ProjectExceptionArgs("Stylesheet Not Set", "xmlTransformer", "_Transform", null, SeverityLevel.Critical, LogLevel.Event);
                    throw new ProjectException(args);
                }

                else if (!File.Exists(classXSLObjectSource))
                {
                    string errmsg = string.Format("Could not find stylesheet: {0}", classXSLObjectSource);
                    ProjectExceptionArgs args = new ProjectExceptionArgs(errmsg, "_Transform", "_Transform", null, SeverityLevel.Critical, LogLevel.Event);
                    throw new ProjectException(args);
                }

                //check for XML Source
                //load up empty if non existent
                if (classXMLObjectSource == null)
                {
                    classXMLObjectSource = new XmlDocument();
                    classXMLObjectSource.LoadXml(@"<?xml version='1.0'?><ROOT/>");
                }

                //create a navigator object
                XPathNavigator xn;
                xn = classXMLObjectSource.CreateNavigator();

                //run the transformation
                xslTransformer(xn, clsXSLArgs);

            }
            catch (IOException e)
            {
                string errmsg = "FileIO Transformation Error";
                ProjectExceptionArgs args = new ProjectExceptionArgs(errmsg, "xmlTransformer", "_Transform", null, SeverityLevel.Critical, LogLevel.Event);
                throw new ProjectException(args, e);
            }
            catch (XmlException e)
            {
                string errmsg = "XmlException Transformation Error";
                ProjectExceptionArgs args = new ProjectExceptionArgs(errmsg, "xmlTransformer", "_Transform", null, SeverityLevel.Critical, LogLevel.Event);
                throw new ProjectException(args, e);
            }
            catch (HttpException e)
            {
                string errmsg = "HttpResponse Transformation Error";
                ProjectExceptionArgs args = new ProjectExceptionArgs(errmsg, "xmlTransformer", "_Transform", null, SeverityLevel.Critical, LogLevel.Event);
                throw new ProjectException(args, e);
            }
        }
Exemple #12
0
        /// <summary>
        /// Resolves Xml Content for the current page request and returns the relative location where it was resolved
        /// </summary>
        /// <param name="content"></param>
        /// <param name="LocalPath"></param>
        /// <returns></returns>
        private string getXmlResources(XmlDocument content, ref XmlNode current)
        {
            try
            {
                if (!_useCache)
                {
                    try
                    {
                        foreach (var key in _cacheKeys)
                            Cache.Remove(key.Value);
                    }
                    catch { }
                }
                if (_useCache)
                {

                    if (Cache[_cacheKeys[_cacheKeyEnum.XmlCacheKey]] == null)
                    {
                        foreach (var key in _cacheKeys)
                            Cache.Remove(key.Value);
                    }
                    else
                    {
                        var obj = Cache[_cacheKeys[_cacheKeyEnum.XmlCacheKey]];

                        content = (XmlDocument)Cache[_cacheKeys[_cacheKeyEnum.XmlCacheKey]];
                        current = (XmlNode)Cache[_cacheKeys[_cacheKeyEnum.ContextCacheKey]];
                        if (!((string)Cache[_cacheKeys[_cacheKeyEnum.XslCacheKey]] == "--DEFAULT--"))                 // no stylesheet resolved, this falls back to a default stylesheet
                            TMPLT.setXslt((string)Cache[_cacheKeys[_cacheKeyEnum.XslCacheKey]]);

                        if (Cache[_cacheKeys[_cacheKeyEnum.PHCacheKey]] != null)
                        {
                            _pageHeirarchy = new List<string>();
                            TMPLT.ClearBrowserpageItem("PAGE_HEIRARCHY");
                            var browseritems = (XmlNode)Cache[_cacheKeys[_cacheKeyEnum.PHCacheKey]];
                            foreach (XmlNode phnode in browseritems.SelectNodes("item"))
                            {
                                _pageHeirarchy.Add(phnode.InnerText);
                                TMPLT.AddBrowserPageItem("PAGE_HEIRARCHY", phnode.InnerText);
                            }
                        }
                        return (string)Cache[_cacheKeys[_cacheKeyEnum.ContentPathKey]];
                    }
                }

                bool foundXml = false;
                bool foundXsl = false;
                string resultcontentpath = null;
                string xslpath = null;
                string localxmlpath = null;

                //burn down approach, looking for relative content
                for (int x = _pageHeirarchy.Count; x > 0; x--)
                {
                    if (!foundXml)
                    {
                        localxmlpath = String.Join("/", _pageHeirarchy.ToArray(), 0, x);
                        if (_resources.Exists(String.Format("{0}/{1}.xml", localxmlpath, _pageHeirarchy[x - 1])))
                        {
                            resultcontentpath = localxmlpath;
                            if (_useCdn)
                                content.Load(_resources.FullWebPath(_resources.IndexOf) + "?timestamp" + DateTime.Now.ToString("yyyyMMddHHmmssffff"));
                            else
                                content.Load(Server.MapPath(_resources.AbsolutePath(_resources.IndexOf)));
                            foundXml = true;
                        }
                    }

                    if (!foundXsl)
                    {
                        var tempxsl = String.Join("/", _pageHeirarchy.ToArray(), 0, x);
                        if (_resources.Exists(String.Format("{0}/{1}.xsl", tempxsl, _pageHeirarchy[x - 1])))
                        {
                            foundXsl = true;
                            resultcontentpath = localxmlpath;
                            xslpath = _resources.FullWebPath(_resources.IndexOf) + "?timestamp" + DateTime.Now.ToString("yyyyMMddHHmmssffff");
                        }
                    }

                }

                // look for default content in root client projectFlx path considering a default as well
                if (!foundXml || !foundXsl)
                {
                    if(!foundXml)
                        resultcontentpath = localxmlpath = "";

                    string[] resource = new string[] { _pageHeirarchy[0], "default" };
                    foreach (string s in resource)
                    {
                        if (!foundXml && _resources.Exists(String.Format("{0}.xml", s)))
                        {
                            if (s == "default")
                            {
                                resultcontentpath = "default";
                                //_pageHeirarchy = new List<string>();
                                //_pageHeirarchy.Add("default");
                                //TMPLT.ClearBrowserpageItem("PAGE_HEIRARCHY");
                                //TMPLT.AddBrowserPageItem("PAGE_HEIRARCHY", "default");

                                if (_useCache)
                                    Cache.Insert(_cacheKeys[_cacheKeyEnum.PHCacheKey], TMPLT.DOCxml.SelectSingleNode("flx/proj/browser/page/PAGE_HEIRARCHY"));
                            }

                            if (_useCdn)
                                content.Load(_resources.FullWebPath(_resources.IndexOf) + "?timestamp" + DateTime.Now.ToString("yyyyMMddHHmmssffff"));
                            else
                                content.Load(Server.MapPath(_resources.AbsolutePath(_resources.IndexOf)));
                            foundXml = true;
                        }

                        if (foundXml && _resources.Exists(String.Format("{0}.xsl", s)))
                            if (_useCdn)
                                xslpath = _resources.FullWebPath(_resources.IndexOf);
                            else
                                xslpath = Server.MapPath(_resources.AbsolutePath(_resources.IndexOf));
                    }
                }

                if (foundXml)
                {
                    if (!String.IsNullOrEmpty(xslpath))
                        TMPLT.setXslt(xslpath);
                }
                else
                {

                    if (!foundXml && File.Exists(Path.Combine(_projectFlxPath, "content/projectflx.xml")))
                    {
                        content.Load(Path.Combine(_projectFlxPath, "content/projectflx.xml"));
                        TMPLT.setXslt(Path.Combine(_projectFlxPath, "Documents/WEB_DOCUMENT_TEMPLATE.xsl"));
                    }
                }

                // context for the current page
                var context2 = (XmlNode)content.DocumentElement.Clone();
                if (context2 == null)
                    throw new Exception("Failed to load content for the request");

                string xpath;
                _pageHeirarchy.ForEach(pg =>
                {
                    xpath = String.Format("page[translate(@name, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')='{0}'] | content[translate(@name,'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')='{0}']", pg);
                    if (context2.SelectSingleNode(xpath) != null)
                        context2 = context2.SelectSingleNode(xpath);
                    else
                        return;
                });

                current = context2;

                // strip child context nodes
                foreach (XmlNode node in current.SelectNodes("content"))
                    current.RemoveChild(node);

                if (_useCache)
                {
                    string depFile = Server.MapPath(Path.Combine("/ac", _cacheKeys[_cacheKeyEnum.XmlCacheKey].Substring("cache:".Length) + ".cache"));
                    using (StreamWriter writer = new StreamWriter(depFile))
                    {
                        writer.WriteLine(DateTime.Now.ToString("yyyyMMddHHmmssffff"));
                    }
                    var cachedependency = new CacheDependency(depFile);

                    Cache.Insert(_cacheKeys[_cacheKeyEnum.XmlCacheKey], content, cachedependency, DateTime.Now.AddMinutes(_cacheMinutes), System.Web.Caching.Cache.NoSlidingExpiration);
                    Cache.Insert(_cacheKeys[_cacheKeyEnum.ContextCacheKey], current);
                    Cache.Insert(_cacheKeys[_cacheKeyEnum.XslCacheKey], String.IsNullOrEmpty(xslpath) ? "--DEFAULT--" : xslpath);
                    Cache.Insert(_cacheKeys[_cacheKeyEnum.ContentPathKey], resultcontentpath);
                }

                return resultcontentpath;
            }
            catch (Exception unhandled)
            {
                var args = new ProjectExceptionArgs("Unhandled Exception Caught", "ProjectFlx.FlxMain", "getXmlResources(XmlDocument, XmlNode)", null, SeverityLevel.Critical, LogLevel.Debug);
                throw new ProjectException(args, unhandled);
            }
        }
Exemple #13
0
        /// <summary>
        /// Execute Site Termination Code
        /// </summary>
        public virtual void SITE_TERMINATE()
        {
            if(_SiteMap)
                return;

            List<XmlNode> rawscript;

            if (_useCache && Cache[_cacheKeys[_cacheKeyEnum.WaitClosureKey]] == null)
            {
                // TODO: this remains cached even after deleting dependent user file

                if (Cache[_cacheKeys[_cacheKeyEnum.ScriptCacheKey]] != null)
                {
                    rawscript = (List<XmlNode>)Cache[_cacheKeys[_cacheKeyEnum.ScriptCacheKey]];
                    TMPLT.DOCxml.SelectSingleNode("/flx/proj/browser/page/SCRIPT").RemoveAll();
                    foreach (XmlNode node in rawscript)
                        TMPLT.AddBrowserPageItem("RAW_SCRIPT", node.InnerText);
                    return;
                }

                try
                {
                    StringWriter writer = new StringWriter();
                    JsonTextWriter jwriter = new JsonTextWriter(writer);

                    jwriter.WriteStartObject();
                    jwriter.WritePropertyName("joiner");
                    jwriter.WriteStartArray();
                    jwriter.WriteStartObject();
                    jwriter.WritePropertyName("application");
                    jwriter.WriteValue("FLXIncludedScript");
                    jwriter.WritePropertyName("compile");
                    jwriter.WriteValue(true);
                    jwriter.WritePropertyName("version");
                    jwriter.WriteValue(1.0d);
                    jwriter.WritePropertyName("required");
                    jwriter.WriteStartArray();

                    if (TMPLT == null || TMPLT.DOCxml == null || TMPLT.DOCxml.DocumentElement == null)
                        throw new Exception("TMPLT not properly initialized");

                    foreach (XmlNode node in TMPLT.DOCxml.SelectNodes("/flx/proj/browser/page/SCRIPT/item"))
                    {
                        jwriter.WriteValue(node.InnerText);
                    }
                    jwriter.WriteEndArray();
                    jwriter.WriteEndObject();
                    jwriter.WriteEndObject();
                    jwriter.Flush();

                    var result = Stub.jsJoiner.Joiner.invokeWebApplicationJoiner2(writer.ToString());

                    if (result == null)
                        throw new Exception("jsJoiner returns null at: Stub.jsJoine.Joiner.invokeWebApplicationJoiner2");

                    // write a query to check for server errors
                    var query = (from r in result
                                 where r.Xml.SelectSingleNode("compilationResult/errors/error | compilationResult/serverErrors/error") != null
                                 select r.Xml).ToList();

                    if (query == null || query.Count == 0)
                    {
                        rawscript = new List<XmlNode>();
                        // no errors, embed script in page
                        XmlNode scriptnode = TMPLT.DOCxml.SelectSingleNode("/flx/proj/browser/page/SCRIPT");
                        if (scriptnode != null)
                        {
                            try
                            {
                                query = (from r in result select r.Xml).ToList();

                                foreach (XmlNode node in query)
                                {
                                    if (node.SelectSingleNode("compilationResult/serverErrors/error") != null)
                                    {
                                        if (node.SelectSingleNode("compilationResult/serverErrors/error[@code=\"22\"]") != null)
                                            throw new ProjectException("Too many compiles");
                                        else
                                            throw new Exception(node.SelectSingleNode("compilationResult/serverErrors/error").InnerText);
                                    }

                                    TMPLT.AddBrowserPageItem("RAW_SCRIPT", node.SelectSingleNode("compilationResult/compiledCode").InnerText);
                                    rawscript.Add(node.SelectSingleNode("compilationResult/compiledCode"));
                                }

                                if (_useCache)
                                {
                                    Cache.Insert(_cacheKeys[_cacheKeyEnum.ScriptCacheKey], rawscript, null, DateTime.Now.AddMinutes(_cacheMinutes), System.Web.Caching.Cache.NoSlidingExpiration);
                                }

                                scriptnode.RemoveAll();
                            }
                            catch (ProjectException handled)
                            {
                                if (handled.Message == "Too many compiles")
                                {
                                    Cache.Insert(_cacheKeys[_cacheKeyEnum.WaitClosureKey], DateTime.Now.ToUniversalTime(), null, DateTime.Now.AddMinutes(15), System.Web.Caching.Cache.NoSlidingExpiration);
                                    TMPLT.AddCommentTag("jsCompile", handled.Message);
                                }
                                else
                                    TMPLT.AddException(handled);

                            }
                            catch (Exception unhandled)
                            {
                                try
                                {
                                    foreach (var gc in result)
                                    {
                                        TMPLT.AddXML(gc.Xml);
                                    }
                                }
                                catch { }

                                throw new Exception("Error compiling jsJoiner code", unhandled);
                            }

                        }
                    }
                    else
                    {
                        // pass errors to our template for later evaluation
                        foreach (XmlNode node in query)
                        {
                            XmlDocument addDoc = new XmlDocument();
                            addDoc.InnerXml = node.OuterXml;
                            TMPLT.AddXML(addDoc);
                        }
                    }
                }
                catch (Exception unhandled)
                {
                    var args = new ProjectExceptionArgs("Unhandled Exception Caught in FlxWebsite SITE_TERMINATE", "ProjectFlx.FlxMain", "SITE_TERMINATE", null, SeverityLevel.Critical, LogLevel.Debug);
                    throw new ProjectException(args, unhandled);
                }
            }
            else
            {
                try
                {
                    if (Cache[_cacheKeys[_cacheKeyEnum.WaitClosureKey]] != null)
                        TMPLT.AddCommentTag("GoogleClosurePaused", ((DateTime)Cache[_cacheKeys[_cacheKeyEnum.WaitClosureKey]]).ToString("yyyyMMddHHmmssffff"));

                    if (Cache[_cacheKeys[_cacheKeyEnum.ScriptCacheKey]] != null)
                        Cache.Remove(_cacheKeys[_cacheKeyEnum.ScriptCacheKey]);
                }
                catch { }
            }
        }
Exemple #14
0
 public ProjectException(ProjectExceptionArgs Args, Exception inner) : base(Args.Message, inner)
 {
     _args = Args;
 }
Exemple #15
0
 public ProjectException(string Message, Exception inner) : base(Message, inner)
 {
     _args = new ProjectExceptionArgs(Message);
 }
Exemple #16
0
 public ProjectException(ProjectExceptionArgs Args) : base(Args.Message)
 {
     _args = Args;
 }