Exemplo n.º 1
0
        public void SetUp()
        {
            engine = new VelocityEngine();

            ExtendedProperties extendedProperties = new ExtendedProperties();

            extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_ERROR_STACKTRACE, "true");
            extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_WARN_STACKTRACE, "true");
            extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_INFO_STACKTRACE, "true");

            engine.Init(extendedProperties);
            context = new VelocityContext();
        }
Exemplo n.º 2
0
        public void Test_ExtendedProperties()
        {
            FileInfo file = new FileInfo("test1.properties");
            StreamWriter sw = file.CreateText();
            sw.WriteLine("# lines starting with # are comments.  Blank lines are ignored");
            sw.WriteLine(string.Empty);
            sw.WriteLine("# This is the simplest property");
            sw.WriteLine("prefix.key = value");
            sw.WriteLine(string.Empty);
            sw.WriteLine("# A long property may be separated on multiple lines");
            sw.WriteLine("prefix.longvalue = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \\");
            sw.WriteLine("                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
            sw.WriteLine(string.Empty);
            sw.WriteLine("# This is a property with many tokens");
            sw.WriteLine("prefix.tokens_on_a_line = first token, second token");
            sw.WriteLine(string.Empty);
            sw.WriteLine("# This sequence generates exactly the same result");
            sw.WriteLine("prefix.tokens_on_multiple_lines = first token");
            sw.WriteLine("prefix.tokens_on_multiple_lines = second token");
            sw.WriteLine(string.Empty);
            sw.WriteLine("# commas may be escaped in tokens");
            sw.WriteLine("prefix.commas.excaped = Hi\\, what'up?");
            sw.Flush();
            sw.Close();

            StreamReader sr = file.OpenText();
            String s = sr.ReadToEnd();
            sr.Close();

            ExtendedProperties props = new ExtendedProperties(file.FullName);
            VerifyProperties(props, "prefix.");

            StringWriter writer = new StringWriter();
            props.Save(writer, "header");

            // make sure that combine does not change types
            ExtendedProperties p = new ExtendedProperties();
            p.Combine(props);
            VerifyProperties(p, "prefix.");

            // make sure that subset does not change property types
            ExtendedProperties p2 = p.Subset("prefix");
            VerifyProperties(p2, string.Empty);
        }
        protected void SetUp()
        {
            velocityEngine = new VelocityEngine();

            ExtendedProperties extendedProperties = new ExtendedProperties();

            extendedProperties.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH,
                                           TemplateTest.FILE_RESOURCE_LOADER_PATH);

            extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_ERROR_STACKTRACE, "true");
            extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_WARN_STACKTRACE, "true");
            extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_INFO_STACKTRACE, "true");
            extendedProperties.SetProperty("userdirective",
                                           "NVelocity.Runtime.Directive.Component;NVelocity,NVelocity.Runtime.Directive.BlockComponent;NVelocity");

            velocityEngine.Init(extendedProperties);

            testProperties = new ExtendedProperties();
            testProperties.Load(new FileStream(TemplateTest.TEST_CASE_PROPERTIES, FileMode.Open, FileAccess.Read));
        }
Exemplo n.º 4
0
		/// <summary>
		/// Creates a new instance.
		/// </summary>
		public TemplateTestCase()
		{
			try
			{
				velocityEngine = new VelocityEngine();

				ExtendedProperties extendedProperties = new ExtendedProperties();
				extendedProperties.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, TemplateTest.FILE_RESOURCE_LOADER_PATH);

				extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_ERROR_STACKTRACE, "true");
				extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_WARN_STACKTRACE, "true");
				extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_INFO_STACKTRACE, "true");

				velocityEngine.Init(extendedProperties);

				testProperties = new ExtendedProperties();
				testProperties.Load(new FileStream(TemplateTest.TEST_CASE_PROPERTIES, FileMode.Open, FileAccess.Read));
			}
			catch(Exception)
			{
				throw new Exception("Cannot setup TemplateTestSuite!");
			}
		}
Exemplo n.º 5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="UserBase"/> class.
 /// </summary>
 public UserBase()
 {
     this.extendedProperties = new ExtendedProperties();
 }
Exemplo n.º 6
0
        protected override void ExecuteTask()
        {
            if (stylesheet == null)
            {
                throw new BuildException("no stylesheet specified", Location);
            }

            /*
             * make a DVSL and set validation
             */
            dvsl = new NVelocity.Dvsl.Dvsl();
            dvsl.ValidatingParser = validatingParser;

            /*
             * If a logfile attribute was specified, use that for the log file name,
             * TODO: otherwise use a NVelocity to NAnt logging adapter.
             */
            if (logFile != null)
            {
                dvsl.LogFile = logFile;
            }
            else
            {
                //dvsl.setLogSystem(new AntLogSystem(this));
            }

            /*
             * now the stylesheet
             */
            try {
                Log.WriteLine(LogPrefix + "Loading stylesheet " + stylesheet.FullName);
                dvsl.SetStylesheet(stylesheet);
            } catch (System.Exception ex) {
                Log.WriteLine(LogPrefix + "Failed to read stylesheet " + stylesheet.FullName);
                throw new BuildException(ex.ToString());
            }

            /*
             *  now, if we were given a toolbox, set that up too
             */
            toolboxProps = new ExtendedProperties();

            try {
                if (toolboxFile != null)
                {
                    toolboxProps.Load(toolboxFile.OpenRead());
                }

                /*
                 *  Overlay any parameters
                 */
                //		for (Enumeration e = toolAttr.elements(); e.hasMoreElements();) {
                //		    Tool p = (Tool)e.nextElement();
                //		    toolboxProps.setProperty(p.getName(), p.getValue());
                //		}

                dvsl.Toolbox = toolboxProps;
            } catch (System.Exception ee) {
                throw new BuildException("Error loading the toolbox : " + ee);
            }

            /*
             * if we have an in file and out then process them
             */

            if (inFile != null && outFile != null)
            {
                Process(inFile, outFile, stylesheet);
                return;
            }

            /*
             * if we get here, in and out have not been specified, we are
             * in batch processing mode.
             */

            /*
             *   make sure Source directory exists...
             */
            if (destDir == null)
            {
                throw new BuildException("destdir attributes must be set!");
            }

            Log.WriteLine(LogPrefix + "Transforming into " + destDir);

            /*
             *  Process all the files marked for styling
             */
            // get the base directory from the fileset - needed to colapse ../ syntax
            DirectoryInfo di = new DirectoryInfo(fileset.BaseDirectory);

            // get a list of files to work on
            foreach (string filename in fileset.FileNames)
            {
                String   relativeFilename = filename.Substring(di.FullName.Length + 1);
                FileInfo file             = new FileInfo(filename);
                if (file.Exists)
                {
                    Process(di, file, destDir, stylesheet);
                }
            }
        }
Exemplo n.º 7
0
		public void Test_Example1()
		{
			String templateFile = "example1.vm";
			try
			{
				/*
				* setup
				*/

				VelocityEngine velocityEngine = new VelocityEngine();

				ExtendedProperties extendedProperties = new ExtendedProperties();
				extendedProperties.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, TemplateTest.FILE_RESOURCE_LOADER_PATH);

				velocityEngine.Init(extendedProperties);

				/*
				*  Make a context object and populate with the data.  This 
				*  is where the Velocity engine gets the data to resolve the
				*  references (ex. $list) in the template
				*/
				VelocityContext context = new VelocityContext();
				context.Put("list", GetNames());

				ExtendedProperties props = new ExtendedProperties();
				props.Add("runtime.log", "nvelocity.log");
				context.Put("props", props);

				/*
				*    get the Template object.  This is the parsed version of your 
				*  template input file.  Note that getTemplate() can throw
				*   ResourceNotFoundException : if it doesn't find the template
				*   ParseErrorException : if there is something wrong with the VTL
				*   Exception : if something else goes wrong (this is generally
				*        indicative of as serious problem...)
				*/
				Template template = null;

				try
				{
					template = velocityEngine.GetTemplate(templateFile);
				}
				catch(ResourceNotFoundException resourceNotFoundException)
				{
					Console.Out.WriteLine("Example : error : cannot find template {0} : \n{1}", templateFile,
					                      resourceNotFoundException.Message);
					Assert.Fail();
				}
				catch(ParseErrorException parseErrorException)
				{
					Console.Out.WriteLine("Example : Syntax error in template {0} : \n{1}", templateFile, parseErrorException);
					Assert.Fail();
				}

				/*
				*  Now have the template engine process your template using the
				*  data placed into the context.  Think of it as a  'merge' 
				*  of the template and the data to produce the output stream.
				*/

				// using Console.Out will send it to the screen
				TextWriter writer = new StringWriter();
				if (template != null)
					template.Merge(context, writer);

				/*
				*  flush and cleanup
				*/

				writer.Flush();
				writer.Close();
			}
			catch(Exception ex)
			{
				Assert.Fail(ex.Message);
			}
		}
	public virtual void  init(ExtendedProperties configuration) {
	    dataSourceName = configuration.getString("resource.datasource");
	    tableName = configuration.getString("resource.table");
	    keyColumn = configuration.getString("resource.keycolumn");
	    templateColumn = configuration.getString("resource.templatecolumn");
	    timestampColumn = configuration.getString("resource.timestampcolumn");

	    System.Diagnostics.Process.info("Resources Loaded From: " + dataSourceName + "/" + tableName);
	    System.Diagnostics.Process.info("Resource Loader using columns: " + keyColumn + ", " + templateColumn + " and " + timestampColumn);
	    System.Diagnostics.Process.info("Resource Loader Initalized.");
	}
Exemplo n.º 9
0
            public DataSet ToUntypedDataSet()
            {
                var dataSet = new DataSet();

                dataSet.DataSetName        = DataSetName;
                dataSet.CaseSensitive      = CaseSensitive;
                dataSet.EnforceConstraints = EnforceConstraints;
                dataSet.Locale             = Locale;
                dataSet.Namespace          = Namespace;
                dataSet.Prefix             = Prefix;
                dataSet.RemotingFormat     = RemotingFormat;

                foreach (var typedTable in Tables.Cast <DataTable>())
                {
                    var dataTable = new DataTable();

                    dataTable.TableName         = typedTable.TableName;
                    dataTable.DisplayExpression = typedTable.DisplayExpression;
                    dataTable.MinimumCapacity   = typedTable.MinimumCapacity;
                    dataTable.Namespace         = typedTable.Namespace;
                    dataTable.Prefix            = typedTable.Prefix;
                    dataTable.RemotingFormat    = typedTable.RemotingFormat;

                    foreach (var column in typedTable.Columns.Cast <DataColumn>())
                    {
                        var dataColumn = new DataColumn();

                        dataColumn.ColumnName        = column.ColumnName;
                        dataColumn.AllowDBNull       = column.AllowDBNull;
                        dataColumn.AutoIncrement     = column.AutoIncrement;
                        dataColumn.AutoIncrementSeed = column.AutoIncrementSeed;
                        dataColumn.AutoIncrementStep = column.AutoIncrementStep;
                        dataColumn.Caption           = column.Caption;
                        dataColumn.ColumnMapping     = column.ColumnMapping;
                        dataColumn.DataType          = column.DataType;
                        dataColumn.DateTimeMode      = column.DateTimeMode;
                        dataColumn.DefaultValue      = column.DefaultValue;
                        dataColumn.Expression        = column.Expression;
                        dataColumn.MaxLength         = column.MaxLength;
                        dataColumn.Namespace         = column.Namespace;
                        dataColumn.Prefix            = column.Prefix;
                        dataColumn.ReadOnly          = column.ReadOnly;

                        foreach (var property in column.ExtendedProperties.Cast <DictionaryEntry>())
                        {
                            dataColumn.ExtendedProperties.Add(property.Key, property.Value);
                        }

                        dataTable.Columns.Add(dataColumn);
                    }

                    foreach (var row in typedTable.Rows.Cast <DataRow>())
                    {
                        dataTable.ImportRow(row);
                    }

                    dataTable.PrimaryKey = typedTable.PrimaryKey
                                           .Select(col => dataTable.Columns[col.ColumnName])
                                           .ToArray();

                    foreach (var property in typedTable.ExtendedProperties.Cast <DictionaryEntry>())
                    {
                        dataTable.ExtendedProperties.Add(property.Key, property.Value);
                    }

                    foreach (var constraint in typedTable.Constraints.Cast <Constraint>())
                    {
                        if (!Relations.Cast <DataRelation>().Any(rel =>
                                                                 (rel.ChildKeyConstraint == constraint) ||
                                                                 (rel.ParentKeyConstraint == constraint)))
                        {
                            if (constraint is UniqueConstraint uniqueConstraint)
                            {
                                if (!uniqueConstraint.IsPrimaryKey)
                                {
                                    dataTable.Constraints.Add(new UniqueConstraint(
                                                                  name: uniqueConstraint.ConstraintName,
                                                                  column: dataTable.Columns[uniqueConstraint.Columns.Single().ColumnName]));
                                }
                            }
                            else
                            {
                                throw new Exception($"Don't know how to clone a constraint of type {constraint.GetType()}");
                            }
                        }
                    }

                    dataSet.Tables.Add(dataTable);
                }

                foreach (var property in ExtendedProperties.Cast <DictionaryEntry>())
                {
                    dataSet.ExtendedProperties.Add(property.Key, property.Value);
                }

                foreach (var relation in Relations.Cast <DataRelation>())
                {
                    // NB: In the context of the unit test, this is assuming that there is only one column in a relation.
                    var dataRelation = new DataRelation(
                        relation.RelationName,
                        parentColumn: dataSet.Tables[relation.ParentTable.TableName].Columns[relation.ParentColumns.Single().ColumnName],
                        childColumn: dataSet.Tables[relation.ChildTable.TableName].Columns[relation.ChildColumns.Single().ColumnName]);

                    foreach (var property in relation.ExtendedProperties.Cast <DictionaryEntry>())
                    {
                        dataRelation.ExtendedProperties.Add(property.Key, property.Value);
                    }

                    dataSet.Relations.Add(dataRelation);
                }

                return(dataSet);
            }
 /// <summary>
 /// Initialize the Velocity Runtime with a Properties
 /// object.
 /// </summary>
 /// <param name="p">Properties</param>
 public void Init(ExtendedProperties p)
 {
     overridingProperties = ExtendedProperties.ConvertProperties(p);
     Init();
 }
Exemplo n.º 11
0
 /// <summary>
 /// Set an entire configuration at once. This is
 /// useful in cases where the parent application uses
 /// the ExtendedProperties class and the velocity configuration
 /// is a subset of the parent application's configuration.
 /// </summary>
 public static void SetExtendedProperties(ExtendedProperties value)
 {
     RuntimeSingleton.Configuration = value;
 }
Exemplo n.º 12
0
 public ExtendedPropertyNodeFactory( ExtendedProperty property, ExtendedProperties collection )
 {
     _property = property;
     _collection = collection;
 }
Exemplo n.º 13
0
        public override string ToSql()
        {
            Database    database = null;
            ISchemaBase current  = this;

            while (database == null && current.Parent != null)
            {
                database = current.Parent as Database;
                current  = current.Parent;
            }
            var isAzure10 = database.Info.Version == DatabaseInfo.VersionTypeEnum.SQLServerAzure10;

            StringBuilder sql      = new StringBuilder();
            string        includes = "";

            if ((Type == IndexTypeEnum.Clustered) && (IsUniqueKey))
            {
                sql.Append("CREATE UNIQUE CLUSTERED ");
            }
            if ((Type == IndexTypeEnum.Clustered) && (!IsUniqueKey))
            {
                sql.Append("CREATE CLUSTERED ");
            }
            if ((Type == IndexTypeEnum.Nonclustered) && (IsUniqueKey))
            {
                sql.Append("CREATE UNIQUE NONCLUSTERED ");
            }
            if ((Type == IndexTypeEnum.Nonclustered) && (!IsUniqueKey))
            {
                sql.Append("CREATE NONCLUSTERED ");
            }
            if (Type == IndexTypeEnum.XML)
            {
                sql.Append("CREATE PRIMARY XML ");
            }
            sql.Append("INDEX [" + Name + "] ON " + Parent.FullName + "\r\n(\r\n");
            /*Ordena la coleccion de campos del Indice en funcion de la propieda IsIncluded*/
            Columns.Sort();
            for (int j = 0; j < Columns.Count; j++)
            {
                if (!Columns[j].IsIncluded)
                {
                    sql.Append("\t[" + Columns[j].Name + "]");
                    if (Type != IndexTypeEnum.XML)
                    {
                        if (Columns[j].Order)
                        {
                            sql.Append(" DESC");
                        }
                        else
                        {
                            sql.Append(" ASC");
                        }
                    }
                    if (j < Columns.Count - 1)
                    {
                        sql.Append(",");
                    }
                    sql.Append("\r\n");
                }
                else
                {
                    if (String.IsNullOrEmpty(includes))
                    {
                        includes = ") INCLUDE (";
                    }
                    includes += "[" + Columns[j].Name + "],";
                }
            }
            if (!String.IsNullOrEmpty(includes))
            {
                includes = includes.Substring(0, includes.Length - 1);
            }
            sql.Append(includes);
            sql.Append(")");
            if (!String.IsNullOrEmpty(FilterDefintion))
            {
                sql.Append("\r\n WHERE " + FilterDefintion + "\r\n");
            }
            sql.Append(" WITH (");
            if (Parent.ObjectType == Enums.ObjectType.TableType)
            {
                if ((IgnoreDupKey) && (IsUniqueKey))
                {
                    sql.Append("IGNORE_DUP_KEY = ON ");
                }
                else
                {
                    sql.Append("IGNORE_DUP_KEY  = OFF ");
                }
            }
            else
            {
                if (!isAzure10)
                {
                    if (IsPadded)
                    {
                        sql.Append("PAD_INDEX = ON, ");
                    }
                    else
                    {
                        sql.Append("PAD_INDEX  = OFF, ");
                    }
                }

                if (IsAutoStatistics)
                {
                    sql.Append("STATISTICS_NORECOMPUTE = ON");
                }
                else
                {
                    sql.Append("STATISTICS_NORECOMPUTE  = OFF");
                }
                if (Type != IndexTypeEnum.XML)
                {
                    if ((IgnoreDupKey) && (IsUniqueKey))
                    {
                        sql.Append("IGNORE_DUP_KEY = ON, ");
                    }
                    else
                    {
                        sql.Append(", IGNORE_DUP_KEY  = OFF");
                    }
                }

                if (!isAzure10)
                {
                    if (AllowRowLocks)
                    {
                        sql.Append(", ALLOW_ROW_LOCKS = ON");
                    }
                    else
                    {
                        sql.Append(", ALLOW_ROW_LOCKS  = OFF");
                    }
                    if (AllowPageLocks)
                    {
                        sql.Append(", ALLOW_PAGE_LOCKS = ON");
                    }
                    else
                    {
                        sql.Append(", ALLOW_PAGE_LOCKS  = OFF");
                    }
                    if (FillFactor != 0)
                    {
                        sql.Append(", FILLFACTOR = " + FillFactor.ToString());
                    }
                }
            }
            sql.Append(")");
            if (!isAzure10)
            {
                if (!String.IsNullOrEmpty(FileGroup))
                {
                    sql.Append(" ON [" + FileGroup + "]");
                }
            }
            sql.Append("\r\nGO\r\n");
            if (IsDisabled)
            {
                sql.Append("ALTER INDEX [" + Name + "] ON " + ((Table)Parent).FullName + " DISABLE\r\nGO\r\n");
            }

            sql.Append(ExtendedProperties.ToSql());
            return(sql.ToString());
        }
Exemplo n.º 14
0
 /// <summary>
 /// initialize the Velocity runtime engine, using default properties
 /// plus the properties in the passed in java.util.Properties object
 /// </summary>
 /// <param name="p">
 /// Proprties object containing initialization properties
 /// </param>
 public static void Init(ExtendedProperties p)
 {
     RuntimeSingleton.Init(p);
 }
Exemplo n.º 15
0
        public void Apply(IEnumerable <ChangeScript> changeScripts, bool createChangeLogTable)
        {
            string filename = syntax.GetTemplateFileNameFor(GetTemplateQualifier());

            var model = new Hashtable();

            model.Add("scripts", changeScripts);
            model.Add("changeLogTableName", changeLogTableName);
            model.Add("delimiter", delimiter);
            model.Add("separator", delimiterType is RowDelimiter ? Environment.NewLine : string.Empty);

            try
            {
                var props = new ExtendedProperties();

                var assemblyName = GetType().Assembly.GetName().Name;

                ReplaceManagersWithDbDeployVersions(props, assemblyName);

                if (templateDirectory == null)
                {
                    props.AddProperty("resource.loader", "assembly");
                    props.AddProperty("assembly.resource.loader.class",
                                      // See the ; there? It will be replaced by , in the resource loader factory
                                      // this is because if we add a property with a comma in the value, it will add *two* values to the property.
                                      // oh joy.
                                      typeof(DbDeployAssemblyResourceLoader).FullName + "; " + assemblyName);
                    props.AddProperty("assembly.resource.loader.assembly", assemblyName);
                    filename = "Net.Sf.Dbdeploy.Resources." + filename;
                }
                else
                {
                    props.SetProperty("file.resource.loader.path", templateDirectory.FullName);
                }

                if (createChangeLogTable)
                {
                    writer.Write(syntax.CreateChangeLogTableSqlScript(changeLogTableName));
                }

                var templateEngine = new VelocityEngine(props);

                var context = new VelocityContext(model);

                var template = templateEngine.GetTemplate(filename);

                template.Merge(context, writer);
            }
            catch (ResourceNotFoundException ex)
            {
                string locationMessage;
                if (templateDirectory == null)
                {
                    locationMessage = "";
                }
                else
                {
                    locationMessage = " at " + templateDirectory.FullName;
                }
                throw new UsageException(
                          "Could not find template named " + filename + locationMessage + Environment.NewLine
                          + "Check that you have got the name of the database syntax correct.",
                          ex);
            }
        }
Exemplo n.º 16
0
 /// <summary> Initialize the Velocity Runtime with a Properties
 /// object.
 ///
 /// </summary>
 /// <param name="p">
 /// </param>
 /// <throws>  Exception When an Error occurs during initialization. </throws>
 /// <seealso cref="RuntimeInstance.Init(Properties)">
 /// </seealso>
 public static void Init(ExtendedProperties p)
 {
     ri.Init(p);
 }
        /// <summary>
        /// Load all video summary from the specified url
        /// </summary>
        /// <param name="url"></param>
        /// <param name="session"></param>
        /// <returns></returns>
        public static List <VideoInfo> LoadVideosFromUrl(this string url, AmazonBrowserSession session)
        {
            var          results    = new List <VideoInfo>();
            HtmlDocument doc        = null;
            var          tmpWeb     = session;
            HtmlNode     detailNode = null;

            // Attempt the URL up to 5 times as amazon wants us to use the api!
            for (int i = 0; i < 5; i++)
            {
                doc        = tmpWeb.Load(url);
                detailNode = doc.GetElementbyId("aiv-main-content");

                if (detailNode == null)
                {
                    Thread.Sleep(400);
                }
                else
                {
                    break;
                }
            }

            if (detailNode == null)
            {
                return(results);
            }

            var episodeContainer = doc.GetElementbyId("dv-episode-list");

            if (episodeContainer == null || episodeContainer.FindFirstChildElement() == null)
            {
                // Movie, load this video
                var video = new VideoInfo();

                video.Title = detailNode.SelectSingleNode(".//h1[@id = 'aiv-content-title']").FirstChild.GetInnerTextTrim();
                //doc.DocumentNode.GetNodeByClass("product_image").Attributes["alt"].Value;
                var infoNode = detailNode.GetNodeByClass("dv-info");

                var dvMetaInfo = infoNode.GetNodeByClass("dv-meta-info");
                var altTitle   = detailNode.NavigatePath(new[] { 0, 0 }).FirstChild.GetInnerTextTrim();
                video.Description = string.Format("({0}amazon {1})\r\n{2}\r\n{3} {4}",
                                                  video.Title == altTitle ? "" : altTitle + ", ",
                                                  doc.GetElementbyId("summaryStars").FindFirstChildElement() == null ? string.Empty : doc.GetElementbyId("summaryStars").FindFirstChildElement().Attributes["title"].Value,
                                                  infoNode.GetNodeByClass("synopsis").GetInnerTextTrim(),
                                                  dvMetaInfo.NavigatePath(new[] { 0 }).GetInnerTextTrim(),
                                                  dvMetaInfo.NavigatePath(new[] { 1 }).GetInnerTextTrim());

                var imageUrlNode = detailNode.GetNodeByClass("dp-meta-icon-container");
                video.Thumb   = imageUrlNode == null ? string.Empty : imageUrlNode.SelectSingleNode(".//img").Attributes["src"].Value;
                video.Airdate = detailNode.GetNodeByClass("release-year").GetInnerTextTrim();
                video.Length  = dvMetaInfo.NavigatePath(new[] { 3 }).GetInnerTextTrim();
                video.Other   = detailNode.GetNodeByClass("dv-play-btn-content")?.Attributes["data-asin"].Value;
                results.Add(video);
            }
            else
            {
                // TV Series, load all videos
                var episodeList = episodeContainer.GetNodesByClass("episode-list-link");
                int layoutType  = 0;

                if (episodeList == null)
                {
                    layoutType  = 1;
                    episodeList = episodeContainer.GetNodesByClass("episode-list-item-inner");
                }
                if (episodeList == null)
                {
                    layoutType  = 2;
                    episodeList = episodeContainer.GetNodesByClass("dv-episode-container");
                }
                if (episodeList == null)
                {
                    Log.Error("Could not load episode list!");
                    return(results);
                }
                foreach (var item in episodeList)
                {
                    var extendedProperties = new ExtendedProperties();
                    var video = new VideoInfo {
                        Other = extendedProperties
                    };
                    var titleNode =
                        layoutType == 0 ? item.GetNodeByClass("dv-extender").NavigatePath(new[] { 0, 0 }) :
                        layoutType == 1 ? item.GetNodeByClass("episode-title") :
                        item.GetNodeByClass("dv-el-title");

                    var seen = "";

                    /*if (item.GetNodeByClass("progress-bar") == null)
                     *  {
                     *      seen = " (new)";
                     *  }*/
                    video.Title = Regex.Replace(titleNode.GetInnerTextTrim(), @"^\d+", m => m.Value.PadLeft(2, '0')) + seen;

                    string   videoUrl = null;
                    HtmlNode imageUrlNode;
                    if (layoutType == 2)
                    {
                        var synopsis = item.GetNodeByClass("dv-el-synopsis-content");
                        if (synopsis != null)
                        {
                            video.Description = synopsis.FirstChild.NextSibling.GetInnerTextTrim();
                        }
                        // <div class="dv-el-packshot-image" style="background-image: url(http://ecx.images-amazon.com/images/I/....jpg);"></div>
                        imageUrlNode = item.GetNodeByClass("dv-el-packshot-image");
                        if (imageUrlNode != null)
                        {
                            var re            = new Regex("\\((.*?)\\)");
                            var htmlAttribute = imageUrlNode.GetAttributeValue("style", null);
                            if (htmlAttribute != null)
                            {
                                var match = re.Match(htmlAttribute);
                                if (match.Groups.Count == 2)
                                {
                                    video.ThumbnailImage = match.Groups[1].Value;
                                }
                            }
                        }

                        // Certification, can be different classes,i.e. dv-ages_16_and_over
                        var certificationClasses = item.GetNodesByClass("dv-el-badge dv-ages_", true);
                        if (certificationClasses != null)
                        {
                            var certification = certificationClasses.First();
                            extendedProperties.VideoProperties["Certificate"] = certification.GetInnerTextTrim();
                        }

                        // Playback progress
                        extendedProperties.VideoProperties["Progress"] = string.Format("{0:0}%", 0);
                        var progress = item.GetNodesByClass("dv-linear-progress");
                        if (progress != null && progress.Count > 0)
                        {
                            var progressSpan = progress[0].ChildNodes.FirstOrDefault(n => n.Name == "span");
                            if (progressSpan != null)
                            {
                                var    width = progressSpan.Attributes["style"].Value;
                                double percent;
                                if (double.TryParse(width.Replace("width:", "").Replace("%", ""), NumberStyles.Any, CultureInfo.InvariantCulture, out percent))
                                {
                                    extendedProperties.VideoProperties["Progress"] = string.Format("{0:0}%", percent);
                                }
                            }
                        }

                        var tagValues = item.GetNodesByClass("dv-el-attr-value");
                        if (tagValues.Count == 3)
                        {
                            video.Airdate = tagValues[2].GetInnerTextTrim();
                            video.Length  = tagValues[1].GetInnerTextTrim();
                        }
                        var urlNode = item.GetNodeByClass("dv-playback-container");
                        if (urlNode != null)
                        {
                            videoUrl = urlNode.GetAttributeValue("data-asin", null);
                        }
                    }
                    else
                    {
                        video.Description = titleNode.NextSibling.GetInnerTextTrim();
                        video.Airdate     = item.GetNodeByClass("release-date").GetInnerTextTrim();
                        imageUrlNode      = item.GetNodeByClass("episode-list-image");
                        video.Length      = item.GetNodeByClass("runtime").GetInnerTextTrim();
                        videoUrl          = layoutType == 0 ? titleNode.GetAttribute("href") : item.GetAttribute("href");
                        videoUrl          = videoUrl.Substring(videoUrl.IndexOf("/product/") + 9);
                        videoUrl          = videoUrl.Substring(0, videoUrl.IndexOf("/"));

                        if (imageUrlNode != null)
                        {
                            video.Thumb = imageUrlNode.Attributes["src"].Value;
                        }
                        else
                        {
                            imageUrlNode = doc.GetElementbyId("dv-dp-left-content").GetNodeByClass("dp-meta-icon-container");
                            video.Thumb  = imageUrlNode == null ? string.Empty : imageUrlNode.SelectSingleNode(".//img").Attributes["src"].Value;
                        }
                    }
                    extendedProperties.Other = videoUrl;
                    video.CleanDescriptionAndTitle();
                    results.Add(video);
                }
            }

            return(results);
        }
        /// <summary>
        /// Initialize the ResourceManager.
        /// </summary>
        public void initialize(RuntimeServices rs)
        {
            rsvc = rs;

            rsvc.info("Default ResourceManager initializing. (" + this.GetType() + ")");

            ResourceLoader resourceLoader;

            assembleResourceLoaderInitializers();

            for (int i = 0; i < sourceInitializerList.Count; i++)
            {
                ExtendedProperties configuration = (ExtendedProperties)sourceInitializerList[i];
                String             loaderClass   = configuration.GetString("class");

                if (loaderClass == null)
                {
                    rsvc.error("Unable to find '" + configuration.GetString(RESOURCE_LOADER_IDENTIFIER) + ".resource.loader.class' specification in configuation." + " This is a critical value.  Please adjust configuration.");
                    continue;
                }

                resourceLoader = ResourceLoaderFactory.getLoader(rsvc, loaderClass);
                resourceLoader.commonInit(rsvc, configuration);
                resourceLoader.init(configuration);
                resourceLoaders.Add(resourceLoader);
            }

            /*
             * now see if this is overridden by configuration
             */

            logWhenFound = rsvc.getBoolean(RuntimeConstants_Fields.RESOURCE_MANAGER_LOGWHENFOUND, true);

            /*
             *  now, is a global cache specified?
             */
            String claz = rsvc.getString(RuntimeConstants_Fields.RESOURCE_MANAGER_CACHE_CLASS);
            Object o    = null;

            if (claz != null && claz.Length > 0)
            {
                try
                {
                    Type type = Type.GetType(claz);
                    o = Activator.CreateInstance(type);
                }
                catch (Exception cnfe)
                {
                    String err = "The specified class for ResourceCache (" + claz + ") does not exist (or is not accessible to the current classlaoder).";
                    rsvc.error(err);
                    o = null;
                }

                if (!(o is ResourceCache))
                {
                    String err = "The specified class for ResourceCache (" + claz + ") does not implement NVelocity.Runtime.Resource.ResourceCache." + " Using default ResourceCache implementation.";
                    rsvc.error(err);
                    o = null;
                }
            }

            /*
             *  if we didn't get through that, just use the default.
             */
            if (o == null)
            {
                o = new ResourceCacheImpl();
            }

            globalCache = (ResourceCache)o;
            globalCache.initialize(rsvc);
            rsvc.info("Default ResourceManager initialization complete.");
        }
Exemplo n.º 19
0
 /// <summary>
 /// Initialize the Velocity Runtime with the name of
 /// ExtendedProperties object.
 /// </summary>
 /// <param name="configurationFile">Properties</param>
 public void Init(String configurationFile)
 {
     overridingProperties = new ExtendedProperties(configurationFile);
     Init();
 }
Exemplo n.º 20
0
        public NVelocityViewEngine(IDictionary <string, object> properties)
        {
            string themeRoot = "~" + Config.GetString("theme_root", "/Themes/")
                               + Setting.GetString("site_theme", "default");

            string areaRoot = themeRoot + "/Plugins";

            this.AreaViewLocationFormats = new[]
            {
                areaRoot + "/{2}/Views/{1}/{0}.htm",
                themeRoot + "/Areas/{2}/Views/{1}/{0}.htm",
                "~/Plugins/{2}/Views/{1}/{0}.htm",
                "~/Areas/{2}/Views/{1}/{0}.htm",
            };
            this.AreaMasterLocationFormats = new[]
            {
                areaRoot + "/{2}/Views/Shared/{0}.htm",
                themeRoot + "/Areas/{2}/Views/Shared/{0}.htm",
                "~/Plugins/{2}/Views/Shared/{0}.htm",
                "~/Areas/{2}/Views/Shared/{0}.htm",
            };
            this.AreaPartialViewLocationFormats = new[]
            {
                areaRoot + "/{2}/Views/{1}/{0}.htm",
                areaRoot + "/{2}/Views/Shared/{0}.htm",
                themeRoot + "/Areas/{2}/Views/{1}/{0}.htm",
                themeRoot + "/Areas/{2}/Views/Shared/{0}.htm",
                "~/Plugins/{2}/Views/{1}/{0}.htm",
                "~/Plugins/{2}/Views/Shared/{0}.htm",
                "~/Areas/{2}/Views/{1}/{0}.htm",
                "~/Areas/{2}/Views/Shared/{0}.htm",
            };
            this.ViewLocationFormats = new[]
            {
                themeRoot + "/Views/{0}.htm",
                themeRoot + "/Views/{1}/{0}.htm",
                "~/Views/{0}.htm",
                "~/Views/{1}/{0}.htm",
            };
            this.MasterLocationFormats = new[]
            {
                themeRoot + "/Views/Shared/{0}.htm",
                "~/Views/Shared/{0}.htm",
            };
            this.PartialViewLocationFormats = new[]
            {
                themeRoot + "/Views/{0}.htm", themeRoot + "/Views/{1}/{0}.htm",
                themeRoot + "/Views/Shared/{0}.htm", "~/Views/{0}.htm",
                "~/Views/{1}/{0}.htm", "~/Views/Shared/{0}.htm",
            };
            this.FileExtensions = new[] { "htm" };

            if (properties == null)
            {
                properties = DefaultProperties;
            }

            var props = new ExtendedProperties();

            foreach (var item in properties)
            {
                props.AddProperty(item.Key, item.Value);
            }

            this.engine = new VelocityEngine();
            this.engine.Init(props);
        }
Exemplo n.º 21
0
 public void AddProjectType(Guid guid)
 {
     ExtendedProperties.Add("ProjectTypeGuids", guid.ToString());
 }
Exemplo n.º 22
0
        private void VerifyProperties(ExtendedProperties props, String prefix)
        {
            Assert.IsTrue(props.Count == 5, "expected to have 5 properties, had " + props.Count);

            Assert.IsTrue(props.GetString(prefix + "key").Equals("value"),
                          "key was not correct: " + props.GetString(prefix + "key"));

            // make sure the comma escaping is working correctly
            Assert.IsTrue(props.GetString(prefix + "commas.excaped").Equals("Hi, what'up?"),
                          "commas.excaped was not correct: " + props.GetString(prefix + "commas.excaped"));

            // make sure that multiple tokens on a single line are parsed correctly
            Object o = props.GetProperty(prefix + "tokens_on_a_line");
            Assert.IsTrue((o is ArrayList), prefix + "tokens_on_a_line was expected to be an ArrayList");
            Assert.IsTrue(((ArrayList) o).Count == 2, prefix + "tokens_on_a_line was expected to be an ArrayList with 2 elements");

            // make sure that tokens specified on multiple lines get put together correctly
            o = props.GetProperty(prefix + "tokens_on_multiple_lines");
            Assert.IsTrue((o is ArrayList), prefix + "tokens_on_multiple_lines was expected to be an ArrayList");
            Assert.IsTrue(((ArrayList) o).Count == 2,
                          prefix + "tokens_on_multiple_lines was expected to be an ArrayList with 2 elements");
        }
Exemplo n.º 23
0
        public override void Init(ExtendedProperties configuration)
        {
            runtimeServices.Info("FileResourceLoader : initialization starting.");

            paths = configuration.GetVector("path");
        }