diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6cb918b --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +_ReSharper*/ +ShowOff.Core/bin/ +ShowOff.Core/obj/ +ShowOff.Tests/bin/ +ShowOff.Tests/obj/ +ShowOff.IntegrationTests/bin/ +ShowOff.IntegrationTests/obj/ +ShowOff/bin/ +ShowOff/obj/ +TestResults/ \ No newline at end of file diff --git a/LocalTestRun.testrunconfig b/LocalTestRun.testrunconfig new file mode 100644 index 0000000..b2e1b86 --- /dev/null +++ b/LocalTestRun.testrunconfig @@ -0,0 +1,8 @@ + + + This is a default test run configuration for a local test run. + + + + + \ No newline at end of file diff --git a/ShowOff.4.1.resharper.user b/ShowOff.4.1.resharper.user new file mode 100644 index 0000000..e73d452 --- /dev/null +++ b/ShowOff.4.1.resharper.user @@ -0,0 +1,277 @@ + + + + + 0 + + + False + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + True + False + True + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ShowOff.Core/App.config b/ShowOff.Core/App.config new file mode 100644 index 0000000..e92446c --- /dev/null +++ b/ShowOff.Core/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/ShowOff.Core/Data/Maps.cs b/ShowOff.Core/Data/Maps.cs new file mode 100644 index 0000000..c7aecc9 --- /dev/null +++ b/ShowOff.Core/Data/Maps.cs @@ -0,0 +1,59 @@ +using FluentNHibernate.Mapping; +using ShowOff.Core.Model; + +namespace ShowOff.Core.Data +{ + public class ItemMap : ClassMap + { + //public virtual int ID { get; set; } + //public virtual string Name { get; set; } + //public virtual string Description { get; set; } + //public virtual string Url { get; set; } + //public virtual string CreatedDate { get; set; } + //public virtual string ModifiedDate { get; set; } + //public virtual int DisplayPriority { get; set; } + //public virtual IList Images { get; set; } + //public virtual ItemImage CoverImage { get; set; } + //public virtual ItemType Type { get; set; } + public ItemMap() + { + Id(x => x.ID); + Map(x => x.Name).Unique().Not.Nullable(); + Map(x => x.Description); + Map(x => x.Url); + Map(x => x.CreatedDate).Not.Nullable(); + Map(x => x.ModifiedDate).Not.Nullable(); + Map(x => x.DisplayPriority); + HasMany(x => x.Images).KeyColumn("ItemID").Cascade.All(); + References(x => x.CoverImage).Column("CoverImageID").Cascade.All().Nullable(); + References(x => x.Type).Column("ItemTypeID").Cascade.All().Not.Nullable(); + } + } + + public class ItemImageMap : ClassMap + { + //public virtual int ID { get; set; } + //public virtual string Filename { get; set; } + //public virtual string ThumbFilename { get; set; } + public ItemImageMap() + { + Id(x => x.ID); + Map(x => x.Filename).Not.Nullable(); + Map(x => x.ThumbFilename).Not.Nullable(); + References(x => x.ItemID).Column("ItemID"); + } + } + + public class ItemTypeMap : ClassMap + { + //public virtual int ID { get; set; } + //public virtual string Name { get; set; } + //public virtual string DisplayName { get; set; } + public ItemTypeMap() + { + Id(x => x.ID).GeneratedBy.Assigned(); + Map(x => x.Name).Not.Nullable(); + Map(x => x.DisplayName).Not.Nullable(); + } + } +} \ No newline at end of file diff --git a/ShowOff.Core/Data/SessionFactoryFactory.cs b/ShowOff.Core/Data/SessionFactoryFactory.cs new file mode 100644 index 0000000..f8c1eb9 --- /dev/null +++ b/ShowOff.Core/Data/SessionFactoryFactory.cs @@ -0,0 +1,59 @@ +using System.Configuration; +using System.Reflection; +using FluentNHibernate.Cfg; +using FluentNHibernate.Cfg.Db; +using NHibernate; +using NHibernate.Tool.hbm2ddl; +using Configuration=NHibernate.Cfg.Configuration; + +namespace ShowOff.Core.Data +{ + public static class SessionFactoryFactory + { + private static Configuration _configuration; + private static ISessionFactory _sessionFactory; + + private static string ConnectionString + { + get { return ConfigurationManager.ConnectionStrings["ShowOffConnectionString"].ConnectionString; } + } + + private static Configuration Configuration + { + get + { + if(_configuration == null) + _configuration = Fluently.Configure() + .Database(MsSqlConfiguration.MsSql2008.ConnectionString(ConnectionString)) + .Mappings(x => x.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly())).BuildConfiguration(); + + return _configuration; + } + } + + public static ISessionFactory GetSessionFactory() + { + if(_sessionFactory == null) + _sessionFactory = Configuration.BuildSessionFactory(); + + return _sessionFactory; + } + + public static void DropSchema() + { + + new SchemaExport(Configuration).Drop(false, true); + } + + public static void CreateSchema() + { + new SchemaExport(Configuration).Create(false, true); + } + + public static void ExportMapping() + { + ////Fluently.Configure().Database(MsSqlConfiguration.MsSql2008.ConnectionString(ConnectionString)) + //// .Mappings(x => x.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly()).ExportTo("c:\temp\mappings")).BuildConfiguration(); + } + } +} \ No newline at end of file diff --git a/ShowOff.Core/Data/SetupHelper.cs b/ShowOff.Core/Data/SetupHelper.cs new file mode 100644 index 0000000..b4048a0 --- /dev/null +++ b/ShowOff.Core/Data/SetupHelper.cs @@ -0,0 +1,77 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using ShowOff.Core.Model; +using ShowOff.Core.Repository; + +namespace ShowOff.Core.Data +{ + public static class SetupHelper + { + public static void ResetDatabase() + { + SessionFactoryFactory.DropSchema(); + SessionFactoryFactory.CreateSchema(); + } + + public static void AddDefaultData() + { + var session = SessionFactoryFactory.GetSessionFactory().OpenSession(); + + // item types + var websiteItemType = new ItemType() { ID = 1, Name = "Website", DisplayName = "Website" }; + var logoItemType = new ItemType() { ID = 2, Name = "Logo", DisplayName = "Logo" }; + var printItemType = new ItemType() { ID = 3, Name = "Print", DisplayName = "Print" }; + var apparelItemType = new ItemType() { ID = 4, Name = "Apparel", DisplayName = "Apparel" }; + + session.SaveOrUpdate(websiteItemType); + session.SaveOrUpdate(logoItemType); + session.SaveOrUpdate(printItemType); + session.SaveOrUpdate(apparelItemType); + + for (int j = 0; j < 10; j++) + { + // item images + var itemImageRepo = new ItemImageRepository(); + + var fileNames = new List() + { + "test1.jpg", + "test2.jpg", + "test3.jpg", + "test4.jpg", + "test5.jpg" + }; + + + var images = + fileNames.Select( + p => + new ItemImage() + { + Filename = p, + ThumbFilename = Path.GetFileNameWithoutExtension(p) + "_thumb" + Path.GetExtension(p) + }). + ToList(); + + var item = new Item() + { + Name = "ShowOff Item " + j, + Description = "Show me off to the world.", + Url = "http://www.showoffgallery.com", + CreatedDate = DateTime.Now, + ModifiedDate = DateTime.Now, + Type = websiteItemType, + Images = images, + CoverImage = images[new Random().Next(0, 4)], + DisplayPriority = 0 + }; + + session.SaveOrUpdate(item); + session.Flush(); + + } + } + } +} \ No newline at end of file diff --git a/ShowOff.Core/Model/Item.cs b/ShowOff.Core/Model/Item.cs new file mode 100644 index 0000000..be09d37 --- /dev/null +++ b/ShowOff.Core/Model/Item.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; + +namespace ShowOff.Core.Model +{ + public class Item + { + public virtual int ID { get; set; } + [Required] + public virtual string Name { get; set; } + [Required] + public virtual string Description { get; set; } + [Required] + public virtual string Url { get; set; } + + public virtual DateTime CreatedDate { get; set; } + public virtual DateTime ModifiedDate { get; set; } + public virtual int DisplayPriority { get; set; } + public virtual IList Images { get; set; } + public virtual ItemImage CoverImage { get; set; } + public virtual ItemType Type { get; set; } + } +} \ No newline at end of file diff --git a/ShowOff.Core/Model/ItemImage.cs b/ShowOff.Core/Model/ItemImage.cs new file mode 100644 index 0000000..4337b7d --- /dev/null +++ b/ShowOff.Core/Model/ItemImage.cs @@ -0,0 +1,10 @@ +namespace ShowOff.Core.Model +{ + public class ItemImage + { + public virtual int ID { get; set;} + public virtual string Filename { get; set;} + public virtual string ThumbFilename { get; set; } + public virtual Item ItemID { get; set; } + } +} \ No newline at end of file diff --git a/ShowOff.Core/Model/ItemType.cs b/ShowOff.Core/Model/ItemType.cs new file mode 100644 index 0000000..145609e --- /dev/null +++ b/ShowOff.Core/Model/ItemType.cs @@ -0,0 +1,9 @@ +namespace ShowOff.Core.Model +{ + public class ItemType + { + public virtual int ID { get; set; } + public virtual string Name { get; set; } + public virtual string DisplayName { get; set; } + } +} \ No newline at end of file diff --git a/ShowOff.Core/Properties/AssemblyInfo.cs b/ShowOff.Core/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..27eb885 --- /dev/null +++ b/ShowOff.Core/Properties/AssemblyInfo.cs @@ -0,0 +1,38 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Security; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("ShowOff.Core")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("ShowOff.Core")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2009")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] +[assembly: AllowPartiallyTrustedCallers] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("4d16ae0a-61f5-41de-8ec4-5a721a928732")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/ShowOff.Core/Repository/IRepository.cs b/ShowOff.Core/Repository/IRepository.cs new file mode 100644 index 0000000..21a8720 --- /dev/null +++ b/ShowOff.Core/Repository/IRepository.cs @@ -0,0 +1,15 @@ +using System.Collections.Generic; + +namespace ShowOff.Core.Repository +{ + public interface IRepository + { + void Save(); + IList GetAll(); + T GetById(int id); + void Add(T itemToAdd); + void Add(IList itemsToAdd); + void Delete(T itemToDelete); + void Delete(IList itemsToDelete); + } +} \ No newline at end of file diff --git a/ShowOff.Core/Repository/ItemImageRepository.cs b/ShowOff.Core/Repository/ItemImageRepository.cs new file mode 100644 index 0000000..46b6840 --- /dev/null +++ b/ShowOff.Core/Repository/ItemImageRepository.cs @@ -0,0 +1,96 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using ShowOff.Core.Model; +using ShowOff.Core.Util; + +namespace ShowOff.Core.Repository +{ + public interface IItemImageRepository + { + IList GetAll(); + ItemImage GetById(int id); + void Add(ItemImage entity); + void Add(IList entities); + void Update(ItemImage entity); + void Delete(ItemImage entity); + void Delete(IList entities); + void Save(); + string SaveImageFile(string fileName, Stream inputStream); + string CreateThumb(string fileName); + } + + public class ItemImageRepository : NHibernateRepositoryBase, IItemImageRepository + { + public const string RelativePath = "Content\\Uploads\\Images\\"; + public const int ThumbWidthPixels = 200; + public const int FullWidthPixels = 800; + + private string _storeLocation; + + public ItemImageRepository() + { + _storeLocation = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, RelativePath); + } + + public string CreateThumb(string fileName) + { + var fileInfo = new FileInfo(fileName); + + if(!fileInfo.Exists) + throw new FileNotFoundException("Can not create thumb.", fileName); + + string thumbFileName = RandomFilenameHelper.GetRandomFileName(_storeLocation, fileInfo.Extension); + + fileInfo.CopyTo(thumbFileName); + + var thumbFileInfo = new FileInfo(thumbFileName); + + if(!thumbFileInfo.Exists) + throw new FileNotFoundException("Unable to locate file copy to resize", thumbFileName); + + ImageUtil.ResizeImage(thumbFileName, ThumbWidthPixels); + + return thumbFileInfo.FullName; + } + + public string SaveImageFile(string fileName, Stream inputStream) + { + var ext = Path.GetExtension(fileName); + + var fileInfo = new FileInfo(RandomFilenameHelper.GetRandomFileName(_storeLocation, ext)); + + if (fileInfo.Exists) + throw new ApplicationException("File already exits."); + + Debug.WriteLine("Saving file: " + fileInfo.FullName); + + var fileStream = new FileStream(fileInfo.FullName, FileMode.Create); + int bytesRead = 0; + var buffer = new byte[1024]; + + try + { + do + { + bytesRead = inputStream.Read(buffer, 0, 1024); + fileStream.Write(buffer, 0, bytesRead); + + } while (bytesRead > 0); + } + finally + { + fileStream.Close(); + fileStream.Dispose(); + } + + if(!new FileInfo(fileInfo.FullName).Exists) + throw new FileNotFoundException("File not found.", fileInfo.FullName); + + ImageUtil.ResizeImage(fileInfo.FullName, FullWidthPixels); + + return fileInfo.FullName; + } + } +} \ No newline at end of file diff --git a/ShowOff.Core/Repository/ItemRepository.cs b/ShowOff.Core/Repository/ItemRepository.cs new file mode 100644 index 0000000..855501e --- /dev/null +++ b/ShowOff.Core/Repository/ItemRepository.cs @@ -0,0 +1,22 @@ +using System.Collections.Generic; +using ShowOff.Core.Model; + +namespace ShowOff.Core.Repository +{ + public interface IItemRepository + { + IList GetAll(); + Item GetById(int id); + void Add(Item entity); + void Add(IList entities); + void Update(Item entity); + void Delete(Item entity); + void Delete(IList entities); + void Save(); + } + + public class ItemRepository : NHibernateRepositoryBase, IItemRepository + { + + } +} \ No newline at end of file diff --git a/ShowOff.Core/Repository/ItemTypeRepository.cs b/ShowOff.Core/Repository/ItemTypeRepository.cs new file mode 100644 index 0000000..fad2ab9 --- /dev/null +++ b/ShowOff.Core/Repository/ItemTypeRepository.cs @@ -0,0 +1,22 @@ +using System.Collections.Generic; +using ShowOff.Core.Model; + +namespace ShowOff.Core.Repository +{ + public interface IItemTypeRepository + { + IList GetAll(); + ItemType GetById(int id); + void Add(ItemType entity); + void Add(IList entities); + void Update(ItemType entity); + void Delete(ItemType entity); + void Delete(IList entities); + void Save(); + } + + public class ItemTypeRepository : NHibernateRepositoryBase, IItemTypeRepository + { + + } +} \ No newline at end of file diff --git a/ShowOff.Core/Repository/NHibernateRepositoryBase.cs b/ShowOff.Core/Repository/NHibernateRepositoryBase.cs new file mode 100644 index 0000000..c258fbc --- /dev/null +++ b/ShowOff.Core/Repository/NHibernateRepositoryBase.cs @@ -0,0 +1,67 @@ +using System.Collections.Generic; +using System.Linq; +using NHibernate; + +using ShowOff.Core.Data; + +namespace ShowOff.Core.Repository +{ + public abstract class NHibernateRepositoryBase : IRepository where T : class + { + protected ISession _session; + + public NHibernateRepositoryBase() + { + _session = SessionFactoryFactory.GetSessionFactory().OpenSession(); + } + + public virtual IList GetAll() + { + var criteria = _session.CreateCriteria(typeof(T)); + + return criteria.List(); + } + + public virtual T GetById(int id) + { + return _session.Get(id); + } + + public virtual void Add(T entity) + { + _session.SaveOrUpdate(entity); + } + + public virtual void Add(IList entities) + { + foreach (var t in entities) + { + Add(t); + } + } + + public virtual void Update(T entity) + { + _session.SaveOrUpdate(entity); + } + + public virtual void Delete(T entity) + { + _session.Delete(entity); + } + + public virtual void Delete(IList entities) + { + foreach (var t in entities) + { + Delete(t); + } + } + + public virtual void Save() + { + _session.Flush(); + } + + } +} \ No newline at end of file diff --git a/ShowOff.Core/ShowOff.Core.csproj b/ShowOff.Core/ShowOff.Core.csproj new file mode 100644 index 0000000..8a6d4ba --- /dev/null +++ b/ShowOff.Core/ShowOff.Core.csproj @@ -0,0 +1,111 @@ + + + + Debug + AnyCPU + 9.0.30729 + 2.0 + {A1C59F74-87E6-4C8B-AC65-EC41D2DE13E8} + Library + Properties + ShowOff.Core + ShowOff.Core + v3.5 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + False + ..\lib\nhib\Antlr3.Runtime.dll + + + False + ..\lib\nhib\Castle.Core.dll + + + False + ..\lib\nhib\Castle.DynamicProxy2.dll + + + False + ..\lib\nhib\FluentNHibernate.dll + + + False + ..\lib\nhib\Iesi.Collections.dll + + + False + ..\lib\nhib\log4net.dll + + + False + ..\lib\nhib\NHibernate.dll + + + False + ..\lib\nhib\NHibernate.ByteCode.Castle.dll + + + + 3.5 + + + + 3.5 + + + + 3.5 + + + 3.5 + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ShowOff.Core/Util/ImageUtil.cs b/ShowOff.Core/Util/ImageUtil.cs new file mode 100644 index 0000000..51b6e49 --- /dev/null +++ b/ShowOff.Core/Util/ImageUtil.cs @@ -0,0 +1,40 @@ +using System; +using System.Data; +using System.Configuration; +using System.Drawing.Imaging; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.IO; + +namespace ShowOff.Core.Util +{ + public class ImageUtil + { + public static void ResizeImage(string fileName, int newWidth) + { + var fi = new FileInfo(fileName); + + if(!fi.Exists) + throw new ArgumentException(fileName + " does not exist."); + + Bitmap newbmp; + + using (Bitmap originalBitmap = Bitmap.FromFile(fileName, true) as Bitmap) + { + float ratio = (float)newWidth / (float)originalBitmap.Width; + double newHeight = (ratio) * originalBitmap.Height; + + newbmp = new Bitmap(newWidth, (int)newHeight); + + using (Graphics newg = Graphics.FromImage(newbmp)) + { + newg.DrawImage(originalBitmap, 0, 0, (float)newWidth, (float)newHeight); + newg.Save(); + } + } + + newbmp.Save(fileName, ImageFormat.Jpeg); + newbmp.Dispose(); + } + } +} diff --git a/ShowOff.Core/Util/RandomFileNameHelper.cs b/ShowOff.Core/Util/RandomFileNameHelper.cs new file mode 100644 index 0000000..bba7293 --- /dev/null +++ b/ShowOff.Core/Util/RandomFileNameHelper.cs @@ -0,0 +1,16 @@ +using System; +using System.IO; + +namespace ShowOff.Core.Util +{ + + public static class RandomFilenameHelper + { + public static string GetRandomFileName(string path, string ext) + { + var fileName = Guid.NewGuid().ToString() + ext; + return Path.Combine(path, fileName); + } + } + +} \ No newline at end of file diff --git a/ShowOff.IntegrationTests/App.config b/ShowOff.IntegrationTests/App.config new file mode 100644 index 0000000..e92446c --- /dev/null +++ b/ShowOff.IntegrationTests/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/ShowOff.IntegrationTests/AuthoringTests.txt b/ShowOff.IntegrationTests/AuthoringTests.txt new file mode 100644 index 0000000..c94b3cf --- /dev/null +++ b/ShowOff.IntegrationTests/AuthoringTests.txt @@ -0,0 +1,136 @@ +========================================================================== + Visual Studio Team System: Overview of Authoring and Running Tests +========================================================================== + +This overview describes the features for authoring and running tests in +Visual Studio Team System and Visual Studio Team Edition for Software Testers. + +Opening Tests +------------- +To open a test, open a test project or a test metadata file (a file with +extension .vsmdi) that contains the definition of the test. You can find +test projects and metadata files in Solution Explorer. + +Viewing Tests +------------- +To see which tests are available to you, open the Test View window. Or, +if you have installed Team Edition for Software Testers, you can also open +the Test List Editor window to view tests. + +To open the Test View window, click the Test menu, point to Windows, and +then click Test View. To open the Test List Editor window (if you have +installed Team Edition for Software Testers), click Test, point to Windows, +and then click Test List Editor. + +Running Tests +------------- +You can run tests from the Test View window and the Test List Editor window. +See Viewing Tests to learn how to open these windows. To run one or more +tests displayed in the Test View window, first select the tests in that +window; to select multiple tests, hold either the Shift or CTRL key while +clicking tests. Then click the Run Tests button in the Test View window +toolbar. + +If you have installed Visual Studio Team Edition for Software Testers, you can +also use the Test List Editor window to run tests. To run tests in Test List Editor, +select the check box next to each test that you want to run. Then click the +Run Tests button in the Test List Editor window toolbar. + +Viewing Test Results +-------------------- +When you run a test or a series of tests, the results of the test run will be +shown in the Test Results window. Each individual test in the run is shown on +a separate line so that you can see its status. The window contains an +embedded status bar in the top half of the window that provides you with +summary details of the complete test run. + +To see more detailed results for a particular test result, double-click it in +the Test Results window. This opens a window that provides more information +about the particular test result, such as any specific error messages returned +by the test. + +Changing the way that tests are run +----------------------------------- +Each time you run one or more tests, a collection of settings is used to +determine how those tests are run. These settings are contained in a “test +run configuration” file. + +Here is a partial list of the changes you can make with a test run +configuration file: + + - Change the naming scheme for each test run. + - Change the test controller that the tests are run on so that you can run + tests remotely. + - Gather code coverage data for the code being tested so that you can see + which lines of code are covered by your tests. + - Enable and disable test deployment. + - Specify additional files to deploy before tests are run. + - Select a different host, ASP.NET, for running ASP.NET unit tests. + - Select a different host, the smart device test host, for running smart device unit tests. + - Set various properties for the test agents that run your tests. + - Run custom scripts at the start and end of each test run so that you can + set up the test environment exactly as required each time tests are run. + - Set time limits for tests and test runs. + - Set the browser mix and the number of times to repeat Web tests in the + test run. + +By default, a test run configuration file is created whenever you create a +new test project. You make changes to this file by double-clicking it in +Solution Explorer and then changing its settings. (Test run configuration +files have the extension .testrunconfig.) + +A solution can contain multiple test run configuration files. Only one of +those files, known as the “Active” test run configuration file, is used to +determine the settings that are currently used for test runs. You select +the active test run configuration by clicking Select Active Test Run +Configuration on the Test menu. + +------------------------------------------------------------------------------- + +Test Types +---------- +Using Visual Studio Team Edition for Software Testers, you can create a number +of different test types: + +Unit test: Use a unit test to create a programmatic test in C++, Visual C# or +Visual Basic that exercises source code. A unit test calls the methods of a +class, passing suitable parameters, and verifies that the returned value is +what you expect. +There are three specialized variants of unit tests: + - Data-driven unit tests are created when you configure a unit test to be + called repeatedly for each row of a data source. The data from each row + is used by the unit test as input data. + - ASP.NET unit tests are unit tests that exercise code in an ASP.NET Web + application. + - Smart device unit tests are unit tests that are deployed to a smart device + or emulator and then executed by the smart device test host. + +Web Test: Web tests consist of an ordered series of HTTP requests that you +record in a browser session using Microsoft Internet Explorer. You can have +the test report specific details about the pages or sites it requests, such +as whether a particular page contains a specified string. + +Load Test: You use a load test to encapsulate non-manual tests, such as +unit, Web, and generic tests, and then run them simultaneously by using +virtual users. Running these tests under load generates test results, +including performance and other counters, in tables and in graphs. + +Generic test: A generic test is an existing program wrapped to function as a +test in Visual Studio. The following are examples of tests or programs that +you can turn into generic tests: + - An existing test that uses process exit codes to communicate whether the + test passed or failed. 0 indicates passing and any other value indicates + a failure. + - A general program to obtain specific functionality during a test scenario. + - A test or program that uses a special XML file (called a “summary results + file”), to communicate detailed results. + +Manual test: The manual test type is used when the test tasks are to be +completed by a test engineer as opposed to an automated script. + +Ordered test: Use an ordered test to execute a set of tests in an order you +specify. + +------------------------------------------------------------------------------- + + diff --git a/ShowOff.IntegrationTests/Data/DataTests.cs b/ShowOff.IntegrationTests/Data/DataTests.cs new file mode 100644 index 0000000..197e5a0 --- /dev/null +++ b/ShowOff.IntegrationTests/Data/DataTests.cs @@ -0,0 +1,90 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Data.Linq; +using ShowOff.Core.Data; +using ShowOff.Core.Model; +using ShowOff.Core.Repository; + +namespace ShowOff.IntegrationTests.Data +{ + [TestClass] + public class DataTests + { + public DataTests() + { + + } + + [ClassInitialize] + public static void SetupDatabase(TestContext testContext) + { + SessionFactoryFactory.DropSchema(); + SessionFactoryFactory.CreateSchema(); + } + + [TestMethod] + public void CreateData() + { + var session = SessionFactoryFactory.GetSessionFactory().OpenSession(); + + // item types + var websiteItemType = new ItemType() {ID = 1, Name = "Website", DisplayName = "Website"}; + var logoItemType = new ItemType() { ID = 2, Name = "Logo", DisplayName = "Logo" }; + var printItemType = new ItemType() { ID = 3, Name = "Print", DisplayName = "Print" }; + var apparelItemType = new ItemType() { ID = 4, Name = "Apparel", DisplayName = "Apparel" }; + + session.SaveOrUpdate(websiteItemType); + session.SaveOrUpdate(logoItemType); + session.SaveOrUpdate(printItemType); + session.SaveOrUpdate(apparelItemType); + + for (int j = 0; j < 10; j++) + { + // item images + var itemImageRepo = new ItemImageRepository(); + + var fileNames = new List() + { + "test1.jpg", + "test2.jpg", + "test3.jpg", + "test4.jpg", + "test5.jpg" + }; + + + var images = fileNames.Select(p => new ItemImage() {Filename = p, ThumbFilename = p}).ToList(); + + var item = new Item() + { + Name = "ShowOff Item " + j, + Description = "Show me off to the world.", + Url = "http://www.showoffgallery.com", + CreatedDate = DateTime.Now, + ModifiedDate = DateTime.Now, + Type = websiteItemType, + Images = images, + CoverImage = images[0], + DisplayPriority = 0 + }; + + session.SaveOrUpdate(item); + session.Flush(); + } + } + + [TestMethod] + public void UpdateData() + { + } + + [TestMethod] + public void DeleteData() + { + } + } +} \ No newline at end of file diff --git a/ShowOff.IntegrationTests/EmbededResources/Chrysanthemum.jpg b/ShowOff.IntegrationTests/EmbededResources/Chrysanthemum.jpg new file mode 100644 index 0000000..757c2a6 Binary files /dev/null and b/ShowOff.IntegrationTests/EmbededResources/Chrysanthemum.jpg differ diff --git a/ShowOff.IntegrationTests/Properties/AssemblyInfo.cs b/ShowOff.IntegrationTests/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..d0db06b --- /dev/null +++ b/ShowOff.IntegrationTests/Properties/AssemblyInfo.cs @@ -0,0 +1,35 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("ShowOff.IntegrationTests")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("ShowOff.IntegrationTests")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2009")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM componenets. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("0e135ef5-8ede-4f38-9f41-01c2ba6760a8")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Revision and Build Numbers +// by using the '*' as shown below: +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/ShowOff.IntegrationTests/ShowOff.IntegrationTests.csproj b/ShowOff.IntegrationTests/ShowOff.IntegrationTests.csproj new file mode 100644 index 0000000..dad2850 --- /dev/null +++ b/ShowOff.IntegrationTests/ShowOff.IntegrationTests.csproj @@ -0,0 +1,100 @@ + + + Debug + AnyCPU + 9.0.30729 + 2.0 + {EECEB95A-9E01-4C79-B48E-7D22049E7093} + Library + Properties + ShowOff.IntegrationTests + ShowOff.IntegrationTests + v3.5 + 512 + {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + False + ..\lib\nhib\Antlr3.Runtime.dll + + + False + ..\lib\nhib\Castle.Core.dll + + + False + ..\lib\nhib\Castle.DynamicProxy2.dll + + + False + ..\lib\nhib\FluentNHibernate.dll + + + False + ..\lib\nhib\Iesi.Collections.dll + + + False + ..\lib\nhib\log4net.dll + + + + False + ..\lib\nhib\NHibernate.dll + + + False + ..\lib\nhib\NHibernate.ByteCode.Castle.dll + + + + 3.5 + + + 3.5 + + + + + + + + + + + + + {A1C59F74-87E6-4C8B-AC65-EC41D2DE13E8} + ShowOff.Core + + + + + + + + \ No newline at end of file diff --git a/ShowOff.Tests/App.config b/ShowOff.Tests/App.config new file mode 100644 index 0000000..f00e873 --- /dev/null +++ b/ShowOff.Tests/App.config @@ -0,0 +1,14 @@ + + + + + + + + + + + diff --git a/ShowOff.Tests/Controllers/AccountControllerTest.cs b/ShowOff.Tests/Controllers/AccountControllerTest.cs new file mode 100644 index 0000000..87e6470 --- /dev/null +++ b/ShowOff.Tests/Controllers/AccountControllerTest.cs @@ -0,0 +1,405 @@ +using System; +using System.Security.Principal; +using System.Web; +using System.Web.Mvc; +using System.Web.Routing; +using System.Web.Security; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using ShowOff; +using ShowOff.Controllers; +using ShowOff.Models; + +namespace ShowOff.Tests.Controllers +{ + + [TestClass] + public class AccountControllerTest + { + + [TestMethod] + public void ChangePassword_Get_ReturnsView() + { + // Arrange + AccountController controller = GetAccountController(); + + // Act + ActionResult result = controller.ChangePassword(); + + // Assert + Assert.IsInstanceOfType(result, typeof(ViewResult)); + } + + [TestMethod] + public void ChangePassword_Post_ReturnsRedirectOnSuccess() + { + // Arrange + AccountController controller = GetAccountController(); + ChangePasswordModel model = new ChangePasswordModel() + { + OldPassword = "goodOldPassword", + NewPassword = "goodNewPassword", + ConfirmPassword = "goodNewPassword" + }; + + // Act + ActionResult result = controller.ChangePassword(model); + + // Assert + Assert.IsInstanceOfType(result, typeof(RedirectToRouteResult)); + RedirectToRouteResult redirectResult = (RedirectToRouteResult)result; + Assert.AreEqual("ChangePasswordSuccess", redirectResult.RouteValues["action"]); + } + + [TestMethod] + public void ChangePassword_Post_ReturnsViewIfChangePasswordFails() + { + // Arrange + AccountController controller = GetAccountController(); + ChangePasswordModel model = new ChangePasswordModel() + { + OldPassword = "goodOldPassword", + NewPassword = "badNewPassword", + ConfirmPassword = "badNewPassword" + }; + + // Act + ActionResult result = controller.ChangePassword(model); + + // Assert + Assert.IsInstanceOfType(result, typeof(ViewResult)); + ViewResult viewResult = (ViewResult)result; + Assert.AreEqual(model, viewResult.ViewData.Model); + Assert.AreEqual("The current password is incorrect or the new password is invalid.", controller.ModelState[""].Errors[0].ErrorMessage); + } + + [TestMethod] + public void ChangePassword_Post_ReturnsViewIfModelStateIsInvalid() + { + // Arrange + AccountController controller = GetAccountController(); + ChangePasswordModel model = new ChangePasswordModel() + { + OldPassword = "goodOldPassword", + NewPassword = "goodNewPassword", + ConfirmPassword = "goodNewPassword" + }; + controller.ModelState.AddModelError("", "Dummy error message."); + + // Act + ActionResult result = controller.ChangePassword(model); + + // Assert + Assert.IsInstanceOfType(result, typeof(ViewResult)); + ViewResult viewResult = (ViewResult)result; + Assert.AreEqual(model, viewResult.ViewData.Model); + } + + [TestMethod] + public void ChangePasswordSuccess_ReturnsView() + { + // Arrange + AccountController controller = GetAccountController(); + + // Act + ActionResult result = controller.ChangePasswordSuccess(); + + // Assert + Assert.IsInstanceOfType(result, typeof(ViewResult)); + } + + [TestMethod] + public void LogOff_LogsOutAndRedirects() + { + // Arrange + AccountController controller = GetAccountController(); + + // Act + ActionResult result = controller.LogOff(); + + // Assert + Assert.IsInstanceOfType(result, typeof(RedirectToRouteResult)); + RedirectToRouteResult redirectResult = (RedirectToRouteResult)result; + Assert.AreEqual("Home", redirectResult.RouteValues["controller"]); + Assert.AreEqual("Index", redirectResult.RouteValues["action"]); + Assert.IsTrue(((MockFormsAuthenticationService)controller.FormsService).SignOut_WasCalled); + } + + [TestMethod] + public void LogOn_Get_ReturnsView() + { + // Arrange + AccountController controller = GetAccountController(); + + // Act + ActionResult result = controller.LogOn(); + + // Assert + Assert.IsInstanceOfType(result, typeof(ViewResult)); + } + + [TestMethod] + public void LogOn_Post_ReturnsRedirectOnSuccess_WithoutReturnUrl() + { + // Arrange + AccountController controller = GetAccountController(); + LogOnModel model = new LogOnModel() + { + UserName = "someUser", + Password = "goodPassword", + RememberMe = false + }; + + // Act + ActionResult result = controller.LogOn(model, null); + + // Assert + Assert.IsInstanceOfType(result, typeof(RedirectToRouteResult)); + RedirectToRouteResult redirectResult = (RedirectToRouteResult)result; + Assert.AreEqual("Home", redirectResult.RouteValues["controller"]); + Assert.AreEqual("Index", redirectResult.RouteValues["action"]); + Assert.IsTrue(((MockFormsAuthenticationService)controller.FormsService).SignIn_WasCalled); + } + + [TestMethod] + public void LogOn_Post_ReturnsRedirectOnSuccess_WithReturnUrl() + { + // Arrange + AccountController controller = GetAccountController(); + LogOnModel model = new LogOnModel() + { + UserName = "someUser", + Password = "goodPassword", + RememberMe = false + }; + + // Act + ActionResult result = controller.LogOn(model, "/someUrl"); + + // Assert + Assert.IsInstanceOfType(result, typeof(RedirectResult)); + RedirectResult redirectResult = (RedirectResult)result; + Assert.AreEqual("/someUrl", redirectResult.Url); + Assert.IsTrue(((MockFormsAuthenticationService)controller.FormsService).SignIn_WasCalled); + } + + [TestMethod] + public void LogOn_Post_ReturnsViewIfModelStateIsInvalid() + { + // Arrange + AccountController controller = GetAccountController(); + LogOnModel model = new LogOnModel() + { + UserName = "someUser", + Password = "goodPassword", + RememberMe = false + }; + controller.ModelState.AddModelError("", "Dummy error message."); + + // Act + ActionResult result = controller.LogOn(model, null); + + // Assert + Assert.IsInstanceOfType(result, typeof(ViewResult)); + ViewResult viewResult = (ViewResult)result; + Assert.AreEqual(model, viewResult.ViewData.Model); + } + + [TestMethod] + public void LogOn_Post_ReturnsViewIfValidateUserFails() + { + // Arrange + AccountController controller = GetAccountController(); + LogOnModel model = new LogOnModel() + { + UserName = "someUser", + Password = "badPassword", + RememberMe = false + }; + + // Act + ActionResult result = controller.LogOn(model, null); + + // Assert + Assert.IsInstanceOfType(result, typeof(ViewResult)); + ViewResult viewResult = (ViewResult)result; + Assert.AreEqual(model, viewResult.ViewData.Model); + Assert.AreEqual("The user name or password provided is incorrect.", controller.ModelState[""].Errors[0].ErrorMessage); + } + + [TestMethod] + public void OnActionExecuting_SetsViewData() + { + // Arrange + AccountController controller = GetAccountController(); + + // Act + ((IActionFilter)controller).OnActionExecuting(null); + + // Assert + Assert.AreEqual(10, controller.ViewData["PasswordLength"]); + } + + [TestMethod] + public void Register_Get_ReturnsView() + { + // Arrange + AccountController controller = GetAccountController(); + + // Act + ActionResult result = controller.Register(); + + // Assert + Assert.IsInstanceOfType(result, typeof(ViewResult)); + } + + [TestMethod] + public void Register_Post_ReturnsRedirectOnSuccess() + { + // Arrange + AccountController controller = GetAccountController(); + RegisterModel model = new RegisterModel() + { + UserName = "someUser", + Email = "goodEmail", + Password = "goodPassword", + ConfirmPassword = "goodPassword" + }; + + // Act + ActionResult result = controller.Register(model); + + // Assert + Assert.IsInstanceOfType(result, typeof(RedirectToRouteResult)); + RedirectToRouteResult redirectResult = (RedirectToRouteResult)result; + Assert.AreEqual("Home", redirectResult.RouteValues["controller"]); + Assert.AreEqual("Index", redirectResult.RouteValues["action"]); + } + + [TestMethod] + public void Register_Post_ReturnsViewIfRegistrationFails() + { + // Arrange + AccountController controller = GetAccountController(); + RegisterModel model = new RegisterModel() + { + UserName = "duplicateUser", + Email = "goodEmail", + Password = "goodPassword", + ConfirmPassword = "goodPassword" + }; + + // Act + ActionResult result = controller.Register(model); + + // Assert + Assert.IsInstanceOfType(result, typeof(ViewResult)); + ViewResult viewResult = (ViewResult)result; + Assert.AreEqual(model, viewResult.ViewData.Model); + Assert.AreEqual("Username already exists. Please enter a different user name.", controller.ModelState[""].Errors[0].ErrorMessage); + } + + [TestMethod] + public void Register_Post_ReturnsViewIfModelStateIsInvalid() + { + // Arrange + AccountController controller = GetAccountController(); + RegisterModel model = new RegisterModel() + { + UserName = "someUser", + Email = "goodEmail", + Password = "goodPassword", + ConfirmPassword = "goodPassword" + }; + controller.ModelState.AddModelError("", "Dummy error message."); + + // Act + ActionResult result = controller.Register(model); + + // Assert + Assert.IsInstanceOfType(result, typeof(ViewResult)); + ViewResult viewResult = (ViewResult)result; + Assert.AreEqual(model, viewResult.ViewData.Model); + } + + private static AccountController GetAccountController() + { + AccountController controller = new AccountController(new MockFormsAuthenticationService(), new MockMembershipService()); + controller.ControllerContext = new ControllerContext() + { + Controller = controller, + RequestContext = new RequestContext(new MockHttpContext(), new RouteData()) + }; + return controller; + } + + private class MockFormsAuthenticationService : IFormsAuthenticationService + { + public bool SignIn_WasCalled; + public bool SignOut_WasCalled; + + public void SignIn(string userName, bool createPersistentCookie) + { + // verify that the arguments are what we expected + Assert.AreEqual("someUser", userName); + Assert.IsFalse(createPersistentCookie); + + SignIn_WasCalled = true; + } + + public void SignOut() + { + SignOut_WasCalled = true; + } + } + + private class MockHttpContext : HttpContextBase + { + private readonly IPrincipal _user = new GenericPrincipal(new GenericIdentity("someUser"), null /* roles */); + + public override IPrincipal User + { + get + { + return _user; + } + set + { + base.User = value; + } + } + } + + private class MockMembershipService : IMembershipService + { + public int MinPasswordLength + { + get { return 10; } + } + + public bool ValidateUser(string userName, string password) + { + return (userName == "someUser" && password == "goodPassword"); + } + + public MembershipCreateStatus CreateUser(string userName, string password, string email) + { + if (userName == "duplicateUser") + { + return MembershipCreateStatus.DuplicateUserName; + } + + // verify that values are what we expected + Assert.AreEqual("goodPassword", password); + Assert.AreEqual("goodEmail", email); + + return MembershipCreateStatus.Success; + } + + public bool ChangePassword(string userName, string oldPassword, string newPassword) + { + return (userName == "someUser" && oldPassword == "goodOldPassword" && newPassword == "goodNewPassword"); + } + } + + } +} diff --git a/ShowOff.Tests/Controllers/HomeControllerTest.cs b/ShowOff.Tests/Controllers/HomeControllerTest.cs new file mode 100644 index 0000000..e00dbd3 --- /dev/null +++ b/ShowOff.Tests/Controllers/HomeControllerTest.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Web.Mvc; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using ShowOff; +using ShowOff.Controllers; + +namespace ShowOff.Tests.Controllers +{ + [TestClass] + public class HomeControllerTest + { + [TestMethod] + public void Index() + { + // Arrange + HomeController controller = new HomeController(); + + // Act + ViewResult result = controller.Index() as ViewResult; + + // Assert + ViewDataDictionary viewData = result.ViewData; + Assert.AreEqual("Welcome to ASP.NET MVC!", viewData["Message"]); + } + + [TestMethod] + public void About() + { + // Arrange + HomeController controller = new HomeController(); + + // Act + ViewResult result = controller.About() as ViewResult; + + // Assert + Assert.IsNotNull(result); + } + } +} diff --git a/ShowOff.Tests/Properties/AssemblyInfo.cs b/ShowOff.Tests/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..3f71698 --- /dev/null +++ b/ShowOff.Tests/Properties/AssemblyInfo.cs @@ -0,0 +1,35 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("ShowOff.Tests")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("ShowOff.Tests")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2009")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("3a079aca-4f97-49c6-bb20-c96b7ac930c1")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Revision and Build Numbers +// by using the '*' as shown below: +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/ShowOff.Tests/ShowOff.Tests.csproj b/ShowOff.Tests/ShowOff.Tests.csproj new file mode 100644 index 0000000..8311489 --- /dev/null +++ b/ShowOff.Tests/ShowOff.Tests.csproj @@ -0,0 +1,76 @@ + + + Debug + AnyCPU + 9.0.30729 + 2.0 + {B7DA4F03-FCFC-4F80-9BC9-3AC77DD7B5AF} + Library + Properties + ShowOff.Tests + ShowOff.Tests + v3.5 + 512 + {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + 3.5 + + + + 3.5 + + + + 3.5 + + + + False + ..\..\..\..\..\..\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 2\\Assemblies\System.Web.Mvc.dll + + + + + + + + + + + + + + {16953589-C324-4750-B9F4-4D699078373D} + ShowOff + + + + + \ No newline at end of file diff --git a/ShowOff.sln b/ShowOff.sln new file mode 100644 index 0000000..04a41d6 --- /dev/null +++ b/ShowOff.sln @@ -0,0 +1,47 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShowOff", "ShowOff\ShowOff.csproj", "{16953589-C324-4750-B9F4-4D699078373D}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShowOff.Tests", "ShowOff.Tests\ShowOff.Tests.csproj", "{B7DA4F03-FCFC-4F80-9BC9-3AC77DD7B5AF}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShowOff.Core", "ShowOff.Core\ShowOff.Core.csproj", "{A1C59F74-87E6-4C8B-AC65-EC41D2DE13E8}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShowOff.IntegrationTests", "ShowOff.IntegrationTests\ShowOff.IntegrationTests.csproj", "{EECEB95A-9E01-4C79-B48E-7D22049E7093}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{DC1FA00A-74A8-4C64-82FA-C1A5885DED64}" + ProjectSection(SolutionItems) = preProject + LocalTestRun.testrunconfig = LocalTestRun.testrunconfig + ShowOff.vsmdi = ShowOff.vsmdi + EndProjectSection +EndProject +Global + GlobalSection(TestCaseManagementSettings) = postSolution + CategoryFile = ShowOff.vsmdi + EndGlobalSection + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {16953589-C324-4750-B9F4-4D699078373D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {16953589-C324-4750-B9F4-4D699078373D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {16953589-C324-4750-B9F4-4D699078373D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {16953589-C324-4750-B9F4-4D699078373D}.Release|Any CPU.Build.0 = Release|Any CPU + {B7DA4F03-FCFC-4F80-9BC9-3AC77DD7B5AF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B7DA4F03-FCFC-4F80-9BC9-3AC77DD7B5AF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B7DA4F03-FCFC-4F80-9BC9-3AC77DD7B5AF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B7DA4F03-FCFC-4F80-9BC9-3AC77DD7B5AF}.Release|Any CPU.Build.0 = Release|Any CPU + {A1C59F74-87E6-4C8B-AC65-EC41D2DE13E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A1C59F74-87E6-4C8B-AC65-EC41D2DE13E8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A1C59F74-87E6-4C8B-AC65-EC41D2DE13E8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A1C59F74-87E6-4C8B-AC65-EC41D2DE13E8}.Release|Any CPU.Build.0 = Release|Any CPU + {EECEB95A-9E01-4C79-B48E-7D22049E7093}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {EECEB95A-9E01-4C79-B48E-7D22049E7093}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EECEB95A-9E01-4C79-B48E-7D22049E7093}.Release|Any CPU.ActiveCfg = Release|Any CPU + {EECEB95A-9E01-4C79-B48E-7D22049E7093}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/ShowOff.suo b/ShowOff.suo new file mode 100644 index 0000000..0f90034 Binary files /dev/null and b/ShowOff.suo differ diff --git a/ShowOff.vsmdi b/ShowOff.vsmdi new file mode 100644 index 0000000..9afc921 --- /dev/null +++ b/ShowOff.vsmdi @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/ShowOff/App_Data/ASPNETDB.MDF b/ShowOff/App_Data/ASPNETDB.MDF new file mode 100644 index 0000000..7c87b5a Binary files /dev/null and b/ShowOff/App_Data/ASPNETDB.MDF differ diff --git a/ShowOff/App_Data/aspnetdb_log.ldf b/ShowOff/App_Data/aspnetdb_log.ldf new file mode 100644 index 0000000..49db40b Binary files /dev/null and b/ShowOff/App_Data/aspnetdb_log.ldf differ diff --git a/ShowOff/Content/Images/1.gif b/ShowOff/Content/Images/1.gif new file mode 100644 index 0000000..4045136 Binary files /dev/null and b/ShowOff/Content/Images/1.gif differ diff --git a/ShowOff/Content/Images/2.gif b/ShowOff/Content/Images/2.gif new file mode 100644 index 0000000..be8dd39 Binary files /dev/null and b/ShowOff/Content/Images/2.gif differ diff --git a/ShowOff/Content/Images/3.gif b/ShowOff/Content/Images/3.gif new file mode 100644 index 0000000..0ada87d Binary files /dev/null and b/ShowOff/Content/Images/3.gif differ diff --git a/ShowOff/Content/Images/4.gif b/ShowOff/Content/Images/4.gif new file mode 100644 index 0000000..d56f4cf Binary files /dev/null and b/ShowOff/Content/Images/4.gif differ diff --git a/ShowOff/Content/Images/5.gif b/ShowOff/Content/Images/5.gif new file mode 100644 index 0000000..5b5a417 Binary files /dev/null and b/ShowOff/Content/Images/5.gif differ diff --git a/ShowOff/Content/Images/6.gif b/ShowOff/Content/Images/6.gif new file mode 100644 index 0000000..f179755 Binary files /dev/null and b/ShowOff/Content/Images/6.gif differ diff --git a/ShowOff/Content/Images/about_header.gif b/ShowOff/Content/Images/about_header.gif new file mode 100644 index 0000000..60bd835 Binary files /dev/null and b/ShowOff/Content/Images/about_header.gif differ diff --git a/ShowOff/Content/Images/approach_header.gif b/ShowOff/Content/Images/approach_header.gif new file mode 100644 index 0000000..b3e290a Binary files /dev/null and b/ShowOff/Content/Images/approach_header.gif differ diff --git a/ShowOff/Content/Images/bg-communities-bottom.gif b/ShowOff/Content/Images/bg-communities-bottom.gif new file mode 100644 index 0000000..8a14094 Binary files /dev/null and b/ShowOff/Content/Images/bg-communities-bottom.gif differ diff --git a/ShowOff/Content/Images/bg-communities-top.gif b/ShowOff/Content/Images/bg-communities-top.gif new file mode 100644 index 0000000..3cdcdec Binary files /dev/null and b/ShowOff/Content/Images/bg-communities-top.gif differ diff --git a/ShowOff/Content/Images/bg-communities.gif b/ShowOff/Content/Images/bg-communities.gif new file mode 100644 index 0000000..71815ae Binary files /dev/null and b/ShowOff/Content/Images/bg-communities.gif differ diff --git a/ShowOff/Content/Images/bg-footer-hp.gif b/ShowOff/Content/Images/bg-footer-hp.gif new file mode 100644 index 0000000..17cffde Binary files /dev/null and b/ShowOff/Content/Images/bg-footer-hp.gif differ diff --git a/ShowOff/Content/Images/bg-footer.gif b/ShowOff/Content/Images/bg-footer.gif new file mode 100644 index 0000000..130972d Binary files /dev/null and b/ShowOff/Content/Images/bg-footer.gif differ diff --git a/ShowOff/Content/Images/bg-greetings-bottom.gif b/ShowOff/Content/Images/bg-greetings-bottom.gif new file mode 100644 index 0000000..10954aa Binary files /dev/null and b/ShowOff/Content/Images/bg-greetings-bottom.gif differ diff --git a/ShowOff/Content/Images/bg-greetings-top.gif b/ShowOff/Content/Images/bg-greetings-top.gif new file mode 100644 index 0000000..22cf62a Binary files /dev/null and b/ShowOff/Content/Images/bg-greetings-top.gif differ diff --git a/ShowOff/Content/Images/bg-greetings.gif b/ShowOff/Content/Images/bg-greetings.gif new file mode 100644 index 0000000..4454a74 Binary files /dev/null and b/ShowOff/Content/Images/bg-greetings.gif differ diff --git a/ShowOff/Content/Images/bg-main-hp.gif b/ShowOff/Content/Images/bg-main-hp.gif new file mode 100644 index 0000000..9ee4aef Binary files /dev/null and b/ShowOff/Content/Images/bg-main-hp.gif differ diff --git a/ShowOff/Content/Images/bg-service-list.gif b/ShowOff/Content/Images/bg-service-list.gif new file mode 100644 index 0000000..f3ca695 Binary files /dev/null and b/ShowOff/Content/Images/bg-service-list.gif differ diff --git a/ShowOff/Content/Images/btn-share.gif b/ShowOff/Content/Images/btn-share.gif new file mode 100644 index 0000000..4ff7dbd Binary files /dev/null and b/ShowOff/Content/Images/btn-share.gif differ diff --git a/ShowOff/Content/Images/btn-submit.gif b/ShowOff/Content/Images/btn-submit.gif new file mode 100644 index 0000000..a1b8080 Binary files /dev/null and b/ShowOff/Content/Images/btn-submit.gif differ diff --git a/ShowOff/Content/Images/communityheader.gif b/ShowOff/Content/Images/communityheader.gif new file mode 100644 index 0000000..9cd5619 Binary files /dev/null and b/ShowOff/Content/Images/communityheader.gif differ diff --git a/ShowOff/Content/Images/contact_header.gif b/ShowOff/Content/Images/contact_header.gif new file mode 100644 index 0000000..771aae7 Binary files /dev/null and b/ShowOff/Content/Images/contact_header.gif differ diff --git a/ShowOff/Content/Images/contentpage.jpg b/ShowOff/Content/Images/contentpage.jpg new file mode 100644 index 0000000..3127125 Binary files /dev/null and b/ShowOff/Content/Images/contentpage.jpg differ diff --git a/ShowOff/Content/Images/corissa.jpg b/ShowOff/Content/Images/corissa.jpg new file mode 100644 index 0000000..da62ff9 Binary files /dev/null and b/ShowOff/Content/Images/corissa.jpg differ diff --git a/ShowOff/Content/Images/couture_slide.jpg b/ShowOff/Content/Images/couture_slide.jpg new file mode 100644 index 0000000..7f40b64 Binary files /dev/null and b/ShowOff/Content/Images/couture_slide.jpg differ diff --git a/ShowOff/Content/Images/delilahs_slide.jpg b/ShowOff/Content/Images/delilahs_slide.jpg new file mode 100644 index 0000000..3130ebd Binary files /dev/null and b/ShowOff/Content/Images/delilahs_slide.jpg differ diff --git a/ShowOff/Content/Images/facebook.gif b/ShowOff/Content/Images/facebook.gif new file mode 100644 index 0000000..36cff62 Binary files /dev/null and b/ShowOff/Content/Images/facebook.gif differ diff --git a/ShowOff/Content/Images/facebook_white.gif b/ShowOff/Content/Images/facebook_white.gif new file mode 100644 index 0000000..23237af Binary files /dev/null and b/ShowOff/Content/Images/facebook_white.gif differ diff --git a/ShowOff/Content/Images/follow.gif b/ShowOff/Content/Images/follow.gif new file mode 100644 index 0000000..9585eaf Binary files /dev/null and b/ShowOff/Content/Images/follow.gif differ diff --git a/ShowOff/Content/Images/footer_facebook.gif b/ShowOff/Content/Images/footer_facebook.gif new file mode 100644 index 0000000..cc7319a Binary files /dev/null and b/ShowOff/Content/Images/footer_facebook.gif differ diff --git a/ShowOff/Content/Images/footer_join.gif b/ShowOff/Content/Images/footer_join.gif new file mode 100644 index 0000000..a735345 Binary files /dev/null and b/ShowOff/Content/Images/footer_join.gif differ diff --git a/ShowOff/Content/Images/footer_linkdin.gif b/ShowOff/Content/Images/footer_linkdin.gif new file mode 100644 index 0000000..cadd6b7 Binary files /dev/null and b/ShowOff/Content/Images/footer_linkdin.gif differ diff --git a/ShowOff/Content/Images/footer_myspace.gif b/ShowOff/Content/Images/footer_myspace.gif new file mode 100644 index 0000000..c22091b Binary files /dev/null and b/ShowOff/Content/Images/footer_myspace.gif differ diff --git a/ShowOff/Content/Images/footer_sep.gif b/ShowOff/Content/Images/footer_sep.gif new file mode 100644 index 0000000..d363d78 Binary files /dev/null and b/ShowOff/Content/Images/footer_sep.gif differ diff --git a/ShowOff/Content/Images/footer_twitter.gif b/ShowOff/Content/Images/footer_twitter.gif new file mode 100644 index 0000000..6a284fb Binary files /dev/null and b/ShowOff/Content/Images/footer_twitter.gif differ diff --git a/ShowOff/Content/Images/ico-facebook.gif b/ShowOff/Content/Images/ico-facebook.gif new file mode 100644 index 0000000..e2f4530 Binary files /dev/null and b/ShowOff/Content/Images/ico-facebook.gif differ diff --git a/ShowOff/Content/Images/ico-linked.gif b/ShowOff/Content/Images/ico-linked.gif new file mode 100644 index 0000000..fdd3b3b Binary files /dev/null and b/ShowOff/Content/Images/ico-linked.gif differ diff --git a/ShowOff/Content/Images/ico-twitter.gif b/ShowOff/Content/Images/ico-twitter.gif new file mode 100644 index 0000000..cdd6f75 Binary files /dev/null and b/ShowOff/Content/Images/ico-twitter.gif differ diff --git a/ShowOff/Content/Images/icons.gif b/ShowOff/Content/Images/icons.gif new file mode 100644 index 0000000..e80abdd Binary files /dev/null and b/ShowOff/Content/Images/icons.gif differ diff --git a/ShowOff/Content/Images/inkdin.gif b/ShowOff/Content/Images/inkdin.gif new file mode 100644 index 0000000..09bbba2 Binary files /dev/null and b/ShowOff/Content/Images/inkdin.gif differ diff --git a/ShowOff/Content/Images/join_button.gif b/ShowOff/Content/Images/join_button.gif new file mode 100644 index 0000000..e37ddac Binary files /dev/null and b/ShowOff/Content/Images/join_button.gif differ diff --git a/ShowOff/Content/Images/joinnow_newsletter.gif b/ShowOff/Content/Images/joinnow_newsletter.gif new file mode 100644 index 0000000..b811f5f Binary files /dev/null and b/ShowOff/Content/Images/joinnow_newsletter.gif differ diff --git a/ShowOff/Content/Images/latestwork2.jpg b/ShowOff/Content/Images/latestwork2.jpg new file mode 100644 index 0000000..c441298 Binary files /dev/null and b/ShowOff/Content/Images/latestwork2.jpg differ diff --git a/ShowOff/Content/Images/latestwork3.jpg b/ShowOff/Content/Images/latestwork3.jpg new file mode 100644 index 0000000..1ee23dc Binary files /dev/null and b/ShowOff/Content/Images/latestwork3.jpg differ diff --git a/ShowOff/Content/Images/latestwork_1.jpg b/ShowOff/Content/Images/latestwork_1.jpg new file mode 100644 index 0000000..b1cfa4d Binary files /dev/null and b/ShowOff/Content/Images/latestwork_1.jpg differ diff --git a/ShowOff/Content/Images/latestwork_corissa.jpg b/ShowOff/Content/Images/latestwork_corissa.jpg new file mode 100644 index 0000000..543e1e8 Binary files /dev/null and b/ShowOff/Content/Images/latestwork_corissa.jpg differ diff --git a/ShowOff/Content/Images/latestwork_das.jpg b/ShowOff/Content/Images/latestwork_das.jpg new file mode 100644 index 0000000..12202d3 Binary files /dev/null and b/ShowOff/Content/Images/latestwork_das.jpg differ diff --git a/ShowOff/Content/Images/latestwork_mgf.jpg b/ShowOff/Content/Images/latestwork_mgf.jpg new file mode 100644 index 0000000..cda8c3e Binary files /dev/null and b/ShowOff/Content/Images/latestwork_mgf.jpg differ diff --git a/ShowOff/Content/Images/linkdin_white.gif b/ShowOff/Content/Images/linkdin_white.gif new file mode 100644 index 0000000..1d05c09 Binary files /dev/null and b/ShowOff/Content/Images/linkdin_white.gif differ diff --git a/ShowOff/Content/Images/logo.gif b/ShowOff/Content/Images/logo.gif new file mode 100644 index 0000000..523d47e Binary files /dev/null and b/ShowOff/Content/Images/logo.gif differ diff --git a/ShowOff/Content/Images/main_header.jpg b/ShowOff/Content/Images/main_header.jpg new file mode 100644 index 0000000..9a86a65 Binary files /dev/null and b/ShowOff/Content/Images/main_header.jpg differ diff --git a/ShowOff/Content/Images/mainheader.jpg b/ShowOff/Content/Images/mainheader.jpg new file mode 100644 index 0000000..7f943d9 Binary files /dev/null and b/ShowOff/Content/Images/mainheader.jpg differ diff --git a/ShowOff/Content/Images/manren.jpg b/ShowOff/Content/Images/manren.jpg new file mode 100644 index 0000000..22730b0 Binary files /dev/null and b/ShowOff/Content/Images/manren.jpg differ diff --git a/ShowOff/Content/Images/manren_latestwork.jpg b/ShowOff/Content/Images/manren_latestwork.jpg new file mode 100644 index 0000000..c741620 Binary files /dev/null and b/ShowOff/Content/Images/manren_latestwork.jpg differ diff --git a/ShowOff/Content/Images/middle_sep.gif b/ShowOff/Content/Images/middle_sep.gif new file mode 100644 index 0000000..7ac4178 Binary files /dev/null and b/ShowOff/Content/Images/middle_sep.gif differ diff --git a/ShowOff/Content/Images/myspace.gif b/ShowOff/Content/Images/myspace.gif new file mode 100644 index 0000000..64215dc Binary files /dev/null and b/ShowOff/Content/Images/myspace.gif differ diff --git a/ShowOff/Content/Images/myspace_white.gif b/ShowOff/Content/Images/myspace_white.gif new file mode 100644 index 0000000..21a1fad Binary files /dev/null and b/ShowOff/Content/Images/myspace_white.gif differ diff --git a/ShowOff/Content/Images/newsletter_h.gif b/ShowOff/Content/Images/newsletter_h.gif new file mode 100644 index 0000000..b2b8ccd Binary files /dev/null and b/ShowOff/Content/Images/newsletter_h.gif differ diff --git a/ShowOff/Content/Images/newsletter_header.gif b/ShowOff/Content/Images/newsletter_header.gif new file mode 100644 index 0000000..c95e17a Binary files /dev/null and b/ShowOff/Content/Images/newsletter_header.gif differ diff --git a/ShowOff/Content/Images/newsletterpackage.jpg b/ShowOff/Content/Images/newsletterpackage.jpg new file mode 100644 index 0000000..acede01 Binary files /dev/null and b/ShowOff/Content/Images/newsletterpackage.jpg differ diff --git a/ShowOff/Content/Images/newsletterpackage2.jpg b/ShowOff/Content/Images/newsletterpackage2.jpg new file mode 100644 index 0000000..3d2e03a Binary files /dev/null and b/ShowOff/Content/Images/newsletterpackage2.jpg differ diff --git a/ShowOff/Content/Images/ourclients_header.gif b/ShowOff/Content/Images/ourclients_header.gif new file mode 100644 index 0000000..78965e4 Binary files /dev/null and b/ShowOff/Content/Images/ourclients_header.gif differ diff --git a/ShowOff/Content/Images/ourworld.gif b/ShowOff/Content/Images/ourworld.gif new file mode 100644 index 0000000..924f65e Binary files /dev/null and b/ShowOff/Content/Images/ourworld.gif differ diff --git a/ShowOff/Content/Images/overview_header.gif b/ShowOff/Content/Images/overview_header.gif new file mode 100644 index 0000000..8d32d47 Binary files /dev/null and b/ShowOff/Content/Images/overview_header.gif differ diff --git a/ShowOff/Content/Images/pic01.jpg b/ShowOff/Content/Images/pic01.jpg new file mode 100644 index 0000000..5103bf7 Binary files /dev/null and b/ShowOff/Content/Images/pic01.jpg differ diff --git a/ShowOff/Content/Images/pic02.jpg b/ShowOff/Content/Images/pic02.jpg new file mode 100644 index 0000000..019d92a Binary files /dev/null and b/ShowOff/Content/Images/pic02.jpg differ diff --git a/ShowOff/Content/Images/pic03.jpg b/ShowOff/Content/Images/pic03.jpg new file mode 100644 index 0000000..83a4832 Binary files /dev/null and b/ShowOff/Content/Images/pic03.jpg differ diff --git a/ShowOff/Content/Images/pic04.jpg b/ShowOff/Content/Images/pic04.jpg new file mode 100644 index 0000000..b29c631 Binary files /dev/null and b/ShowOff/Content/Images/pic04.jpg differ diff --git a/ShowOff/Content/Images/pic05.jpg b/ShowOff/Content/Images/pic05.jpg new file mode 100644 index 0000000..a28db69 Binary files /dev/null and b/ShowOff/Content/Images/pic05.jpg differ diff --git a/ShowOff/Content/Images/pic06.jpg b/ShowOff/Content/Images/pic06.jpg new file mode 100644 index 0000000..8875ec1 Binary files /dev/null and b/ShowOff/Content/Images/pic06.jpg differ diff --git a/ShowOff/Content/Images/pinkslide.jpg b/ShowOff/Content/Images/pinkslide.jpg new file mode 100644 index 0000000..2311414 Binary files /dev/null and b/ShowOff/Content/Images/pinkslide.jpg differ diff --git a/ShowOff/Content/Images/quote_hp.gif b/ShowOff/Content/Images/quote_hp.gif new file mode 100644 index 0000000..aede976 Binary files /dev/null and b/ShowOff/Content/Images/quote_hp.gif differ diff --git a/ShowOff/Content/Images/readmore.gif b/ShowOff/Content/Images/readmore.gif new file mode 100644 index 0000000..a35a482 Binary files /dev/null and b/ShowOff/Content/Images/readmore.gif differ diff --git a/ShowOff/Content/Images/separator.gif b/ShowOff/Content/Images/separator.gif new file mode 100644 index 0000000..f51f087 Binary files /dev/null and b/ShowOff/Content/Images/separator.gif differ diff --git a/ShowOff/Content/Images/services_header.gif b/ShowOff/Content/Images/services_header.gif new file mode 100644 index 0000000..44b989d Binary files /dev/null and b/ShowOff/Content/Images/services_header.gif differ diff --git a/ShowOff/Content/Images/shoresummer_slide.jpg b/ShowOff/Content/Images/shoresummer_slide.jpg new file mode 100644 index 0000000..d8e62fc Binary files /dev/null and b/ShowOff/Content/Images/shoresummer_slide.jpg differ diff --git a/ShowOff/Content/Images/shoresummer_work.jpg b/ShowOff/Content/Images/shoresummer_work.jpg new file mode 100644 index 0000000..7edf88b Binary files /dev/null and b/ShowOff/Content/Images/shoresummer_work.jpg differ diff --git a/ShowOff/Content/Images/theprocess_header.gif b/ShowOff/Content/Images/theprocess_header.gif new file mode 100644 index 0000000..71cf4ef Binary files /dev/null and b/ShowOff/Content/Images/theprocess_header.gif differ diff --git a/ShowOff/Content/Images/twitter.gif b/ShowOff/Content/Images/twitter.gif new file mode 100644 index 0000000..e4f4aa5 Binary files /dev/null and b/ShowOff/Content/Images/twitter.gif differ diff --git a/ShowOff/Content/Images/twitter_white.gif b/ShowOff/Content/Images/twitter_white.gif new file mode 100644 index 0000000..02f6151 Binary files /dev/null and b/ShowOff/Content/Images/twitter_white.gif differ diff --git a/ShowOff/Content/Images/validate-css.gif b/ShowOff/Content/Images/validate-css.gif new file mode 100644 index 0000000..6f2de8b Binary files /dev/null and b/ShowOff/Content/Images/validate-css.gif differ diff --git a/ShowOff/Content/Images/validate-html.gif b/ShowOff/Content/Images/validate-html.gif new file mode 100644 index 0000000..6a0a219 Binary files /dev/null and b/ShowOff/Content/Images/validate-html.gif differ diff --git a/ShowOff/Content/Images/video-picture.gif b/ShowOff/Content/Images/video-picture.gif new file mode 100644 index 0000000..d15d952 Binary files /dev/null and b/ShowOff/Content/Images/video-picture.gif differ diff --git a/ShowOff/Content/Images/welcomeheader.gif b/ShowOff/Content/Images/welcomeheader.gif new file mode 100644 index 0000000..249f19a Binary files /dev/null and b/ShowOff/Content/Images/welcomeheader.gif differ diff --git a/ShowOff/Content/Images/window_header.gif b/ShowOff/Content/Images/window_header.gif new file mode 100644 index 0000000..8d1e81d Binary files /dev/null and b/ShowOff/Content/Images/window_header.gif differ diff --git a/ShowOff/Content/Images/zeebar_slide.jpg b/ShowOff/Content/Images/zeebar_slide.jpg new file mode 100644 index 0000000..9cc0e20 Binary files /dev/null and b/ShowOff/Content/Images/zeebar_slide.jpg differ diff --git a/ShowOff/Content/Uploads/Images/test1.jpg b/ShowOff/Content/Uploads/Images/test1.jpg new file mode 100644 index 0000000..dce6b4c Binary files /dev/null and b/ShowOff/Content/Uploads/Images/test1.jpg differ diff --git a/ShowOff/Content/Uploads/Images/test1_thumb.jpg b/ShowOff/Content/Uploads/Images/test1_thumb.jpg new file mode 100644 index 0000000..90120fa Binary files /dev/null and b/ShowOff/Content/Uploads/Images/test1_thumb.jpg differ diff --git a/ShowOff/Content/Uploads/Images/test2.jpg b/ShowOff/Content/Uploads/Images/test2.jpg new file mode 100644 index 0000000..24dc8f5 Binary files /dev/null and b/ShowOff/Content/Uploads/Images/test2.jpg differ diff --git a/ShowOff/Content/Uploads/Images/test2_thumb.jpg b/ShowOff/Content/Uploads/Images/test2_thumb.jpg new file mode 100644 index 0000000..dd31933 Binary files /dev/null and b/ShowOff/Content/Uploads/Images/test2_thumb.jpg differ diff --git a/ShowOff/Content/Uploads/Images/test3.jpg b/ShowOff/Content/Uploads/Images/test3.jpg new file mode 100644 index 0000000..2aa4573 Binary files /dev/null and b/ShowOff/Content/Uploads/Images/test3.jpg differ diff --git a/ShowOff/Content/Uploads/Images/test3_thumb.jpg b/ShowOff/Content/Uploads/Images/test3_thumb.jpg new file mode 100644 index 0000000..e63e433 Binary files /dev/null and b/ShowOff/Content/Uploads/Images/test3_thumb.jpg differ diff --git a/ShowOff/Content/Uploads/Images/test4.jpg b/ShowOff/Content/Uploads/Images/test4.jpg new file mode 100644 index 0000000..39d34da Binary files /dev/null and b/ShowOff/Content/Uploads/Images/test4.jpg differ diff --git a/ShowOff/Content/Uploads/Images/test4_thumb.jpg b/ShowOff/Content/Uploads/Images/test4_thumb.jpg new file mode 100644 index 0000000..22556a4 Binary files /dev/null and b/ShowOff/Content/Uploads/Images/test4_thumb.jpg differ diff --git a/ShowOff/Content/Uploads/Images/test5.jpg b/ShowOff/Content/Uploads/Images/test5.jpg new file mode 100644 index 0000000..e663896 Binary files /dev/null and b/ShowOff/Content/Uploads/Images/test5.jpg differ diff --git a/ShowOff/Content/Uploads/Images/test5_thumb.jpg b/ShowOff/Content/Uploads/Images/test5_thumb.jpg new file mode 100644 index 0000000..fad39a3 Binary files /dev/null and b/ShowOff/Content/Uploads/Images/test5_thumb.jpg differ diff --git a/ShowOff/Content/css/Site.css b/ShowOff/Content/css/Site.css new file mode 100644 index 0000000..ccb862c --- /dev/null +++ b/ShowOff/Content/css/Site.css @@ -0,0 +1,340 @@ +/*---------------------------------------------------------- +The base color for this template is #5c87b2. If you'd like +to use a different color start by replacing all instances of +#5c87b2 with your new color. +----------------------------------------------------------*/ +body +{ + background-color: #5c87b2; + font-size: .75em; + font-family: Verdana, Helvetica, Sans-Serif; + margin: 0; + padding: 0; + color: #696969; +} + +a:link +{ + color: #034af3; + text-decoration: underline; +} +a:visited +{ + color: #505abc; +} +a:hover +{ + color: #1d60ff; + text-decoration: none; +} +a:active +{ + color: #12eb87; +} + +p, ul +{ + margin-bottom: 20px; + line-height: 1.6em; +} + +/* HEADINGS +----------------------------------------------------------*/ +h1, h2, h3, h4, h5, h6 +{ + font-size: 1.5em; + color: #000; + font-family: Arial, Helvetica, sans-serif; +} + +h1 +{ + font-size: 2em; + padding-bottom: 0; + margin-bottom: 0; +} +h2 +{ + padding: 0 0 10px 0; +} +h3 +{ + font-size: 1.2em; +} +h4 +{ + font-size: 1.1em; +} +h5, h6 +{ + font-size: 1em; +} + +/* this rule styles

tags that are the +first child of the left and right table columns */ +.rightColumn > h1, .rightColumn > h2, .leftColumn > h1, .leftColumn > h2 +{ + margin-top: 0; +} + +/* PRIMARY LAYOUT ELEMENTS +----------------------------------------------------------*/ + +/* you can specify a greater or lesser percentage for the +page width. Or, you can specify an exact pixel width. */ +.page +{ + width: 90%; + margin-left: auto; + margin-right: auto; +} + +#header +{ + position: relative; + margin-bottom: 0px; + color: #000; + padding: 0; +} + +#header h1 +{ + font-weight: bold; + padding: 5px 0; + margin: 0; + color: #fff; + border: none; + line-height: 2em; + font-family: Arial, Helvetica, sans-serif; + font-size: 32px !important; +} + +#main +{ + padding: 30px 30px 15px 30px; + background-color: #fff; + margin-bottom: 30px; + _height: 1px; /* only IE6 applies CSS properties starting with an underscore */ +} + +#footer +{ + color: #999; + padding: 10px 0; + text-align: center; + line-height: normal; + margin: 0; + font-size: .9em; +} + +/* TAB MENU +----------------------------------------------------------*/ +ul#menu +{ + border-bottom: 1px #5C87B2 solid; + padding: 0 0 2px; + position: relative; + margin: 0; + text-align: right; +} + +ul#menu li +{ + display: inline; + list-style: none; +} + +ul#menu li#greeting +{ + padding: 10px 20px; + font-weight: bold; + text-decoration: none; + line-height: 2.8em; + color: #fff; +} + +ul#menu li a +{ + padding: 10px 20px; + font-weight: bold; + text-decoration: none; + line-height: 2.8em; + background-color: #e8eef4; + color: #034af3; +} + +ul#menu li a:hover +{ + background-color: #fff; + text-decoration: none; +} + +ul#menu li a:active +{ + background-color: #a6e2a6; + text-decoration: none; +} + +ul#menu li.selected a +{ + background-color: #fff; + color: #000; +} + +/* FORM LAYOUT ELEMENTS +----------------------------------------------------------*/ + +fieldset +{ + margin: 1em 0; + padding: 1em; + border: 1px solid #CCC; +} + +fieldset p +{ + margin: 2px 12px 10px 10px; +} + +legend +{ + font-size: 1.1em; + font-weight: 600; + padding: 2px 4px 8px 4px; +} + +input[type="text"] +{ + width: 200px; + border: 1px solid #CCC; +} + +input[type="password"] +{ + width: 200px; + border: 1px solid #CCC; +} + +/* TABLE +----------------------------------------------------------*/ + +table +{ + border: solid 1px #e8eef4; + border-collapse: collapse; +} + +table td +{ + padding: 5px; + border: solid 1px #e8eef4; +} + +table th +{ + padding: 6px 5px; + text-align: left; + background-color: #e8eef4; + border: solid 1px #e8eef4; +} + +/* MISC +----------------------------------------------------------*/ +.clear +{ + clear: both; +} + +.error +{ + color:Red; +} + +#menucontainer +{ + margin-top:40px; +} + +div#title +{ + display:block; + float:left; + text-align:left; +} + +#logindisplay +{ + font-size:1.1em; + display:block; + text-align:right; + margin:10px; + color:White; +} + +#logindisplay a:link +{ + color: white; + text-decoration: underline; +} + +#logindisplay a:visited +{ + color: white; + text-decoration: underline; +} + +#logindisplay a:hover +{ + color: white; + text-decoration: none; +} + +.field-validation-error +{ + color: #ff0000; +} + +.field-validation-valid +{ + display: none; +} + +.input-validation-error +{ + border: 1px solid #ff0000; + background-color: #ffeeee; +} + +.validation-summary-errors +{ + font-weight: bold; + color: #ff0000; +} + +.validation-summary-valid +{ + display: none; +} + +.display-label, +.editor-label, +.display-field, +.editor-field +{ + margin: 0.5em 0; +} + +.text-box +{ + width: 30em; +} + +.text-box.multi-line +{ + height: 6.5em; +} + +.tri-state +{ + width: 6em; +} diff --git a/ShowOff/Content/css/all.css b/ShowOff/Content/css/all.css new file mode 100644 index 0000000..296b36c --- /dev/null +++ b/ShowOff/Content/css/all.css @@ -0,0 +1,342 @@ +body{ + margin:0; + color:#5e5e5e; + font: 12px/16px Verdana, Tahoma, Arial, sans-serif; +} +form,fieldset,img{margin:0;padding:0;border:0;} +a{color:#fc03be;text-decoration:none;} +a:hover{text-decoration:underline;} +input, +textarea, +select{ + font:100% arial,sans-serif; + vertical-align:middle; +} +#wrapper{ + width:900px; + margin:0 auto; + overflow:visible; +} +/*-- header --*/ +#header{ + width:100%; + overflow:hidden; + padding:21px 0 0; +} +#header h1{ + width:469px; + height:71px; + overflow:hidden; + margin:0; + text-indent:-9999px; + background: url(../images/logo.gif) no-repeat; +} +#header h1 a{ + display:block; + height:100%; +} +#navigation{ + margin:0; + padding:0; + list-style:none; + text-align:right; + font-size:13px; + line-height:14px; +} +#navigation li{ + display:inline; + margin:0 0 0 20px; +} +#navigation a{ + color:#5e5e5e; + text-decoration:none; +} +#navigation a:hover, +#navigation li.active a{ + color:#fc03be; +} +.hold-pictures{ + width:100%; + overflow:hidden; + padding:25px 0; +} +.hold-pictures img{ + display:block; +} +/*-- gallery --*/ +#gallery{ + width:100%; + overflow:hidden; +} +#gallery .title{ + background:#e3e3e3; + font-size:13px; + color:#4f4f4f; + padding:7px 15px; +} +#gallery .title strong{ + font-weight:normal; +} +#gallery ul{ + margin:0; + padding:0; + list-style:none; +} +#gallery ul li{ + float:left; + margin:2px 1px; + display:inline; +} +#gallery ul img{ + display:block; +} +#gallery ul a{ + float:left; + padding:0 0 2px; + border-bottom:5px solid #ccc; +} +#gallery ul a:hover{ + border-bottom:5px solid #fd12c3; +} +#main{ + width:100%; + overflow:visible; +} +/*-- greetings --*/ +#greetings, +.greetings-inner, +.greetings-area{ + width:100%; + overflow:hidden; + background: url(../images/bg-greetings.gif) repeat-y 478px 0; +} +.greetings-inner{ + background: url(../images/bg-greetings-top.gif) no-repeat 478px 0; +} +.greetings-area{ + padding:40px 0 20px; + min-height:260px; + background: url(../images/bg-greetings-bottom.gif) no-repeat 478px 100%; +} +* html .greetings-area{ + height:260px; + overflow:visible; +} +.greetings-cont{ + width:478px; + float:left; +} +.greetings-side{ + width:344px; + float:right; +} +#greetings .hold-video img{ + display:block; +} +#communities, +.communities-inner, +.communities-area{ + width:100%; + overflow:hidden; + background: url(../images/bg-communities.gif) repeat-y 478px 0; +} +.communities-inner{ + background: url(../images/bg-communities-top.gif) no-repeat 478px 0; +} +.communities-area{ + padding:40px 0 20px; + min-height:115px; + background: url(../images/bg-communities-bottom.gif) no-repeat 478px 100%; +} +* html .communities-area{ + height:115px; + overflow:visible; +} +.communities-cont{ + width:478px; + float:left; +} +.communities-cont ul{ + margin:0; + padding:20px 0 0; + list-style:none; + width:100%; + overflow:hidden; +} +.communities-cont ul li{ + float:left; + margin:15px 23px 0 0; + display:inline; +} +.communities-cont a img{ + display:block; +} +.communities-side{ + width:344px; + float:right; + font-size:11px; + line-height:12px; +} +.communities-side p{ + margin:12px 0; +} +.communities-side form .hold{ + width:100%; + overflow:hidden; + padding:0 0 7px; +} +.communities-side form .text{ + display:block; + border:0; + margin:0; + width:314px; + padding:8px 15px; + background:#bababa; + color:#434242; + font: 14px/16px Verdana, Tahoma, Arial, sans-serif; +} +.communities-side form .btn{ + float:right; + border:0; + padding:0 0 2px; + margin:0; + width:110px; + height:31px; + color:#fff; + cursor:pointer; + font: 16px/18px Verdana, Tahoma, Arial, sans-serif; + background: url(../images/btn-submit.gif) no-repeat; +} +#main h2, +#main h3{ + font-size:36px; + line-height:36px; + margin:0; + font-weight:normal; + color:#000; +} +#main h3{ + font-size:20px; + line-height:20px; +} +#main .title em{ + font-style:normal; + color:#fc03be; + font-size:14px; +} +#main p{ + margin:16px 0; +} +#service-list{ + padding:20px 0 40px; + margin:0; + list-style:none; +} +#service-list li{ + width:100%; + overflow:hidden; +} +#service-list li:hover, +#service-list li.hover{ + background: url(../images/bg-service-list.gif) repeat-y 100% 0; +} +#service-list li:hover .info-box, +#service-list li.hover .info-box{ + border-top:8px solid #fff; + padding-top:6px; +} +#service-list .number-box{ + width:135px; + float:left; + overflow:hidden; + text-align:right; + font-size:115px; + line-height:96px; + letter-spacing:-5px; + white-space:nowrap; +} +#service-list .info-box{ + width:755px; + float:right; + padding:14px 5px 0; +} +#service-list h3{ + font-weight:normal; + font-size:24px; + line-height:28px; + color:#000; + margin:0; +} +#service-list p{ + margin:0; +} +/*-- footer --*/ +#footer{ + overflow:hidden; + color:#767676; + padding:24px 95px 60px 0; + font-size:12px; + line-height:14px; + letter-spacing:-1px; + margin:13px 0 0; + background: url(../images/bg-footer.gif) no-repeat; +} +.hp #footer{ + background: url(../images/bg-footer-hp.gif) no-repeat; +} +#footer a{ + color:#767676; +} +#footer .inf{ + margin:0; + padding:0; + list-style:none; + display:inline; +} +#footer .inf li{ + display:inline; + padding:0 4px 0 0; + background: url(../images/separator.gif) no-repeat 100% 50%; +} +* html #footer .inf li{ + margin-right:3px; +} +*+html #footer .inf li{ + margin-right:3px; +} +#footer dl, +#footer dt, +#footer dd{ + margin:0; + display:inline; +} +#footer dt{ + font-weight:bold; +} +#footer dd{ + margin:0 4px 0 0; +} +#footer .validate{ + margin:0; + padding:0; + list-style:none; + float:left; +} +#footer .validate li{ + float:left; + margin:0 8px 0 0; +} +#footer .share{ + margin:8px 0 0 17px; + float:left; +} +#footer .ico{ + width:100%; + overflow:hidden; + margin:32px 0 0; +} + +#showOff img +{ + padding: 0 20px 10px 0; +} diff --git a/ShowOff/Controllers/AccountController.cs b/ShowOff/Controllers/AccountController.cs new file mode 100644 index 0000000..d9ba1be --- /dev/null +++ b/ShowOff/Controllers/AccountController.cs @@ -0,0 +1,204 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Security.Principal; +using System.Web; +using System.Web.Mvc; +using System.Web.Routing; +using System.Web.Security; +using ShowOff.Models; + +namespace ShowOff.Controllers +{ + + [HandleError] + public class AccountController : Controller + { + + // This constructor is used by the MVC framework to instantiate the controller using + // the default forms authentication and membership providers. + public AccountController() + : this(null, null) + { + } + + // This constructor is not used by the MVC framework but is instead provided for ease + // of unit testing this type. See the comments in AccountModels.cs for more information. + public AccountController(IFormsAuthenticationService formsService, IMembershipService membershipService) + { + FormsService = formsService ?? new FormsAuthenticationService(); + MembershipService = membershipService ?? new AccountMembershipService(); + } + + public IFormsAuthenticationService FormsService + { + get; + private set; + } + + public IMembershipService MembershipService + { + get; + private set; + } + + protected override void Initialize(RequestContext requestContext) + { + if (requestContext.HttpContext.User.Identity is WindowsIdentity) + { + throw new InvalidOperationException("Windows authentication is not supported."); + } + else + { + base.Initialize(requestContext); + } + } + + protected override void OnActionExecuting(ActionExecutingContext filterContext) + { + ViewData["PasswordLength"] = MembershipService.MinPasswordLength; + + base.OnActionExecuting(filterContext); + } + + [Authorize] + public ActionResult ChangePassword() + { + return View(); + } + + [Authorize] + [HttpPost] + public ActionResult ChangePassword(ChangePasswordModel model) + { + if (ModelState.IsValid) + { + if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword)) + { + return RedirectToAction("ChangePasswordSuccess"); + } + else + { + ModelState.AddModelError("", "The current password is incorrect or the new password is invalid."); + } + } + + // If we got this far, something failed, redisplay form + return View(model); + } + + public ActionResult ChangePasswordSuccess() + { + return View(); + } + + public ActionResult LogOff() + { + FormsService.SignOut(); + + return RedirectToAction("Index", "Home"); + } + + public ActionResult LogOn() + { + return View(); + } + + [HttpPost] + [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", + Justification = "Needs to take same parameter type as Controller.Redirect()")] + public ActionResult LogOn(LogOnModel model, string returnUrl) + { + if (ModelState.IsValid) + { + if (MembershipService.ValidateUser(model.UserName, model.Password)) + { + FormsService.SignIn(model.UserName, model.RememberMe); + if (!String.IsNullOrEmpty(returnUrl)) + { + return Redirect(returnUrl); + } + else + { + return RedirectToAction("Index", "Home"); + } + } + else + { + ModelState.AddModelError("", "The user name or password provided is incorrect."); + } + } + + // If we got this far, something failed, redisplay form + return View(model); + } + + public ActionResult Register() + { + return View(); + } + + [HttpPost] + public ActionResult Register(RegisterModel model) + { + if (ModelState.IsValid) + { + // Attempt to register the user + MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email); + + if (createStatus == MembershipCreateStatus.Success) + { + FormsService.SignIn(model.UserName, false /* createPersistentCookie */); + return RedirectToAction("Index", "Home"); + } + else + { + ModelState.AddModelError("", ErrorCodeToString(createStatus)); + } + } + + // If we got this far, something failed, redisplay form + return View(model); + } + + private static string ErrorCodeToString(MembershipCreateStatus createStatus) + { + // See http://go.microsoft.com/fwlink/?LinkID=177550 for + // a full list of status codes. + switch (createStatus) + { + case MembershipCreateStatus.DuplicateUserName: + return "Username already exists. Please enter a different user name."; + + case MembershipCreateStatus.DuplicateEmail: + return "A username for that e-mail address already exists. Please enter a different e-mail address."; + + case MembershipCreateStatus.InvalidPassword: + return "The password provided is invalid. Please enter a valid password value."; + + case MembershipCreateStatus.InvalidEmail: + return "The e-mail address provided is invalid. Please check the value and try again."; + + case MembershipCreateStatus.InvalidAnswer: + return "The password retrieval answer provided is invalid. Please check the value and try again."; + + case MembershipCreateStatus.InvalidQuestion: + return "The password retrieval question provided is invalid. Please check the value and try again."; + + case MembershipCreateStatus.InvalidUserName: + return "The user name provided is invalid. Please check the value and try again."; + + case MembershipCreateStatus.ProviderError: + return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator."; + + case MembershipCreateStatus.UserRejected: + return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator."; + + default: + return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator."; + } + } + + } +} diff --git a/ShowOff/Controllers/HomeController.cs b/ShowOff/Controllers/HomeController.cs new file mode 100644 index 0000000..bd18b64 --- /dev/null +++ b/ShowOff/Controllers/HomeController.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using System.Web.Mvc; + +namespace ShowOff.Controllers +{ + [HandleError] + public class HomeController : Controller + { + public ActionResult Index() + { + ViewData["Message"] = "Welcome to ASP.NET MVC!"; + + return View(); + } + + public ActionResult About() + { + return View(); + } + } +} diff --git a/ShowOff/Controllers/ItemController.cs b/ShowOff/Controllers/ItemController.cs new file mode 100644 index 0000000..9fbe1c2 --- /dev/null +++ b/ShowOff/Controllers/ItemController.cs @@ -0,0 +1,180 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Web; +using System.Web.Mvc; +using ShowOff.Core.Model; +using ShowOff.Core.Repository; + +namespace ShowOff.Controllers +{ + public class ItemController : Controller + { + private IItemRepository _itemRepository; + private IItemTypeRepository _itemTypeRepository; + private IItemImageRepository _itemImageRepository; + + public ItemController() : this(null, null, null) { } + + public ItemController(IItemRepository itemRepository, IItemTypeRepository itemTypeRepository, ItemImageRepository itemImageRepository) + { + _itemRepository = itemRepository ?? new ItemRepository(); + _itemTypeRepository = itemTypeRepository ?? new ItemTypeRepository(); + _itemImageRepository = itemImageRepository ?? new ItemImageRepository(); + } + + // + // GET: /Item/ + + public ActionResult Index() + { + var items = _itemRepository.GetAll(); + + return View(items); + } + + // + // GET: /Item/Details/5 + + public ActionResult Details(int id) + { + var item = _itemRepository.GetById(id); + + return View(item); + } + + // + // GET: /Item/Create + + public ActionResult Create() + { + var types = _itemTypeRepository.GetAll().OrderBy(x => x.DisplayName); + + ViewData["Types"] = new SelectList(types, "id", "displayname"); + + var item = new Item(); + + return View(item); + } + + // + // POST: /Item/Create + + [HttpPost] + public ActionResult Create(FormCollection collection) + { + var item = new Item(); + + try + { + // bind + TryUpdateModel(item); + + // set the rest + item.Type = _itemTypeRepository.GetById(Convert.ToInt32(collection["Type"])); + item.CreatedDate = DateTime.Now; + item.ModifiedDate = DateTime.Now; + + // save + _itemRepository.Add(item); + _itemRepository.Save(); + + return RedirectToAction("Edit", new {id = item.ID}); + } + catch + { + return View(item); + } + } + + // + // GET: /Item/Edit/5 + + public ActionResult Edit(int id) + { + var item = _itemRepository.GetById(id); + + return View(item); + } + + // + // POST: /Item/Edit/5 + + [HttpPost] + public ActionResult Edit(int id, FormCollection collection) + { + var item = _itemRepository.GetById(id); + try + { + TryUpdateModel(item); + + item.ModifiedDate = DateTime.Now; + + _itemRepository.Update(item); + _itemRepository.Save(); + + return RedirectToAction("Index"); + } + catch + { + return View(item); + } + } + + [HttpPost] + public ActionResult AddImage(int id) + { + if(Request.Files[0] == null) + throw new ApplicationException("No file found."); + + string filePath = _itemImageRepository.SaveImageFile(Request.Files[0].FileName, Request.Files[0].InputStream); + string thumbFilePath = _itemImageRepository.CreateThumb(filePath); + + string fileName = Path.GetFileName(filePath); + string thumbFileName = Path.GetFileName(thumbFilePath); + + var item = _itemRepository.GetById(id); + var itemImage = new ItemImage() {Filename = fileName, ThumbFilename = thumbFileName}; + + item.Images.Add(itemImage); + + if (item.Images.Count == 1) + item.CoverImage = itemImage; + + _itemRepository.Update(item); + _itemRepository.Save(); + + return RedirectToAction("Edit", new { id = id }); + } + + [HttpPost] + public ActionResult SetDefaultImage(int id, int imageID) + { + var item = _itemRepository.GetById(id); + var image = _itemImageRepository.GetById(imageID); + + item.CoverImage = image; + + _itemRepository.Update(item); + _itemRepository.Save(); + + return RedirectToAction("Edit", new { id = id }); + } + + [HttpPost] + public ActionResult DeleteImage(int id, int imageID) + { + var item = _itemRepository.GetById(id); + var image = _itemImageRepository.GetById(imageID); + + if (item.CoverImage.ID == imageID) + throw new ApplicationException("Can not delete Cover Image."); + + _itemImageRepository.Delete(image); + _itemImageRepository.Save(); + + return RedirectToAction("Edit", new { id = id }); + } + } +} diff --git a/ShowOff/Controllers/SetupController.cs b/ShowOff/Controllers/SetupController.cs new file mode 100644 index 0000000..9e9aa87 --- /dev/null +++ b/ShowOff/Controllers/SetupController.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using System.Web.Mvc; +using ShowOff.Core.Data; +using ShowOff.Core.Model; +using ShowOff.Core.Repository; + +namespace ShowOff.Controllers +{ + public class SetupController : Controller + { + // + // GET: /Setup/ + + public ActionResult Index() + { + return View(); + } + + [HttpPost] + [ActionName("Index")] + public string Setup() + { + + SetupHelper.ResetDatabase(); + SetupHelper.AddDefaultData(); + + return "Setup complete"; + } + } +} diff --git a/ShowOff/Controllers/ShowOffController.cs b/ShowOff/Controllers/ShowOffController.cs new file mode 100644 index 0000000..c47e18b --- /dev/null +++ b/ShowOff/Controllers/ShowOffController.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using System.Web.Mvc; +using ShowOff.Core.Repository; + +namespace ShowOff.Controllers +{ + public class ShowOffController : Controller + { + private IItemRepository _itemRepository; + + public ShowOffController() : this(null) { } + + public ShowOffController(IItemRepository itemRepository) + { + _itemRepository = itemRepository ?? new ItemRepository(); + } + + // + // GET: /ShowOff/ + + public ActionResult Index() + { + var items = _itemRepository.GetAll(); + + return View(items); + } + + // + // GET: /ShowOff/Details/5 + + public ActionResult Details(int id) + { + var item = _itemRepository.GetById(id); + + return View(item); + } + } +} diff --git a/ShowOff/Global.asax b/ShowOff/Global.asax new file mode 100644 index 0000000..5621066 --- /dev/null +++ b/ShowOff/Global.asax @@ -0,0 +1 @@ +<%@ Application Codebehind="Global.asax.cs" Inherits="ShowOff.MvcApplication" Language="C#" %> diff --git a/ShowOff/Global.asax.cs b/ShowOff/Global.asax.cs new file mode 100644 index 0000000..4fc54f1 --- /dev/null +++ b/ShowOff/Global.asax.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using System.Web.Mvc; +using System.Web.Routing; + +namespace ShowOff +{ + // Note: For instructions on enabling IIS6 or IIS7 classic mode, + // visit http://go.microsoft.com/?LinkId=9394801 + + public class MvcApplication : System.Web.HttpApplication + { + public static void RegisterRoutes(RouteCollection routes) + { + routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); + + routes.MapRoute( + "Default", // Route name + "{controller}/{action}/{id}", // URL with parameters + new { controller = "ShowOff", action = "Index", id = "" } // Parameter defaults + ); + + } + + protected void Application_Start() + { + AreaRegistration.RegisterAllAreas(); + + RegisterRoutes(RouteTable.Routes); + } + } +} \ No newline at end of file diff --git a/ShowOff/Helpers/AppHelper.cs b/ShowOff/Helpers/AppHelper.cs new file mode 100644 index 0000000..a92c094 --- /dev/null +++ b/ShowOff/Helpers/AppHelper.cs @@ -0,0 +1,86 @@ +using System.Web; +using System.Web.Mvc; + +using ShowOff.Core.Repository; + +namespace ShowOff.Helpers +{ + public static class AppHelper + { + public static string UploadImageUrl(this HtmlHelper helper, string fileName) + { + return VirtualPathUtility.ToAbsolute("~/" + ItemImageRepository.RelativePath + fileName); + } + + public static string ImageUrl(this HtmlHelper helper, string fileName) + { + return VirtualPathUtility.ToAbsolute("~/Content/Images/" + fileName); + } + + /// + /// Normalizes a url in the form ~/path/to/resource.aspx. + /// + /// + /// + /// + public static string ResolveUrl(this HtmlHelper html, string relativeUrl) + { + return VirtualPathUtility.ToAbsolute(relativeUrl); + } + + /// + /// Renders a link tag referencing the stylesheet. Assumes the CSS is in the /content/css directory unless a + /// full relative URL is specified. + /// + /// + /// + /// + public static string Stylesheet(this HtmlHelper html, string cssFile) + { + string cssPath = cssFile.Contains("~") ? cssFile : "~/content/css/" + cssFile; + string url = ResolveUrl(html, cssPath); + return string.Format("\n", url); + } + + /// + /// Renders a link tag referencing the stylesheet. Assumes the CSS is in the /content/css directory unless a + /// full relative URL is specified. Also provides an additional parameter to specify the media + /// that the stylesheet is targeting. + /// + /// + /// + /// + /// + public static string Stylesheet(this HtmlHelper html, string cssFile, string media) + { + string cssPath = cssFile.Contains("~") ? cssFile : "~/content/css/" + cssFile; + string url = ResolveUrl(html, cssPath); + return string.Format("\n", url, media); + } + + /// + /// Renders a script tag referencing the javascript file. Assumes the file is in the /scripts directory + /// unless a full relative URL is specified. + /// + /// + /// + /// + public static string ScriptInclude(this HtmlHelper html, string jsFile) + { + string jsPath = jsFile.Contains("~") ? jsFile : "~/Scripts/" + jsFile; + string url = ResolveUrl(html, jsPath); + return string.Format("\n", url); + } + + /// + /// Renders a favicon link tag. Points to ~/favicon.ico. + /// + /// + /// + public static string Favicon(this HtmlHelper html) + { + string path = ResolveUrl(html, "~/favicon.ico"); + return string.Format("\n", path); + } + } +} \ No newline at end of file diff --git a/ShowOff/Models/AccountModels.cs b/ShowOff/Models/AccountModels.cs new file mode 100644 index 0000000..c3f9aab --- /dev/null +++ b/ShowOff/Models/AccountModels.cs @@ -0,0 +1,266 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using System.Globalization; +using System.Linq; +using System.Web; +using System.Web.Mvc; +using System.Web.Security; + +namespace ShowOff.Models +{ + + #region Services + // The FormsAuthentication type is sealed and contains static members, so it is difficult to + // unit test code that calls its members. The interface and helper class below demonstrate + // how to create an abstract wrapper around such a type in order to make the AccountController + // code unit testable. + + public interface IMembershipService + { + int MinPasswordLength { get; } + + bool ValidateUser(string userName, string password); + MembershipCreateStatus CreateUser(string userName, string password, string email); + bool ChangePassword(string userName, string oldPassword, string newPassword); + } + + public class AccountMembershipService : IMembershipService + { + private readonly MembershipProvider _provider; + + public AccountMembershipService() + : this(null) + { + } + + public AccountMembershipService(MembershipProvider provider) + { + _provider = provider ?? Membership.Provider; + } + + public int MinPasswordLength + { + get + { + return _provider.MinRequiredPasswordLength; + } + } + + public bool ValidateUser(string userName, string password) + { + ValidationUtil.ValidateRequiredStringValue(userName, "userName"); + ValidationUtil.ValidateRequiredStringValue(password, "password"); + + return _provider.ValidateUser(userName, password); + } + + public MembershipCreateStatus CreateUser(string userName, string password, string email) + { + ValidationUtil.ValidateRequiredStringValue(userName, "userName"); + ValidationUtil.ValidateRequiredStringValue(password, "password"); + ValidationUtil.ValidateRequiredStringValue(email, "email"); + + MembershipCreateStatus status; + _provider.CreateUser(userName, password, email, null, null, true, null, out status); + return status; + } + + public bool ChangePassword(string userName, string oldPassword, string newPassword) + { + ValidationUtil.ValidateRequiredStringValue(userName, "userName"); + ValidationUtil.ValidateRequiredStringValue(oldPassword, "oldPassword"); + ValidationUtil.ValidateRequiredStringValue(newPassword, "newPassword"); + + // The underlying ChangePassword() will throw an exception rather + // than return false in certain failure scenarios. + try + { + MembershipUser currentUser = _provider.GetUser(userName, true /* userIsOnline */); + return currentUser.ChangePassword(oldPassword, newPassword); + } + catch (ArgumentException) + { + return false; + } + catch (MembershipPasswordException) + { + return false; + } + } + } + + public interface IFormsAuthenticationService + { + void SignIn(string userName, bool createPersistentCookie); + void SignOut(); + } + + public class FormsAuthenticationService : IFormsAuthenticationService + { + public void SignIn(string userName, bool createPersistentCookie) + { + ValidationUtil.ValidateRequiredStringValue(userName, "userName"); + + FormsAuthentication.SetAuthCookie(userName, createPersistentCookie); + } + + public void SignOut() + { + FormsAuthentication.SignOut(); + } + } + + internal static class ValidationUtil + { + private const string _stringRequiredErrorMessage = "Value cannot be null or empty."; + + public static void ValidateRequiredStringValue(string value, string parameterName) + { + if (String.IsNullOrEmpty(value)) + { + throw new ArgumentException(_stringRequiredErrorMessage, parameterName); + } + } + } + #endregion + + #region Models + [PropertiesMustMatch("NewPassword", "ConfirmPassword", ErrorMessage = "The new password and confirmation password do not match.")] + public class ChangePasswordModel + { + [Required] + [DataType(DataType.Password)] + [DisplayName("Current password")] + public string OldPassword { get; set; } + + [Required] + [ValidatePasswordLength] + [DataType(DataType.Password)] + [DisplayName("New password")] + public string NewPassword { get; set; } + + [Required] + [DataType(DataType.Password)] + [DisplayName("Confirm new password")] + public string ConfirmPassword { get; set; } + } + + public class LogOnModel + { + [Required] + [DisplayName("User name")] + public string UserName { get; set; } + + [Required] + [DataType(DataType.Password)] + [DisplayName("Password")] + public string Password { get; set; } + + [DisplayName("Remember me?")] + public bool RememberMe { get; set; } + } + + [PropertiesMustMatch("Password", "ConfirmPassword", ErrorMessage = "The password and confirmation password do not match.")] + public class RegisterModel + { + [Required] + [DisplayName("User name")] + public string UserName { get; set; } + + [Required] + [DataType(DataType.EmailAddress)] + [DisplayName("Email address")] + public string Email { get; set; } + + [Required] + [ValidatePasswordLength] + [DataType(DataType.Password)] + [DisplayName("Password")] + public string Password { get; set; } + + [Required] + [DataType(DataType.Password)] + [DisplayName("Confirm password")] + public string ConfirmPassword { get; set; } + } + #endregion + + #region Validation + [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)] + public sealed class PropertiesMustMatchAttribute : ValidationAttribute + { + private const string _defaultErrorMessage = "'{0}' and '{1}' do not match."; + + private readonly object _typeId = new object(); + + public PropertiesMustMatchAttribute(string originalProperty, string confirmProperty) + : base(_defaultErrorMessage) + { + OriginalProperty = originalProperty; + ConfirmProperty = confirmProperty; + } + + public string ConfirmProperty + { + get; + private set; + } + + public string OriginalProperty + { + get; + private set; + } + + public override object TypeId + { + get + { + return _typeId; + } + } + + public override string FormatErrorMessage(string name) + { + return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString, + OriginalProperty, ConfirmProperty); + } + + public override bool IsValid(object value) + { + PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value); + object originalValue = properties.Find(OriginalProperty, true /* ignoreCase */).GetValue(value); + object confirmValue = properties.Find(ConfirmProperty, true /* ignoreCase */).GetValue(value); + return Object.Equals(originalValue, confirmValue); + } + } + + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)] + public sealed class ValidatePasswordLengthAttribute : ValidationAttribute + { + private const string _defaultErrorMessage = "'{0}' must be at least {1} characters long."; + + private readonly int _minCharacters = Membership.Provider.MinRequiredPasswordLength; + + public ValidatePasswordLengthAttribute() + : base(_defaultErrorMessage) + { + } + + public override string FormatErrorMessage(string name) + { + return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString, + name, _minCharacters); + } + + public override bool IsValid(object value) + { + string valueAsString = value as string; + return (valueAsString != null && valueAsString.Length >= _minCharacters); + } + } + #endregion + +} diff --git a/ShowOff/Properties/AssemblyInfo.cs b/ShowOff/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..d5ea4ca --- /dev/null +++ b/ShowOff/Properties/AssemblyInfo.cs @@ -0,0 +1,35 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("ShowOff")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("ShowOff")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2009")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("02c177ef-fd88-46e5-9dfc-f117067303b9")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Revision and Build Numbers +// by using the '*' as shown below: +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/ShowOff/Scripts/MicrosoftAjax.debug.js b/ShowOff/Scripts/MicrosoftAjax.debug.js new file mode 100644 index 0000000..7b7de62 --- /dev/null +++ b/ShowOff/Scripts/MicrosoftAjax.debug.js @@ -0,0 +1,6850 @@ +// Name: MicrosoftAjax.debug.js +// Assembly: System.Web.Extensions +// Version: 3.5.0.0 +// FileVersion: 3.5.30729.1 +//----------------------------------------------------------------------- +// Copyright (C) Microsoft Corporation. All rights reserved. +//----------------------------------------------------------------------- +// MicrosoftAjax.js +// Microsoft AJAX Framework. + +Function.__typeName = 'Function'; +Function.__class = true; +Function.createCallback = function Function$createCallback(method, context) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "method", type: Function}, + {name: "context", mayBeNull: true} + ]); + if (e) throw e; + return function() { + var l = arguments.length; + if (l > 0) { + var args = []; + for (var i = 0; i < l; i++) { + args[i] = arguments[i]; + } + args[l] = context; + return method.apply(this, args); + } + return method.call(this, context); + } +} +Function.createDelegate = function Function$createDelegate(instance, method) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "instance", mayBeNull: true}, + {name: "method", type: Function} + ]); + if (e) throw e; + return function() { + return method.apply(instance, arguments); + } +} +Function.emptyFunction = Function.emptyMethod = function Function$emptyMethod() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); +} +Function._validateParams = function Function$_validateParams(params, expectedParams) { + var e; + e = Function._validateParameterCount(params, expectedParams); + if (e) { + e.popStackFrame(); + return e; + } + for (var i=0; i < params.length; i++) { + var expectedParam = expectedParams[Math.min(i, expectedParams.length - 1)]; + var paramName = expectedParam.name; + if (expectedParam.parameterArray) { + paramName += "[" + (i - expectedParams.length + 1) + "]"; + } + e = Function._validateParameter(params[i], expectedParam, paramName); + if (e) { + e.popStackFrame(); + return e; + } + } + return null; +} +Function._validateParameterCount = function Function$_validateParameterCount(params, expectedParams) { + var maxParams = expectedParams.length; + var minParams = 0; + for (var i=0; i < expectedParams.length; i++) { + if (expectedParams[i].parameterArray) { + maxParams = Number.MAX_VALUE; + } + else if (!expectedParams[i].optional) { + minParams++; + } + } + if (params.length < minParams || params.length > maxParams) { + var e = Error.parameterCount(); + e.popStackFrame(); + return e; + } + return null; +} +Function._validateParameter = function Function$_validateParameter(param, expectedParam, paramName) { + var e; + var expectedType = expectedParam.type; + var expectedInteger = !!expectedParam.integer; + var expectedDomElement = !!expectedParam.domElement; + var mayBeNull = !!expectedParam.mayBeNull; + e = Function._validateParameterType(param, expectedType, expectedInteger, expectedDomElement, mayBeNull, paramName); + if (e) { + e.popStackFrame(); + return e; + } + var expectedElementType = expectedParam.elementType; + var elementMayBeNull = !!expectedParam.elementMayBeNull; + if (expectedType === Array && typeof(param) !== "undefined" && param !== null && + (expectedElementType || !elementMayBeNull)) { + var expectedElementInteger = !!expectedParam.elementInteger; + var expectedElementDomElement = !!expectedParam.elementDomElement; + for (var i=0; i < param.length; i++) { + var elem = param[i]; + e = Function._validateParameterType(elem, expectedElementType, + expectedElementInteger, expectedElementDomElement, elementMayBeNull, + paramName + "[" + i + "]"); + if (e) { + e.popStackFrame(); + return e; + } + } + } + return null; +} +Function._validateParameterType = function Function$_validateParameterType(param, expectedType, expectedInteger, expectedDomElement, mayBeNull, paramName) { + var e; + if (typeof(param) === "undefined") { + if (mayBeNull) { + return null; + } + else { + e = Error.argumentUndefined(paramName); + e.popStackFrame(); + return e; + } + } + if (param === null) { + if (mayBeNull) { + return null; + } + else { + e = Error.argumentNull(paramName); + e.popStackFrame(); + return e; + } + } + if (expectedType && expectedType.__enum) { + if (typeof(param) !== 'number') { + e = Error.argumentType(paramName, Object.getType(param), expectedType); + e.popStackFrame(); + return e; + } + if ((param % 1) === 0) { + var values = expectedType.prototype; + if (!expectedType.__flags || (param === 0)) { + for (var i in values) { + if (values[i] === param) return null; + } + } + else { + var v = param; + for (var i in values) { + var vali = values[i]; + if (vali === 0) continue; + if ((vali & param) === vali) { + v -= vali; + } + if (v === 0) return null; + } + } + } + e = Error.argumentOutOfRange(paramName, param, String.format(Sys.Res.enumInvalidValue, param, expectedType.getName())); + e.popStackFrame(); + return e; + } + if (expectedDomElement) { + var val; + if (typeof(param.nodeType) !== 'number') { + var doc = param.ownerDocument || param.document || param; + if (doc != param) { + var w = doc.defaultView || doc.parentWindow; + val = (w != param) && !(w.document && param.document && (w.document === param.document)); + } + else { + val = (typeof(doc.body) === 'undefined'); + } + } + else { + val = (param.nodeType === 3); + } + if (val) { + e = Error.argument(paramName, Sys.Res.argumentDomElement); + e.popStackFrame(); + return e; + } + } + if (expectedType && !expectedType.isInstanceOfType(param)) { + e = Error.argumentType(paramName, Object.getType(param), expectedType); + e.popStackFrame(); + return e; + } + if (expectedType === Number && expectedInteger) { + if ((param % 1) !== 0) { + e = Error.argumentOutOfRange(paramName, param, Sys.Res.argumentInteger); + e.popStackFrame(); + return e; + } + } + return null; +} + +Error.__typeName = 'Error'; +Error.__class = true; +Error.create = function Error$create(message, errorInfo) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "message", type: String, mayBeNull: true, optional: true}, + {name: "errorInfo", mayBeNull: true, optional: true} + ]); + if (e) throw e; + var e = new Error(message); + e.message = message; + if (errorInfo) { + for (var v in errorInfo) { + e[v] = errorInfo[v]; + } + } + e.popStackFrame(); + return e; +} +Error.argument = function Error$argument(paramName, message) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "paramName", type: String, mayBeNull: true, optional: true}, + {name: "message", type: String, mayBeNull: true, optional: true} + ]); + if (e) throw e; + var displayMessage = "Sys.ArgumentException: " + (message ? message : Sys.Res.argument); + if (paramName) { + displayMessage += "\n" + String.format(Sys.Res.paramName, paramName); + } + var e = Error.create(displayMessage, { name: "Sys.ArgumentException", paramName: paramName }); + e.popStackFrame(); + return e; +} +Error.argumentNull = function Error$argumentNull(paramName, message) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "paramName", type: String, mayBeNull: true, optional: true}, + {name: "message", type: String, mayBeNull: true, optional: true} + ]); + if (e) throw e; + var displayMessage = "Sys.ArgumentNullException: " + (message ? message : Sys.Res.argumentNull); + if (paramName) { + displayMessage += "\n" + String.format(Sys.Res.paramName, paramName); + } + var e = Error.create(displayMessage, { name: "Sys.ArgumentNullException", paramName: paramName }); + e.popStackFrame(); + return e; +} +Error.argumentOutOfRange = function Error$argumentOutOfRange(paramName, actualValue, message) { + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "paramName", type: String, mayBeNull: true, optional: true}, + {name: "actualValue", mayBeNull: true, optional: true}, + {name: "message", type: String, mayBeNull: true, optional: true} + ]); + if (e) throw e; + var displayMessage = "Sys.ArgumentOutOfRangeException: " + (message ? message : Sys.Res.argumentOutOfRange); + if (paramName) { + displayMessage += "\n" + String.format(Sys.Res.paramName, paramName); + } + if (typeof(actualValue) !== "undefined" && actualValue !== null) { + displayMessage += "\n" + String.format(Sys.Res.actualValue, actualValue); + } + var e = Error.create(displayMessage, { + name: "Sys.ArgumentOutOfRangeException", + paramName: paramName, + actualValue: actualValue + }); + e.popStackFrame(); + return e; +} +Error.argumentType = function Error$argumentType(paramName, actualType, expectedType, message) { + /// + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "paramName", type: String, mayBeNull: true, optional: true}, + {name: "actualType", type: Type, mayBeNull: true, optional: true}, + {name: "expectedType", type: Type, mayBeNull: true, optional: true}, + {name: "message", type: String, mayBeNull: true, optional: true} + ]); + if (e) throw e; + var displayMessage = "Sys.ArgumentTypeException: "; + if (message) { + displayMessage += message; + } + else if (actualType && expectedType) { + displayMessage += + String.format(Sys.Res.argumentTypeWithTypes, actualType.getName(), expectedType.getName()); + } + else { + displayMessage += Sys.Res.argumentType; + } + if (paramName) { + displayMessage += "\n" + String.format(Sys.Res.paramName, paramName); + } + var e = Error.create(displayMessage, { + name: "Sys.ArgumentTypeException", + paramName: paramName, + actualType: actualType, + expectedType: expectedType + }); + e.popStackFrame(); + return e; +} +Error.argumentUndefined = function Error$argumentUndefined(paramName, message) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "paramName", type: String, mayBeNull: true, optional: true}, + {name: "message", type: String, mayBeNull: true, optional: true} + ]); + if (e) throw e; + var displayMessage = "Sys.ArgumentUndefinedException: " + (message ? message : Sys.Res.argumentUndefined); + if (paramName) { + displayMessage += "\n" + String.format(Sys.Res.paramName, paramName); + } + var e = Error.create(displayMessage, { name: "Sys.ArgumentUndefinedException", paramName: paramName }); + e.popStackFrame(); + return e; +} +Error.format = function Error$format(message) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "message", type: String, mayBeNull: true, optional: true} + ]); + if (e) throw e; + var displayMessage = "Sys.FormatException: " + (message ? message : Sys.Res.format); + var e = Error.create(displayMessage, {name: 'Sys.FormatException'}); + e.popStackFrame(); + return e; +} +Error.invalidOperation = function Error$invalidOperation(message) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "message", type: String, mayBeNull: true, optional: true} + ]); + if (e) throw e; + var displayMessage = "Sys.InvalidOperationException: " + (message ? message : Sys.Res.invalidOperation); + var e = Error.create(displayMessage, {name: 'Sys.InvalidOperationException'}); + e.popStackFrame(); + return e; +} +Error.notImplemented = function Error$notImplemented(message) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "message", type: String, mayBeNull: true, optional: true} + ]); + if (e) throw e; + var displayMessage = "Sys.NotImplementedException: " + (message ? message : Sys.Res.notImplemented); + var e = Error.create(displayMessage, {name: 'Sys.NotImplementedException'}); + e.popStackFrame(); + return e; +} +Error.parameterCount = function Error$parameterCount(message) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "message", type: String, mayBeNull: true, optional: true} + ]); + if (e) throw e; + var displayMessage = "Sys.ParameterCountException: " + (message ? message : Sys.Res.parameterCount); + var e = Error.create(displayMessage, {name: 'Sys.ParameterCountException'}); + e.popStackFrame(); + return e; +} +Error.prototype.popStackFrame = function Error$popStackFrame() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (typeof(this.stack) === "undefined" || this.stack === null || + typeof(this.fileName) === "undefined" || this.fileName === null || + typeof(this.lineNumber) === "undefined" || this.lineNumber === null) { + return; + } + var stackFrames = this.stack.split("\n"); + var currentFrame = stackFrames[0]; + var pattern = this.fileName + ":" + this.lineNumber; + while(typeof(currentFrame) !== "undefined" && + currentFrame !== null && + currentFrame.indexOf(pattern) === -1) { + stackFrames.shift(); + currentFrame = stackFrames[0]; + } + var nextFrame = stackFrames[1]; + if (typeof(nextFrame) === "undefined" || nextFrame === null) { + return; + } + var nextFrameParts = nextFrame.match(/@(.*):(\d+)$/); + if (typeof(nextFrameParts) === "undefined" || nextFrameParts === null) { + return; + } + this.fileName = nextFrameParts[1]; + this.lineNumber = parseInt(nextFrameParts[2]); + stackFrames.shift(); + this.stack = stackFrames.join("\n"); +} + +Object.__typeName = 'Object'; +Object.__class = true; +Object.getType = function Object$getType(instance) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "instance"} + ]); + if (e) throw e; + var ctor = instance.constructor; + if (!ctor || (typeof(ctor) !== "function") || !ctor.__typeName || (ctor.__typeName === 'Object')) { + return Object; + } + return ctor; +} +Object.getTypeName = function Object$getTypeName(instance) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "instance"} + ]); + if (e) throw e; + return Object.getType(instance).getName(); +} + +String.__typeName = 'String'; +String.__class = true; +String.prototype.endsWith = function String$endsWith(suffix) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "suffix", type: String} + ]); + if (e) throw e; + return (this.substr(this.length - suffix.length) === suffix); +} +String.prototype.startsWith = function String$startsWith(prefix) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "prefix", type: String} + ]); + if (e) throw e; + return (this.substr(0, prefix.length) === prefix); +} +String.prototype.trim = function String$trim() { + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this.replace(/^\s+|\s+$/g, ''); +} +String.prototype.trimEnd = function String$trimEnd() { + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this.replace(/\s+$/, ''); +} +String.prototype.trimStart = function String$trimStart() { + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this.replace(/^\s+/, ''); +} +String.format = function String$format(format, args) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "format", type: String}, + {name: "args", mayBeNull: true, parameterArray: true} + ]); + if (e) throw e; + return String._toFormattedString(false, arguments); +} +String.localeFormat = function String$localeFormat(format, args) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "format", type: String}, + {name: "args", mayBeNull: true, parameterArray: true} + ]); + if (e) throw e; + return String._toFormattedString(true, arguments); +} +String._toFormattedString = function String$_toFormattedString(useLocale, args) { + var result = ''; + var format = args[0]; + for (var i=0;;) { + var open = format.indexOf('{', i); + var close = format.indexOf('}', i); + if ((open < 0) && (close < 0)) { + result += format.slice(i); + break; + } + if ((close > 0) && ((close < open) || (open < 0))) { + if (format.charAt(close + 1) !== '}') { + throw Error.argument('format', Sys.Res.stringFormatBraceMismatch); + } + result += format.slice(i, close + 1); + i = close + 2; + continue; + } + result += format.slice(i, open); + i = open + 1; + if (format.charAt(i) === '{') { + result += '{'; + i++; + continue; + } + if (close < 0) throw Error.argument('format', Sys.Res.stringFormatBraceMismatch); + var brace = format.substring(i, close); + var colonIndex = brace.indexOf(':'); + var argNumber = parseInt((colonIndex < 0)? brace : brace.substring(0, colonIndex), 10) + 1; + if (isNaN(argNumber)) throw Error.argument('format', Sys.Res.stringFormatInvalid); + var argFormat = (colonIndex < 0)? '' : brace.substring(colonIndex + 1); + var arg = args[argNumber]; + if (typeof(arg) === "undefined" || arg === null) { + arg = ''; + } + if (arg.toFormattedString) { + result += arg.toFormattedString(argFormat); + } + else if (useLocale && arg.localeFormat) { + result += arg.localeFormat(argFormat); + } + else if (arg.format) { + result += arg.format(argFormat); + } + else + result += arg.toString(); + i = close + 1; + } + return result; +} + +Boolean.__typeName = 'Boolean'; +Boolean.__class = true; +Boolean.parse = function Boolean$parse(value) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "value", type: String} + ]); + if (e) throw e; + var v = value.trim().toLowerCase(); + if (v === 'false') return false; + if (v === 'true') return true; + throw Error.argumentOutOfRange('value', value, Sys.Res.boolTrueOrFalse); +} + +Date.__typeName = 'Date'; +Date.__class = true; +Date._appendPreOrPostMatch = function Date$_appendPreOrPostMatch(preMatch, strBuilder) { + var quoteCount = 0; + var escaped = false; + for (var i = 0, il = preMatch.length; i < il; i++) { + var c = preMatch.charAt(i); + switch (c) { + case '\'': + if (escaped) strBuilder.append("'"); + else quoteCount++; + escaped = false; + break; + case '\\': + if (escaped) strBuilder.append("\\"); + escaped = !escaped; + break; + default: + strBuilder.append(c); + escaped = false; + break; + } + } + return quoteCount; +} +Date._expandFormat = function Date$_expandFormat(dtf, format) { + if (!format) { + format = "F"; + } + if (format.length === 1) { + switch (format) { + case "d": + return dtf.ShortDatePattern; + case "D": + return dtf.LongDatePattern; + case "t": + return dtf.ShortTimePattern; + case "T": + return dtf.LongTimePattern; + case "F": + return dtf.FullDateTimePattern; + case "M": case "m": + return dtf.MonthDayPattern; + case "s": + return dtf.SortableDateTimePattern; + case "Y": case "y": + return dtf.YearMonthPattern; + default: + throw Error.format(Sys.Res.formatInvalidString); + } + } + return format; +} +Date._expandYear = function Date$_expandYear(dtf, year) { + if (year < 100) { + var curr = new Date().getFullYear(); + year += curr - (curr % 100); + if (year > dtf.Calendar.TwoDigitYearMax) { + return year - 100; + } + } + return year; +} +Date._getParseRegExp = function Date$_getParseRegExp(dtf, format) { + if (!dtf._parseRegExp) { + dtf._parseRegExp = {}; + } + else if (dtf._parseRegExp[format]) { + return dtf._parseRegExp[format]; + } + var expFormat = Date._expandFormat(dtf, format); + expFormat = expFormat.replace(/([\^\$\.\*\+\?\|\[\]\(\)\{\}])/g, "\\\\$1"); + var regexp = new Sys.StringBuilder("^"); + var groups = []; + var index = 0; + var quoteCount = 0; + var tokenRegExp = Date._getTokenRegExp(); + var match; + while ((match = tokenRegExp.exec(expFormat)) !== null) { + var preMatch = expFormat.slice(index, match.index); + index = tokenRegExp.lastIndex; + quoteCount += Date._appendPreOrPostMatch(preMatch, regexp); + if ((quoteCount%2) === 1) { + regexp.append(match[0]); + continue; + } + switch (match[0]) { + case 'dddd': case 'ddd': + case 'MMMM': case 'MMM': + regexp.append("(\\D+)"); + break; + case 'tt': case 't': + regexp.append("(\\D*)"); + break; + case 'yyyy': + regexp.append("(\\d{4})"); + break; + case 'fff': + regexp.append("(\\d{3})"); + break; + case 'ff': + regexp.append("(\\d{2})"); + break; + case 'f': + regexp.append("(\\d)"); + break; + case 'dd': case 'd': + case 'MM': case 'M': + case 'yy': case 'y': + case 'HH': case 'H': + case 'hh': case 'h': + case 'mm': case 'm': + case 'ss': case 's': + regexp.append("(\\d\\d?)"); + break; + case 'zzz': + regexp.append("([+-]?\\d\\d?:\\d{2})"); + break; + case 'zz': case 'z': + regexp.append("([+-]?\\d\\d?)"); + break; + } + Array.add(groups, match[0]); + } + Date._appendPreOrPostMatch(expFormat.slice(index), regexp); + regexp.append("$"); + var regexpStr = regexp.toString().replace(/\s+/g, "\\s+"); + var parseRegExp = {'regExp': regexpStr, 'groups': groups}; + dtf._parseRegExp[format] = parseRegExp; + return parseRegExp; +} +Date._getTokenRegExp = function Date$_getTokenRegExp() { + return /dddd|ddd|dd|d|MMMM|MMM|MM|M|yyyy|yy|y|hh|h|HH|H|mm|m|ss|s|tt|t|fff|ff|f|zzz|zz|z/g; +} +Date.parseLocale = function Date$parseLocale(value, formats) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "value", type: String}, + {name: "formats", mayBeNull: true, optional: true, parameterArray: true} + ]); + if (e) throw e; + return Date._parse(value, Sys.CultureInfo.CurrentCulture, arguments); +} +Date.parseInvariant = function Date$parseInvariant(value, formats) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "value", type: String}, + {name: "formats", mayBeNull: true, optional: true, parameterArray: true} + ]); + if (e) throw e; + return Date._parse(value, Sys.CultureInfo.InvariantCulture, arguments); +} +Date._parse = function Date$_parse(value, cultureInfo, args) { + var custom = false; + for (var i = 1, il = args.length; i < il; i++) { + var format = args[i]; + if (format) { + custom = true; + var date = Date._parseExact(value, format, cultureInfo); + if (date) return date; + } + } + if (! custom) { + var formats = cultureInfo._getDateTimeFormats(); + for (var i = 0, il = formats.length; i < il; i++) { + var date = Date._parseExact(value, formats[i], cultureInfo); + if (date) return date; + } + } + return null; +} +Date._parseExact = function Date$_parseExact(value, format, cultureInfo) { + value = value.trim(); + var dtf = cultureInfo.dateTimeFormat; + var parseInfo = Date._getParseRegExp(dtf, format); + var match = new RegExp(parseInfo.regExp).exec(value); + if (match === null) return null; + + var groups = parseInfo.groups; + var year = null, month = null, date = null, weekDay = null; + var hour = 0, min = 0, sec = 0, msec = 0, tzMinOffset = null; + var pmHour = false; + for (var j = 0, jl = groups.length; j < jl; j++) { + var matchGroup = match[j+1]; + if (matchGroup) { + switch (groups[j]) { + case 'dd': case 'd': + date = parseInt(matchGroup, 10); + if ((date < 1) || (date > 31)) return null; + break; + case 'MMMM': + month = cultureInfo._getMonthIndex(matchGroup); + if ((month < 0) || (month > 11)) return null; + break; + case 'MMM': + month = cultureInfo._getAbbrMonthIndex(matchGroup); + if ((month < 0) || (month > 11)) return null; + break; + case 'M': case 'MM': + var month = parseInt(matchGroup, 10) - 1; + if ((month < 0) || (month > 11)) return null; + break; + case 'y': case 'yy': + year = Date._expandYear(dtf,parseInt(matchGroup, 10)); + if ((year < 0) || (year > 9999)) return null; + break; + case 'yyyy': + year = parseInt(matchGroup, 10); + if ((year < 0) || (year > 9999)) return null; + break; + case 'h': case 'hh': + hour = parseInt(matchGroup, 10); + if (hour === 12) hour = 0; + if ((hour < 0) || (hour > 11)) return null; + break; + case 'H': case 'HH': + hour = parseInt(matchGroup, 10); + if ((hour < 0) || (hour > 23)) return null; + break; + case 'm': case 'mm': + min = parseInt(matchGroup, 10); + if ((min < 0) || (min > 59)) return null; + break; + case 's': case 'ss': + sec = parseInt(matchGroup, 10); + if ((sec < 0) || (sec > 59)) return null; + break; + case 'tt': case 't': + var upperToken = matchGroup.toUpperCase(); + pmHour = (upperToken === dtf.PMDesignator.toUpperCase()); + if (!pmHour && (upperToken !== dtf.AMDesignator.toUpperCase())) return null; + break; + case 'f': + msec = parseInt(matchGroup, 10) * 100; + if ((msec < 0) || (msec > 999)) return null; + break; + case 'ff': + msec = parseInt(matchGroup, 10) * 10; + if ((msec < 0) || (msec > 999)) return null; + break; + case 'fff': + msec = parseInt(matchGroup, 10); + if ((msec < 0) || (msec > 999)) return null; + break; + case 'dddd': + weekDay = cultureInfo._getDayIndex(matchGroup); + if ((weekDay < 0) || (weekDay > 6)) return null; + break; + case 'ddd': + weekDay = cultureInfo._getAbbrDayIndex(matchGroup); + if ((weekDay < 0) || (weekDay > 6)) return null; + break; + case 'zzz': + var offsets = matchGroup.split(/:/); + if (offsets.length !== 2) return null; + var hourOffset = parseInt(offsets[0], 10); + if ((hourOffset < -12) || (hourOffset > 13)) return null; + var minOffset = parseInt(offsets[1], 10); + if ((minOffset < 0) || (minOffset > 59)) return null; + tzMinOffset = (hourOffset * 60) + (matchGroup.startsWith('-')? -minOffset : minOffset); + break; + case 'z': case 'zz': + var hourOffset = parseInt(matchGroup, 10); + if ((hourOffset < -12) || (hourOffset > 13)) return null; + tzMinOffset = hourOffset * 60; + break; + } + } + } + var result = new Date(); + if (year === null) { + year = result.getFullYear(); + } + if (month === null) { + month = result.getMonth(); + } + if (date === null) { + date = result.getDate(); + } + result.setFullYear(year, month, date); + if (result.getDate() !== date) return null; + if ((weekDay !== null) && (result.getDay() !== weekDay)) { + return null; + } + if (pmHour && (hour < 12)) { + hour += 12; + } + result.setHours(hour, min, sec, msec); + if (tzMinOffset !== null) { + var adjustedMin = result.getMinutes() - (tzMinOffset + result.getTimezoneOffset()); + result.setHours(result.getHours() + parseInt(adjustedMin/60, 10), adjustedMin%60); + } + return result; +} +Date.prototype.format = function Date$format(format) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "format", type: String} + ]); + if (e) throw e; + return this._toFormattedString(format, Sys.CultureInfo.InvariantCulture); +} +Date.prototype.localeFormat = function Date$localeFormat(format) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "format", type: String} + ]); + if (e) throw e; + return this._toFormattedString(format, Sys.CultureInfo.CurrentCulture); +} +Date.prototype._toFormattedString = function Date$_toFormattedString(format, cultureInfo) { + if (!format || (format.length === 0) || (format === 'i')) { + if (cultureInfo && (cultureInfo.name.length > 0)) { + return this.toLocaleString(); + } + else { + return this.toString(); + } + } + var dtf = cultureInfo.dateTimeFormat; + format = Date._expandFormat(dtf, format); + var ret = new Sys.StringBuilder(); + var hour; + function addLeadingZero(num) { + if (num < 10) { + return '0' + num; + } + return num.toString(); + } + function addLeadingZeros(num) { + if (num < 10) { + return '00' + num; + } + if (num < 100) { + return '0' + num; + } + return num.toString(); + } + var quoteCount = 0; + var tokenRegExp = Date._getTokenRegExp(); + for (;;) { + var index = tokenRegExp.lastIndex; + var ar = tokenRegExp.exec(format); + var preMatch = format.slice(index, ar ? ar.index : format.length); + quoteCount += Date._appendPreOrPostMatch(preMatch, ret); + if (!ar) break; + if ((quoteCount%2) === 1) { + ret.append(ar[0]); + continue; + } + switch (ar[0]) { + case "dddd": + ret.append(dtf.DayNames[this.getDay()]); + break; + case "ddd": + ret.append(dtf.AbbreviatedDayNames[this.getDay()]); + break; + case "dd": + ret.append(addLeadingZero(this.getDate())); + break; + case "d": + ret.append(this.getDate()); + break; + case "MMMM": + ret.append(dtf.MonthNames[this.getMonth()]); + break; + case "MMM": + ret.append(dtf.AbbreviatedMonthNames[this.getMonth()]); + break; + case "MM": + ret.append(addLeadingZero(this.getMonth() + 1)); + break; + case "M": + ret.append(this.getMonth() + 1); + break; + case "yyyy": + ret.append(this.getFullYear()); + break; + case "yy": + ret.append(addLeadingZero(this.getFullYear() % 100)); + break; + case "y": + ret.append(this.getFullYear() % 100); + break; + case "hh": + hour = this.getHours() % 12; + if (hour === 0) hour = 12; + ret.append(addLeadingZero(hour)); + break; + case "h": + hour = this.getHours() % 12; + if (hour === 0) hour = 12; + ret.append(hour); + break; + case "HH": + ret.append(addLeadingZero(this.getHours())); + break; + case "H": + ret.append(this.getHours()); + break; + case "mm": + ret.append(addLeadingZero(this.getMinutes())); + break; + case "m": + ret.append(this.getMinutes()); + break; + case "ss": + ret.append(addLeadingZero(this.getSeconds())); + break; + case "s": + ret.append(this.getSeconds()); + break; + case "tt": + ret.append((this.getHours() < 12) ? dtf.AMDesignator : dtf.PMDesignator); + break; + case "t": + ret.append(((this.getHours() < 12) ? dtf.AMDesignator : dtf.PMDesignator).charAt(0)); + break; + case "f": + ret.append(addLeadingZeros(this.getMilliseconds()).charAt(0)); + break; + case "ff": + ret.append(addLeadingZeros(this.getMilliseconds()).substr(0, 2)); + break; + case "fff": + ret.append(addLeadingZeros(this.getMilliseconds())); + break; + case "z": + hour = this.getTimezoneOffset() / 60; + ret.append(((hour <= 0) ? '+' : '-') + Math.floor(Math.abs(hour))); + break; + case "zz": + hour = this.getTimezoneOffset() / 60; + ret.append(((hour <= 0) ? '+' : '-') + addLeadingZero(Math.floor(Math.abs(hour)))); + break; + case "zzz": + hour = this.getTimezoneOffset() / 60; + ret.append(((hour <= 0) ? '+' : '-') + addLeadingZero(Math.floor(Math.abs(hour))) + + dtf.TimeSeparator + addLeadingZero(Math.abs(this.getTimezoneOffset() % 60))); + break; + } + } + return ret.toString(); +} + +Number.__typeName = 'Number'; +Number.__class = true; +Number.parseLocale = function Number$parseLocale(value) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "value", type: String} + ]); + if (e) throw e; + return Number._parse(value, Sys.CultureInfo.CurrentCulture); +} +Number.parseInvariant = function Number$parseInvariant(value) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "value", type: String} + ]); + if (e) throw e; + return Number._parse(value, Sys.CultureInfo.InvariantCulture); +} +Number._parse = function Number$_parse(value, cultureInfo) { + value = value.trim(); + + if (value.match(/^[+-]?infinity$/i)) { + return parseFloat(value); + } + if (value.match(/^0x[a-f0-9]+$/i)) { + return parseInt(value); + } + var numFormat = cultureInfo.numberFormat; + var signInfo = Number._parseNumberNegativePattern(value, numFormat, numFormat.NumberNegativePattern); + var sign = signInfo[0]; + var num = signInfo[1]; + + if ((sign === '') && (numFormat.NumberNegativePattern !== 1)) { + signInfo = Number._parseNumberNegativePattern(value, numFormat, 1); + sign = signInfo[0]; + num = signInfo[1]; + } + if (sign === '') sign = '+'; + + var exponent; + var intAndFraction; + var exponentPos = num.indexOf('e'); + if (exponentPos < 0) exponentPos = num.indexOf('E'); + if (exponentPos < 0) { + intAndFraction = num; + exponent = null; + } + else { + intAndFraction = num.substr(0, exponentPos); + exponent = num.substr(exponentPos + 1); + } + + var integer; + var fraction; + var decimalPos = intAndFraction.indexOf(numFormat.NumberDecimalSeparator); + if (decimalPos < 0) { + integer = intAndFraction; + fraction = null; + } + else { + integer = intAndFraction.substr(0, decimalPos); + fraction = intAndFraction.substr(decimalPos + numFormat.NumberDecimalSeparator.length); + } + + integer = integer.split(numFormat.NumberGroupSeparator).join(''); + var altNumGroupSeparator = numFormat.NumberGroupSeparator.replace(/\u00A0/g, " "); + if (numFormat.NumberGroupSeparator !== altNumGroupSeparator) { + integer = integer.split(altNumGroupSeparator).join(''); + } + + var p = sign + integer; + if (fraction !== null) { + p += '.' + fraction; + } + if (exponent !== null) { + var expSignInfo = Number._parseNumberNegativePattern(exponent, numFormat, 1); + if (expSignInfo[0] === '') { + expSignInfo[0] = '+'; + } + p += 'e' + expSignInfo[0] + expSignInfo[1]; + } + if (p.match(/^[+-]?\d*\.?\d*(e[+-]?\d+)?$/)) { + return parseFloat(p); + } + return Number.NaN; +} +Number._parseNumberNegativePattern = function Number$_parseNumberNegativePattern(value, numFormat, numberNegativePattern) { + var neg = numFormat.NegativeSign; + var pos = numFormat.PositiveSign; + switch (numberNegativePattern) { + case 4: + neg = ' ' + neg; + pos = ' ' + pos; + case 3: + if (value.endsWith(neg)) { + return ['-', value.substr(0, value.length - neg.length)]; + } + else if (value.endsWith(pos)) { + return ['+', value.substr(0, value.length - pos.length)]; + } + break; + case 2: + neg += ' '; + pos += ' '; + case 1: + if (value.startsWith(neg)) { + return ['-', value.substr(neg.length)]; + } + else if (value.startsWith(pos)) { + return ['+', value.substr(pos.length)]; + } + break; + case 0: + if (value.startsWith('(') && value.endsWith(')')) { + return ['-', value.substr(1, value.length - 2)]; + } + break; + } + return ['', value]; +} +Number.prototype.format = function Number$format(format) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "format", type: String} + ]); + if (e) throw e; + return this._toFormattedString(format, Sys.CultureInfo.InvariantCulture); +} +Number.prototype.localeFormat = function Number$localeFormat(format) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "format", type: String} + ]); + if (e) throw e; + return this._toFormattedString(format, Sys.CultureInfo.CurrentCulture); +} +Number.prototype._toFormattedString = function Number$_toFormattedString(format, cultureInfo) { + if (!format || (format.length === 0) || (format === 'i')) { + if (cultureInfo && (cultureInfo.name.length > 0)) { + return this.toLocaleString(); + } + else { + return this.toString(); + } + } + + var _percentPositivePattern = ["n %", "n%", "%n" ]; + var _percentNegativePattern = ["-n %", "-n%", "-%n"]; + var _numberNegativePattern = ["(n)","-n","- n","n-","n -"]; + var _currencyPositivePattern = ["$n","n$","$ n","n $"]; + var _currencyNegativePattern = ["($n)","-$n","$-n","$n-","(n$)","-n$","n-$","n$-","-n $","-$ n","n $-","$ n-","$ -n","n- $","($ n)","(n $)"]; + function zeroPad(str, count, left) { + for (var l=str.length; l < count; l++) { + str = (left ? ('0' + str) : (str + '0')); + } + return str; + } + + function expandNumber(number, precision, groupSizes, sep, decimalChar) { + + var curSize = groupSizes[0]; + var curGroupIndex = 1; + var factor = Math.pow(10, precision); + var rounded = (Math.round(number * factor) / factor); + if (!isFinite(rounded)) { + rounded = number; + } + number = rounded; + + var numberString = number.toString(); + var right = ""; + var exponent; + + + var split = numberString.split(/e/i); + numberString = split[0]; + exponent = (split.length > 1 ? parseInt(split[1]) : 0); + split = numberString.split('.'); + numberString = split[0]; + right = split.length > 1 ? split[1] : ""; + + var l; + if (exponent > 0) { + right = zeroPad(right, exponent, false); + numberString += right.slice(0, exponent); + right = right.substr(exponent); + } + else if (exponent < 0) { + exponent = -exponent; + numberString = zeroPad(numberString, exponent+1, true); + right = numberString.slice(-exponent, numberString.length) + right; + numberString = numberString.slice(0, -exponent); + } + if (precision > 0) { + if (right.length > precision) { + right = right.slice(0, precision); + } + else { + right = zeroPad(right, precision, false); + } + right = decimalChar + right; + } + else { + right = ""; + } + var stringIndex = numberString.length-1; + var ret = ""; + while (stringIndex >= 0) { + if (curSize === 0 || curSize > stringIndex) { + if (ret.length > 0) + return numberString.slice(0, stringIndex + 1) + sep + ret + right; + else + return numberString.slice(0, stringIndex + 1) + right; + } + if (ret.length > 0) + ret = numberString.slice(stringIndex - curSize + 1, stringIndex+1) + sep + ret; + else + ret = numberString.slice(stringIndex - curSize + 1, stringIndex+1); + stringIndex -= curSize; + if (curGroupIndex < groupSizes.length) { + curSize = groupSizes[curGroupIndex]; + curGroupIndex++; + } + } + return numberString.slice(0, stringIndex + 1) + sep + ret + right; + } + var nf = cultureInfo.numberFormat; + var number = Math.abs(this); + if (!format) + format = "D"; + var precision = -1; + if (format.length > 1) precision = parseInt(format.slice(1), 10); + var pattern; + switch (format.charAt(0)) { + case "d": + case "D": + pattern = 'n'; + if (precision !== -1) { + number = zeroPad(""+number, precision, true); + } + if (this < 0) number = -number; + break; + case "c": + case "C": + if (this < 0) pattern = _currencyNegativePattern[nf.CurrencyNegativePattern]; + else pattern = _currencyPositivePattern[nf.CurrencyPositivePattern]; + if (precision === -1) precision = nf.CurrencyDecimalDigits; + number = expandNumber(Math.abs(this), precision, nf.CurrencyGroupSizes, nf.CurrencyGroupSeparator, nf.CurrencyDecimalSeparator); + break; + case "n": + case "N": + if (this < 0) pattern = _numberNegativePattern[nf.NumberNegativePattern]; + else pattern = 'n'; + if (precision === -1) precision = nf.NumberDecimalDigits; + number = expandNumber(Math.abs(this), precision, nf.NumberGroupSizes, nf.NumberGroupSeparator, nf.NumberDecimalSeparator); + break; + case "p": + case "P": + if (this < 0) pattern = _percentNegativePattern[nf.PercentNegativePattern]; + else pattern = _percentPositivePattern[nf.PercentPositivePattern]; + if (precision === -1) precision = nf.PercentDecimalDigits; + number = expandNumber(Math.abs(this) * 100, precision, nf.PercentGroupSizes, nf.PercentGroupSeparator, nf.PercentDecimalSeparator); + break; + default: + throw Error.format(Sys.Res.formatBadFormatSpecifier); + } + var regex = /n|\$|-|%/g; + var ret = ""; + for (;;) { + var index = regex.lastIndex; + var ar = regex.exec(pattern); + ret += pattern.slice(index, ar ? ar.index : pattern.length); + if (!ar) + break; + switch (ar[0]) { + case "n": + ret += number; + break; + case "$": + ret += nf.CurrencySymbol; + break; + case "-": + ret += nf.NegativeSign; + break; + case "%": + ret += nf.PercentSymbol; + break; + } + } + return ret; +} + +RegExp.__typeName = 'RegExp'; +RegExp.__class = true; + +Array.__typeName = 'Array'; +Array.__class = true; +Array.add = Array.enqueue = function Array$enqueue(array, item) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "array", type: Array, elementMayBeNull: true}, + {name: "item", mayBeNull: true} + ]); + if (e) throw e; + array[array.length] = item; +} +Array.addRange = function Array$addRange(array, items) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "array", type: Array, elementMayBeNull: true}, + {name: "items", type: Array, elementMayBeNull: true} + ]); + if (e) throw e; + array.push.apply(array, items); +} +Array.clear = function Array$clear(array) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "array", type: Array, elementMayBeNull: true} + ]); + if (e) throw e; + array.length = 0; +} +Array.clone = function Array$clone(array) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "array", type: Array, elementMayBeNull: true} + ]); + if (e) throw e; + if (array.length === 1) { + return [array[0]]; + } + else { + return Array.apply(null, array); + } +} +Array.contains = function Array$contains(array, item) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "array", type: Array, elementMayBeNull: true}, + {name: "item", mayBeNull: true} + ]); + if (e) throw e; + return (Array.indexOf(array, item) >= 0); +} +Array.dequeue = function Array$dequeue(array) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "array", type: Array, elementMayBeNull: true} + ]); + if (e) throw e; + return array.shift(); +} +Array.forEach = function Array$forEach(array, method, instance) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "array", type: Array, elementMayBeNull: true}, + {name: "method", type: Function}, + {name: "instance", mayBeNull: true, optional: true} + ]); + if (e) throw e; + for (var i = 0, l = array.length; i < l; i++) { + var elt = array[i]; + if (typeof(elt) !== 'undefined') method.call(instance, elt, i, array); + } +} +Array.indexOf = function Array$indexOf(array, item, start) { + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "array", type: Array, elementMayBeNull: true}, + {name: "item", mayBeNull: true, optional: true}, + {name: "start", mayBeNull: true, optional: true} + ]); + if (e) throw e; + if (typeof(item) === "undefined") return -1; + var length = array.length; + if (length !== 0) { + start = start - 0; + if (isNaN(start)) { + start = 0; + } + else { + if (isFinite(start)) { + start = start - (start % 1); + } + if (start < 0) { + start = Math.max(0, length + start); + } + } + for (var i = start; i < length; i++) { + if ((typeof(array[i]) !== "undefined") && (array[i] === item)) { + return i; + } + } + } + return -1; +} +Array.insert = function Array$insert(array, index, item) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "array", type: Array, elementMayBeNull: true}, + {name: "index", mayBeNull: true}, + {name: "item", mayBeNull: true} + ]); + if (e) throw e; + array.splice(index, 0, item); +} +Array.parse = function Array$parse(value) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "value", type: String, mayBeNull: true} + ]); + if (e) throw e; + if (!value) return []; + var v = eval(value); + if (!Array.isInstanceOfType(v)) throw Error.argument('value', Sys.Res.arrayParseBadFormat); + return v; +} +Array.remove = function Array$remove(array, item) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "array", type: Array, elementMayBeNull: true}, + {name: "item", mayBeNull: true} + ]); + if (e) throw e; + var index = Array.indexOf(array, item); + if (index >= 0) { + array.splice(index, 1); + } + return (index >= 0); +} +Array.removeAt = function Array$removeAt(array, index) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "array", type: Array, elementMayBeNull: true}, + {name: "index", mayBeNull: true} + ]); + if (e) throw e; + array.splice(index, 1); +} + +if (!window) this.window = this; +window.Type = Function; +Type.__fullyQualifiedIdentifierRegExp = new RegExp("^[^.0-9 \\s|,;:&*=+\\-()\\[\\]{}^%#@!~\\n\\r\\t\\f\\\\]([^ \\s|,;:&*=+\\-()\\[\\]{}^%#@!~\\n\\r\\t\\f\\\\]*[^. \\s|,;:&*=+\\-()\\[\\]{}^%#@!~\\n\\r\\t\\f\\\\])?$", "i"); +Type.__identifierRegExp = new RegExp("^[^.0-9 \\s|,;:&*=+\\-()\\[\\]{}^%#@!~\\n\\r\\t\\f\\\\][^. \\s|,;:&*=+\\-()\\[\\]{}^%#@!~\\n\\r\\t\\f\\\\]*$", "i"); +Type.prototype.callBaseMethod = function Type$callBaseMethod(instance, name, baseArguments) { + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "instance"}, + {name: "name", type: String}, + {name: "baseArguments", type: Array, mayBeNull: true, optional: true, elementMayBeNull: true} + ]); + if (e) throw e; + var baseMethod = this.getBaseMethod(instance, name); + if (!baseMethod) throw Error.invalidOperation(String.format(Sys.Res.methodNotFound, name)); + if (!baseArguments) { + return baseMethod.apply(instance); + } + else { + return baseMethod.apply(instance, baseArguments); + } +} +Type.prototype.getBaseMethod = function Type$getBaseMethod(instance, name) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "instance"}, + {name: "name", type: String} + ]); + if (e) throw e; + if (!this.isInstanceOfType(instance)) throw Error.argumentType('instance', Object.getType(instance), this); + var baseType = this.getBaseType(); + if (baseType) { + var baseMethod = baseType.prototype[name]; + return (baseMethod instanceof Function) ? baseMethod : null; + } + return null; +} +Type.prototype.getBaseType = function Type$getBaseType() { + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return (typeof(this.__baseType) === "undefined") ? null : this.__baseType; +} +Type.prototype.getInterfaces = function Type$getInterfaces() { + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + var result = []; + var type = this; + while(type) { + var interfaces = type.__interfaces; + if (interfaces) { + for (var i = 0, l = interfaces.length; i < l; i++) { + var interfaceType = interfaces[i]; + if (!Array.contains(result, interfaceType)) { + result[result.length] = interfaceType; + } + } + } + type = type.__baseType; + } + return result; +} +Type.prototype.getName = function Type$getName() { + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return (typeof(this.__typeName) === "undefined") ? "" : this.__typeName; +} +Type.prototype.implementsInterface = function Type$implementsInterface(interfaceType) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "interfaceType", type: Type} + ]); + if (e) throw e; + this.resolveInheritance(); + var interfaceName = interfaceType.getName(); + var cache = this.__interfaceCache; + if (cache) { + var cacheEntry = cache[interfaceName]; + if (typeof(cacheEntry) !== 'undefined') return cacheEntry; + } + else { + cache = this.__interfaceCache = {}; + } + var baseType = this; + while (baseType) { + var interfaces = baseType.__interfaces; + if (interfaces) { + if (Array.indexOf(interfaces, interfaceType) !== -1) { + return cache[interfaceName] = true; + } + } + baseType = baseType.__baseType; + } + return cache[interfaceName] = false; +} +Type.prototype.inheritsFrom = function Type$inheritsFrom(parentType) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "parentType", type: Type} + ]); + if (e) throw e; + this.resolveInheritance(); + var baseType = this.__baseType; + while (baseType) { + if (baseType === parentType) { + return true; + } + baseType = baseType.__baseType; + } + return false; +} +Type.prototype.initializeBase = function Type$initializeBase(instance, baseArguments) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "instance"}, + {name: "baseArguments", type: Array, mayBeNull: true, optional: true, elementMayBeNull: true} + ]); + if (e) throw e; + if (!this.isInstanceOfType(instance)) throw Error.argumentType('instance', Object.getType(instance), this); + this.resolveInheritance(); + if (this.__baseType) { + if (!baseArguments) { + this.__baseType.apply(instance); + } + else { + this.__baseType.apply(instance, baseArguments); + } + } + return instance; +} +Type.prototype.isImplementedBy = function Type$isImplementedBy(instance) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "instance", mayBeNull: true} + ]); + if (e) throw e; + if (typeof(instance) === "undefined" || instance === null) return false; + var instanceType = Object.getType(instance); + return !!(instanceType.implementsInterface && instanceType.implementsInterface(this)); +} +Type.prototype.isInstanceOfType = function Type$isInstanceOfType(instance) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "instance", mayBeNull: true} + ]); + if (e) throw e; + if (typeof(instance) === "undefined" || instance === null) return false; + if (instance instanceof this) return true; + var instanceType = Object.getType(instance); + return !!(instanceType === this) || + (instanceType.inheritsFrom && instanceType.inheritsFrom(this)) || + (instanceType.implementsInterface && instanceType.implementsInterface(this)); +} +Type.prototype.registerClass = function Type$registerClass(typeName, baseType, interfaceTypes) { + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "typeName", type: String}, + {name: "baseType", type: Type, mayBeNull: true, optional: true}, + {name: "interfaceTypes", type: Type, parameterArray: true} + ]); + if (e) throw e; + if (!Type.__fullyQualifiedIdentifierRegExp.test(typeName)) throw Error.argument('typeName', Sys.Res.notATypeName); + var parsedName; + try { + parsedName = eval(typeName); + } + catch(e) { + throw Error.argument('typeName', Sys.Res.argumentTypeName); + } + if (parsedName !== this) throw Error.argument('typeName', Sys.Res.badTypeName); + if (Sys.__registeredTypes[typeName]) throw Error.invalidOperation(String.format(Sys.Res.typeRegisteredTwice, typeName)); + if ((arguments.length > 1) && (typeof(baseType) === 'undefined')) throw Error.argumentUndefined('baseType'); + if (baseType && !baseType.__class) throw Error.argument('baseType', Sys.Res.baseNotAClass); + this.prototype.constructor = this; + this.__typeName = typeName; + this.__class = true; + if (baseType) { + this.__baseType = baseType; + this.__basePrototypePending = true; + } + Sys.__upperCaseTypes[typeName.toUpperCase()] = this; + if (interfaceTypes) { + this.__interfaces = []; + this.resolveInheritance(); + for (var i = 2, l = arguments.length; i < l; i++) { + var interfaceType = arguments[i]; + if (!interfaceType.__interface) throw Error.argument('interfaceTypes[' + (i - 2) + ']', Sys.Res.notAnInterface); + for (var methodName in interfaceType.prototype) { + var method = interfaceType.prototype[methodName]; + if (!this.prototype[methodName]) { + this.prototype[methodName] = method; + } + } + this.__interfaces.push(interfaceType); + } + } + Sys.__registeredTypes[typeName] = true; + return this; +} +Type.prototype.registerInterface = function Type$registerInterface(typeName) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "typeName", type: String} + ]); + if (e) throw e; + if (!Type.__fullyQualifiedIdentifierRegExp.test(typeName)) throw Error.argument('typeName', Sys.Res.notATypeName); + var parsedName; + try { + parsedName = eval(typeName); + } + catch(e) { + throw Error.argument('typeName', Sys.Res.argumentTypeName); + } + if (parsedName !== this) throw Error.argument('typeName', Sys.Res.badTypeName); + if (Sys.__registeredTypes[typeName]) throw Error.invalidOperation(String.format(Sys.Res.typeRegisteredTwice, typeName)); + Sys.__upperCaseTypes[typeName.toUpperCase()] = this; + this.prototype.constructor = this; + this.__typeName = typeName; + this.__interface = true; + Sys.__registeredTypes[typeName] = true; + return this; +} +Type.prototype.resolveInheritance = function Type$resolveInheritance() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (this.__basePrototypePending) { + var baseType = this.__baseType; + baseType.resolveInheritance(); + for (var memberName in baseType.prototype) { + var memberValue = baseType.prototype[memberName]; + if (!this.prototype[memberName]) { + this.prototype[memberName] = memberValue; + } + } + delete this.__basePrototypePending; + } +} +Type.getRootNamespaces = function Type$getRootNamespaces() { + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return Array.clone(Sys.__rootNamespaces); +} +Type.isClass = function Type$isClass(type) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "type", mayBeNull: true} + ]); + if (e) throw e; + if ((typeof(type) === 'undefined') || (type === null)) return false; + return !!type.__class; +} +Type.isInterface = function Type$isInterface(type) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "type", mayBeNull: true} + ]); + if (e) throw e; + if ((typeof(type) === 'undefined') || (type === null)) return false; + return !!type.__interface; +} +Type.isNamespace = function Type$isNamespace(object) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "object", mayBeNull: true} + ]); + if (e) throw e; + if ((typeof(object) === 'undefined') || (object === null)) return false; + return !!object.__namespace; +} +Type.parse = function Type$parse(typeName, ns) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "typeName", type: String, mayBeNull: true}, + {name: "ns", mayBeNull: true, optional: true} + ]); + if (e) throw e; + var fn; + if (ns) { + fn = Sys.__upperCaseTypes[ns.getName().toUpperCase() + '.' + typeName.toUpperCase()]; + return fn || null; + } + if (!typeName) return null; + if (!Type.__htClasses) { + Type.__htClasses = {}; + } + fn = Type.__htClasses[typeName]; + if (!fn) { + fn = eval(typeName); + if (typeof(fn) !== 'function') throw Error.argument('typeName', Sys.Res.notATypeName); + Type.__htClasses[typeName] = fn; + } + return fn; +} +Type.registerNamespace = function Type$registerNamespace(namespacePath) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "namespacePath", type: String} + ]); + if (e) throw e; + if (!Type.__fullyQualifiedIdentifierRegExp.test(namespacePath)) throw Error.argument('namespacePath', Sys.Res.invalidNameSpace); + var rootObject = window; + var namespaceParts = namespacePath.split('.'); + for (var i = 0; i < namespaceParts.length; i++) { + var currentPart = namespaceParts[i]; + var ns = rootObject[currentPart]; + if (ns && !ns.__namespace) { + throw Error.invalidOperation(String.format(Sys.Res.namespaceContainsObject, namespaceParts.splice(0, i + 1).join('.'))); + } + if (!ns) { + ns = rootObject[currentPart] = { + __namespace: true, + __typeName: namespaceParts.slice(0, i + 1).join('.') + }; + if (i === 0) { + Sys.__rootNamespaces[Sys.__rootNamespaces.length] = ns; + } + var parsedName; + try { + parsedName = eval(ns.__typeName); + } + catch(e) { + parsedName = null; + } + if (parsedName !== ns) { + delete rootObject[currentPart]; + throw Error.argument('namespacePath', Sys.Res.invalidNameSpace); + } + ns.getName = function ns$getName() {return this.__typeName;} + } + rootObject = ns; + } +} +window.Sys = { + __namespace: true, + __typeName: "Sys", + getName: function() {return "Sys";}, + __upperCaseTypes: {} +}; +Sys.__rootNamespaces = [Sys]; +Sys.__registeredTypes = {}; + +Sys.IDisposable = function Sys$IDisposable() { + throw Error.notImplemented(); +} + function Sys$IDisposable$dispose() { + throw Error.notImplemented(); + } +Sys.IDisposable.prototype = { + dispose: Sys$IDisposable$dispose +} +Sys.IDisposable.registerInterface('Sys.IDisposable'); + +Sys.StringBuilder = function Sys$StringBuilder(initialText) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "initialText", mayBeNull: true, optional: true} + ]); + if (e) throw e; + this._parts = (typeof(initialText) !== 'undefined' && initialText !== null && initialText !== '') ? + [initialText.toString()] : []; + this._value = {}; + this._len = 0; +} + function Sys$StringBuilder$append(text) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "text", mayBeNull: true} + ]); + if (e) throw e; + this._parts[this._parts.length] = text; + } + function Sys$StringBuilder$appendLine(text) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "text", mayBeNull: true, optional: true} + ]); + if (e) throw e; + this._parts[this._parts.length] = + ((typeof(text) === 'undefined') || (text === null) || (text === '')) ? + '\r\n' : text + '\r\n'; + } + function Sys$StringBuilder$clear() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + this._parts = []; + this._value = {}; + this._len = 0; + } + function Sys$StringBuilder$isEmpty() { + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (this._parts.length === 0) return true; + return this.toString() === ''; + } + function Sys$StringBuilder$toString(separator) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "separator", type: String, mayBeNull: true, optional: true} + ]); + if (e) throw e; + separator = separator || ''; + var parts = this._parts; + if (this._len !== parts.length) { + this._value = {}; + this._len = parts.length; + } + var val = this._value; + if (typeof(val[separator]) === 'undefined') { + if (separator !== '') { + for (var i = 0; i < parts.length;) { + if ((typeof(parts[i]) === 'undefined') || (parts[i] === '') || (parts[i] === null)) { + parts.splice(i, 1); + } + else { + i++; + } + } + } + val[separator] = this._parts.join(separator); + } + return val[separator]; + } +Sys.StringBuilder.prototype = { + append: Sys$StringBuilder$append, + appendLine: Sys$StringBuilder$appendLine, + clear: Sys$StringBuilder$clear, + isEmpty: Sys$StringBuilder$isEmpty, + toString: Sys$StringBuilder$toString +} +Sys.StringBuilder.registerClass('Sys.StringBuilder'); + +if (!window.XMLHttpRequest) { + window.XMLHttpRequest = function window$XMLHttpRequest() { + var progIDs = [ 'Msxml2.XMLHTTP.3.0', 'Msxml2.XMLHTTP' ]; + for (var i = 0, l = progIDs.length; i < l; i++) { + try { + return new ActiveXObject(progIDs[i]); + } + catch (ex) { + } + } + return null; + } +} + +Sys.Browser = {}; +Sys.Browser.InternetExplorer = {}; +Sys.Browser.Firefox = {}; +Sys.Browser.Safari = {}; +Sys.Browser.Opera = {}; +Sys.Browser.agent = null; +Sys.Browser.hasDebuggerStatement = false; +Sys.Browser.name = navigator.appName; +Sys.Browser.version = parseFloat(navigator.appVersion); +Sys.Browser.documentMode = 0; +if (navigator.userAgent.indexOf(' MSIE ') > -1) { + Sys.Browser.agent = Sys.Browser.InternetExplorer; + Sys.Browser.version = parseFloat(navigator.userAgent.match(/MSIE (\d+\.\d+)/)[1]); + if (Sys.Browser.version >= 8) { + if (document.documentMode >= 7) { + Sys.Browser.documentMode = document.documentMode; + } + } + Sys.Browser.hasDebuggerStatement = true; +} +else if (navigator.userAgent.indexOf(' Firefox/') > -1) { + Sys.Browser.agent = Sys.Browser.Firefox; + Sys.Browser.version = parseFloat(navigator.userAgent.match(/ Firefox\/(\d+\.\d+)/)[1]); + Sys.Browser.name = 'Firefox'; + Sys.Browser.hasDebuggerStatement = true; +} +else if (navigator.userAgent.indexOf(' AppleWebKit/') > -1) { + Sys.Browser.agent = Sys.Browser.Safari; + Sys.Browser.version = parseFloat(navigator.userAgent.match(/ AppleWebKit\/(\d+(\.\d+)?)/)[1]); + Sys.Browser.name = 'Safari'; +} +else if (navigator.userAgent.indexOf('Opera/') > -1) { + Sys.Browser.agent = Sys.Browser.Opera; +} +Type.registerNamespace('Sys.UI'); + +Sys._Debug = function Sys$_Debug() { + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); +} + function Sys$_Debug$_appendConsole(text) { + if ((typeof(Debug) !== 'undefined') && Debug.writeln) { + Debug.writeln(text); + } + if (window.console && window.console.log) { + window.console.log(text); + } + if (window.opera) { + window.opera.postError(text); + } + if (window.debugService) { + window.debugService.trace(text); + } + } + function Sys$_Debug$_appendTrace(text) { + var traceElement = document.getElementById('TraceConsole'); + if (traceElement && (traceElement.tagName.toUpperCase() === 'TEXTAREA')) { + traceElement.value += text + '\n'; + } + } + function Sys$_Debug$assert(condition, message, displayCaller) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "condition", type: Boolean}, + {name: "message", type: String, mayBeNull: true, optional: true}, + {name: "displayCaller", type: Boolean, optional: true} + ]); + if (e) throw e; + if (!condition) { + message = (displayCaller && this.assert.caller) ? + String.format(Sys.Res.assertFailedCaller, message, this.assert.caller) : + String.format(Sys.Res.assertFailed, message); + if (confirm(String.format(Sys.Res.breakIntoDebugger, message))) { + this.fail(message); + } + } + } + function Sys$_Debug$clearTrace() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + var traceElement = document.getElementById('TraceConsole'); + if (traceElement && (traceElement.tagName.toUpperCase() === 'TEXTAREA')) { + traceElement.value = ''; + } + } + function Sys$_Debug$fail(message) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "message", type: String, mayBeNull: true} + ]); + if (e) throw e; + this._appendConsole(message); + if (Sys.Browser.hasDebuggerStatement) { + eval('debugger'); + } + } + function Sys$_Debug$trace(text) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "text"} + ]); + if (e) throw e; + this._appendConsole(text); + this._appendTrace(text); + } + function Sys$_Debug$traceDump(object, name) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "object", mayBeNull: true}, + {name: "name", type: String, mayBeNull: true, optional: true} + ]); + if (e) throw e; + var text = this._traceDump(object, name, true); + } + function Sys$_Debug$_traceDump(object, name, recursive, indentationPadding, loopArray) { + name = name? name : 'traceDump'; + indentationPadding = indentationPadding? indentationPadding : ''; + if (object === null) { + this.trace(indentationPadding + name + ': null'); + return; + } + switch(typeof(object)) { + case 'undefined': + this.trace(indentationPadding + name + ': Undefined'); + break; + case 'number': case 'string': case 'boolean': + this.trace(indentationPadding + name + ': ' + object); + break; + default: + if (Date.isInstanceOfType(object) || RegExp.isInstanceOfType(object)) { + this.trace(indentationPadding + name + ': ' + object.toString()); + break; + } + if (!loopArray) { + loopArray = []; + } + else if (Array.contains(loopArray, object)) { + this.trace(indentationPadding + name + ': ...'); + return; + } + Array.add(loopArray, object); + if ((object == window) || (object === document) || + (window.HTMLElement && (object instanceof HTMLElement)) || + (typeof(object.nodeName) === 'string')) { + var tag = object.tagName? object.tagName : 'DomElement'; + if (object.id) { + tag += ' - ' + object.id; + } + this.trace(indentationPadding + name + ' {' + tag + '}'); + } + else { + var typeName = Object.getTypeName(object); + this.trace(indentationPadding + name + (typeof(typeName) === 'string' ? ' {' + typeName + '}' : '')); + if ((indentationPadding === '') || recursive) { + indentationPadding += " "; + var i, length, properties, p, v; + if (Array.isInstanceOfType(object)) { + length = object.length; + for (i = 0; i < length; i++) { + this._traceDump(object[i], '[' + i + ']', recursive, indentationPadding, loopArray); + } + } + else { + for (p in object) { + v = object[p]; + if (!Function.isInstanceOfType(v)) { + this._traceDump(v, p, recursive, indentationPadding, loopArray); + } + } + } + } + } + Array.remove(loopArray, object); + } + } +Sys._Debug.prototype = { + _appendConsole: Sys$_Debug$_appendConsole, + _appendTrace: Sys$_Debug$_appendTrace, + assert: Sys$_Debug$assert, + clearTrace: Sys$_Debug$clearTrace, + fail: Sys$_Debug$fail, + trace: Sys$_Debug$trace, + traceDump: Sys$_Debug$traceDump, + _traceDump: Sys$_Debug$_traceDump +} +Sys._Debug.registerClass('Sys._Debug'); +Sys.Debug = new Sys._Debug(); + Sys.Debug.isDebug = true; + +function Sys$Enum$parse(value, ignoreCase) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "value", type: String}, + {name: "ignoreCase", type: Boolean, optional: true} + ]); + if (e) throw e; + var values, parsed, val; + if (ignoreCase) { + values = this.__lowerCaseValues; + if (!values) { + this.__lowerCaseValues = values = {}; + var prototype = this.prototype; + for (var name in prototype) { + values[name.toLowerCase()] = prototype[name]; + } + } + } + else { + values = this.prototype; + } + if (!this.__flags) { + val = (ignoreCase ? value.toLowerCase() : value); + parsed = values[val.trim()]; + if (typeof(parsed) !== 'number') throw Error.argument('value', String.format(Sys.Res.enumInvalidValue, value, this.__typeName)); + return parsed; + } + else { + var parts = (ignoreCase ? value.toLowerCase() : value).split(','); + var v = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var part = parts[i].trim(); + parsed = values[part]; + if (typeof(parsed) !== 'number') throw Error.argument('value', String.format(Sys.Res.enumInvalidValue, value.split(',')[i].trim(), this.__typeName)); + v |= parsed; + } + return v; + } +} +function Sys$Enum$toString(value) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "value", mayBeNull: true, optional: true} + ]); + if (e) throw e; + if ((typeof(value) === 'undefined') || (value === null)) return this.__string; + if ((typeof(value) != 'number') || ((value % 1) !== 0)) throw Error.argumentType('value', Object.getType(value), this); + var values = this.prototype; + var i; + if (!this.__flags || (value === 0)) { + for (i in values) { + if (values[i] === value) { + return i; + } + } + } + else { + var sorted = this.__sortedValues; + if (!sorted) { + sorted = []; + for (i in values) { + sorted[sorted.length] = {key: i, value: values[i]}; + } + sorted.sort(function(a, b) { + return a.value - b.value; + }); + this.__sortedValues = sorted; + } + var parts = []; + var v = value; + for (i = sorted.length - 1; i >= 0; i--) { + var kvp = sorted[i]; + var vali = kvp.value; + if (vali === 0) continue; + if ((vali & value) === vali) { + parts[parts.length] = kvp.key; + v -= vali; + if (v === 0) break; + } + } + if (parts.length && v === 0) return parts.reverse().join(', '); + } + throw Error.argumentOutOfRange('value', value, String.format(Sys.Res.enumInvalidValue, value, this.__typeName)); +} +Type.prototype.registerEnum = function Type$registerEnum(name, flags) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "name", type: String}, + {name: "flags", type: Boolean, optional: true} + ]); + if (e) throw e; + if (!Type.__fullyQualifiedIdentifierRegExp.test(name)) throw Error.argument('name', Sys.Res.notATypeName); + var parsedName; + try { + parsedName = eval(name); + } + catch(e) { + throw Error.argument('name', Sys.Res.argumentTypeName); + } + if (parsedName !== this) throw Error.argument('name', Sys.Res.badTypeName); + if (Sys.__registeredTypes[name]) throw Error.invalidOperation(String.format(Sys.Res.typeRegisteredTwice, name)); + for (var i in this.prototype) { + var val = this.prototype[i]; + if (!Type.__identifierRegExp.test(i)) throw Error.invalidOperation(String.format(Sys.Res.enumInvalidValueName, i)); + if (typeof(val) !== 'number' || (val % 1) !== 0) throw Error.invalidOperation(Sys.Res.enumValueNotInteger); + if (typeof(this[i]) !== 'undefined') throw Error.invalidOperation(String.format(Sys.Res.enumReservedName, i)); + } + Sys.__upperCaseTypes[name.toUpperCase()] = this; + for (var i in this.prototype) { + this[i] = this.prototype[i]; + } + this.__typeName = name; + this.parse = Sys$Enum$parse; + this.__string = this.toString(); + this.toString = Sys$Enum$toString; + this.__flags = flags; + this.__enum = true; + Sys.__registeredTypes[name] = true; +} +Type.isEnum = function Type$isEnum(type) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "type", mayBeNull: true} + ]); + if (e) throw e; + if ((typeof(type) === 'undefined') || (type === null)) return false; + return !!type.__enum; +} +Type.isFlags = function Type$isFlags(type) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "type", mayBeNull: true} + ]); + if (e) throw e; + if ((typeof(type) === 'undefined') || (type === null)) return false; + return !!type.__flags; +} + +Sys.EventHandlerList = function Sys$EventHandlerList() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + this._list = {}; +} + function Sys$EventHandlerList$addHandler(id, handler) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "id", type: String}, + {name: "handler", type: Function} + ]); + if (e) throw e; + Array.add(this._getEvent(id, true), handler); + } + function Sys$EventHandlerList$removeHandler(id, handler) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "id", type: String}, + {name: "handler", type: Function} + ]); + if (e) throw e; + var evt = this._getEvent(id); + if (!evt) return; + Array.remove(evt, handler); + } + function Sys$EventHandlerList$getHandler(id) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "id", type: String} + ]); + if (e) throw e; + var evt = this._getEvent(id); + if (!evt || (evt.length === 0)) return null; + evt = Array.clone(evt); + return function(source, args) { + for (var i = 0, l = evt.length; i < l; i++) { + evt[i](source, args); + } + }; + } + function Sys$EventHandlerList$_getEvent(id, create) { + if (!this._list[id]) { + if (!create) return null; + this._list[id] = []; + } + return this._list[id]; + } +Sys.EventHandlerList.prototype = { + addHandler: Sys$EventHandlerList$addHandler, + removeHandler: Sys$EventHandlerList$removeHandler, + getHandler: Sys$EventHandlerList$getHandler, + _getEvent: Sys$EventHandlerList$_getEvent +} +Sys.EventHandlerList.registerClass('Sys.EventHandlerList'); + +Sys.EventArgs = function Sys$EventArgs() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); +} +Sys.EventArgs.registerClass('Sys.EventArgs'); +Sys.EventArgs.Empty = new Sys.EventArgs(); + +Sys.CancelEventArgs = function Sys$CancelEventArgs() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + Sys.CancelEventArgs.initializeBase(this); + this._cancel = false; +} + function Sys$CancelEventArgs$get_cancel() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._cancel; + } + function Sys$CancelEventArgs$set_cancel(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Boolean}]); + if (e) throw e; + this._cancel = value; + } +Sys.CancelEventArgs.prototype = { + get_cancel: Sys$CancelEventArgs$get_cancel, + set_cancel: Sys$CancelEventArgs$set_cancel +} +Sys.CancelEventArgs.registerClass('Sys.CancelEventArgs', Sys.EventArgs); + +Sys.INotifyPropertyChange = function Sys$INotifyPropertyChange() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); +} + function Sys$INotifyPropertyChange$add_propertyChanged(handler) { + /// + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + throw Error.notImplemented(); + } + function Sys$INotifyPropertyChange$remove_propertyChanged(handler) { + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + throw Error.notImplemented(); + } +Sys.INotifyPropertyChange.prototype = { + add_propertyChanged: Sys$INotifyPropertyChange$add_propertyChanged, + remove_propertyChanged: Sys$INotifyPropertyChange$remove_propertyChanged +} +Sys.INotifyPropertyChange.registerInterface('Sys.INotifyPropertyChange'); + +Sys.PropertyChangedEventArgs = function Sys$PropertyChangedEventArgs(propertyName) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "propertyName", type: String} + ]); + if (e) throw e; + Sys.PropertyChangedEventArgs.initializeBase(this); + this._propertyName = propertyName; +} + + function Sys$PropertyChangedEventArgs$get_propertyName() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._propertyName; + } +Sys.PropertyChangedEventArgs.prototype = { + get_propertyName: Sys$PropertyChangedEventArgs$get_propertyName +} +Sys.PropertyChangedEventArgs.registerClass('Sys.PropertyChangedEventArgs', Sys.EventArgs); + +Sys.INotifyDisposing = function Sys$INotifyDisposing() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); +} + function Sys$INotifyDisposing$add_disposing(handler) { + /// + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + throw Error.notImplemented(); + } + function Sys$INotifyDisposing$remove_disposing(handler) { + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + throw Error.notImplemented(); + } +Sys.INotifyDisposing.prototype = { + add_disposing: Sys$INotifyDisposing$add_disposing, + remove_disposing: Sys$INotifyDisposing$remove_disposing +} +Sys.INotifyDisposing.registerInterface("Sys.INotifyDisposing"); + +Sys.Component = function Sys$Component() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (Sys.Application) Sys.Application.registerDisposableObject(this); +} + function Sys$Component$get_events() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (!this._events) { + this._events = new Sys.EventHandlerList(); + } + return this._events; + } + function Sys$Component$get_id() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._id; + } + function Sys$Component$set_id(value) { + var e = Function._validateParams(arguments, [{name: "value", type: String}]); + if (e) throw e; + if (this._idSet) throw Error.invalidOperation(Sys.Res.componentCantSetIdTwice); + this._idSet = true; + var oldId = this.get_id(); + if (oldId && Sys.Application.findComponent(oldId)) throw Error.invalidOperation(Sys.Res.componentCantSetIdAfterAddedToApp); + this._id = value; + } + function Sys$Component$get_isInitialized() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._initialized; + } + function Sys$Component$get_isUpdating() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._updating; + } + function Sys$Component$add_disposing(handler) { + /// + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this.get_events().addHandler("disposing", handler); + } + function Sys$Component$remove_disposing(handler) { + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this.get_events().removeHandler("disposing", handler); + } + function Sys$Component$add_propertyChanged(handler) { + /// + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this.get_events().addHandler("propertyChanged", handler); + } + function Sys$Component$remove_propertyChanged(handler) { + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this.get_events().removeHandler("propertyChanged", handler); + } + function Sys$Component$beginUpdate() { + this._updating = true; + } + function Sys$Component$dispose() { + if (this._events) { + var handler = this._events.getHandler("disposing"); + if (handler) { + handler(this, Sys.EventArgs.Empty); + } + } + delete this._events; + Sys.Application.unregisterDisposableObject(this); + Sys.Application.removeComponent(this); + } + function Sys$Component$endUpdate() { + this._updating = false; + if (!this._initialized) this.initialize(); + this.updated(); + } + function Sys$Component$initialize() { + this._initialized = true; + } + function Sys$Component$raisePropertyChanged(propertyName) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "propertyName", type: String} + ]); + if (e) throw e; + if (!this._events) return; + var handler = this._events.getHandler("propertyChanged"); + if (handler) { + handler(this, new Sys.PropertyChangedEventArgs(propertyName)); + } + } + function Sys$Component$updated() { + } +Sys.Component.prototype = { + _id: null, + _idSet: false, + _initialized: false, + _updating: false, + get_events: Sys$Component$get_events, + get_id: Sys$Component$get_id, + set_id: Sys$Component$set_id, + get_isInitialized: Sys$Component$get_isInitialized, + get_isUpdating: Sys$Component$get_isUpdating, + add_disposing: Sys$Component$add_disposing, + remove_disposing: Sys$Component$remove_disposing, + add_propertyChanged: Sys$Component$add_propertyChanged, + remove_propertyChanged: Sys$Component$remove_propertyChanged, + beginUpdate: Sys$Component$beginUpdate, + dispose: Sys$Component$dispose, + endUpdate: Sys$Component$endUpdate, + initialize: Sys$Component$initialize, + raisePropertyChanged: Sys$Component$raisePropertyChanged, + updated: Sys$Component$updated +} +Sys.Component.registerClass('Sys.Component', null, Sys.IDisposable, Sys.INotifyPropertyChange, Sys.INotifyDisposing); +function Sys$Component$_setProperties(target, properties) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "target"}, + {name: "properties"} + ]); + if (e) throw e; + var current; + var targetType = Object.getType(target); + var isObject = (targetType === Object) || (targetType === Sys.UI.DomElement); + var isComponent = Sys.Component.isInstanceOfType(target) && !target.get_isUpdating(); + if (isComponent) target.beginUpdate(); + for (var name in properties) { + var val = properties[name]; + var getter = isObject ? null : target["get_" + name]; + if (isObject || typeof(getter) !== 'function') { + var targetVal = target[name]; + if (!isObject && typeof(targetVal) === 'undefined') throw Error.invalidOperation(String.format(Sys.Res.propertyUndefined, name)); + if (!val || (typeof(val) !== 'object') || (isObject && !targetVal)) { + target[name] = val; + } + else { + Sys$Component$_setProperties(targetVal, val); + } + } + else { + var setter = target["set_" + name]; + if (typeof(setter) === 'function') { + setter.apply(target, [val]); + } + else if (val instanceof Array) { + current = getter.apply(target); + if (!(current instanceof Array)) throw new Error.invalidOperation(String.format(Sys.Res.propertyNotAnArray, name)); + for (var i = 0, j = current.length, l= val.length; i < l; i++, j++) { + current[j] = val[i]; + } + } + else if ((typeof(val) === 'object') && (Object.getType(val) === Object)) { + current = getter.apply(target); + if ((typeof(current) === 'undefined') || (current === null)) throw new Error.invalidOperation(String.format(Sys.Res.propertyNullOrUndefined, name)); + Sys$Component$_setProperties(current, val); + } + else { + throw new Error.invalidOperation(String.format(Sys.Res.propertyNotWritable, name)); + } + } + } + if (isComponent) target.endUpdate(); +} +function Sys$Component$_setReferences(component, references) { + for (var name in references) { + var setter = component["set_" + name]; + var reference = $find(references[name]); + if (typeof(setter) !== 'function') throw new Error.invalidOperation(String.format(Sys.Res.propertyNotWritable, name)); + if (!reference) throw Error.invalidOperation(String.format(Sys.Res.referenceNotFound, references[name])); + setter.apply(component, [reference]); + } +} +var $create = Sys.Component.create = function Sys$Component$create(type, properties, events, references, element) { + /// + /// + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "type", type: Type}, + {name: "properties", mayBeNull: true, optional: true}, + {name: "events", mayBeNull: true, optional: true}, + {name: "references", mayBeNull: true, optional: true}, + {name: "element", mayBeNull: true, domElement: true, optional: true} + ]); + if (e) throw e; + if (!type.inheritsFrom(Sys.Component)) { + throw Error.argument('type', String.format(Sys.Res.createNotComponent, type.getName())); + } + if (type.inheritsFrom(Sys.UI.Behavior) || type.inheritsFrom(Sys.UI.Control)) { + if (!element) throw Error.argument('element', Sys.Res.createNoDom); + } + else if (element) throw Error.argument('element', Sys.Res.createComponentOnDom); + var component = (element ? new type(element): new type()); + var app = Sys.Application; + var creatingComponents = app.get_isCreatingComponents(); + component.beginUpdate(); + if (properties) { + Sys$Component$_setProperties(component, properties); + } + if (events) { + for (var name in events) { + if (!(component["add_" + name] instanceof Function)) throw new Error.invalidOperation(String.format(Sys.Res.undefinedEvent, name)); + if (!(events[name] instanceof Function)) throw new Error.invalidOperation(Sys.Res.eventHandlerNotFunction); + component["add_" + name](events[name]); + } + } + if (component.get_id()) { + app.addComponent(component); + } + if (creatingComponents) { + app._createdComponents[app._createdComponents.length] = component; + if (references) { + app._addComponentToSecondPass(component, references); + } + else { + component.endUpdate(); + } + } + else { + if (references) { + Sys$Component$_setReferences(component, references); + } + component.endUpdate(); + } + return component; +} + +Sys.UI.MouseButton = function Sys$UI$MouseButton() { + /// + /// + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); +} +Sys.UI.MouseButton.prototype = { + leftButton: 0, + middleButton: 1, + rightButton: 2 +} +Sys.UI.MouseButton.registerEnum("Sys.UI.MouseButton"); + +Sys.UI.Key = function Sys$UI$Key() { + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); +} +Sys.UI.Key.prototype = { + backspace: 8, + tab: 9, + enter: 13, + esc: 27, + space: 32, + pageUp: 33, + pageDown: 34, + end: 35, + home: 36, + left: 37, + up: 38, + right: 39, + down: 40, + del: 127 +} +Sys.UI.Key.registerEnum("Sys.UI.Key"); + +Sys.UI.Point = function Sys$UI$Point(x, y) { + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "x", type: Number, integer: true}, + {name: "y", type: Number, integer: true} + ]); + if (e) throw e; + this.x = x; + this.y = y; +} +Sys.UI.Point.registerClass('Sys.UI.Point'); + +Sys.UI.Bounds = function Sys$UI$Bounds(x, y, width, height) { + /// + /// + /// + /// + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "x", type: Number, integer: true}, + {name: "y", type: Number, integer: true}, + {name: "height", type: Number, integer: true}, + {name: "width", type: Number, integer: true} + ]); + if (e) throw e; + this.x = x; + this.y = y; + this.height = height; + this.width = width; +} +Sys.UI.Bounds.registerClass('Sys.UI.Bounds'); + +Sys.UI.DomEvent = function Sys$UI$DomEvent(eventObject) { + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "eventObject"} + ]); + if (e) throw e; + var e = eventObject; + var etype = this.type = e.type.toLowerCase(); + this.rawEvent = e; + this.altKey = e.altKey; + if (typeof(e.button) !== 'undefined') { + this.button = (typeof(e.which) !== 'undefined') ? e.button : + (e.button === 4) ? Sys.UI.MouseButton.middleButton : + (e.button === 2) ? Sys.UI.MouseButton.rightButton : + Sys.UI.MouseButton.leftButton; + } + if (etype === 'keypress') { + this.charCode = e.charCode || e.keyCode; + } + else if (e.keyCode && (e.keyCode === 46)) { + this.keyCode = 127; + } + else { + this.keyCode = e.keyCode; + } + this.clientX = e.clientX; + this.clientY = e.clientY; + this.ctrlKey = e.ctrlKey; + this.target = e.target ? e.target : e.srcElement; + if (!etype.startsWith('key')) { + if ((typeof(e.offsetX) !== 'undefined') && (typeof(e.offsetY) !== 'undefined')) { + this.offsetX = e.offsetX; + this.offsetY = e.offsetY; + } + else if (this.target && (this.target.nodeType !== 3) && (typeof(e.clientX) === 'number')) { + var loc = Sys.UI.DomElement.getLocation(this.target); + var w = Sys.UI.DomElement._getWindow(this.target); + this.offsetX = (w.pageXOffset || 0) + e.clientX - loc.x; + this.offsetY = (w.pageYOffset || 0) + e.clientY - loc.y; + } + } + this.screenX = e.screenX; + this.screenY = e.screenY; + this.shiftKey = e.shiftKey; +} + function Sys$UI$DomEvent$preventDefault() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (this.rawEvent.preventDefault) { + this.rawEvent.preventDefault(); + } + else if (window.event) { + this.rawEvent.returnValue = false; + } + } + function Sys$UI$DomEvent$stopPropagation() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (this.rawEvent.stopPropagation) { + this.rawEvent.stopPropagation(); + } + else if (window.event) { + this.rawEvent.cancelBubble = true; + } + } +Sys.UI.DomEvent.prototype = { + preventDefault: Sys$UI$DomEvent$preventDefault, + stopPropagation: Sys$UI$DomEvent$stopPropagation +} +Sys.UI.DomEvent.registerClass('Sys.UI.DomEvent'); +var $addHandler = Sys.UI.DomEvent.addHandler = function Sys$UI$DomEvent$addHandler(element, eventName, handler) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element"}, + {name: "eventName", type: String}, + {name: "handler", type: Function} + ]); + if (e) throw e; + Sys.UI.DomEvent._ensureDomNode(element); + if (eventName === "error") throw Error.invalidOperation(Sys.Res.addHandlerCantBeUsedForError); + if (!element._events) { + element._events = {}; + } + var eventCache = element._events[eventName]; + if (!eventCache) { + element._events[eventName] = eventCache = []; + } + var browserHandler; + if (element.addEventListener) { + browserHandler = function(e) { + return handler.call(element, new Sys.UI.DomEvent(e)); + } + element.addEventListener(eventName, browserHandler, false); + } + else if (element.attachEvent) { + browserHandler = function() { + var e = {}; + try {e = Sys.UI.DomElement._getWindow(element).event} catch(ex) {} + return handler.call(element, new Sys.UI.DomEvent(e)); + } + element.attachEvent('on' + eventName, browserHandler); + } + eventCache[eventCache.length] = {handler: handler, browserHandler: browserHandler}; +} +var $addHandlers = Sys.UI.DomEvent.addHandlers = function Sys$UI$DomEvent$addHandlers(element, events, handlerOwner) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element"}, + {name: "events", type: Object}, + {name: "handlerOwner", optional: true} + ]); + if (e) throw e; + Sys.UI.DomEvent._ensureDomNode(element); + for (var name in events) { + var handler = events[name]; + if (typeof(handler) !== 'function') throw Error.invalidOperation(Sys.Res.cantAddNonFunctionhandler); + if (handlerOwner) { + handler = Function.createDelegate(handlerOwner, handler); + } + $addHandler(element, name, handler); + } +} +var $clearHandlers = Sys.UI.DomEvent.clearHandlers = function Sys$UI$DomEvent$clearHandlers(element) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element"} + ]); + if (e) throw e; + Sys.UI.DomEvent._ensureDomNode(element); + if (element._events) { + var cache = element._events; + for (var name in cache) { + var handlers = cache[name]; + for (var i = handlers.length - 1; i >= 0; i--) { + $removeHandler(element, name, handlers[i].handler); + } + } + element._events = null; + } +} +var $removeHandler = Sys.UI.DomEvent.removeHandler = function Sys$UI$DomEvent$removeHandler(element, eventName, handler) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element"}, + {name: "eventName", type: String}, + {name: "handler", type: Function} + ]); + if (e) throw e; + Sys.UI.DomEvent._ensureDomNode(element); + var browserHandler = null; + if ((typeof(element._events) !== 'object') || (element._events == null)) throw Error.invalidOperation(Sys.Res.eventHandlerInvalid); + var cache = element._events[eventName]; + if (!(cache instanceof Array)) throw Error.invalidOperation(Sys.Res.eventHandlerInvalid); + for (var i = 0, l = cache.length; i < l; i++) { + if (cache[i].handler === handler) { + browserHandler = cache[i].browserHandler; + break; + } + } + if (typeof(browserHandler) !== 'function') throw Error.invalidOperation(Sys.Res.eventHandlerInvalid); + if (element.removeEventListener) { + element.removeEventListener(eventName, browserHandler, false); + } + else if (element.detachEvent) { + element.detachEvent('on' + eventName, browserHandler); + } + cache.splice(i, 1); +} +Sys.UI.DomEvent._ensureDomNode = function Sys$UI$DomEvent$_ensureDomNode(element) { + if (element.tagName && (element.tagName.toUpperCase() === "SCRIPT")) return; + + var doc = element.ownerDocument || element.document || element; + if ((typeof(element.document) !== 'object') && (element != doc) && (typeof(element.nodeType) !== 'number')) { + throw Error.argument("element", Sys.Res.argumentDomNode); + } +} + +Sys.UI.DomElement = function Sys$UI$DomElement() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); +} +Sys.UI.DomElement.registerClass('Sys.UI.DomElement'); +Sys.UI.DomElement.addCssClass = function Sys$UI$DomElement$addCssClass(element, className) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true}, + {name: "className", type: String} + ]); + if (e) throw e; + if (!Sys.UI.DomElement.containsCssClass(element, className)) { + if (element.className === '') { + element.className = className; + } + else { + element.className += ' ' + className; + } + } +} +Sys.UI.DomElement.containsCssClass = function Sys$UI$DomElement$containsCssClass(element, className) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true}, + {name: "className", type: String} + ]); + if (e) throw e; + return Array.contains(element.className.split(' '), className); +} +Sys.UI.DomElement.getBounds = function Sys$UI$DomElement$getBounds(element) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true} + ]); + if (e) throw e; + var offset = Sys.UI.DomElement.getLocation(element); + return new Sys.UI.Bounds(offset.x, offset.y, element.offsetWidth || 0, element.offsetHeight || 0); +} +var $get = Sys.UI.DomElement.getElementById = function Sys$UI$DomElement$getElementById(id, element) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "id", type: String}, + {name: "element", mayBeNull: true, domElement: true, optional: true} + ]); + if (e) throw e; + if (!element) return document.getElementById(id); + if (element.getElementById) return element.getElementById(id); + var nodeQueue = []; + var childNodes = element.childNodes; + for (var i = 0; i < childNodes.length; i++) { + var node = childNodes[i]; + if (node.nodeType == 1) { + nodeQueue[nodeQueue.length] = node; + } + } + while (nodeQueue.length) { + node = nodeQueue.shift(); + if (node.id == id) { + return node; + } + childNodes = node.childNodes; + for (i = 0; i < childNodes.length; i++) { + node = childNodes[i]; + if (node.nodeType == 1) { + nodeQueue[nodeQueue.length] = node; + } + } + } + return null; +} +switch(Sys.Browser.agent) { + case Sys.Browser.InternetExplorer: + Sys.UI.DomElement.getLocation = function Sys$UI$DomElement$getLocation(element) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true} + ]); + if (e) throw e; + if (element.self || element.nodeType === 9) return new Sys.UI.Point(0,0); + var clientRect = element.getBoundingClientRect(); + if (!clientRect) { + return new Sys.UI.Point(0,0); + } + var documentElement = element.ownerDocument.documentElement; + var offsetX = clientRect.left - 2 + documentElement.scrollLeft, + offsetY = clientRect.top - 2 + documentElement.scrollTop; + + try { + var f = element.ownerDocument.parentWindow.frameElement || null; + if (f) { + var offset = (f.frameBorder === "0" || f.frameBorder === "no") ? 2 : 0; + offsetX += offset; + offsetY += offset; + } + } + catch(ex) { + } + + return new Sys.UI.Point(offsetX, offsetY); + } + break; + case Sys.Browser.Safari: + Sys.UI.DomElement.getLocation = function Sys$UI$DomElement$getLocation(element) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true} + ]); + if (e) throw e; + if ((element.window && (element.window === element)) || element.nodeType === 9) return new Sys.UI.Point(0,0); + var offsetX = 0; + var offsetY = 0; + var previous = null; + var previousStyle = null; + var currentStyle; + for (var parent = element; parent; previous = parent, previousStyle = currentStyle, parent = parent.offsetParent) { + currentStyle = Sys.UI.DomElement._getCurrentStyle(parent); + var tagName = parent.tagName ? parent.tagName.toUpperCase() : null; + if ((parent.offsetLeft || parent.offsetTop) && + ((tagName !== "BODY") || (!previousStyle || previousStyle.position !== "absolute"))) { + offsetX += parent.offsetLeft; + offsetY += parent.offsetTop; + } + } + currentStyle = Sys.UI.DomElement._getCurrentStyle(element); + var elementPosition = currentStyle ? currentStyle.position : null; + if (!elementPosition || (elementPosition !== "absolute")) { + for (var parent = element.parentNode; parent; parent = parent.parentNode) { + tagName = parent.tagName ? parent.tagName.toUpperCase() : null; + if ((tagName !== "BODY") && (tagName !== "HTML") && (parent.scrollLeft || parent.scrollTop)) { + offsetX -= (parent.scrollLeft || 0); + offsetY -= (parent.scrollTop || 0); + } + currentStyle = Sys.UI.DomElement._getCurrentStyle(parent); + var parentPosition = currentStyle ? currentStyle.position : null; + if (parentPosition && (parentPosition === "absolute")) break; + } + } + return new Sys.UI.Point(offsetX, offsetY); + } + break; + case Sys.Browser.Opera: + Sys.UI.DomElement.getLocation = function Sys$UI$DomElement$getLocation(element) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true} + ]); + if (e) throw e; + if ((element.window && (element.window === element)) || element.nodeType === 9) return new Sys.UI.Point(0,0); + var offsetX = 0; + var offsetY = 0; + var previous = null; + for (var parent = element; parent; previous = parent, parent = parent.offsetParent) { + var tagName = parent.tagName; + offsetX += parent.offsetLeft || 0; + offsetY += parent.offsetTop || 0; + } + var elementPosition = element.style.position; + var elementPositioned = elementPosition && (elementPosition !== "static"); + for (var parent = element.parentNode; parent; parent = parent.parentNode) { + tagName = parent.tagName ? parent.tagName.toUpperCase() : null; + if ((tagName !== "BODY") && (tagName !== "HTML") && (parent.scrollLeft || parent.scrollTop) && + ((elementPositioned && + ((parent.style.overflow === "scroll") || (parent.style.overflow === "auto"))))) { + offsetX -= (parent.scrollLeft || 0); + offsetY -= (parent.scrollTop || 0); + } + var parentPosition = (parent && parent.style) ? parent.style.position : null; + elementPositioned = elementPositioned || (parentPosition && (parentPosition !== "static")); + } + return new Sys.UI.Point(offsetX, offsetY); + } + break; + default: + Sys.UI.DomElement.getLocation = function Sys$UI$DomElement$getLocation(element) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true} + ]); + if (e) throw e; + if ((element.window && (element.window === element)) || element.nodeType === 9) return new Sys.UI.Point(0,0); + var offsetX = 0; + var offsetY = 0; + var previous = null; + var previousStyle = null; + var currentStyle = null; + for (var parent = element; parent; previous = parent, previousStyle = currentStyle, parent = parent.offsetParent) { + var tagName = parent.tagName ? parent.tagName.toUpperCase() : null; + currentStyle = Sys.UI.DomElement._getCurrentStyle(parent); + if ((parent.offsetLeft || parent.offsetTop) && + !((tagName === "BODY") && + (!previousStyle || previousStyle.position !== "absolute"))) { + offsetX += parent.offsetLeft; + offsetY += parent.offsetTop; + } + if (previous !== null && currentStyle) { + if ((tagName !== "TABLE") && (tagName !== "TD") && (tagName !== "HTML")) { + offsetX += parseInt(currentStyle.borderLeftWidth) || 0; + offsetY += parseInt(currentStyle.borderTopWidth) || 0; + } + if (tagName === "TABLE" && + (currentStyle.position === "relative" || currentStyle.position === "absolute")) { + offsetX += parseInt(currentStyle.marginLeft) || 0; + offsetY += parseInt(currentStyle.marginTop) || 0; + } + } + } + currentStyle = Sys.UI.DomElement._getCurrentStyle(element); + var elementPosition = currentStyle ? currentStyle.position : null; + if (!elementPosition || (elementPosition !== "absolute")) { + for (var parent = element.parentNode; parent; parent = parent.parentNode) { + tagName = parent.tagName ? parent.tagName.toUpperCase() : null; + if ((tagName !== "BODY") && (tagName !== "HTML") && (parent.scrollLeft || parent.scrollTop)) { + offsetX -= (parent.scrollLeft || 0); + offsetY -= (parent.scrollTop || 0); + currentStyle = Sys.UI.DomElement._getCurrentStyle(parent); + if (currentStyle) { + offsetX += parseInt(currentStyle.borderLeftWidth) || 0; + offsetY += parseInt(currentStyle.borderTopWidth) || 0; + } + } + } + } + return new Sys.UI.Point(offsetX, offsetY); + } + break; +} +Sys.UI.DomElement.removeCssClass = function Sys$UI$DomElement$removeCssClass(element, className) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true}, + {name: "className", type: String} + ]); + if (e) throw e; + var currentClassName = ' ' + element.className + ' '; + var index = currentClassName.indexOf(' ' + className + ' '); + if (index >= 0) { + element.className = (currentClassName.substr(0, index) + ' ' + + currentClassName.substring(index + className.length + 1, currentClassName.length)).trim(); + } +} +Sys.UI.DomElement.setLocation = function Sys$UI$DomElement$setLocation(element, x, y) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true}, + {name: "x", type: Number, integer: true}, + {name: "y", type: Number, integer: true} + ]); + if (e) throw e; + var style = element.style; + style.position = 'absolute'; + style.left = x + "px"; + style.top = y + "px"; +} +Sys.UI.DomElement.toggleCssClass = function Sys$UI$DomElement$toggleCssClass(element, className) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true}, + {name: "className", type: String} + ]); + if (e) throw e; + if (Sys.UI.DomElement.containsCssClass(element, className)) { + Sys.UI.DomElement.removeCssClass(element, className); + } + else { + Sys.UI.DomElement.addCssClass(element, className); + } +} +Sys.UI.DomElement.getVisibilityMode = function Sys$UI$DomElement$getVisibilityMode(element) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true} + ]); + if (e) throw e; + return (element._visibilityMode === Sys.UI.VisibilityMode.hide) ? + Sys.UI.VisibilityMode.hide : + Sys.UI.VisibilityMode.collapse; +} +Sys.UI.DomElement.setVisibilityMode = function Sys$UI$DomElement$setVisibilityMode(element, value) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true}, + {name: "value", type: Sys.UI.VisibilityMode} + ]); + if (e) throw e; + Sys.UI.DomElement._ensureOldDisplayMode(element); + if (element._visibilityMode !== value) { + element._visibilityMode = value; + if (Sys.UI.DomElement.getVisible(element) === false) { + if (element._visibilityMode === Sys.UI.VisibilityMode.hide) { + element.style.display = element._oldDisplayMode; + } + else { + element.style.display = 'none'; + } + } + element._visibilityMode = value; + } +} +Sys.UI.DomElement.getVisible = function Sys$UI$DomElement$getVisible(element) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true} + ]); + if (e) throw e; + var style = element.currentStyle || Sys.UI.DomElement._getCurrentStyle(element); + if (!style) return true; + return (style.visibility !== 'hidden') && (style.display !== 'none'); +} +Sys.UI.DomElement.setVisible = function Sys$UI$DomElement$setVisible(element, value) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true}, + {name: "value", type: Boolean} + ]); + if (e) throw e; + if (value !== Sys.UI.DomElement.getVisible(element)) { + Sys.UI.DomElement._ensureOldDisplayMode(element); + element.style.visibility = value ? 'visible' : 'hidden'; + if (value || (element._visibilityMode === Sys.UI.VisibilityMode.hide)) { + element.style.display = element._oldDisplayMode; + } + else { + element.style.display = 'none'; + } + } +} +Sys.UI.DomElement._ensureOldDisplayMode = function Sys$UI$DomElement$_ensureOldDisplayMode(element) { + if (!element._oldDisplayMode) { + var style = element.currentStyle || Sys.UI.DomElement._getCurrentStyle(element); + element._oldDisplayMode = style ? style.display : null; + if (!element._oldDisplayMode || element._oldDisplayMode === 'none') { + switch(element.tagName.toUpperCase()) { + case 'DIV': case 'P': case 'ADDRESS': case 'BLOCKQUOTE': case 'BODY': case 'COL': + case 'COLGROUP': case 'DD': case 'DL': case 'DT': case 'FIELDSET': case 'FORM': + case 'H1': case 'H2': case 'H3': case 'H4': case 'H5': case 'H6': case 'HR': + case 'IFRAME': case 'LEGEND': case 'OL': case 'PRE': case 'TABLE': case 'TD': + case 'TH': case 'TR': case 'UL': + element._oldDisplayMode = 'block'; + break; + case 'LI': + element._oldDisplayMode = 'list-item'; + break; + default: + element._oldDisplayMode = 'inline'; + } + } + } +} +Sys.UI.DomElement._getWindow = function Sys$UI$DomElement$_getWindow(element) { + var doc = element.ownerDocument || element.document || element; + return doc.defaultView || doc.parentWindow; +} +Sys.UI.DomElement._getCurrentStyle = function Sys$UI$DomElement$_getCurrentStyle(element) { + if (element.nodeType === 3) return null; + var w = Sys.UI.DomElement._getWindow(element); + if (element.documentElement) element = element.documentElement; + var computedStyle = (w && (element !== w) && w.getComputedStyle) ? + w.getComputedStyle(element, null) : + element.currentStyle || element.style; + if (!computedStyle && (Sys.Browser.agent === Sys.Browser.Safari) && element.style) { + var oldDisplay = element.style.display; + var oldPosition = element.style.position; + element.style.position = 'absolute'; + element.style.display = 'block'; + var style = w.getComputedStyle(element, null); + element.style.display = oldDisplay; + element.style.position = oldPosition; + computedStyle = {}; + for (var n in style) { + computedStyle[n] = style[n]; + } + computedStyle.display = 'none'; + } + return computedStyle; +} + +Sys.IContainer = function Sys$IContainer() { + throw Error.notImplemented(); +} + function Sys$IContainer$addComponent(component) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "component", type: Sys.Component} + ]); + if (e) throw e; + throw Error.notImplemented(); + } + function Sys$IContainer$removeComponent(component) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "component", type: Sys.Component} + ]); + if (e) throw e; + throw Error.notImplemented(); + } + function Sys$IContainer$findComponent(id) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "id", type: String} + ]); + if (e) throw e; + throw Error.notImplemented(); + } + function Sys$IContainer$getComponents() { + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); + } +Sys.IContainer.prototype = { + addComponent: Sys$IContainer$addComponent, + removeComponent: Sys$IContainer$removeComponent, + findComponent: Sys$IContainer$findComponent, + getComponents: Sys$IContainer$getComponents +} +Sys.IContainer.registerInterface("Sys.IContainer"); + +Sys._ScriptLoader = function Sys$_ScriptLoader() { + this._scriptsToLoad = null; + this._sessions = []; + this._scriptLoadedDelegate = Function.createDelegate(this, this._scriptLoadedHandler); +} + function Sys$_ScriptLoader$dispose() { + this._stopSession(); + this._loading = false; + if(this._events) { + delete this._events; + } + this._sessions = null; + this._currentSession = null; + this._scriptLoadedDelegate = null; + } + function Sys$_ScriptLoader$loadScripts(scriptTimeout, allScriptsLoadedCallback, scriptLoadFailedCallback, scriptLoadTimeoutCallback) { + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "scriptTimeout", type: Number, integer: true}, + {name: "allScriptsLoadedCallback", type: Function, mayBeNull: true}, + {name: "scriptLoadFailedCallback", type: Function, mayBeNull: true}, + {name: "scriptLoadTimeoutCallback", type: Function, mayBeNull: true} + ]); + if (e) throw e; + var session = { + allScriptsLoadedCallback: allScriptsLoadedCallback, + scriptLoadFailedCallback: scriptLoadFailedCallback, + scriptLoadTimeoutCallback: scriptLoadTimeoutCallback, + scriptsToLoad: this._scriptsToLoad, + scriptTimeout: scriptTimeout }; + this._scriptsToLoad = null; + this._sessions[this._sessions.length] = session; + + if (!this._loading) { + this._nextSession(); + } + } + function Sys$_ScriptLoader$notifyScriptLoaded() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + + if(!this._loading) { + return; + } + this._currentTask._notified++; + + if(Sys.Browser.agent === Sys.Browser.Safari) { + if(this._currentTask._notified === 1) { + window.setTimeout(Function.createDelegate(this, function() { + this._scriptLoadedHandler(this._currentTask.get_scriptElement(), true); + }), 0); + } + } + } + function Sys$_ScriptLoader$queueCustomScriptTag(scriptAttributes) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "scriptAttributes"} + ]); + if (e) throw e; + if(!this._scriptsToLoad) { + this._scriptsToLoad = []; + } + Array.add(this._scriptsToLoad, scriptAttributes); + } + function Sys$_ScriptLoader$queueScriptBlock(scriptContent) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "scriptContent", type: String} + ]); + if (e) throw e; + if(!this._scriptsToLoad) { + this._scriptsToLoad = []; + } + Array.add(this._scriptsToLoad, {text: scriptContent}); + } + function Sys$_ScriptLoader$queueScriptReference(scriptUrl) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "scriptUrl", type: String} + ]); + if (e) throw e; + if(!this._scriptsToLoad) { + this._scriptsToLoad = []; + } + Array.add(this._scriptsToLoad, {src: scriptUrl}); + } + function Sys$_ScriptLoader$_createScriptElement(queuedScript) { + var scriptElement = document.createElement('script'); + scriptElement.type = 'text/javascript'; + for (var attr in queuedScript) { + scriptElement[attr] = queuedScript[attr]; + } + + return scriptElement; + } + function Sys$_ScriptLoader$_loadScriptsInternal() { + var session = this._currentSession; + if (session.scriptsToLoad && session.scriptsToLoad.length > 0) { + var nextScript = Array.dequeue(session.scriptsToLoad); + var scriptElement = this._createScriptElement(nextScript); + + if (scriptElement.text && Sys.Browser.agent === Sys.Browser.Safari) { + scriptElement.innerHTML = scriptElement.text; + delete scriptElement.text; + } + if (typeof(nextScript.src) === "string") { + this._currentTask = new Sys._ScriptLoaderTask(scriptElement, this._scriptLoadedDelegate); + this._currentTask.execute(); + } + else { + var headElements = document.getElementsByTagName('head'); + if (headElements.length === 0) { + throw new Error.invalidOperation(Sys.Res.scriptLoadFailedNoHead); + } + else { + headElements[0].appendChild(scriptElement); + } + + + Sys._ScriptLoader._clearScript(scriptElement); + this._loadScriptsInternal(); + } + } + else { + this._stopSession(); + var callback = session.allScriptsLoadedCallback; + if(callback) { + callback(this); + } + this._nextSession(); + } + } + function Sys$_ScriptLoader$_nextSession() { + if (this._sessions.length === 0) { + this._loading = false; + this._currentSession = null; + return; + } + this._loading = true; + + var session = Array.dequeue(this._sessions); + this._currentSession = session; + this._loadScriptsInternal(); + } + function Sys$_ScriptLoader$_raiseError(multipleCallbacks) { + var callback = this._currentSession.scriptLoadFailedCallback; + var scriptElement = this._currentTask.get_scriptElement(); + this._stopSession(); + + if(callback) { + callback(this, scriptElement, multipleCallbacks); + this._nextSession(); + } + else { + this._loading = false; + throw Sys._ScriptLoader._errorScriptLoadFailed(scriptElement.src, multipleCallbacks); + } + } + function Sys$_ScriptLoader$_scriptLoadedHandler(scriptElement, loaded) { + if(loaded && this._currentTask._notified) { + if(this._currentTask._notified > 1) { + this._raiseError(true); + } + else { + Array.add(Sys._ScriptLoader._getLoadedScripts(), scriptElement.src); + this._currentTask.dispose(); + this._currentTask = null; + this._loadScriptsInternal(); + } + } + else { + this._raiseError(false); + } + } + function Sys$_ScriptLoader$_scriptLoadTimeoutHandler() { + var callback = this._currentSession.scriptLoadTimeoutCallback; + this._stopSession(); + if(callback) { + callback(this); + } + this._nextSession(); + } + function Sys$_ScriptLoader$_stopSession() { + if(this._currentTask) { + this._currentTask.dispose(); + this._currentTask = null; + } + } +Sys._ScriptLoader.prototype = { + dispose: Sys$_ScriptLoader$dispose, + loadScripts: Sys$_ScriptLoader$loadScripts, + notifyScriptLoaded: Sys$_ScriptLoader$notifyScriptLoaded, + queueCustomScriptTag: Sys$_ScriptLoader$queueCustomScriptTag, + queueScriptBlock: Sys$_ScriptLoader$queueScriptBlock, + queueScriptReference: Sys$_ScriptLoader$queueScriptReference, + _createScriptElement: Sys$_ScriptLoader$_createScriptElement, + _loadScriptsInternal: Sys$_ScriptLoader$_loadScriptsInternal, + _nextSession: Sys$_ScriptLoader$_nextSession, + _raiseError: Sys$_ScriptLoader$_raiseError, + _scriptLoadedHandler: Sys$_ScriptLoader$_scriptLoadedHandler, + _scriptLoadTimeoutHandler: Sys$_ScriptLoader$_scriptLoadTimeoutHandler, + _stopSession: Sys$_ScriptLoader$_stopSession +} +Sys._ScriptLoader.registerClass('Sys._ScriptLoader', null, Sys.IDisposable); +Sys._ScriptLoader.getInstance = function Sys$_ScriptLoader$getInstance() { + var sl = Sys._ScriptLoader._activeInstance; + if(!sl) { + sl = Sys._ScriptLoader._activeInstance = new Sys._ScriptLoader(); + } + return sl; +} +Sys._ScriptLoader.isScriptLoaded = function Sys$_ScriptLoader$isScriptLoaded(scriptSrc) { + var dummyScript = document.createElement('script'); + dummyScript.src = scriptSrc; + return Array.contains(Sys._ScriptLoader._getLoadedScripts(), dummyScript.src); +} +Sys._ScriptLoader.readLoadedScripts = function Sys$_ScriptLoader$readLoadedScripts() { + if(!Sys._ScriptLoader._referencedScripts) { + var referencedScripts = Sys._ScriptLoader._referencedScripts = []; + var existingScripts = document.getElementsByTagName('script'); + for (i = existingScripts.length - 1; i >= 0; i--) { + var scriptNode = existingScripts[i]; + var scriptSrc = scriptNode.src; + if (scriptSrc.length) { + if (!Array.contains(referencedScripts, scriptSrc)) { + Array.add(referencedScripts, scriptSrc); + } + } + } + } +} +Sys._ScriptLoader._clearScript = function Sys$_ScriptLoader$_clearScript(scriptElement) { + if (!Sys.Debug.isDebug) { + scriptElement.parentNode.removeChild(scriptElement); + } +} +Sys._ScriptLoader._errorScriptLoadFailed = function Sys$_ScriptLoader$_errorScriptLoadFailed(scriptUrl, multipleCallbacks) { + var errorMessage; + if(multipleCallbacks) { + errorMessage = Sys.Res.scriptLoadMultipleCallbacks; + } + else { + errorMessage = Sys.Res.scriptLoadFailedDebug; + } + var displayMessage = "Sys.ScriptLoadFailedException: " + String.format(errorMessage, scriptUrl); + var e = Error.create(displayMessage, {name: 'Sys.ScriptLoadFailedException', 'scriptUrl': scriptUrl }); + e.popStackFrame(); + return e; +} +Sys._ScriptLoader._getLoadedScripts = function Sys$_ScriptLoader$_getLoadedScripts() { + if(!Sys._ScriptLoader._referencedScripts) { + Sys._ScriptLoader._referencedScripts = []; + Sys._ScriptLoader.readLoadedScripts(); + } + return Sys._ScriptLoader._referencedScripts; +} + +Sys._ScriptLoaderTask = function Sys$_ScriptLoaderTask(scriptElement, completedCallback) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "scriptElement", domElement: true}, + {name: "completedCallback", type: Function} + ]); + if (e) throw e; + this._scriptElement = scriptElement; + this._completedCallback = completedCallback; + this._notified = 0; +} + function Sys$_ScriptLoaderTask$get_scriptElement() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._scriptElement; + } + function Sys$_ScriptLoaderTask$dispose() { + if(this._disposed) { + return; + } + this._disposed = true; + this._removeScriptElementHandlers(); + Sys._ScriptLoader._clearScript(this._scriptElement); + this._scriptElement = null; + } + function Sys$_ScriptLoaderTask$execute() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + this._addScriptElementHandlers(); + var headElements = document.getElementsByTagName('head'); + if (headElements.length === 0) { + throw new Error.invalidOperation(Sys.Res.scriptLoadFailedNoHead); + } + else { + headElements[0].appendChild(this._scriptElement); + } + } + function Sys$_ScriptLoaderTask$_addScriptElementHandlers() { + this._scriptLoadDelegate = Function.createDelegate(this, this._scriptLoadHandler); + + if (Sys.Browser.agent !== Sys.Browser.InternetExplorer) { + this._scriptElement.readyState = 'loaded'; + $addHandler(this._scriptElement, 'load', this._scriptLoadDelegate); + } + else { + $addHandler(this._scriptElement, 'readystatechange', this._scriptLoadDelegate); + } + if (this._scriptElement.addEventListener) { + this._scriptErrorDelegate = Function.createDelegate(this, this._scriptErrorHandler); + this._scriptElement.addEventListener('error', this._scriptErrorDelegate, false); + } + } + function Sys$_ScriptLoaderTask$_removeScriptElementHandlers() { + if(this._scriptLoadDelegate) { + var scriptElement = this.get_scriptElement(); + if (Sys.Browser.agent !== Sys.Browser.InternetExplorer) { + $removeHandler(scriptElement, 'load', this._scriptLoadDelegate); + } + else { + $removeHandler(scriptElement, 'readystatechange', this._scriptLoadDelegate); + } + if (this._scriptErrorDelegate) { + this._scriptElement.removeEventListener('error', this._scriptErrorDelegate, false); + this._scriptErrorDelegate = null; + } + this._scriptLoadDelegate = null; + } + } + function Sys$_ScriptLoaderTask$_scriptErrorHandler() { + if(this._disposed) { + return; + } + + this._completedCallback(this.get_scriptElement(), false); + } + function Sys$_ScriptLoaderTask$_scriptLoadHandler() { + if(this._disposed) { + return; + } + var scriptElement = this.get_scriptElement(); + if ((scriptElement.readyState !== 'loaded') && + (scriptElement.readyState !== 'complete')) { + return; + } + + var _this = this; + window.setTimeout(function() { + _this._completedCallback(scriptElement, true); + }, 0); + } +Sys._ScriptLoaderTask.prototype = { + get_scriptElement: Sys$_ScriptLoaderTask$get_scriptElement, + dispose: Sys$_ScriptLoaderTask$dispose, + execute: Sys$_ScriptLoaderTask$execute, + _addScriptElementHandlers: Sys$_ScriptLoaderTask$_addScriptElementHandlers, + _removeScriptElementHandlers: Sys$_ScriptLoaderTask$_removeScriptElementHandlers, + _scriptErrorHandler: Sys$_ScriptLoaderTask$_scriptErrorHandler, + _scriptLoadHandler: Sys$_ScriptLoaderTask$_scriptLoadHandler +} +Sys._ScriptLoaderTask.registerClass("Sys._ScriptLoaderTask", null, Sys.IDisposable); + +Sys.ApplicationLoadEventArgs = function Sys$ApplicationLoadEventArgs(components, isPartialLoad) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "components", type: Array, elementType: Sys.Component}, + {name: "isPartialLoad", type: Boolean} + ]); + if (e) throw e; + Sys.ApplicationLoadEventArgs.initializeBase(this); + this._components = components; + this._isPartialLoad = isPartialLoad; +} + + function Sys$ApplicationLoadEventArgs$get_components() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._components; + } + function Sys$ApplicationLoadEventArgs$get_isPartialLoad() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._isPartialLoad; + } +Sys.ApplicationLoadEventArgs.prototype = { + get_components: Sys$ApplicationLoadEventArgs$get_components, + get_isPartialLoad: Sys$ApplicationLoadEventArgs$get_isPartialLoad +} +Sys.ApplicationLoadEventArgs.registerClass('Sys.ApplicationLoadEventArgs', Sys.EventArgs); +Sys.HistoryEventArgs = function Sys$HistoryEventArgs(state) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "state", type: Object} + ]); + if (e) throw e; + Sys.HistoryEventArgs.initializeBase(this); + this._state = state; +} + function Sys$HistoryEventArgs$get_state() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._state; + } +Sys.HistoryEventArgs.prototype = { + get_state: Sys$HistoryEventArgs$get_state +} +Sys.HistoryEventArgs.registerClass('Sys.HistoryEventArgs', Sys.EventArgs); + +Sys._Application = function Sys$_Application() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + Sys._Application.initializeBase(this); + this._disposableObjects = []; + this._components = {}; + this._createdComponents = []; + this._secondPassComponents = []; + this._appLoadHandler = null; + this._beginRequestHandler = null; + this._clientId = null; + this._currentEntry = ''; + this._endRequestHandler = null; + this._history = null; + this._enableHistory = false; + this._historyEnabledInScriptManager = false; + this._historyFrame = null; + this._historyInitialized = false; + this._historyInitialLength = 0; + this._historyLength = 0; + this._historyPointIsNew = false; + this._ignoreTimer = false; + this._initialState = null; + this._state = {}; + this._timerCookie = 0; + this._timerHandler = null; + this._uniqueId = null; + this._unloadHandlerDelegate = Function.createDelegate(this, this._unloadHandler); + this._loadHandlerDelegate = Function.createDelegate(this, this._loadHandler); + Sys.UI.DomEvent.addHandler(window, "unload", this._unloadHandlerDelegate); + Sys.UI.DomEvent.addHandler(window, "load", this._loadHandlerDelegate); +} + function Sys$_Application$get_isCreatingComponents() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._creatingComponents; + } + function Sys$_Application$get_stateString() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + var hash = window.location.hash; + if (this._isSafari2()) { + var history = this._getHistory(); + if (history) { + hash = history[window.history.length - this._historyInitialLength]; + } + } + if ((hash.length > 0) && (hash.charAt(0) === '#')) { + hash = hash.substring(1); + } + if (Sys.Browser.agent === Sys.Browser.Firefox) { + hash = this._serializeState(this._deserializeState(hash, true)); + } + return hash; + } + function Sys$_Application$get_enableHistory() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._enableHistory; + } + function Sys$_Application$set_enableHistory(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Boolean}]); + if (e) throw e; + if (this._initialized && !this._initializing) { + throw Error.invalidOperation(Sys.Res.historyCannotEnableHistory); + } + else if (this._historyEnabledInScriptManager && !value) { + throw Error.invalidOperation(Sys.Res.invalidHistorySettingCombination); + } + this._enableHistory = value; + } + function Sys$_Application$add_init(handler) { + /// + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + if (this._initialized) { + handler(this, Sys.EventArgs.Empty); + } + else { + this.get_events().addHandler("init", handler); + } + } + function Sys$_Application$remove_init(handler) { + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this.get_events().removeHandler("init", handler); + } + function Sys$_Application$add_load(handler) { + /// + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this.get_events().addHandler("load", handler); + } + function Sys$_Application$remove_load(handler) { + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this.get_events().removeHandler("load", handler); + } + function Sys$_Application$add_navigate(handler) { + /// + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this.get_events().addHandler("navigate", handler); + } + function Sys$_Application$remove_navigate(handler) { + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this.get_events().removeHandler("navigate", handler); + } + function Sys$_Application$add_unload(handler) { + /// + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this.get_events().addHandler("unload", handler); + } + function Sys$_Application$remove_unload(handler) { + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this.get_events().removeHandler("unload", handler); + } + function Sys$_Application$addComponent(component) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "component", type: Sys.Component} + ]); + if (e) throw e; + var id = component.get_id(); + if (!id) throw Error.invalidOperation(Sys.Res.cantAddWithoutId); + if (typeof(this._components[id]) !== 'undefined') throw Error.invalidOperation(String.format(Sys.Res.appDuplicateComponent, id)); + this._components[id] = component; + } + function Sys$_Application$addHistoryPoint(state, title) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "state", type: Object}, + {name: "title", type: String, mayBeNull: true, optional: true} + ]); + if (e) throw e; + if (!this._enableHistory) throw Error.invalidOperation(Sys.Res.historyCannotAddHistoryPointWithHistoryDisabled); + for (var n in state) { + var v = state[n]; + var t = typeof(v); + if ((v !== null) && ((t === 'object') || (t === 'function') || (t === 'undefined'))) { + throw Error.argument('state', Sys.Res.stateMustBeStringDictionary); + } + } + this._ensureHistory(); + var initialState = this._state; + for (var key in state) { + var value = state[key]; + if (value === null) { + if (typeof(initialState[key]) !== 'undefined') { + delete initialState[key]; + } + } + else { + initialState[key] = value; + } + } + var entry = this._serializeState(initialState); + this._historyPointIsNew = true; + this._setState(entry, title); + this._raiseNavigate(); + } + function Sys$_Application$beginCreateComponents() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + this._creatingComponents = true; + } + function Sys$_Application$dispose() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (!this._disposing) { + this._disposing = true; + if (this._timerCookie) { + window.clearTimeout(this._timerCookie); + delete this._timerCookie; + } + if (this._endRequestHandler) { + Sys.WebForms.PageRequestManager.getInstance().remove_endRequest(this._endRequestHandler); + delete this._endRequestHandler; + } + if (this._beginRequestHandler) { + Sys.WebForms.PageRequestManager.getInstance().remove_beginRequest(this._beginRequestHandler); + delete this._beginRequestHandler; + } + if (window.pageUnload) { + window.pageUnload(this, Sys.EventArgs.Empty); + } + var unloadHandler = this.get_events().getHandler("unload"); + if (unloadHandler) { + unloadHandler(this, Sys.EventArgs.Empty); + } + var disposableObjects = Array.clone(this._disposableObjects); + for (var i = 0, l = disposableObjects.length; i < l; i++) { + disposableObjects[i].dispose(); + } + Array.clear(this._disposableObjects); + Sys.UI.DomEvent.removeHandler(window, "unload", this._unloadHandlerDelegate); + if(this._loadHandlerDelegate) { + Sys.UI.DomEvent.removeHandler(window, "load", this._loadHandlerDelegate); + this._loadHandlerDelegate = null; + } + var sl = Sys._ScriptLoader.getInstance(); + if(sl) { + sl.dispose(); + } + Sys._Application.callBaseMethod(this, 'dispose'); + } + } + function Sys$_Application$endCreateComponents() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + var components = this._secondPassComponents; + for (var i = 0, l = components.length; i < l; i++) { + var component = components[i].component; + Sys$Component$_setReferences(component, components[i].references); + component.endUpdate(); + } + this._secondPassComponents = []; + this._creatingComponents = false; + } + function Sys$_Application$findComponent(id, parent) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "id", type: String}, + {name: "parent", mayBeNull: true, optional: true} + ]); + if (e) throw e; + return (parent ? + ((Sys.IContainer.isInstanceOfType(parent)) ? + parent.findComponent(id) : + parent[id] || null) : + Sys.Application._components[id] || null); + } + function Sys$_Application$getComponents() { + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + var res = []; + var components = this._components; + for (var name in components) { + res[res.length] = components[name]; + } + return res; + } + function Sys$_Application$initialize() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if(!this._initialized && !this._initializing) { + this._initializing = true; + window.setTimeout(Function.createDelegate(this, this._doInitialize), 0); + } + } + function Sys$_Application$notifyScriptLoaded() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + var sl = Sys._ScriptLoader.getInstance(); + if(sl) { + sl.notifyScriptLoaded(); + } + } + function Sys$_Application$registerDisposableObject(object) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "object", type: Sys.IDisposable} + ]); + if (e) throw e; + if (!this._disposing) { + this._disposableObjects[this._disposableObjects.length] = object; + } + } + function Sys$_Application$raiseLoad() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + var h = this.get_events().getHandler("load"); + var args = new Sys.ApplicationLoadEventArgs(Array.clone(this._createdComponents), !this._initializing); + if (h) { + h(this, args); + } + if (window.pageLoad) { + window.pageLoad(this, args); + } + this._createdComponents = []; + } + function Sys$_Application$removeComponent(component) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "component", type: Sys.Component} + ]); + if (e) throw e; + var id = component.get_id(); + if (id) delete this._components[id]; + } + function Sys$_Application$setServerId(clientId, uniqueId) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "clientId", type: String}, + {name: "uniqueId", type: String} + ]); + if (e) throw e; + this._clientId = clientId; + this._uniqueId = uniqueId; + } + function Sys$_Application$setServerState(value) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "value", type: String} + ]); + if (e) throw e; + this._ensureHistory(); + this._state.__s = value; + this._updateHiddenField(value); + } + function Sys$_Application$unregisterDisposableObject(object) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "object", type: Sys.IDisposable} + ]); + if (e) throw e; + if (!this._disposing) { + Array.remove(this._disposableObjects, object); + } + } + function Sys$_Application$_addComponentToSecondPass(component, references) { + this._secondPassComponents[this._secondPassComponents.length] = {component: component, references: references}; + } + function Sys$_Application$_deserializeState(entry, skipDecodeUri) { + var result = {}; + entry = entry || ''; + var serverSeparator = entry.indexOf('&&'); + if ((serverSeparator !== -1) && (serverSeparator + 2 < entry.length)) { + result.__s = entry.substr(serverSeparator + 2); + entry = entry.substr(0, serverSeparator); + } + var tokens = entry.split('&'); + for (var i = 0, l = tokens.length; i < l; i++) { + var token = tokens[i]; + var equal = token.indexOf('='); + if ((equal !== -1) && (equal + 1 < token.length)) { + var name = token.substr(0, equal); + var value = token.substr(equal + 1); + result[name] = skipDecodeUri ? value : decodeURIComponent(value); + } + } + return result; + } + function Sys$_Application$_doInitialize() { + Sys._Application.callBaseMethod(this, 'initialize'); + + var handler = this.get_events().getHandler("init"); + if (handler) { + this.beginCreateComponents(); + handler(this, Sys.EventArgs.Empty); + this.endCreateComponents(); + } + if (Sys.WebForms) { + this._beginRequestHandler = Function.createDelegate(this, this._onPageRequestManagerBeginRequest); + Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(this._beginRequestHandler); + this._endRequestHandler = Function.createDelegate(this, this._onPageRequestManagerEndRequest); + Sys.WebForms.PageRequestManager.getInstance().add_endRequest(this._endRequestHandler); + } + + var loadedEntry = this.get_stateString(); + if (loadedEntry !== this._currentEntry) { + this._navigate(loadedEntry); + } + + this.raiseLoad(); + this._initializing = false; + } + function Sys$_Application$_enableHistoryInScriptManager() { + this._enableHistory = true; + this._historyEnabledInScriptManager = true; + } + function Sys$_Application$_ensureHistory() { + if (!this._historyInitialized && this._enableHistory) { + if ((Sys.Browser.agent === Sys.Browser.InternetExplorer) && (Sys.Browser.documentMode < 8)) { + this._historyFrame = document.getElementById('__historyFrame'); + if (!this._historyFrame) throw Error.invalidOperation(Sys.Res.historyMissingFrame); + this._ignoreIFrame = true; + } + if (this._isSafari2()) { + var historyElement = document.getElementById('__history'); + if (!historyElement) throw Error.invalidOperation(Sys.Res.historyMissingHiddenInput); + this._setHistory([window.location.hash]); + this._historyInitialLength = window.history.length; + } + + this._timerHandler = Function.createDelegate(this, this._onIdle); + this._timerCookie = window.setTimeout(this._timerHandler, 100); + + try { + this._initialState = this._deserializeState(this.get_stateString()); + } catch(e) {} + + this._historyInitialized = true; + } + } + function Sys$_Application$_getHistory() { + var historyElement = document.getElementById('__history'); + if (!historyElement) return ''; + var v = historyElement.value; + return v ? Sys.Serialization.JavaScriptSerializer.deserialize(v, true) : ''; + } + function Sys$_Application$_isSafari2() { + return (Sys.Browser.agent === Sys.Browser.Safari) && + (Sys.Browser.version <= 419.3); + } + function Sys$_Application$_loadHandler() { + if(this._loadHandlerDelegate) { + Sys.UI.DomEvent.removeHandler(window, "load", this._loadHandlerDelegate); + this._loadHandlerDelegate = null; + } + this.initialize(); + } + function Sys$_Application$_navigate(entry) { + this._ensureHistory(); + var state = this._deserializeState(entry); + + if (this._uniqueId) { + var oldServerEntry = this._state.__s || ''; + var newServerEntry = state.__s || ''; + if (newServerEntry !== oldServerEntry) { + this._updateHiddenField(newServerEntry); + __doPostBack(this._uniqueId, newServerEntry); + this._state = state; + return; + } + } + this._setState(entry); + this._state = state; + this._raiseNavigate(); + } + function Sys$_Application$_onIdle() { + delete this._timerCookie; + + var entry = this.get_stateString(); + if (entry !== this._currentEntry) { + if (!this._ignoreTimer) { + this._historyPointIsNew = false; + this._navigate(entry); + this._historyLength = window.history.length; + } + } + else { + this._ignoreTimer = false; + } + this._timerCookie = window.setTimeout(this._timerHandler, 100); + } + function Sys$_Application$_onIFrameLoad(entry) { + this._ensureHistory(); + if (!this._ignoreIFrame) { + this._historyPointIsNew = false; + this._navigate(entry); + } + this._ignoreIFrame = false; + } + function Sys$_Application$_onPageRequestManagerBeginRequest(sender, args) { + this._ignoreTimer = true; + } + function Sys$_Application$_onPageRequestManagerEndRequest(sender, args) { + var dataItem = args.get_dataItems()[this._clientId]; + var eventTarget = document.getElementById("__EVENTTARGET"); + if (eventTarget && eventTarget.value === this._uniqueId) { + eventTarget.value = ''; + } + if (typeof(dataItem) !== 'undefined') { + this.setServerState(dataItem); + this._historyPointIsNew = true; + } + else { + this._ignoreTimer = false; + } + var entry = this._serializeState(this._state); + if (entry !== this._currentEntry) { + this._ignoreTimer = true; + this._setState(entry); + this._raiseNavigate(); + } + } + function Sys$_Application$_raiseNavigate() { + var h = this.get_events().getHandler("navigate"); + var stateClone = {}; + for (var key in this._state) { + if (key !== '__s') { + stateClone[key] = this._state[key]; + } + } + var args = new Sys.HistoryEventArgs(stateClone); + if (h) { + h(this, args); + } + } + function Sys$_Application$_serializeState(state) { + var serialized = []; + for (var key in state) { + var value = state[key]; + if (key === '__s') { + var serverState = value; + } + else { + if (key.indexOf('=') !== -1) throw Error.argument('state', Sys.Res.stateFieldNameInvalid); + serialized[serialized.length] = key + '=' + encodeURIComponent(value); + } + } + return serialized.join('&') + (serverState ? '&&' + serverState : ''); + } + function Sys$_Application$_setHistory(historyArray) { + var historyElement = document.getElementById('__history'); + if (historyElement) { + historyElement.value = Sys.Serialization.JavaScriptSerializer.serialize(historyArray); + } + } + function Sys$_Application$_setState(entry, title) { + entry = entry || ''; + if (entry !== this._currentEntry) { + if (window.theForm) { + var action = window.theForm.action; + var hashIndex = action.indexOf('#'); + window.theForm.action = ((hashIndex !== -1) ? action.substring(0, hashIndex) : action) + '#' + entry; + } + + if (this._historyFrame && this._historyPointIsNew) { + this._ignoreIFrame = true; + this._historyPointIsNew = false; + var frameDoc = this._historyFrame.contentWindow.document; + frameDoc.open("javascript:''"); + frameDoc.write("" + (title || document.title) + + "parent.Sys.Application._onIFrameLoad('" + + entry + "');"); + frameDoc.close(); + } + this._ignoreTimer = false; + var currentHash = this.get_stateString(); + this._currentEntry = entry; + if (entry !== currentHash) { + var loc = document.location; + if (loc.href.length - loc.hash.length + entry.length > 1024) { + throw Error.invalidOperation(Sys.Res.urlMustBeLessThan1024chars); + } + if (this._isSafari2()) { + var history = this._getHistory(); + history[window.history.length - this._historyInitialLength + 1] = entry; + this._setHistory(history); + this._historyLength = window.history.length + 1; + var form = document.createElement('form'); + form.method = 'get'; + form.action = '#' + entry; + document.appendChild(form); + form.submit(); + document.removeChild(form); + } + else { + window.location.hash = entry; + } + if ((typeof(title) !== 'undefined') && (title !== null)) { + document.title = title; + } + } + } + } + function Sys$_Application$_unloadHandler(event) { + this.dispose(); + } + function Sys$_Application$_updateHiddenField(value) { + if (this._clientId) { + var serverStateField = document.getElementById(this._clientId); + if (serverStateField) { + serverStateField.value = value; + } + } + } +Sys._Application.prototype = { + _creatingComponents: false, + _disposing: false, + get_isCreatingComponents: Sys$_Application$get_isCreatingComponents, + get_stateString: Sys$_Application$get_stateString, + get_enableHistory: Sys$_Application$get_enableHistory, + set_enableHistory: Sys$_Application$set_enableHistory, + add_init: Sys$_Application$add_init, + remove_init: Sys$_Application$remove_init, + add_load: Sys$_Application$add_load, + remove_load: Sys$_Application$remove_load, + add_navigate: Sys$_Application$add_navigate, + remove_navigate: Sys$_Application$remove_navigate, + add_unload: Sys$_Application$add_unload, + remove_unload: Sys$_Application$remove_unload, + addComponent: Sys$_Application$addComponent, + addHistoryPoint: Sys$_Application$addHistoryPoint, + beginCreateComponents: Sys$_Application$beginCreateComponents, + dispose: Sys$_Application$dispose, + endCreateComponents: Sys$_Application$endCreateComponents, + findComponent: Sys$_Application$findComponent, + getComponents: Sys$_Application$getComponents, + initialize: Sys$_Application$initialize, + notifyScriptLoaded: Sys$_Application$notifyScriptLoaded, + registerDisposableObject: Sys$_Application$registerDisposableObject, + raiseLoad: Sys$_Application$raiseLoad, + removeComponent: Sys$_Application$removeComponent, + setServerId: Sys$_Application$setServerId, + setServerState: Sys$_Application$setServerState, + unregisterDisposableObject: Sys$_Application$unregisterDisposableObject, + _addComponentToSecondPass: Sys$_Application$_addComponentToSecondPass, + _deserializeState: Sys$_Application$_deserializeState, + _doInitialize: Sys$_Application$_doInitialize, + _enableHistoryInScriptManager: Sys$_Application$_enableHistoryInScriptManager, + _ensureHistory: Sys$_Application$_ensureHistory, + _getHistory: Sys$_Application$_getHistory, + _isSafari2: Sys$_Application$_isSafari2, + _loadHandler: Sys$_Application$_loadHandler, + _navigate: Sys$_Application$_navigate, + _onIdle: Sys$_Application$_onIdle, + _onIFrameLoad: Sys$_Application$_onIFrameLoad, + _onPageRequestManagerBeginRequest: Sys$_Application$_onPageRequestManagerBeginRequest, + _onPageRequestManagerEndRequest: Sys$_Application$_onPageRequestManagerEndRequest, + _raiseNavigate: Sys$_Application$_raiseNavigate, + _serializeState: Sys$_Application$_serializeState, + _setHistory: Sys$_Application$_setHistory, + _setState: Sys$_Application$_setState, + _unloadHandler: Sys$_Application$_unloadHandler, + _updateHiddenField: Sys$_Application$_updateHiddenField +} +Sys._Application.registerClass('Sys._Application', Sys.Component, Sys.IContainer); +Sys.Application = new Sys._Application(); +var $find = Sys.Application.findComponent; +Type.registerNamespace('Sys.Net'); + +Sys.Net.WebRequestExecutor = function Sys$Net$WebRequestExecutor() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + this._webRequest = null; + this._resultObject = null; +} + function Sys$Net$WebRequestExecutor$get_webRequest() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._webRequest; + } + function Sys$Net$WebRequestExecutor$_set_webRequest(value) { + if (this.get_started()) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallOnceStarted, 'set_webRequest')); + } + this._webRequest = value; + } + function Sys$Net$WebRequestExecutor$get_started() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); + } + function Sys$Net$WebRequestExecutor$get_responseAvailable() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); + } + function Sys$Net$WebRequestExecutor$get_timedOut() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); + } + function Sys$Net$WebRequestExecutor$get_aborted() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); + } + function Sys$Net$WebRequestExecutor$get_responseData() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); + } + function Sys$Net$WebRequestExecutor$get_statusCode() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); + } + function Sys$Net$WebRequestExecutor$get_statusText() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); + } + function Sys$Net$WebRequestExecutor$get_xml() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); + } + function Sys$Net$WebRequestExecutor$get_object() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (!this._resultObject) { + this._resultObject = Sys.Serialization.JavaScriptSerializer.deserialize(this.get_responseData()); + } + return this._resultObject; + } + function Sys$Net$WebRequestExecutor$executeRequest() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); + } + function Sys$Net$WebRequestExecutor$abort() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); + } + function Sys$Net$WebRequestExecutor$getResponseHeader(header) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "header", type: String} + ]); + if (e) throw e; + throw Error.notImplemented(); + } + function Sys$Net$WebRequestExecutor$getAllResponseHeaders() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); + } +Sys.Net.WebRequestExecutor.prototype = { + get_webRequest: Sys$Net$WebRequestExecutor$get_webRequest, + _set_webRequest: Sys$Net$WebRequestExecutor$_set_webRequest, + get_started: Sys$Net$WebRequestExecutor$get_started, + get_responseAvailable: Sys$Net$WebRequestExecutor$get_responseAvailable, + get_timedOut: Sys$Net$WebRequestExecutor$get_timedOut, + get_aborted: Sys$Net$WebRequestExecutor$get_aborted, + get_responseData: Sys$Net$WebRequestExecutor$get_responseData, + get_statusCode: Sys$Net$WebRequestExecutor$get_statusCode, + get_statusText: Sys$Net$WebRequestExecutor$get_statusText, + get_xml: Sys$Net$WebRequestExecutor$get_xml, + get_object: Sys$Net$WebRequestExecutor$get_object, + executeRequest: Sys$Net$WebRequestExecutor$executeRequest, + abort: Sys$Net$WebRequestExecutor$abort, + getResponseHeader: Sys$Net$WebRequestExecutor$getResponseHeader, + getAllResponseHeaders: Sys$Net$WebRequestExecutor$getAllResponseHeaders +} +Sys.Net.WebRequestExecutor.registerClass('Sys.Net.WebRequestExecutor'); + +Sys.Net.XMLDOM = function Sys$Net$XMLDOM(markup) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "markup", type: String} + ]); + if (e) throw e; + if (!window.DOMParser) { + var progIDs = [ 'Msxml2.DOMDocument.3.0', 'Msxml2.DOMDocument' ]; + for (var i = 0, l = progIDs.length; i < l; i++) { + try { + var xmlDOM = new ActiveXObject(progIDs[i]); + xmlDOM.async = false; + xmlDOM.loadXML(markup); + xmlDOM.setProperty('SelectionLanguage', 'XPath'); + return xmlDOM; + } + catch (ex) { + } + } + } + else { + try { + var domParser = new window.DOMParser(); + return domParser.parseFromString(markup, 'text/xml'); + } + catch (ex) { + } + } + return null; +} +Sys.Net.XMLHttpExecutor = function Sys$Net$XMLHttpExecutor() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + Sys.Net.XMLHttpExecutor.initializeBase(this); + var _this = this; + this._xmlHttpRequest = null; + this._webRequest = null; + this._responseAvailable = false; + this._timedOut = false; + this._timer = null; + this._aborted = false; + this._started = false; + this._onReadyStateChange = (function () { + + if (_this._xmlHttpRequest.readyState === 4 ) { + try { + if (typeof(_this._xmlHttpRequest.status) === "undefined") { + return; + } + } + catch(ex) { + return; + } + + _this._clearTimer(); + _this._responseAvailable = true; + try { + _this._webRequest.completed(Sys.EventArgs.Empty); + } + finally { + if (_this._xmlHttpRequest != null) { + _this._xmlHttpRequest.onreadystatechange = Function.emptyMethod; + _this._xmlHttpRequest = null; + } + } + } + }); + this._clearTimer = (function() { + if (_this._timer != null) { + window.clearTimeout(_this._timer); + _this._timer = null; + } + }); + this._onTimeout = (function() { + if (!_this._responseAvailable) { + _this._clearTimer(); + _this._timedOut = true; + _this._xmlHttpRequest.onreadystatechange = Function.emptyMethod; + _this._xmlHttpRequest.abort(); + _this._webRequest.completed(Sys.EventArgs.Empty); + _this._xmlHttpRequest = null; + } + }); +} + function Sys$Net$XMLHttpExecutor$get_timedOut() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._timedOut; + } + function Sys$Net$XMLHttpExecutor$get_started() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._started; + } + function Sys$Net$XMLHttpExecutor$get_responseAvailable() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._responseAvailable; + } + function Sys$Net$XMLHttpExecutor$get_aborted() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._aborted; + } + function Sys$Net$XMLHttpExecutor$executeRequest() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + this._webRequest = this.get_webRequest(); + if (this._started) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallOnceStarted, 'executeRequest')); + } + if (this._webRequest === null) { + throw Error.invalidOperation(Sys.Res.nullWebRequest); + } + var body = this._webRequest.get_body(); + var headers = this._webRequest.get_headers(); + this._xmlHttpRequest = new XMLHttpRequest(); + this._xmlHttpRequest.onreadystatechange = this._onReadyStateChange; + var verb = this._webRequest.get_httpVerb(); + this._xmlHttpRequest.open(verb, this._webRequest.getResolvedUrl(), true ); + if (headers) { + for (var header in headers) { + var val = headers[header]; + if (typeof(val) !== "function") + this._xmlHttpRequest.setRequestHeader(header, val); + } + } + if (verb.toLowerCase() === "post") { + if ((headers === null) || !headers['Content-Type']) { + this._xmlHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8'); + } + if (!body) { + body = ""; + } + } + var timeout = this._webRequest.get_timeout(); + if (timeout > 0) { + this._timer = window.setTimeout(Function.createDelegate(this, this._onTimeout), timeout); + } + this._xmlHttpRequest.send(body); + this._started = true; + } + function Sys$Net$XMLHttpExecutor$getResponseHeader(header) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "header", type: String} + ]); + if (e) throw e; + if (!this._responseAvailable) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallBeforeResponse, 'getResponseHeader')); + } + if (!this._xmlHttpRequest) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallOutsideHandler, 'getResponseHeader')); + } + var result; + try { + result = this._xmlHttpRequest.getResponseHeader(header); + } catch (e) { + } + if (!result) result = ""; + return result; + } + function Sys$Net$XMLHttpExecutor$getAllResponseHeaders() { + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (!this._responseAvailable) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallBeforeResponse, 'getAllResponseHeaders')); + } + if (!this._xmlHttpRequest) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallOutsideHandler, 'getAllResponseHeaders')); + } + return this._xmlHttpRequest.getAllResponseHeaders(); + } + function Sys$Net$XMLHttpExecutor$get_responseData() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (!this._responseAvailable) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallBeforeResponse, 'get_responseData')); + } + if (!this._xmlHttpRequest) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallOutsideHandler, 'get_responseData')); + } + return this._xmlHttpRequest.responseText; + } + function Sys$Net$XMLHttpExecutor$get_statusCode() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (!this._responseAvailable) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallBeforeResponse, 'get_statusCode')); + } + if (!this._xmlHttpRequest) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallOutsideHandler, 'get_statusCode')); + } + var result = 0; + try { + result = this._xmlHttpRequest.status; + } + catch(ex) { + } + return result; + } + function Sys$Net$XMLHttpExecutor$get_statusText() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (!this._responseAvailable) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallBeforeResponse, 'get_statusText')); + } + if (!this._xmlHttpRequest) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallOutsideHandler, 'get_statusText')); + } + return this._xmlHttpRequest.statusText; + } + function Sys$Net$XMLHttpExecutor$get_xml() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (!this._responseAvailable) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallBeforeResponse, 'get_xml')); + } + if (!this._xmlHttpRequest) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallOutsideHandler, 'get_xml')); + } + var xml = this._xmlHttpRequest.responseXML; + if (!xml || !xml.documentElement) { + xml = Sys.Net.XMLDOM(this._xmlHttpRequest.responseText); + if (!xml || !xml.documentElement) + return null; + } + else if (navigator.userAgent.indexOf('MSIE') !== -1) { + xml.setProperty('SelectionLanguage', 'XPath'); + } + if (xml.documentElement.namespaceURI === "http://www.mozilla.org/newlayout/xml/parsererror.xml" && + xml.documentElement.tagName === "parsererror") { + return null; + } + + if (xml.documentElement.firstChild && xml.documentElement.firstChild.tagName === "parsererror") { + return null; + } + + return xml; + } + function Sys$Net$XMLHttpExecutor$abort() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (!this._started) { + throw Error.invalidOperation(Sys.Res.cannotAbortBeforeStart); + } + if (this._aborted || this._responseAvailable || this._timedOut) + return; + this._aborted = true; + this._clearTimer(); + if (this._xmlHttpRequest && !this._responseAvailable) { + this._xmlHttpRequest.onreadystatechange = Function.emptyMethod; + this._xmlHttpRequest.abort(); + + this._xmlHttpRequest = null; + this._webRequest.completed(Sys.EventArgs.Empty); + } + } +Sys.Net.XMLHttpExecutor.prototype = { + get_timedOut: Sys$Net$XMLHttpExecutor$get_timedOut, + get_started: Sys$Net$XMLHttpExecutor$get_started, + get_responseAvailable: Sys$Net$XMLHttpExecutor$get_responseAvailable, + get_aborted: Sys$Net$XMLHttpExecutor$get_aborted, + executeRequest: Sys$Net$XMLHttpExecutor$executeRequest, + getResponseHeader: Sys$Net$XMLHttpExecutor$getResponseHeader, + getAllResponseHeaders: Sys$Net$XMLHttpExecutor$getAllResponseHeaders, + get_responseData: Sys$Net$XMLHttpExecutor$get_responseData, + get_statusCode: Sys$Net$XMLHttpExecutor$get_statusCode, + get_statusText: Sys$Net$XMLHttpExecutor$get_statusText, + get_xml: Sys$Net$XMLHttpExecutor$get_xml, + abort: Sys$Net$XMLHttpExecutor$abort +} +Sys.Net.XMLHttpExecutor.registerClass('Sys.Net.XMLHttpExecutor', Sys.Net.WebRequestExecutor); + +Sys.Net._WebRequestManager = function Sys$Net$_WebRequestManager() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + this._defaultTimeout = 0; + this._defaultExecutorType = "Sys.Net.XMLHttpExecutor"; +} + function Sys$Net$_WebRequestManager$add_invokingRequest(handler) { + /// + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this._get_eventHandlerList().addHandler("invokingRequest", handler); + } + function Sys$Net$_WebRequestManager$remove_invokingRequest(handler) { + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this._get_eventHandlerList().removeHandler("invokingRequest", handler); + } + function Sys$Net$_WebRequestManager$add_completedRequest(handler) { + /// + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this._get_eventHandlerList().addHandler("completedRequest", handler); + } + function Sys$Net$_WebRequestManager$remove_completedRequest(handler) { + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this._get_eventHandlerList().removeHandler("completedRequest", handler); + } + function Sys$Net$_WebRequestManager$_get_eventHandlerList() { + if (!this._events) { + this._events = new Sys.EventHandlerList(); + } + return this._events; + } + function Sys$Net$_WebRequestManager$get_defaultTimeout() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._defaultTimeout; + } + function Sys$Net$_WebRequestManager$set_defaultTimeout(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Number}]); + if (e) throw e; + if (value < 0) { + throw Error.argumentOutOfRange("value", value, Sys.Res.invalidTimeout); + } + this._defaultTimeout = value; + } + function Sys$Net$_WebRequestManager$get_defaultExecutorType() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._defaultExecutorType; + } + function Sys$Net$_WebRequestManager$set_defaultExecutorType(value) { + var e = Function._validateParams(arguments, [{name: "value", type: String}]); + if (e) throw e; + this._defaultExecutorType = value; + } + function Sys$Net$_WebRequestManager$executeRequest(webRequest) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "webRequest", type: Sys.Net.WebRequest} + ]); + if (e) throw e; + var executor = webRequest.get_executor(); + if (!executor) { + var failed = false; + try { + var executorType = eval(this._defaultExecutorType); + executor = new executorType(); + } catch (e) { + failed = true; + } + if (failed || !Sys.Net.WebRequestExecutor.isInstanceOfType(executor) || !executor) { + throw Error.argument("defaultExecutorType", String.format(Sys.Res.invalidExecutorType, this._defaultExecutorType)); + } + webRequest.set_executor(executor); + } + if (executor.get_aborted()) { + return; + } + var evArgs = new Sys.Net.NetworkRequestEventArgs(webRequest); + var handler = this._get_eventHandlerList().getHandler("invokingRequest"); + if (handler) { + handler(this, evArgs); + } + if (!evArgs.get_cancel()) { + executor.executeRequest(); + } + } +Sys.Net._WebRequestManager.prototype = { + add_invokingRequest: Sys$Net$_WebRequestManager$add_invokingRequest, + remove_invokingRequest: Sys$Net$_WebRequestManager$remove_invokingRequest, + add_completedRequest: Sys$Net$_WebRequestManager$add_completedRequest, + remove_completedRequest: Sys$Net$_WebRequestManager$remove_completedRequest, + _get_eventHandlerList: Sys$Net$_WebRequestManager$_get_eventHandlerList, + get_defaultTimeout: Sys$Net$_WebRequestManager$get_defaultTimeout, + set_defaultTimeout: Sys$Net$_WebRequestManager$set_defaultTimeout, + get_defaultExecutorType: Sys$Net$_WebRequestManager$get_defaultExecutorType, + set_defaultExecutorType: Sys$Net$_WebRequestManager$set_defaultExecutorType, + executeRequest: Sys$Net$_WebRequestManager$executeRequest +} +Sys.Net._WebRequestManager.registerClass('Sys.Net._WebRequestManager'); +Sys.Net.WebRequestManager = new Sys.Net._WebRequestManager(); + +Sys.Net.NetworkRequestEventArgs = function Sys$Net$NetworkRequestEventArgs(webRequest) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "webRequest", type: Sys.Net.WebRequest} + ]); + if (e) throw e; + Sys.Net.NetworkRequestEventArgs.initializeBase(this); + this._webRequest = webRequest; +} + function Sys$Net$NetworkRequestEventArgs$get_webRequest() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._webRequest; + } +Sys.Net.NetworkRequestEventArgs.prototype = { + get_webRequest: Sys$Net$NetworkRequestEventArgs$get_webRequest +} +Sys.Net.NetworkRequestEventArgs.registerClass('Sys.Net.NetworkRequestEventArgs', Sys.CancelEventArgs); + +Sys.Net.WebRequest = function Sys$Net$WebRequest() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + this._url = ""; + this._headers = { }; + this._body = null; + this._userContext = null; + this._httpVerb = null; + this._executor = null; + this._invokeCalled = false; + this._timeout = 0; +} + function Sys$Net$WebRequest$add_completed(handler) { + /// + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this._get_eventHandlerList().addHandler("completed", handler); + } + function Sys$Net$WebRequest$remove_completed(handler) { + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this._get_eventHandlerList().removeHandler("completed", handler); + } + function Sys$Net$WebRequest$completed(eventArgs) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "eventArgs", type: Sys.EventArgs} + ]); + if (e) throw e; + var handler = Sys.Net.WebRequestManager._get_eventHandlerList().getHandler("completedRequest"); + if (handler) { + handler(this._executor, eventArgs); + } + handler = this._get_eventHandlerList().getHandler("completed"); + if (handler) { + handler(this._executor, eventArgs); + } + } + function Sys$Net$WebRequest$_get_eventHandlerList() { + if (!this._events) { + this._events = new Sys.EventHandlerList(); + } + return this._events; + } + function Sys$Net$WebRequest$get_url() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._url; + } + function Sys$Net$WebRequest$set_url(value) { + var e = Function._validateParams(arguments, [{name: "value", type: String}]); + if (e) throw e; + this._url = value; + } + function Sys$Net$WebRequest$get_headers() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._headers; + } + function Sys$Net$WebRequest$get_httpVerb() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (this._httpVerb === null) { + if (this._body === null) { + return "GET"; + } + return "POST"; + } + return this._httpVerb; + } + function Sys$Net$WebRequest$set_httpVerb(value) { + var e = Function._validateParams(arguments, [{name: "value", type: String}]); + if (e) throw e; + if (value.length === 0) { + throw Error.argument('value', Sys.Res.invalidHttpVerb); + } + this._httpVerb = value; + } + function Sys$Net$WebRequest$get_body() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._body; + } + function Sys$Net$WebRequest$set_body(value) { + var e = Function._validateParams(arguments, [{name: "value", mayBeNull: true}]); + if (e) throw e; + this._body = value; + } + function Sys$Net$WebRequest$get_userContext() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._userContext; + } + function Sys$Net$WebRequest$set_userContext(value) { + var e = Function._validateParams(arguments, [{name: "value", mayBeNull: true}]); + if (e) throw e; + this._userContext = value; + } + function Sys$Net$WebRequest$get_executor() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._executor; + } + function Sys$Net$WebRequest$set_executor(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Sys.Net.WebRequestExecutor}]); + if (e) throw e; + if (this._executor !== null && this._executor.get_started()) { + throw Error.invalidOperation(Sys.Res.setExecutorAfterActive); + } + this._executor = value; + this._executor._set_webRequest(this); + } + function Sys$Net$WebRequest$get_timeout() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (this._timeout === 0) { + return Sys.Net.WebRequestManager.get_defaultTimeout(); + } + return this._timeout; + } + function Sys$Net$WebRequest$set_timeout(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Number}]); + if (e) throw e; + if (value < 0) { + throw Error.argumentOutOfRange("value", value, Sys.Res.invalidTimeout); + } + this._timeout = value; + } + function Sys$Net$WebRequest$getResolvedUrl() { + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return Sys.Net.WebRequest._resolveUrl(this._url); + } + function Sys$Net$WebRequest$invoke() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (this._invokeCalled) { + throw Error.invalidOperation(Sys.Res.invokeCalledTwice); + } + Sys.Net.WebRequestManager.executeRequest(this); + this._invokeCalled = true; + } +Sys.Net.WebRequest.prototype = { + add_completed: Sys$Net$WebRequest$add_completed, + remove_completed: Sys$Net$WebRequest$remove_completed, + completed: Sys$Net$WebRequest$completed, + _get_eventHandlerList: Sys$Net$WebRequest$_get_eventHandlerList, + get_url: Sys$Net$WebRequest$get_url, + set_url: Sys$Net$WebRequest$set_url, + get_headers: Sys$Net$WebRequest$get_headers, + get_httpVerb: Sys$Net$WebRequest$get_httpVerb, + set_httpVerb: Sys$Net$WebRequest$set_httpVerb, + get_body: Sys$Net$WebRequest$get_body, + set_body: Sys$Net$WebRequest$set_body, + get_userContext: Sys$Net$WebRequest$get_userContext, + set_userContext: Sys$Net$WebRequest$set_userContext, + get_executor: Sys$Net$WebRequest$get_executor, + set_executor: Sys$Net$WebRequest$set_executor, + get_timeout: Sys$Net$WebRequest$get_timeout, + set_timeout: Sys$Net$WebRequest$set_timeout, + getResolvedUrl: Sys$Net$WebRequest$getResolvedUrl, + invoke: Sys$Net$WebRequest$invoke +} +Sys.Net.WebRequest._resolveUrl = function Sys$Net$WebRequest$_resolveUrl(url, baseUrl) { + if (url && url.indexOf('://') !== -1) { + return url; + } + if (!baseUrl || baseUrl.length === 0) { + var baseElement = document.getElementsByTagName('base')[0]; + if (baseElement && baseElement.href && baseElement.href.length > 0) { + baseUrl = baseElement.href; + } + else { + baseUrl = document.URL; + } + } + var qsStart = baseUrl.indexOf('?'); + if (qsStart !== -1) { + baseUrl = baseUrl.substr(0, qsStart); + } + qsStart = baseUrl.indexOf('#'); + if (qsStart !== -1) { + baseUrl = baseUrl.substr(0, qsStart); + } + baseUrl = baseUrl.substr(0, baseUrl.lastIndexOf('/') + 1); + if (!url || url.length === 0) { + return baseUrl; + } + if (url.charAt(0) === '/') { + var slashslash = baseUrl.indexOf('://'); + if (slashslash === -1) { + throw Error.argument("baseUrl", Sys.Res.badBaseUrl1); + } + var nextSlash = baseUrl.indexOf('/', slashslash + 3); + if (nextSlash === -1) { + throw Error.argument("baseUrl", Sys.Res.badBaseUrl2); + } + return baseUrl.substr(0, nextSlash) + url; + } + else { + var lastSlash = baseUrl.lastIndexOf('/'); + if (lastSlash === -1) { + throw Error.argument("baseUrl", Sys.Res.badBaseUrl3); + } + return baseUrl.substr(0, lastSlash+1) + url; + } +} +Sys.Net.WebRequest._createQueryString = function Sys$Net$WebRequest$_createQueryString(queryString, encodeMethod) { + if (!encodeMethod) + encodeMethod = encodeURIComponent; + var sb = new Sys.StringBuilder(); + var i = 0; + for (var arg in queryString) { + var obj = queryString[arg]; + if (typeof(obj) === "function") continue; + var val = Sys.Serialization.JavaScriptSerializer.serialize(obj); + if (i !== 0) { + sb.append('&'); + } + sb.append(arg); + sb.append('='); + sb.append(encodeMethod(val)); + i++; + } + return sb.toString(); +} +Sys.Net.WebRequest._createUrl = function Sys$Net$WebRequest$_createUrl(url, queryString) { + if (!queryString) { + return url; + } + var qs = Sys.Net.WebRequest._createQueryString(queryString); + if (qs.length > 0) { + var sep = '?'; + if (url && url.indexOf('?') !== -1) + sep = '&'; + return url + sep + qs; + } else { + return url; + } +} +Sys.Net.WebRequest.registerClass('Sys.Net.WebRequest'); + +Sys.Net.WebServiceProxy = function Sys$Net$WebServiceProxy() { +} + function Sys$Net$WebServiceProxy$get_timeout() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._timeout; + } + function Sys$Net$WebServiceProxy$set_timeout(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Number}]); + if (e) throw e; + if (value < 0) { throw Error.argumentOutOfRange('value', value, Sys.Res.invalidTimeout); } + this._timeout = value; + } + function Sys$Net$WebServiceProxy$get_defaultUserContext() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._userContext; + } + function Sys$Net$WebServiceProxy$set_defaultUserContext(value) { + var e = Function._validateParams(arguments, [{name: "value", mayBeNull: true}]); + if (e) throw e; + this._userContext = value; + } + function Sys$Net$WebServiceProxy$get_defaultSucceededCallback() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._succeeded; + } + function Sys$Net$WebServiceProxy$set_defaultSucceededCallback(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Function, mayBeNull: true}]); + if (e) throw e; + this._succeeded = value; + } + function Sys$Net$WebServiceProxy$get_defaultFailedCallback() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._failed; + } + function Sys$Net$WebServiceProxy$set_defaultFailedCallback(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Function, mayBeNull: true}]); + if (e) throw e; + this._failed = value; + } + function Sys$Net$WebServiceProxy$get_path() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._path; + } + function Sys$Net$WebServiceProxy$set_path(value) { + var e = Function._validateParams(arguments, [{name: "value", type: String}]); + if (e) throw e; + this._path = value; + } + function Sys$Net$WebServiceProxy$_invoke(servicePath, methodName, useGet, params, onSuccess, onFailure, userContext) { + /// + /// + /// + /// + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "servicePath", type: String}, + {name: "methodName", type: String}, + {name: "useGet", type: Boolean}, + {name: "params"}, + {name: "onSuccess", type: Function, mayBeNull: true, optional: true}, + {name: "onFailure", type: Function, mayBeNull: true, optional: true}, + {name: "userContext", mayBeNull: true, optional: true} + ]); + if (e) throw e; + if (onSuccess === null || typeof onSuccess === 'undefined') onSuccess = this.get_defaultSucceededCallback(); + if (onFailure === null || typeof onFailure === 'undefined') onFailure = this.get_defaultFailedCallback(); + if (userContext === null || typeof userContext === 'undefined') userContext = this.get_defaultUserContext(); + + return Sys.Net.WebServiceProxy.invoke(servicePath, methodName, useGet, params, onSuccess, onFailure, userContext, this.get_timeout()); + } +Sys.Net.WebServiceProxy.prototype = { + get_timeout: Sys$Net$WebServiceProxy$get_timeout, + set_timeout: Sys$Net$WebServiceProxy$set_timeout, + get_defaultUserContext: Sys$Net$WebServiceProxy$get_defaultUserContext, + set_defaultUserContext: Sys$Net$WebServiceProxy$set_defaultUserContext, + get_defaultSucceededCallback: Sys$Net$WebServiceProxy$get_defaultSucceededCallback, + set_defaultSucceededCallback: Sys$Net$WebServiceProxy$set_defaultSucceededCallback, + get_defaultFailedCallback: Sys$Net$WebServiceProxy$get_defaultFailedCallback, + set_defaultFailedCallback: Sys$Net$WebServiceProxy$set_defaultFailedCallback, + get_path: Sys$Net$WebServiceProxy$get_path, + set_path: Sys$Net$WebServiceProxy$set_path, + _invoke: Sys$Net$WebServiceProxy$_invoke +} +Sys.Net.WebServiceProxy.registerClass('Sys.Net.WebServiceProxy'); +Sys.Net.WebServiceProxy.invoke = function Sys$Net$WebServiceProxy$invoke(servicePath, methodName, useGet, params, onSuccess, onFailure, userContext, timeout) { + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "servicePath", type: String}, + {name: "methodName", type: String}, + {name: "useGet", type: Boolean, optional: true}, + {name: "params", mayBeNull: true, optional: true}, + {name: "onSuccess", type: Function, mayBeNull: true, optional: true}, + {name: "onFailure", type: Function, mayBeNull: true, optional: true}, + {name: "userContext", mayBeNull: true, optional: true}, + {name: "timeout", type: Number, optional: true} + ]); + if (e) throw e; + var request = new Sys.Net.WebRequest(); + request.get_headers()['Content-Type'] = 'application/json; charset=utf-8'; + if (!params) params = {}; + var urlParams = params; + if (!useGet || !urlParams) urlParams = {}; + request.set_url(Sys.Net.WebRequest._createUrl(servicePath+"/"+encodeURIComponent(methodName), urlParams)); + var body = null; + if (!useGet) { + body = Sys.Serialization.JavaScriptSerializer.serialize(params); + if (body === "{}") body = ""; + } + request.set_body(body); + request.add_completed(onComplete); + if (timeout && timeout > 0) request.set_timeout(timeout); + request.invoke(); + function onComplete(response, eventArgs) { + if (response.get_responseAvailable()) { + var statusCode = response.get_statusCode(); + var result = null; + + try { + var contentType = response.getResponseHeader("Content-Type"); + if (contentType.startsWith("application/json")) { + result = response.get_object(); + } + else if (contentType.startsWith("text/xml")) { + result = response.get_xml(); + } + else { + result = response.get_responseData(); + } + } catch (ex) { + } + var error = response.getResponseHeader("jsonerror"); + var errorObj = (error === "true"); + if (errorObj) { + if (result) { + result = new Sys.Net.WebServiceError(false, result.Message, result.StackTrace, result.ExceptionType); + } + } + else if (contentType.startsWith("application/json")) { + if (!result || typeof(result.d) === "undefined") { + throw Sys.Net.WebServiceProxy._createFailedError(methodName, String.format(Sys.Res.webServiceInvalidJsonWrapper, methodName)); + } + result = result.d; + } + if (((statusCode < 200) || (statusCode >= 300)) || errorObj) { + if (onFailure) { + if (!result || !errorObj) { + result = new Sys.Net.WebServiceError(false , String.format(Sys.Res.webServiceFailedNoMsg, methodName), "", ""); + } + result._statusCode = statusCode; + onFailure(result, userContext, methodName); + } + else { + var error; + if (result && errorObj) { + error = result.get_exceptionType() + "-- " + result.get_message(); + } + else { + error = response.get_responseData(); + } + throw Sys.Net.WebServiceProxy._createFailedError(methodName, String.format(Sys.Res.webServiceFailed, methodName, error)); + } + } + else if (onSuccess) { + onSuccess(result, userContext, methodName); + } + } + else { + var msg; + if (response.get_timedOut()) { + msg = String.format(Sys.Res.webServiceTimedOut, methodName); + } + else { + msg = String.format(Sys.Res.webServiceFailedNoMsg, methodName) + } + if (onFailure) { + onFailure(new Sys.Net.WebServiceError(response.get_timedOut(), msg, "", ""), userContext, methodName); + } + else { + throw Sys.Net.WebServiceProxy._createFailedError(methodName, msg); + } + } + } + return request; +} +Sys.Net.WebServiceProxy._createFailedError = function Sys$Net$WebServiceProxy$_createFailedError(methodName, errorMessage) { + var displayMessage = "Sys.Net.WebServiceFailedException: " + errorMessage; + var e = Error.create(displayMessage, { 'name': 'Sys.Net.WebServiceFailedException', 'methodName': methodName }); + e.popStackFrame(); + return e; +} +Sys.Net.WebServiceProxy._defaultFailedCallback = function Sys$Net$WebServiceProxy$_defaultFailedCallback(err, methodName) { + var error = err.get_exceptionType() + "-- " + err.get_message(); + throw Sys.Net.WebServiceProxy._createFailedError(methodName, String.format(Sys.Res.webServiceFailed, methodName, error)); +} +Sys.Net.WebServiceProxy._generateTypedConstructor = function Sys$Net$WebServiceProxy$_generateTypedConstructor(type) { + return function(properties) { + if (properties) { + for (var name in properties) { + this[name] = properties[name]; + } + } + this.__type = type; + } +} + +Sys.Net.WebServiceError = function Sys$Net$WebServiceError(timedOut, message, stackTrace, exceptionType) { + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "timedOut", type: Boolean}, + {name: "message", type: String, mayBeNull: true}, + {name: "stackTrace", type: String, mayBeNull: true}, + {name: "exceptionType", type: String, mayBeNull: true} + ]); + if (e) throw e; + this._timedOut = timedOut; + this._message = message; + this._stackTrace = stackTrace; + this._exceptionType = exceptionType; + this._statusCode = -1; +} + function Sys$Net$WebServiceError$get_timedOut() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._timedOut; + } + function Sys$Net$WebServiceError$get_statusCode() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._statusCode; + } + function Sys$Net$WebServiceError$get_message() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._message; + } + function Sys$Net$WebServiceError$get_stackTrace() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._stackTrace; + } + function Sys$Net$WebServiceError$get_exceptionType() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._exceptionType; + } +Sys.Net.WebServiceError.prototype = { + get_timedOut: Sys$Net$WebServiceError$get_timedOut, + get_statusCode: Sys$Net$WebServiceError$get_statusCode, + get_message: Sys$Net$WebServiceError$get_message, + get_stackTrace: Sys$Net$WebServiceError$get_stackTrace, + get_exceptionType: Sys$Net$WebServiceError$get_exceptionType +} +Sys.Net.WebServiceError.registerClass('Sys.Net.WebServiceError'); +Type.registerNamespace('Sys.Services'); +Sys.Services._ProfileService = function Sys$Services$_ProfileService() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + Sys.Services._ProfileService.initializeBase(this); + this.properties = {}; +} +Sys.Services._ProfileService.DefaultWebServicePath = ''; + function Sys$Services$_ProfileService$get_defaultLoadCompletedCallback() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._defaultLoadCompletedCallback; + } + function Sys$Services$_ProfileService$set_defaultLoadCompletedCallback(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Function, mayBeNull: true}]); + if (e) throw e; + this._defaultLoadCompletedCallback = value; + } + function Sys$Services$_ProfileService$get_defaultSaveCompletedCallback() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._defaultSaveCompletedCallback; + } + function Sys$Services$_ProfileService$set_defaultSaveCompletedCallback(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Function, mayBeNull: true}]); + if (e) throw e; + this._defaultSaveCompletedCallback = value; + } + function Sys$Services$_ProfileService$get_path() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._path || ''; + } + function Sys$Services$_ProfileService$load(propertyNames, loadCompletedCallback, failedCallback, userContext) { + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "propertyNames", type: Array, mayBeNull: true, optional: true, elementType: String}, + {name: "loadCompletedCallback", type: Function, mayBeNull: true, optional: true}, + {name: "failedCallback", type: Function, mayBeNull: true, optional: true}, + {name: "userContext", mayBeNull: true, optional: true} + ]); + if (e) throw e; + var parameters; + var methodName; + if (!propertyNames) { + methodName = "GetAllPropertiesForCurrentUser"; + parameters = { authenticatedUserOnly: false }; + } + else { + methodName = "GetPropertiesForCurrentUser"; + parameters = { properties: this._clonePropertyNames(propertyNames), authenticatedUserOnly: false }; + } + this._invoke(this._get_path(), + methodName, + false, + parameters, + Function.createDelegate(this, this._onLoadComplete), + Function.createDelegate(this, this._onLoadFailed), + [loadCompletedCallback, failedCallback, userContext]); + } + function Sys$Services$_ProfileService$save(propertyNames, saveCompletedCallback, failedCallback, userContext) { + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "propertyNames", type: Array, mayBeNull: true, optional: true, elementType: String}, + {name: "saveCompletedCallback", type: Function, mayBeNull: true, optional: true}, + {name: "failedCallback", type: Function, mayBeNull: true, optional: true}, + {name: "userContext", mayBeNull: true, optional: true} + ]); + if (e) throw e; + var flattenedProperties = this._flattenProperties(propertyNames, this.properties); + this._invoke(this._get_path(), + "SetPropertiesForCurrentUser", + false, + { values: flattenedProperties.value, authenticatedUserOnly: false }, + Function.createDelegate(this, this._onSaveComplete), + Function.createDelegate(this, this._onSaveFailed), + [saveCompletedCallback, failedCallback, userContext, flattenedProperties.count]); + } + function Sys$Services$_ProfileService$_clonePropertyNames(arr) { + var nodups = []; + var seen = {}; + for (var i=0; i < arr.length; i++) { + var prop = arr[i]; + if(!seen[prop]) { Array.add(nodups, prop); seen[prop]=true; }; + } + return nodups; + } + function Sys$Services$_ProfileService$_flattenProperties(propertyNames, properties, groupName) { + var flattenedProperties = {}; + var val; + var key; + var count = 0; + if (propertyNames && propertyNames.length === 0) { + return { value: flattenedProperties, count: 0 }; + } + for (var property in properties) { + val = properties[property]; + key = groupName ? groupName + "." + property : property; + if(Sys.Services.ProfileGroup.isInstanceOfType(val)) { + var obj = this._flattenProperties(propertyNames, val, key); + var groupProperties = obj.value; + count += obj.count; + for(var subKey in groupProperties) { + var subVal = groupProperties[subKey]; + flattenedProperties[subKey] = subVal; + } + } + else { + if(!propertyNames || Array.indexOf(propertyNames, key) !== -1) { + flattenedProperties[key] = val; + count++; + } + } + } + return { value: flattenedProperties, count: count }; + } + function Sys$Services$_ProfileService$_get_path() { + var path = this.get_path(); + if (!path.length) { + path = Sys.Services._ProfileService.DefaultWebServicePath; + } + if (!path || !path.length) { + throw Error.invalidOperation(Sys.Res.servicePathNotSet); + } + return path; + } + function Sys$Services$_ProfileService$_onLoadComplete(result, context, methodName) { + if (typeof(result) !== "object") { + throw Error.invalidOperation(String.format(Sys.Res.webServiceInvalidReturnType, methodName, "Object")); + } + var unflattened = this._unflattenProperties(result); + for (var name in unflattened) { + this.properties[name] = unflattened[name]; + } + + var callback = context[0] || this.get_defaultLoadCompletedCallback() || this.get_defaultSucceededCallback(); + if (callback) { + var userContext = context[2] || this.get_defaultUserContext(); + callback(result.length, userContext, "Sys.Services.ProfileService.load"); + } + } + function Sys$Services$_ProfileService$_onLoadFailed(err, context, methodName) { + var callback = context[1] || this.get_defaultFailedCallback(); + if (callback) { + var userContext = context[2] || this.get_defaultUserContext(); + callback(err, userContext, "Sys.Services.ProfileService.load"); + } + else { + Sys.Net.WebServiceProxy._defaultFailedCallback(err, methodName); + } + } + function Sys$Services$_ProfileService$_onSaveComplete(result, context, methodName) { + var count = context[3]; + if (result !== null) { + if (result instanceof Array) { + count -= result.length; + } + else if (typeof(result) === 'number') { + count = result; + } + else { + throw Error.invalidOperation(String.format(Sys.Res.webServiceInvalidReturnType, methodName, "Array")); + } + } + + var callback = context[0] || this.get_defaultSaveCompletedCallback() || this.get_defaultSucceededCallback(); + if (callback) { + var userContext = context[2] || this.get_defaultUserContext(); + callback(count, userContext, "Sys.Services.ProfileService.save"); + } + } + function Sys$Services$_ProfileService$_onSaveFailed(err, context, methodName) { + var callback = context[1] || this.get_defaultFailedCallback(); + if (callback) { + var userContext = context[2] || this.get_defaultUserContext(); + callback(err, userContext, "Sys.Services.ProfileService.save"); + } + else { + Sys.Net.WebServiceProxy._defaultFailedCallback(err, methodName); + } + } + function Sys$Services$_ProfileService$_unflattenProperties(properties) { + var unflattenedProperties = {}; + var dotIndex; + var val; + var count = 0; + for (var key in properties) { + count++; + val = properties[key]; + dotIndex = key.indexOf('.'); + if (dotIndex !== -1) { + var groupName = key.substr(0, dotIndex); + key = key.substr(dotIndex+1); + var group = unflattenedProperties[groupName]; + if (!group || !Sys.Services.ProfileGroup.isInstanceOfType(group)) { + group = new Sys.Services.ProfileGroup(); + unflattenedProperties[groupName] = group; + } + group[key] = val; + } + else { + unflattenedProperties[key] = val; + } + } + properties.length = count; + return unflattenedProperties; + } +Sys.Services._ProfileService.prototype = { + _defaultLoadCompletedCallback: null, + _defaultSaveCompletedCallback: null, + _path: '', + _timeout: 0, + get_defaultLoadCompletedCallback: Sys$Services$_ProfileService$get_defaultLoadCompletedCallback, + set_defaultLoadCompletedCallback: Sys$Services$_ProfileService$set_defaultLoadCompletedCallback, + get_defaultSaveCompletedCallback: Sys$Services$_ProfileService$get_defaultSaveCompletedCallback, + set_defaultSaveCompletedCallback: Sys$Services$_ProfileService$set_defaultSaveCompletedCallback, + get_path: Sys$Services$_ProfileService$get_path, + load: Sys$Services$_ProfileService$load, + save: Sys$Services$_ProfileService$save, + _clonePropertyNames: Sys$Services$_ProfileService$_clonePropertyNames, + _flattenProperties: Sys$Services$_ProfileService$_flattenProperties, + _get_path: Sys$Services$_ProfileService$_get_path, + _onLoadComplete: Sys$Services$_ProfileService$_onLoadComplete, + _onLoadFailed: Sys$Services$_ProfileService$_onLoadFailed, + _onSaveComplete: Sys$Services$_ProfileService$_onSaveComplete, + _onSaveFailed: Sys$Services$_ProfileService$_onSaveFailed, + _unflattenProperties: Sys$Services$_ProfileService$_unflattenProperties +} +Sys.Services._ProfileService.registerClass('Sys.Services._ProfileService', Sys.Net.WebServiceProxy); +Sys.Services.ProfileService = new Sys.Services._ProfileService(); +Sys.Services.ProfileGroup = function Sys$Services$ProfileGroup(properties) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "properties", mayBeNull: true, optional: true} + ]); + if (e) throw e; + if (properties) { + for (var property in properties) { + this[property] = properties[property]; + } + } +} +Sys.Services.ProfileGroup.registerClass('Sys.Services.ProfileGroup'); +Sys.Services._AuthenticationService = function Sys$Services$_AuthenticationService() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + Sys.Services._AuthenticationService.initializeBase(this); +} +Sys.Services._AuthenticationService.DefaultWebServicePath = ''; + function Sys$Services$_AuthenticationService$get_defaultLoginCompletedCallback() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._defaultLoginCompletedCallback; + } + function Sys$Services$_AuthenticationService$set_defaultLoginCompletedCallback(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Function, mayBeNull: true}]); + if (e) throw e; + this._defaultLoginCompletedCallback = value; + } + function Sys$Services$_AuthenticationService$get_defaultLogoutCompletedCallback() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._defaultLogoutCompletedCallback; + } + function Sys$Services$_AuthenticationService$set_defaultLogoutCompletedCallback(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Function, mayBeNull: true}]); + if (e) throw e; + this._defaultLogoutCompletedCallback = value; + } + function Sys$Services$_AuthenticationService$get_isLoggedIn() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._authenticated; + } + function Sys$Services$_AuthenticationService$get_path() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._path || ''; + } + function Sys$Services$_AuthenticationService$login(username, password, isPersistent, customInfo, redirectUrl, loginCompletedCallback, failedCallback, userContext) { + /// + /// + /// + /// + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "username", type: String}, + {name: "password", type: String, mayBeNull: true}, + {name: "isPersistent", type: Boolean, mayBeNull: true, optional: true}, + {name: "customInfo", type: String, mayBeNull: true, optional: true}, + {name: "redirectUrl", type: String, mayBeNull: true, optional: true}, + {name: "loginCompletedCallback", type: Function, mayBeNull: true, optional: true}, + {name: "failedCallback", type: Function, mayBeNull: true, optional: true}, + {name: "userContext", mayBeNull: true, optional: true} + ]); + if (e) throw e; + this._invoke(this._get_path(), "Login", false, + { userName: username, password: password, createPersistentCookie: isPersistent }, + Function.createDelegate(this, this._onLoginComplete), + Function.createDelegate(this, this._onLoginFailed), + [username, password, isPersistent, customInfo, redirectUrl, loginCompletedCallback, failedCallback, userContext]); + } + function Sys$Services$_AuthenticationService$logout(redirectUrl, logoutCompletedCallback, failedCallback, userContext) { + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "redirectUrl", type: String, mayBeNull: true, optional: true}, + {name: "logoutCompletedCallback", type: Function, mayBeNull: true, optional: true}, + {name: "failedCallback", type: Function, mayBeNull: true, optional: true}, + {name: "userContext", mayBeNull: true, optional: true} + ]); + if (e) throw e; + this._invoke(this._get_path(), "Logout", false, {}, + Function.createDelegate(this, this._onLogoutComplete), + Function.createDelegate(this, this._onLogoutFailed), + [redirectUrl, logoutCompletedCallback, failedCallback, userContext]); + } + function Sys$Services$_AuthenticationService$_get_path() { + var path = this.get_path(); + if(!path.length) { + path = Sys.Services._AuthenticationService.DefaultWebServicePath; + } + if(!path || !path.length) { + throw Error.invalidOperation(Sys.Res.servicePathNotSet); + } + return path; + } + function Sys$Services$_AuthenticationService$_onLoginComplete(result, context, methodName) { + if(typeof(result) !== "boolean") { + throw Error.invalidOperation(String.format(Sys.Res.webServiceInvalidReturnType, methodName, "Boolean")); + } + + var redirectUrl = context[4]; + var userContext = context[7] || this.get_defaultUserContext(); + var callback = context[5] || this.get_defaultLoginCompletedCallback() || this.get_defaultSucceededCallback(); + + if(result) { + this._authenticated = true; + if (callback) { + callback(true, userContext, "Sys.Services.AuthenticationService.login"); + } + + if (typeof(redirectUrl) !== "undefined" && redirectUrl !== null) { + window.location.href = redirectUrl; + } + } + else if (callback) { + callback(false, userContext, "Sys.Services.AuthenticationService.login"); + } + } + function Sys$Services$_AuthenticationService$_onLoginFailed(err, context, methodName) { + var callback = context[6] || this.get_defaultFailedCallback(); + if (callback) { + var userContext = context[7] || this.get_defaultUserContext(); + callback(err, userContext, "Sys.Services.AuthenticationService.login"); + } + else { + Sys.Net.WebServiceProxy._defaultFailedCallback(err, methodName); + } + } + function Sys$Services$_AuthenticationService$_onLogoutComplete(result, context, methodName) { + if(result !== null) { + throw Error.invalidOperation(String.format(Sys.Res.webServiceInvalidReturnType, methodName, "null")); + } + + var redirectUrl = context[0]; + var userContext = context[3] || this.get_defaultUserContext(); + var callback = context[1] || this.get_defaultLogoutCompletedCallback() || this.get_defaultSucceededCallback(); + this._authenticated = false; + + if (callback) { + callback(null, userContext, "Sys.Services.AuthenticationService.logout"); + } + + if(!redirectUrl) { + window.location.reload(); + } + else { + window.location.href = redirectUrl; + } + } + function Sys$Services$_AuthenticationService$_onLogoutFailed(err, context, methodName) { + var callback = context[2] || this.get_defaultFailedCallback(); + if (callback) { + callback(err, context[3], "Sys.Services.AuthenticationService.logout"); + } + else { + Sys.Net.WebServiceProxy._defaultFailedCallback(err, methodName); + } + } + function Sys$Services$_AuthenticationService$_setAuthenticated(authenticated) { + this._authenticated = authenticated; + } +Sys.Services._AuthenticationService.prototype = { + _defaultLoginCompletedCallback: null, + _defaultLogoutCompletedCallback: null, + _path: '', + _timeout: 0, + _authenticated: false, + get_defaultLoginCompletedCallback: Sys$Services$_AuthenticationService$get_defaultLoginCompletedCallback, + set_defaultLoginCompletedCallback: Sys$Services$_AuthenticationService$set_defaultLoginCompletedCallback, + get_defaultLogoutCompletedCallback: Sys$Services$_AuthenticationService$get_defaultLogoutCompletedCallback, + set_defaultLogoutCompletedCallback: Sys$Services$_AuthenticationService$set_defaultLogoutCompletedCallback, + get_isLoggedIn: Sys$Services$_AuthenticationService$get_isLoggedIn, + get_path: Sys$Services$_AuthenticationService$get_path, + login: Sys$Services$_AuthenticationService$login, + logout: Sys$Services$_AuthenticationService$logout, + _get_path: Sys$Services$_AuthenticationService$_get_path, + _onLoginComplete: Sys$Services$_AuthenticationService$_onLoginComplete, + _onLoginFailed: Sys$Services$_AuthenticationService$_onLoginFailed, + _onLogoutComplete: Sys$Services$_AuthenticationService$_onLogoutComplete, + _onLogoutFailed: Sys$Services$_AuthenticationService$_onLogoutFailed, + _setAuthenticated: Sys$Services$_AuthenticationService$_setAuthenticated +} +Sys.Services._AuthenticationService.registerClass('Sys.Services._AuthenticationService', Sys.Net.WebServiceProxy); +Sys.Services.AuthenticationService = new Sys.Services._AuthenticationService(); +Sys.Services._RoleService = function Sys$Services$_RoleService() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + Sys.Services._RoleService.initializeBase(this); + this._roles = []; +} +Sys.Services._RoleService.DefaultWebServicePath = ''; + function Sys$Services$_RoleService$get_defaultLoadCompletedCallback() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._defaultLoadCompletedCallback; + } + function Sys$Services$_RoleService$set_defaultLoadCompletedCallback(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Function, mayBeNull: true}]); + if (e) throw e; + this._defaultLoadCompletedCallback = value; + } + function Sys$Services$_RoleService$get_path() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._path || ''; + } + function Sys$Services$_RoleService$get_roles() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return Array.clone(this._roles); + } + function Sys$Services$_RoleService$isUserInRole(role) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "role", type: String} + ]); + if (e) throw e; + var v = this._get_rolesIndex()[role.trim().toLowerCase()]; + return !!v; + } + function Sys$Services$_RoleService$load(loadCompletedCallback, failedCallback, userContext) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "loadCompletedCallback", type: Function, mayBeNull: true, optional: true}, + {name: "failedCallback", type: Function, mayBeNull: true, optional: true}, + {name: "userContext", mayBeNull: true, optional: true} + ]); + if (e) throw e; + Sys.Net.WebServiceProxy.invoke( + this._get_path(), + "GetRolesForCurrentUser", + false, + {} , + Function.createDelegate(this, this._onLoadComplete), + Function.createDelegate(this, this._onLoadFailed), + [loadCompletedCallback, failedCallback, userContext], + this.get_timeout()); + } + function Sys$Services$_RoleService$_get_path() { + var path = this.get_path(); + if(!path || !path.length) { + path = Sys.Services._RoleService.DefaultWebServicePath; + } + if(!path || !path.length) { + throw Error.invalidOperation(Sys.Res.servicePathNotSet); + } + return path; + } + function Sys$Services$_RoleService$_get_rolesIndex() { + if (!this._rolesIndex) { + var index = {}; + for(var i=0; i < this._roles.length; i++) { + index[this._roles[i].toLowerCase()] = true; + } + this._rolesIndex = index; + } + return this._rolesIndex; + } + function Sys$Services$_RoleService$_onLoadComplete(result, context, methodName) { + if(result && !(result instanceof Array)) { + throw Error.invalidOperation(String.format(Sys.Res.webServiceInvalidReturnType, methodName, "Array")); + } + this._roles = result; + this._rolesIndex = null; + var callback = context[0] || this.get_defaultLoadCompletedCallback() || this.get_defaultSucceededCallback(); + if (callback) { + var userContext = context[2] || this.get_defaultUserContext(); + var clonedResult = Array.clone(result); + callback(clonedResult, userContext, "Sys.Services.RoleService.load"); + } + } + function Sys$Services$_RoleService$_onLoadFailed(err, context, methodName) { + var callback = context[1] || this.get_defaultFailedCallback(); + if (callback) { + var userContext = context[2] || this.get_defaultUserContext(); + callback(err, userContext, "Sys.Services.RoleService.load"); + } + else { + Sys.Net.WebServiceProxy._defaultFailedCallback(err, methodName); + } + } +Sys.Services._RoleService.prototype = { + _defaultLoadCompletedCallback: null, + _rolesIndex: null, + _timeout: 0, + _path: '', + get_defaultLoadCompletedCallback: Sys$Services$_RoleService$get_defaultLoadCompletedCallback, + set_defaultLoadCompletedCallback: Sys$Services$_RoleService$set_defaultLoadCompletedCallback, + get_path: Sys$Services$_RoleService$get_path, + get_roles: Sys$Services$_RoleService$get_roles, + isUserInRole: Sys$Services$_RoleService$isUserInRole, + load: Sys$Services$_RoleService$load, + _get_path: Sys$Services$_RoleService$_get_path, + _get_rolesIndex: Sys$Services$_RoleService$_get_rolesIndex, + _onLoadComplete: Sys$Services$_RoleService$_onLoadComplete, + _onLoadFailed: Sys$Services$_RoleService$_onLoadFailed +} +Sys.Services._RoleService.registerClass('Sys.Services._RoleService', Sys.Net.WebServiceProxy); +Sys.Services.RoleService = new Sys.Services._RoleService(); +Type.registerNamespace('Sys.Serialization'); +Sys.Serialization.JavaScriptSerializer = function Sys$Serialization$JavaScriptSerializer() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); +} +Sys.Serialization.JavaScriptSerializer.registerClass('Sys.Serialization.JavaScriptSerializer'); +Sys.Serialization.JavaScriptSerializer._charsToEscapeRegExs = []; +Sys.Serialization.JavaScriptSerializer._charsToEscape = []; +Sys.Serialization.JavaScriptSerializer._dateRegEx = new RegExp('(^|[^\\\\])\\"\\\\/Date\\((-?[0-9]+)(?:[a-zA-Z]|(?:\\+|-)[0-9]{4})?\\)\\\\/\\"', 'g'); +Sys.Serialization.JavaScriptSerializer._escapeChars = {}; +Sys.Serialization.JavaScriptSerializer._escapeRegEx = new RegExp('["\\\\\\x00-\\x1F]', 'i'); +Sys.Serialization.JavaScriptSerializer._escapeRegExGlobal = new RegExp('["\\\\\\x00-\\x1F]', 'g'); +Sys.Serialization.JavaScriptSerializer._jsonRegEx = new RegExp('[^,:{}\\[\\]0-9.\\-+Eaeflnr-u \\n\\r\\t]', 'g'); +Sys.Serialization.JavaScriptSerializer._jsonStringRegEx = new RegExp('"(\\\\.|[^"\\\\])*"', 'g'); +Sys.Serialization.JavaScriptSerializer._serverTypeFieldName = '__type'; +Sys.Serialization.JavaScriptSerializer._init = function Sys$Serialization$JavaScriptSerializer$_init() { + var replaceChars = ['\\u0000','\\u0001','\\u0002','\\u0003','\\u0004','\\u0005','\\u0006','\\u0007', + '\\b','\\t','\\n','\\u000b','\\f','\\r','\\u000e','\\u000f','\\u0010','\\u0011', + '\\u0012','\\u0013','\\u0014','\\u0015','\\u0016','\\u0017','\\u0018','\\u0019', + '\\u001a','\\u001b','\\u001c','\\u001d','\\u001e','\\u001f']; + Sys.Serialization.JavaScriptSerializer._charsToEscape[0] = '\\'; + Sys.Serialization.JavaScriptSerializer._charsToEscapeRegExs['\\'] = new RegExp('\\\\', 'g'); + Sys.Serialization.JavaScriptSerializer._escapeChars['\\'] = '\\\\'; + Sys.Serialization.JavaScriptSerializer._charsToEscape[1] = '"'; + Sys.Serialization.JavaScriptSerializer._charsToEscapeRegExs['"'] = new RegExp('"', 'g'); + Sys.Serialization.JavaScriptSerializer._escapeChars['"'] = '\\"'; + for (var i = 0; i < 32; i++) { + var c = String.fromCharCode(i); + Sys.Serialization.JavaScriptSerializer._charsToEscape[i+2] = c; + Sys.Serialization.JavaScriptSerializer._charsToEscapeRegExs[c] = new RegExp(c, 'g'); + Sys.Serialization.JavaScriptSerializer._escapeChars[c] = replaceChars[i]; + } +} +Sys.Serialization.JavaScriptSerializer._serializeBooleanWithBuilder = function Sys$Serialization$JavaScriptSerializer$_serializeBooleanWithBuilder(object, stringBuilder) { + stringBuilder.append(object.toString()); +} +Sys.Serialization.JavaScriptSerializer._serializeNumberWithBuilder = function Sys$Serialization$JavaScriptSerializer$_serializeNumberWithBuilder(object, stringBuilder) { + if (isFinite(object)) { + stringBuilder.append(String(object)); + } + else { + throw Error.invalidOperation(Sys.Res.cannotSerializeNonFiniteNumbers); + } +} +Sys.Serialization.JavaScriptSerializer._serializeStringWithBuilder = function Sys$Serialization$JavaScriptSerializer$_serializeStringWithBuilder(string, stringBuilder) { + stringBuilder.append('"'); + if (Sys.Serialization.JavaScriptSerializer._escapeRegEx.test(string)) { + if (Sys.Serialization.JavaScriptSerializer._charsToEscape.length === 0) { + Sys.Serialization.JavaScriptSerializer._init(); + } + if (string.length < 128) { + string = string.replace(Sys.Serialization.JavaScriptSerializer._escapeRegExGlobal, + function(x) { return Sys.Serialization.JavaScriptSerializer._escapeChars[x]; }); + } + else { + for (var i = 0; i < 34; i++) { + var c = Sys.Serialization.JavaScriptSerializer._charsToEscape[i]; + if (string.indexOf(c) !== -1) { + if (Sys.Browser.agent === Sys.Browser.Opera || Sys.Browser.agent === Sys.Browser.FireFox) { + string = string.split(c).join(Sys.Serialization.JavaScriptSerializer._escapeChars[c]); + } + else { + string = string.replace(Sys.Serialization.JavaScriptSerializer._charsToEscapeRegExs[c], + Sys.Serialization.JavaScriptSerializer._escapeChars[c]); + } + } + } + } + } + stringBuilder.append(string); + stringBuilder.append('"'); +} +Sys.Serialization.JavaScriptSerializer._serializeWithBuilder = function Sys$Serialization$JavaScriptSerializer$_serializeWithBuilder(object, stringBuilder, sort, prevObjects) { + var i; + switch (typeof object) { + case 'object': + if (object) { + if (prevObjects){ + for( var j = 0; j < prevObjects.length; j++) { + if (prevObjects[j] === object) { + throw Error.invalidOperation(Sys.Res.cannotSerializeObjectWithCycle); + } + } + } + else { + prevObjects = new Array(); + } + try { + Array.add(prevObjects, object); + + if (Number.isInstanceOfType(object)){ + Sys.Serialization.JavaScriptSerializer._serializeNumberWithBuilder(object, stringBuilder); + } + else if (Boolean.isInstanceOfType(object)){ + Sys.Serialization.JavaScriptSerializer._serializeBooleanWithBuilder(object, stringBuilder); + } + else if (String.isInstanceOfType(object)){ + Sys.Serialization.JavaScriptSerializer._serializeStringWithBuilder(object, stringBuilder); + } + + else if (Array.isInstanceOfType(object)) { + stringBuilder.append('['); + + for (i = 0; i < object.length; ++i) { + if (i > 0) { + stringBuilder.append(','); + } + Sys.Serialization.JavaScriptSerializer._serializeWithBuilder(object[i], stringBuilder,false,prevObjects); + } + stringBuilder.append(']'); + } + else { + if (Date.isInstanceOfType(object)) { + stringBuilder.append('"\\/Date('); + stringBuilder.append(object.getTime()); + stringBuilder.append(')\\/"'); + break; + } + var properties = []; + var propertyCount = 0; + for (var name in object) { + if (name.startsWith('$')) { + continue; + } + if (name === Sys.Serialization.JavaScriptSerializer._serverTypeFieldName && propertyCount !== 0){ + properties[propertyCount++] = properties[0]; + properties[0] = name; + } + else{ + properties[propertyCount++] = name; + } + } + if (sort) properties.sort(); + stringBuilder.append('{'); + var needComma = false; + + for (i=0; i + /// + /// + var e = Function._validateParams(arguments, [ + {name: "object", mayBeNull: true} + ]); + if (e) throw e; + var stringBuilder = new Sys.StringBuilder(); + Sys.Serialization.JavaScriptSerializer._serializeWithBuilder(object, stringBuilder, false); + return stringBuilder.toString(); +} +Sys.Serialization.JavaScriptSerializer.deserialize = function Sys$Serialization$JavaScriptSerializer$deserialize(data, secure) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "data", type: String}, + {name: "secure", type: Boolean, optional: true} + ]); + if (e) throw e; + + if (data.length === 0) throw Error.argument('data', Sys.Res.cannotDeserializeEmptyString); + try { + var exp = data.replace(Sys.Serialization.JavaScriptSerializer._dateRegEx, "$1new Date($2)"); + + if (secure && Sys.Serialization.JavaScriptSerializer._jsonRegEx.test( + exp.replace(Sys.Serialization.JavaScriptSerializer._jsonStringRegEx, ''))) throw null; + return eval('(' + exp + ')'); + } + catch (e) { + throw Error.argument('data', Sys.Res.cannotDeserializeInvalidJson); + } +} + +Sys.CultureInfo = function Sys$CultureInfo(name, numberFormat, dateTimeFormat) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "name", type: String}, + {name: "numberFormat", type: Object}, + {name: "dateTimeFormat", type: Object} + ]); + if (e) throw e; + this.name = name; + this.numberFormat = numberFormat; + this.dateTimeFormat = dateTimeFormat; +} + function Sys$CultureInfo$_getDateTimeFormats() { + if (! this._dateTimeFormats) { + var dtf = this.dateTimeFormat; + this._dateTimeFormats = + [ dtf.MonthDayPattern, + dtf.YearMonthPattern, + dtf.ShortDatePattern, + dtf.ShortTimePattern, + dtf.LongDatePattern, + dtf.LongTimePattern, + dtf.FullDateTimePattern, + dtf.RFC1123Pattern, + dtf.SortableDateTimePattern, + dtf.UniversalSortableDateTimePattern ]; + } + return this._dateTimeFormats; + } + function Sys$CultureInfo$_getMonthIndex(value) { + if (!this._upperMonths) { + this._upperMonths = this._toUpperArray(this.dateTimeFormat.MonthNames); + } + return Array.indexOf(this._upperMonths, this._toUpper(value)); + } + function Sys$CultureInfo$_getAbbrMonthIndex(value) { + if (!this._upperAbbrMonths) { + this._upperAbbrMonths = this._toUpperArray(this.dateTimeFormat.AbbreviatedMonthNames); + } + return Array.indexOf(this._upperAbbrMonths, this._toUpper(value)); + } + function Sys$CultureInfo$_getDayIndex(value) { + if (!this._upperDays) { + this._upperDays = this._toUpperArray(this.dateTimeFormat.DayNames); + } + return Array.indexOf(this._upperDays, this._toUpper(value)); + } + function Sys$CultureInfo$_getAbbrDayIndex(value) { + if (!this._upperAbbrDays) { + this._upperAbbrDays = this._toUpperArray(this.dateTimeFormat.AbbreviatedDayNames); + } + return Array.indexOf(this._upperAbbrDays, this._toUpper(value)); + } + function Sys$CultureInfo$_toUpperArray(arr) { + var result = []; + for (var i = 0, il = arr.length; i < il; i++) { + result[i] = this._toUpper(arr[i]); + } + return result; + } + function Sys$CultureInfo$_toUpper(value) { + return value.split("\u00A0").join(' ').toUpperCase(); + } +Sys.CultureInfo.prototype = { + _getDateTimeFormats: Sys$CultureInfo$_getDateTimeFormats, + _getMonthIndex: Sys$CultureInfo$_getMonthIndex, + _getAbbrMonthIndex: Sys$CultureInfo$_getAbbrMonthIndex, + _getDayIndex: Sys$CultureInfo$_getDayIndex, + _getAbbrDayIndex: Sys$CultureInfo$_getAbbrDayIndex, + _toUpperArray: Sys$CultureInfo$_toUpperArray, + _toUpper: Sys$CultureInfo$_toUpper +} +Sys.CultureInfo._parse = function Sys$CultureInfo$_parse(value) { + var cultureInfo = Sys.Serialization.JavaScriptSerializer.deserialize(value); + return new Sys.CultureInfo(cultureInfo.name, cultureInfo.numberFormat, cultureInfo.dateTimeFormat); +} +Sys.CultureInfo.registerClass('Sys.CultureInfo'); +Sys.CultureInfo.InvariantCulture = Sys.CultureInfo._parse('{"name":"","numberFormat":{"CurrencyDecimalDigits":2,"CurrencyDecimalSeparator":".","IsReadOnly":true,"CurrencyGroupSizes":[3],"NumberGroupSizes":[3],"PercentGroupSizes":[3],"CurrencyGroupSeparator":",","CurrencySymbol":"\u00A4","NaNSymbol":"NaN","CurrencyNegativePattern":0,"NumberNegativePattern":1,"PercentPositivePattern":0,"PercentNegativePattern":0,"NegativeInfinitySymbol":"-Infinity","NegativeSign":"-","NumberDecimalDigits":2,"NumberDecimalSeparator":".","NumberGroupSeparator":",","CurrencyPositivePattern":0,"PositiveInfinitySymbol":"Infinity","PositiveSign":"+","PercentDecimalDigits":2,"PercentDecimalSeparator":".","PercentGroupSeparator":",","PercentSymbol":"%","PerMilleSymbol":"\u2030","NativeDigits":["0","1","2","3","4","5","6","7","8","9"],"DigitSubstitution":1},"dateTimeFormat":{"AMDesignator":"AM","Calendar":{"MinSupportedDateTime":"@-62135568000000@","MaxSupportedDateTime":"@253402300799999@","AlgorithmType":1,"CalendarType":1,"Eras":[1],"TwoDigitYearMax":2029,"IsReadOnly":true},"DateSeparator":"/","FirstDayOfWeek":0,"CalendarWeekRule":0,"FullDateTimePattern":"dddd, dd MMMM yyyy HH:mm:ss","LongDatePattern":"dddd, dd MMMM yyyy","LongTimePattern":"HH:mm:ss","MonthDayPattern":"MMMM dd","PMDesignator":"PM","RFC1123Pattern":"ddd, dd MMM yyyy HH\':\'mm\':\'ss \'GMT\'","ShortDatePattern":"MM/dd/yyyy","ShortTimePattern":"HH:mm","SortableDateTimePattern":"yyyy\'-\'MM\'-\'dd\'T\'HH\':\'mm\':\'ss","TimeSeparator":":","UniversalSortableDateTimePattern":"yyyy\'-\'MM\'-\'dd HH\':\'mm\':\'ss\'Z\'","YearMonthPattern":"yyyy MMMM","AbbreviatedDayNames":["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],"ShortestDayNames":["Su","Mo","Tu","We","Th","Fr","Sa"],"DayNames":["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],"AbbreviatedMonthNames":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",""],"MonthNames":["January","February","March","April","May","June","July","August","September","October","November","December",""],"IsReadOnly":true,"NativeCalendarName":"Gregorian Calendar","AbbreviatedMonthGenitiveNames":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",""],"MonthGenitiveNames":["January","February","March","April","May","June","July","August","September","October","November","December",""]}}'); +if (typeof(__cultureInfo) === 'undefined') { + var __cultureInfo = '{"name":"en-US","numberFormat":{"CurrencyDecimalDigits":2,"CurrencyDecimalSeparator":".","IsReadOnly":false,"CurrencyGroupSizes":[3],"NumberGroupSizes":[3],"PercentGroupSizes":[3],"CurrencyGroupSeparator":",","CurrencySymbol":"$","NaNSymbol":"NaN","CurrencyNegativePattern":0,"NumberNegativePattern":1,"PercentPositivePattern":0,"PercentNegativePattern":0,"NegativeInfinitySymbol":"-Infinity","NegativeSign":"-","NumberDecimalDigits":2,"NumberDecimalSeparator":".","NumberGroupSeparator":",","CurrencyPositivePattern":0,"PositiveInfinitySymbol":"Infinity","PositiveSign":"+","PercentDecimalDigits":2,"PercentDecimalSeparator":".","PercentGroupSeparator":",","PercentSymbol":"%","PerMilleSymbol":"\u2030","NativeDigits":["0","1","2","3","4","5","6","7","8","9"],"DigitSubstitution":1},"dateTimeFormat":{"AMDesignator":"AM","Calendar":{"MinSupportedDateTime":"@-62135568000000@","MaxSupportedDateTime":"@253402300799999@","AlgorithmType":1,"CalendarType":1,"Eras":[1],"TwoDigitYearMax":2029,"IsReadOnly":false},"DateSeparator":"/","FirstDayOfWeek":0,"CalendarWeekRule":0,"FullDateTimePattern":"dddd, MMMM dd, yyyy h:mm:ss tt","LongDatePattern":"dddd, MMMM dd, yyyy","LongTimePattern":"h:mm:ss tt","MonthDayPattern":"MMMM dd","PMDesignator":"PM","RFC1123Pattern":"ddd, dd MMM yyyy HH\':\'mm\':\'ss \'GMT\'","ShortDatePattern":"M/d/yyyy","ShortTimePattern":"h:mm tt","SortableDateTimePattern":"yyyy\'-\'MM\'-\'dd\'T\'HH\':\'mm\':\'ss","TimeSeparator":":","UniversalSortableDateTimePattern":"yyyy\'-\'MM\'-\'dd HH\':\'mm\':\'ss\'Z\'","YearMonthPattern":"MMMM, yyyy","AbbreviatedDayNames":["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],"ShortestDayNames":["Su","Mo","Tu","We","Th","Fr","Sa"],"DayNames":["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],"AbbreviatedMonthNames":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",""],"MonthNames":["January","February","March","April","May","June","July","August","September","October","November","December",""],"IsReadOnly":false,"NativeCalendarName":"Gregorian Calendar","AbbreviatedMonthGenitiveNames":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",""],"MonthGenitiveNames":["January","February","March","April","May","June","July","August","September","October","November","December",""]}}'; +} +Sys.CultureInfo.CurrentCulture = Sys.CultureInfo._parse(__cultureInfo); +delete __cultureInfo; + +Sys.UI.Behavior = function Sys$UI$Behavior(element) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true} + ]); + if (e) throw e; + Sys.UI.Behavior.initializeBase(this); + this._element = element; + var behaviors = element._behaviors; + if (!behaviors) { + element._behaviors = [this]; + } + else { + behaviors[behaviors.length] = this; + } +} + function Sys$UI$Behavior$get_element() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._element; + } + function Sys$UI$Behavior$get_id() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + var baseId = Sys.UI.Behavior.callBaseMethod(this, 'get_id'); + if (baseId) return baseId; + if (!this._element || !this._element.id) return ''; + return this._element.id + '$' + this.get_name(); + } + function Sys$UI$Behavior$get_name() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (this._name) return this._name; + var name = Object.getTypeName(this); + var i = name.lastIndexOf('.'); + if (i != -1) name = name.substr(i + 1); + if (!this.get_isInitialized()) this._name = name; + return name; + } + function Sys$UI$Behavior$set_name(value) { + var e = Function._validateParams(arguments, [{name: "value", type: String}]); + if (e) throw e; + if ((value === '') || (value.charAt(0) === ' ') || (value.charAt(value.length - 1) === ' ')) + throw Error.argument('value', Sys.Res.invalidId); + if (typeof(this._element[value]) !== 'undefined') + throw Error.invalidOperation(String.format(Sys.Res.behaviorDuplicateName, value)); + if (this.get_isInitialized()) throw Error.invalidOperation(Sys.Res.cantSetNameAfterInit); + this._name = value; + } + function Sys$UI$Behavior$initialize() { + Sys.UI.Behavior.callBaseMethod(this, 'initialize'); + var name = this.get_name(); + if (name) this._element[name] = this; + } + function Sys$UI$Behavior$dispose() { + Sys.UI.Behavior.callBaseMethod(this, 'dispose'); + if (this._element) { + var name = this.get_name(); + if (name) { + this._element[name] = null; + } + Array.remove(this._element._behaviors, this); + delete this._element; + } + } +Sys.UI.Behavior.prototype = { + _name: null, + get_element: Sys$UI$Behavior$get_element, + get_id: Sys$UI$Behavior$get_id, + get_name: Sys$UI$Behavior$get_name, + set_name: Sys$UI$Behavior$set_name, + initialize: Sys$UI$Behavior$initialize, + dispose: Sys$UI$Behavior$dispose +} +Sys.UI.Behavior.registerClass('Sys.UI.Behavior', Sys.Component); +Sys.UI.Behavior.getBehaviorByName = function Sys$UI$Behavior$getBehaviorByName(element, name) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true}, + {name: "name", type: String} + ]); + if (e) throw e; + var b = element[name]; + return (b && Sys.UI.Behavior.isInstanceOfType(b)) ? b : null; +} +Sys.UI.Behavior.getBehaviors = function Sys$UI$Behavior$getBehaviors(element) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true} + ]); + if (e) throw e; + if (!element._behaviors) return []; + return Array.clone(element._behaviors); +} +Sys.UI.Behavior.getBehaviorsByType = function Sys$UI$Behavior$getBehaviorsByType(element, type) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true}, + {name: "type", type: Type} + ]); + if (e) throw e; + var behaviors = element._behaviors; + var results = []; + if (behaviors) { + for (var i = 0, l = behaviors.length; i < l; i++) { + if (type.isInstanceOfType(behaviors[i])) { + results[results.length] = behaviors[i]; + } + } + } + return results; +} + +Sys.UI.VisibilityMode = function Sys$UI$VisibilityMode() { + /// + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); +} +Sys.UI.VisibilityMode.prototype = { + hide: 0, + collapse: 1 +} +Sys.UI.VisibilityMode.registerEnum("Sys.UI.VisibilityMode"); + +Sys.UI.Control = function Sys$UI$Control(element) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true} + ]); + if (e) throw e; + if (typeof(element.control) != 'undefined') throw Error.invalidOperation(Sys.Res.controlAlreadyDefined); + Sys.UI.Control.initializeBase(this); + this._element = element; + element.control = this; +} + function Sys$UI$Control$get_element() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._element; + } + function Sys$UI$Control$get_id() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (!this._element) return ''; + return this._element.id; + } + function Sys$UI$Control$set_id(value) { + var e = Function._validateParams(arguments, [{name: "value", type: String}]); + if (e) throw e; + throw Error.invalidOperation(Sys.Res.cantSetId); + } + function Sys$UI$Control$get_parent() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (this._parent) return this._parent; + if (!this._element) return null; + + var parentElement = this._element.parentNode; + while (parentElement) { + if (parentElement.control) { + return parentElement.control; + } + parentElement = parentElement.parentNode; + } + return null; + } + function Sys$UI$Control$set_parent(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Sys.UI.Control}]); + if (e) throw e; + if (!this._element) throw Error.invalidOperation(Sys.Res.cantBeCalledAfterDispose); + var parents = [this]; + var current = value; + while (current) { + if (Array.contains(parents, current)) throw Error.invalidOperation(Sys.Res.circularParentChain); + parents[parents.length] = current; + current = current.get_parent(); + } + this._parent = value; + } + function Sys$UI$Control$get_visibilityMode() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (!this._element) throw Error.invalidOperation(Sys.Res.cantBeCalledAfterDispose); + return Sys.UI.DomElement.getVisibilityMode(this._element); + } + function Sys$UI$Control$set_visibilityMode(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Sys.UI.VisibilityMode}]); + if (e) throw e; + if (!this._element) throw Error.invalidOperation(Sys.Res.cantBeCalledAfterDispose); + Sys.UI.DomElement.setVisibilityMode(this._element, value); + } + function Sys$UI$Control$get_visible() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (!this._element) throw Error.invalidOperation(Sys.Res.cantBeCalledAfterDispose); + return Sys.UI.DomElement.getVisible(this._element); + } + function Sys$UI$Control$set_visible(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Boolean}]); + if (e) throw e; + if (!this._element) throw Error.invalidOperation(Sys.Res.cantBeCalledAfterDispose); + Sys.UI.DomElement.setVisible(this._element, value) + } + function Sys$UI$Control$addCssClass(className) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "className", type: String} + ]); + if (e) throw e; + if (!this._element) throw Error.invalidOperation(Sys.Res.cantBeCalledAfterDispose); + Sys.UI.DomElement.addCssClass(this._element, className); + } + function Sys$UI$Control$dispose() { + Sys.UI.Control.callBaseMethod(this, 'dispose'); + if (this._element) { + this._element.control = undefined; + delete this._element; + } + if (this._parent) delete this._parent; + } + function Sys$UI$Control$onBubbleEvent(source, args) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "source"}, + {name: "args", type: Sys.EventArgs} + ]); + if (e) throw e; + return false; + } + function Sys$UI$Control$raiseBubbleEvent(source, args) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "source"}, + {name: "args", type: Sys.EventArgs} + ]); + if (e) throw e; + var currentTarget = this.get_parent(); + while (currentTarget) { + if (currentTarget.onBubbleEvent(source, args)) { + return; + } + currentTarget = currentTarget.get_parent(); + } + } + function Sys$UI$Control$removeCssClass(className) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "className", type: String} + ]); + if (e) throw e; + if (!this._element) throw Error.invalidOperation(Sys.Res.cantBeCalledAfterDispose); + Sys.UI.DomElement.removeCssClass(this._element, className); + } + function Sys$UI$Control$toggleCssClass(className) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "className", type: String} + ]); + if (e) throw e; + if (!this._element) throw Error.invalidOperation(Sys.Res.cantBeCalledAfterDispose); + Sys.UI.DomElement.toggleCssClass(this._element, className); + } +Sys.UI.Control.prototype = { + _parent: null, + _visibilityMode: Sys.UI.VisibilityMode.hide, + get_element: Sys$UI$Control$get_element, + get_id: Sys$UI$Control$get_id, + set_id: Sys$UI$Control$set_id, + get_parent: Sys$UI$Control$get_parent, + set_parent: Sys$UI$Control$set_parent, + get_visibilityMode: Sys$UI$Control$get_visibilityMode, + set_visibilityMode: Sys$UI$Control$set_visibilityMode, + get_visible: Sys$UI$Control$get_visible, + set_visible: Sys$UI$Control$set_visible, + addCssClass: Sys$UI$Control$addCssClass, + dispose: Sys$UI$Control$dispose, + onBubbleEvent: Sys$UI$Control$onBubbleEvent, + raiseBubbleEvent: Sys$UI$Control$raiseBubbleEvent, + removeCssClass: Sys$UI$Control$removeCssClass, + toggleCssClass: Sys$UI$Control$toggleCssClass +} +Sys.UI.Control.registerClass('Sys.UI.Control', Sys.Component); + + +Type.registerNamespace('Sys'); + +Sys.Res={ +'urlMustBeLessThan1024chars':'The history state must be small enough to not make the url larger than 1024 characters.', +'argumentTypeName':'Value is not the name of an existing type.', +'methodRegisteredTwice':'Method {0} has already been registered.', +'cantSetIdAfterInit':'The id property can\'t be set on this object after initialization.', +'cantBeCalledAfterDispose':'Can\'t be called after dispose.', +'componentCantSetIdAfterAddedToApp':'The id property of a component can\'t be set after it\'s been added to the Application object.', +'behaviorDuplicateName':'A behavior with name \'{0}\' already exists or it is the name of an existing property on the target element.', +'notATypeName':'Value is not a valid type name.', +'typeShouldBeTypeOrString':'Value is not a valid type or a valid type name.', +'historyInvalidHistorySettingCombination':'Cannot set enableHistory to false when ScriptManager.EnableHistory is true.', +'stateMustBeStringDictionary':'The state object can only have null and string fields.', +'boolTrueOrFalse':'Value must be \'true\' or \'false\'.', +'scriptLoadFailedNoHead':'ScriptLoader requires pages to contain a element.', +'stringFormatInvalid':'The format string is invalid.', +'referenceNotFound':'Component \'{0}\' was not found.', +'enumReservedName':'\'{0}\' is a reserved name that can\'t be used as an enum value name.', +'eventHandlerNotFound':'Handler not found.', +'circularParentChain':'The chain of control parents can\'t have circular references.', +'undefinedEvent':'\'{0}\' is not an event.', +'notAMethod':'{0} is not a method.', +'propertyUndefined':'\'{0}\' is not a property or an existing field.', +'historyCannotEnableHistory':'Cannot set enableHistory after initialization.', +'eventHandlerInvalid':'Handler was not added through the Sys.UI.DomEvent.addHandler method.', +'scriptLoadFailedDebug':'The script \'{0}\' failed to load. Check for:\r\n Inaccessible path.\r\n Script errors. (IE) Enable \'Display a notification about every script error\' under advanced settings.\r\n Missing call to Sys.Application.notifyScriptLoaded().', +'propertyNotWritable':'\'{0}\' is not a writable property.', +'enumInvalidValueName':'\'{0}\' is not a valid name for an enum value.', +'controlAlreadyDefined':'A control is already associated with the element.', +'addHandlerCantBeUsedForError':'Can\'t add a handler for the error event using this method. Please set the window.onerror property instead.', +'namespaceContainsObject':'Object {0} already exists and is not a namespace.', +'cantAddNonFunctionhandler':'Can\'t add a handler that is not a function.', +'invalidNameSpace':'Value is not a valid namespace identifier.', +'notAnInterface':'Value is not a valid interface.', +'eventHandlerNotFunction':'Handler must be a function.', +'propertyNotAnArray':'\'{0}\' is not an Array property.', +'typeRegisteredTwice':'Type {0} has already been registered. The type may be defined multiple times or the script file that defines it may have already been loaded. A possible cause is a change of settings during a partial update.', +'cantSetNameAfterInit':'The name property can\'t be set on this object after initialization.', +'historyMissingFrame':'For the history feature to work in IE, the page must have an iFrame element with id \'__historyFrame\' pointed to a page that gets its title from the \'title\' query string parameter and calls Sys.Application._onIFrameLoad() on the parent window. This can be done by setting EnableHistory to true on ScriptManager.', +'appDuplicateComponent':'Two components with the same id \'{0}\' can\'t be added to the application.', +'historyCannotAddHistoryPointWithHistoryDisabled':'A history point can only be added if enableHistory is set to true.', +'appComponentMustBeInitialized':'Components must be initialized before they are added to the Application object.', +'baseNotAClass':'Value is not a class.', +'methodNotFound':'No method found with name \'{0}\'.', +'arrayParseBadFormat':'Value must be a valid string representation for an array. It must start with a \'[\' and end with a \']\'.', +'stateFieldNameInvalid':'State field names must not contain any \'=\' characters.', +'cantSetId':'The id property can\'t be set on this object.', +'historyMissingHiddenInput':'For the history feature to work in Safari 2, the page must have a hidden input element with id \'__history\'.', +'stringFormatBraceMismatch':'The format string contains an unmatched opening or closing brace.', +'enumValueNotInteger':'An enumeration definition can only contain integer values.', +'propertyNullOrUndefined':'Cannot set the properties of \'{0}\' because it returned a null value.', +'argumentDomNode':'Value must be a DOM element or a text node.', +'componentCantSetIdTwice':'The id property of a component can\'t be set more than once.', +'createComponentOnDom':'Value must be null for Components that are not Controls or Behaviors.', +'createNotComponent':'{0} does not derive from Sys.Component.', +'createNoDom':'Value must not be null for Controls and Behaviors.', +'cantAddWithoutId':'Can\'t add a component that doesn\'t have an id.', +'badTypeName':'Value is not the name of the type being registered or the name is a reserved word.', +'argumentInteger':'Value must be an integer.', +'scriptLoadMultipleCallbacks':'The script \'{0}\' contains multiple calls to Sys.Application.notifyScriptLoaded(). Only one is allowed.', +'invokeCalledTwice':'Cannot call invoke more than once.', +'webServiceFailed':'The server method \'{0}\' failed with the following error: {1}', +'webServiceInvalidJsonWrapper':'The server method \'{0}\' returned invalid data. The \'d\' property is missing from the JSON wrapper.', +'argumentType':'Object cannot be converted to the required type.', +'argumentNull':'Value cannot be null.', +'controlCantSetId':'The id property can\'t be set on a control.', +'formatBadFormatSpecifier':'Format specifier was invalid.', +'webServiceFailedNoMsg':'The server method \'{0}\' failed.', +'argumentDomElement':'Value must be a DOM element.', +'invalidExecutorType':'Could not create a valid Sys.Net.WebRequestExecutor from: {0}.', +'cannotCallBeforeResponse':'Cannot call {0} when responseAvailable is false.', +'actualValue':'Actual value was {0}.', +'enumInvalidValue':'\'{0}\' is not a valid value for enum {1}.', +'scriptLoadFailed':'The script \'{0}\' could not be loaded.', +'parameterCount':'Parameter count mismatch.', +'cannotDeserializeEmptyString':'Cannot deserialize empty string.', +'formatInvalidString':'Input string was not in a correct format.', +'invalidTimeout':'Value must be greater than or equal to zero.', +'cannotAbortBeforeStart':'Cannot abort when executor has not started.', +'argument':'Value does not fall within the expected range.', +'cannotDeserializeInvalidJson':'Cannot deserialize. The data does not correspond to valid JSON.', +'invalidHttpVerb':'httpVerb cannot be set to an empty or null string.', +'nullWebRequest':'Cannot call executeRequest with a null webRequest.', +'eventHandlerInvalid':'Handler was not added through the Sys.UI.DomEvent.addHandler method.', +'cannotSerializeNonFiniteNumbers':'Cannot serialize non finite numbers.', +'argumentUndefined':'Value cannot be undefined.', +'webServiceInvalidReturnType':'The server method \'{0}\' returned an invalid type. Expected type: {1}', +'servicePathNotSet':'The path to the web service has not been set.', +'argumentTypeWithTypes':'Object of type \'{0}\' cannot be converted to type \'{1}\'.', +'cannotCallOnceStarted':'Cannot call {0} once started.', +'badBaseUrl1':'Base URL does not contain ://.', +'badBaseUrl2':'Base URL does not contain another /.', +'badBaseUrl3':'Cannot find last / in base URL.', +'setExecutorAfterActive':'Cannot set executor after it has become active.', +'paramName':'Parameter name: {0}', +'cannotCallOutsideHandler':'Cannot call {0} outside of a completed event handler.', +'cannotSerializeObjectWithCycle':'Cannot serialize object with cyclic reference within child properties.', +'format':'One of the identified items was in an invalid format.', +'assertFailedCaller':'Assertion Failed: {0}\r\nat {1}', +'argumentOutOfRange':'Specified argument was out of the range of valid values.', +'webServiceTimedOut':'The server method \'{0}\' timed out.', +'notImplemented':'The method or operation is not implemented.', +'assertFailed':'Assertion Failed: {0}', +'invalidOperation':'Operation is not valid due to the current state of the object.', +'breakIntoDebugger':'{0}\r\n\r\nBreak into debugger?' +}; + +if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded(); diff --git a/ShowOff/Scripts/MicrosoftAjax.js b/ShowOff/Scripts/MicrosoftAjax.js new file mode 100644 index 0000000..db85c14 --- /dev/null +++ b/ShowOff/Scripts/MicrosoftAjax.js @@ -0,0 +1,7 @@ +//---------------------------------------------------------- +// Copyright (C) Microsoft Corporation. All rights reserved. +//---------------------------------------------------------- +// MicrosoftAjax.js +Function.__typeName="Function";Function.__class=true;Function.createCallback=function(b,a){return function(){var e=arguments.length;if(e>0){var d=[];for(var c=0;cc){var f=Error.parameterCount();f.popStackFrame();return f}return null};Function._validateParameter=function(c,a,h){var b,g=a.type,l=!!a.integer,k=!!a.domElement,m=!!a.mayBeNull;b=Function._validateParameterType(c,g,l,k,m,h);if(b){b.popStackFrame();return b}var e=a.elementType,f=!!a.elementMayBeNull;if(g===Array&&typeof c!=="undefined"&&c!==null&&(e||!f)){var j=!!a.elementInteger,i=!!a.elementDomElement;for(var d=0;d0&&(dc.Calendar.TwoDigitYearMax)return a-100}return a};Date._getParseRegExp=function(b,e){if(!b._parseRegExp)b._parseRegExp={};else if(b._parseRegExp[e])return b._parseRegExp[e];var c=Date._expandFormat(b,e);c=c.replace(/([\^\$\.\*\+\?\|\[\]\(\)\{\}])/g,"\\\\$1");var a=new Sys.StringBuilder("^"),j=[],f=0,i=0,h=Date._getTokenRegExp(),d;while((d=h.exec(c))!==null){var l=c.slice(f,d.index);f=h.lastIndex;i+=Date._appendPreOrPostMatch(l,a);if(i%2===1){a.append(d[0]);continue}switch(d[0]){case "dddd":case "ddd":case "MMMM":case "MMM":a.append("(\\D+)");break;case "tt":case "t":a.append("(\\D*)");break;case "yyyy":a.append("(\\d{4})");break;case "fff":a.append("(\\d{3})");break;case "ff":a.append("(\\d{2})");break;case "f":a.append("(\\d)");break;case "dd":case "d":case "MM":case "M":case "yy":case "y":case "HH":case "H":case "hh":case "h":case "mm":case "m":case "ss":case "s":a.append("(\\d\\d?)");break;case "zzz":a.append("([+-]?\\d\\d?:\\d{2})");break;case "zz":case "z":a.append("([+-]?\\d\\d?)")}Array.add(j,d[0])}Date._appendPreOrPostMatch(c.slice(f),a);a.append("$");var k=a.toString().replace(/\s+/g,"\\s+"),g={"regExp":k,"groups":j};b._parseRegExp[e]=g;return g};Date._getTokenRegExp=function(){return /dddd|ddd|dd|d|MMMM|MMM|MM|M|yyyy|yy|y|hh|h|HH|H|mm|m|ss|s|tt|t|fff|ff|f|zzz|zz|z/g};Date.parseLocale=function(a){return Date._parse(a,Sys.CultureInfo.CurrentCulture,arguments)};Date.parseInvariant=function(a){return Date._parse(a,Sys.CultureInfo.InvariantCulture,arguments)};Date._parse=function(g,c,h){var e=false;for(var a=1,i=h.length;a31)return null;break;case "MMMM":c=j._getMonthIndex(a);if(c<0||c>11)return null;break;case "MMM":c=j._getAbbrMonthIndex(a);if(c<0||c>11)return null;break;case "M":case "MM":var c=parseInt(a,10)-1;if(c<0||c>11)return null;break;case "y":case "yy":f=Date._expandYear(m,parseInt(a,10));if(f<0||f>9999)return null;break;case "yyyy":f=parseInt(a,10);if(f<0||f>9999)return null;break;case "h":case "hh":d=parseInt(a,10);if(d===12)d=0;if(d<0||d>11)return null;break;case "H":case "HH":d=parseInt(a,10);if(d<0||d>23)return null;break;case "m":case "mm":n=parseInt(a,10);if(n<0||n>59)return null;break;case "s":case "ss":o=parseInt(a,10);if(o<0||o>59)return null;break;case "tt":case "t":var u=a.toUpperCase();r=u===m.PMDesignator.toUpperCase();if(!r&&u!==m.AMDesignator.toUpperCase())return null;break;case "f":e=parseInt(a,10)*100;if(e<0||e>999)return null;break;case "ff":e=parseInt(a,10)*10;if(e<0||e>999)return null;break;case "fff":e=parseInt(a,10);if(e<0||e>999)return null;break;case "dddd":g=j._getDayIndex(a);if(g<0||g>6)return null;break;case "ddd":g=j._getAbbrDayIndex(a);if(g<0||g>6)return null;break;case "zzz":var q=a.split(/:/);if(q.length!==2)return null;var i=parseInt(q[0],10);if(i<-12||i>13)return null;var l=parseInt(q[1],10);if(l<0||l>59)return null;k=i*60+(a.startsWith("-")?-l:l);break;case "z":case "zz":var i=parseInt(a,10);if(i<-12||i>13)return null;k=i*60}}var b=new Date;if(f===null)f=b.getFullYear();if(c===null)c=b.getMonth();if(h===null)h=b.getDate();b.setFullYear(f,c,h);if(b.getDate()!==h)return null;if(g!==null&&b.getDay()!==g)return null;if(r&&d<12)d+=12;b.setHours(d,n,o,e);if(k!==null){var t=b.getMinutes()-(k+b.getTimezoneOffset());b.setHours(b.getHours()+parseInt(t/60,10),t%60)}return b};Date.prototype.format=function(a){return this._toFormattedString(a,Sys.CultureInfo.InvariantCulture)};Date.prototype.localeFormat=function(a){return this._toFormattedString(a,Sys.CultureInfo.CurrentCulture)};Date.prototype._toFormattedString=function(e,h){if(!e||e.length===0||e==="i")if(h&&h.name.length>0)return this.toLocaleString();else return this.toString();var d=h.dateTimeFormat;e=Date._expandFormat(d,e);var a=new Sys.StringBuilder,b;function c(a){if(a<10)return "0"+a;return a.toString()}function g(a){if(a<10)return "00"+a;if(a<100)return "0"+a;return a.toString()}var j=0,i=Date._getTokenRegExp();for(;true;){var l=i.lastIndex,f=i.exec(e),k=e.slice(l,f?f.index:e.length);j+=Date._appendPreOrPostMatch(k,a);if(!f)break;if(j%2===1){a.append(f[0]);continue}switch(f[0]){case "dddd":a.append(d.DayNames[this.getDay()]);break;case "ddd":a.append(d.AbbreviatedDayNames[this.getDay()]);break;case "dd":a.append(c(this.getDate()));break;case "d":a.append(this.getDate());break;case "MMMM":a.append(d.MonthNames[this.getMonth()]);break;case "MMM":a.append(d.AbbreviatedMonthNames[this.getMonth()]);break;case "MM":a.append(c(this.getMonth()+1));break;case "M":a.append(this.getMonth()+1);break;case "yyyy":a.append(this.getFullYear());break;case "yy":a.append(c(this.getFullYear()%100));break;case "y":a.append(this.getFullYear()%100);break;case "hh":b=this.getHours()%12;if(b===0)b=12;a.append(c(b));break;case "h":b=this.getHours()%12;if(b===0)b=12;a.append(b);break;case "HH":a.append(c(this.getHours()));break;case "H":a.append(this.getHours());break;case "mm":a.append(c(this.getMinutes()));break;case "m":a.append(this.getMinutes());break;case "ss":a.append(c(this.getSeconds()));break;case "s":a.append(this.getSeconds());break;case "tt":a.append(this.getHours()<12?d.AMDesignator:d.PMDesignator);break;case "t":a.append((this.getHours()<12?d.AMDesignator:d.PMDesignator).charAt(0));break;case "f":a.append(g(this.getMilliseconds()).charAt(0));break;case "ff":a.append(g(this.getMilliseconds()).substr(0,2));break;case "fff":a.append(g(this.getMilliseconds()));break;case "z":b=this.getTimezoneOffset()/60;a.append((b<=0?"+":"-")+Math.floor(Math.abs(b)));break;case "zz":b=this.getTimezoneOffset()/60;a.append((b<=0?"+":"-")+c(Math.floor(Math.abs(b))));break;case "zzz":b=this.getTimezoneOffset()/60;a.append((b<=0?"+":"-")+c(Math.floor(Math.abs(b)))+d.TimeSeparator+c(Math.abs(this.getTimezoneOffset()%60)))}}return a.toString()};Number.__typeName="Number";Number.__class=true;Number.parseLocale=function(a){return Number._parse(a,Sys.CultureInfo.CurrentCulture)};Number.parseInvariant=function(a){return Number._parse(a,Sys.CultureInfo.InvariantCulture)};Number._parse=function(b,o){b=b.trim();if(b.match(/^[+-]?infinity$/i))return parseFloat(b);if(b.match(/^0x[a-f0-9]+$/i))return parseInt(b);var a=o.numberFormat,g=Number._parseNumberNegativePattern(b,a,a.NumberNegativePattern),h=g[0],e=g[1];if(h===""&&a.NumberNegativePattern!==1){g=Number._parseNumberNegativePattern(b,a,1);h=g[0];e=g[1]}if(h==="")h="+";var j,d,f=e.indexOf("e");if(f<0)f=e.indexOf("E");if(f<0){d=e;j=null}else{d=e.substr(0,f);j=e.substr(f+1)}var c,k,m=d.indexOf(a.NumberDecimalSeparator);if(m<0){c=d;k=null}else{c=d.substr(0,m);k=d.substr(m+a.NumberDecimalSeparator.length)}c=c.split(a.NumberGroupSeparator).join("");var n=a.NumberGroupSeparator.replace(/\u00A0/g," ");if(a.NumberGroupSeparator!==n)c=c.split(n).join("");var l=h+c;if(k!==null)l+="."+k;if(j!==null){var i=Number._parseNumberNegativePattern(j,a,1);if(i[0]==="")i[0]="+";l+="e"+i[0]+i[1]}if(l.match(/^[+-]?\d*\.?\d*(e[+-]?\d+)?$/))return parseFloat(l);return Number.NaN};Number._parseNumberNegativePattern=function(a,d,e){var b=d.NegativeSign,c=d.PositiveSign;switch(e){case 4:b=" "+b;c=" "+c;case 3:if(a.endsWith(b))return ["-",a.substr(0,a.length-b.length)];else if(a.endsWith(c))return ["+",a.substr(0,a.length-c.length)];break;case 2:b+=" ";c+=" ";case 1:if(a.startsWith(b))return ["-",a.substr(b.length)];else if(a.startsWith(c))return ["+",a.substr(c.length)];break;case 0:if(a.startsWith("(")&&a.endsWith(")"))return ["-",a.substr(1,a.length-2)]}return ["",a]};Number.prototype.format=function(a){return this._toFormattedString(a,Sys.CultureInfo.InvariantCulture)};Number.prototype.localeFormat=function(a){return this._toFormattedString(a,Sys.CultureInfo.CurrentCulture)};Number.prototype._toFormattedString=function(d,j){if(!d||d.length===0||d==="i")if(j&&j.name.length>0)return this.toLocaleString();else return this.toString();var o=["n %","n%","%n"],n=["-n %","-n%","-%n"],p=["(n)","-n","- n","n-","n -"],m=["$n","n$","$ n","n $"],l=["($n)","-$n","$-n","$n-","(n$)","-n$","n-$","n$-","-n $","-$ n","n $-","$ n-","$ -n","n- $","($ n)","(n $)"];function g(a,c,d){for(var b=a.length;b1?parseInt(e[1]):0;e=b.split(".");b=e[0];a=e.length>1?e[1]:"";var q;if(c>0){a=g(a,c,false);b+=a.slice(0,c);a=a.substr(c)}else if(c<0){c=-c;b=g(b,c+1,true);a=b.slice(-c,b.length)+a;b=b.slice(0,-c)}if(i>0){if(a.length>i)a=a.slice(0,i);else a=g(a,i,false);a=p+a}else a="";var d=b.length-1,f="";while(d>=0){if(h===0||h>d)if(f.length>0)return b.slice(0,d+1)+n+f+a;else return b.slice(0,d+1)+a;if(f.length>0)f=b.slice(d-h+1,d+1)+n+f;else f=b.slice(d-h+1,d+1);d-=h;if(k1)b=parseInt(d.slice(1),10);var c;switch(d.charAt(0)){case "d":case "D":c="n";if(b!==-1)e=g(""+e,b,true);if(this<0)e=-e;break;case "c":case "C":if(this<0)c=l[a.CurrencyNegativePattern];else c=m[a.CurrencyPositivePattern];if(b===-1)b=a.CurrencyDecimalDigits;e=i(Math.abs(this),b,a.CurrencyGroupSizes,a.CurrencyGroupSeparator,a.CurrencyDecimalSeparator);break;case "n":case "N":if(this<0)c=p[a.NumberNegativePattern];else c="n";if(b===-1)b=a.NumberDecimalDigits;e=i(Math.abs(this),b,a.NumberGroupSizes,a.NumberGroupSeparator,a.NumberDecimalSeparator);break;case "p":case "P":if(this<0)c=n[a.PercentNegativePattern];else c=o[a.PercentPositivePattern];if(b===-1)b=a.PercentDecimalDigits;e=i(Math.abs(this)*100,b,a.PercentGroupSizes,a.PercentGroupSeparator,a.PercentDecimalSeparator);break;default:throw Error.format(Sys.Res.formatBadFormatSpecifier)}var k=/n|\$|-|%/g,f="";for(;true;){var q=k.lastIndex,h=k.exec(c);f+=c.slice(q,h?h.index:c.length);if(!h)break;switch(h[0]){case "n":f+=e;break;case "$":f+=a.CurrencySymbol;break;case "-":f+=a.NegativeSign;break;case "%":f+=a.PercentSymbol}}return f};RegExp.__typeName="RegExp";RegExp.__class=true;Array.__typeName="Array";Array.__class=true;Array.add=Array.enqueue=function(a,b){a[a.length]=b};Array.addRange=function(a,b){a.push.apply(a,b)};Array.clear=function(a){a.length=0};Array.clone=function(a){if(a.length===1)return [a[0]];else return Array.apply(null,a)};Array.contains=function(a,b){return Array.indexOf(a,b)>=0};Array.dequeue=function(a){return a.shift()};Array.forEach=function(b,e,d){for(var a=0,f=b.length;a=0)b.splice(a,1);return a>=0};Array.removeAt=function(a,b){a.splice(b,1)};if(!window)this.window=this;window.Type=Function;Type.prototype.callBaseMethod=function(a,d,b){var c=this.getBaseMethod(a,d);if(!b)return c.apply(a);else return c.apply(a,b)};Type.prototype.getBaseMethod=function(d,c){var b=this.getBaseType();if(b){var a=b.prototype[c];return a instanceof Function?a:null}return null};Type.prototype.getBaseType=function(){return typeof this.__baseType==="undefined"?null:this.__baseType};Type.prototype.getInterfaces=function(){var a=[],b=this;while(b){var c=b.__interfaces;if(c)for(var d=0,f=c.length;d-1){Sys.Browser.agent=Sys.Browser.InternetExplorer;Sys.Browser.version=parseFloat(navigator.userAgent.match(/MSIE (\d+\.\d+)/)[1]);if(Sys.Browser.version>=8)if(document.documentMode>=7)Sys.Browser.documentMode=document.documentMode;Sys.Browser.hasDebuggerStatement=true}else if(navigator.userAgent.indexOf(" Firefox/")>-1){Sys.Browser.agent=Sys.Browser.Firefox;Sys.Browser.version=parseFloat(navigator.userAgent.match(/Firefox\/(\d+\.\d+)/)[1]);Sys.Browser.name="Firefox";Sys.Browser.hasDebuggerStatement=true}else if(navigator.userAgent.indexOf(" AppleWebKit/")>-1){Sys.Browser.agent=Sys.Browser.Safari;Sys.Browser.version=parseFloat(navigator.userAgent.match(/AppleWebKit\/(\d+(\.\d+)?)/)[1]);Sys.Browser.name="Safari"}else if(navigator.userAgent.indexOf("Opera/")>-1)Sys.Browser.agent=Sys.Browser.Opera;Type.registerNamespace("Sys.UI");Sys._Debug=function(){};Sys._Debug.prototype={_appendConsole:function(a){if(typeof Debug!=="undefined"&&Debug.writeln)Debug.writeln(a);if(window.console&&window.console.log)window.console.log(a);if(window.opera)window.opera.postError(a);if(window.debugService)window.debugService.trace(a)},_appendTrace:function(b){var a=document.getElementById("TraceConsole");if(a&&a.tagName.toUpperCase()==="TEXTAREA")a.value+=b+"\n"},assert:function(c,a,b){if(!c){a=b&&this.assert.caller?String.format(Sys.Res.assertFailedCaller,a,this.assert.caller):String.format(Sys.Res.assertFailed,a);if(confirm(String.format(Sys.Res.breakIntoDebugger,a)))this.fail(a)}},clearTrace:function(){var a=document.getElementById("TraceConsole");if(a&&a.tagName.toUpperCase()==="TEXTAREA")a.value=""},fail:function(message){this._appendConsole(message);if(Sys.Browser.hasDebuggerStatement)eval("debugger")},trace:function(a){this._appendConsole(a);this._appendTrace(a)},traceDump:function(a,b){var c=this._traceDump(a,b,true)},_traceDump:function(a,c,f,b,d){c=c?c:"traceDump";b=b?b:"";if(a===null){this.trace(b+c+": null");return}switch(typeof a){case "undefined":this.trace(b+c+": Undefined");break;case "number":case "string":case "boolean":this.trace(b+c+": "+a);break;default:if(Date.isInstanceOfType(a)||RegExp.isInstanceOfType(a)){this.trace(b+c+": "+a.toString());break}if(!d)d=[];else if(Array.contains(d,a)){this.trace(b+c+": ...");return}Array.add(d,a);if(a==window||a===document||window.HTMLElement&&a instanceof HTMLElement||typeof a.nodeName==="string"){var k=a.tagName?a.tagName:"DomElement";if(a.id)k+=" - "+a.id;this.trace(b+c+" {"+k+"}")}else{var i=Object.getTypeName(a);this.trace(b+c+(typeof i==="string"?" {"+i+"}":""));if(b===""||f){b+=" ";var e,j,l,g,h;if(Array.isInstanceOfType(a)){j=a.length;for(e=0;e=0;d--){var k=h[d].trim();b=a[k];if(typeof b!=="number")throw Error.argument("value",String.format(Sys.Res.enumInvalidValue,c.split(",")[d].trim(),this.__typeName));j|=b}return j}}function Sys$Enum$toString(c){if(typeof c==="undefined"||c===null)return this.__string;var d=this.prototype,a;if(!this.__flags||c===0){for(a in d)if(d[a]===c)return a}else{var b=this.__sortedValues;if(!b){b=[];for(a in d)b[b.length]={key:a,value:d[a]};b.sort(function(a,b){return a.value-b.value});this.__sortedValues=b}var e=[],g=c;for(a=b.length-1;a>=0;a--){var h=b[a],f=h.value;if(f===0)continue;if((f&c)===f){e[e.length]=h.key;g-=f;if(g===0)break}}if(e.length&&g===0)return e.reverse().join(", ")}return ""}Type.prototype.registerEnum=function(b,c){Sys.__upperCaseTypes[b.toUpperCase()]=this;for(var a in this.prototype)this[a]=this.prototype[a];this.__typeName=b;this.parse=Sys$Enum$parse;this.__string=this.toString();this.toString=Sys$Enum$toString;this.__flags=c;this.__enum=true};Type.isEnum=function(a){if(typeof a==="undefined"||a===null)return false;return !!a.__enum};Type.isFlags=function(a){if(typeof a==="undefined"||a===null)return false;return !!a.__flags};Sys.EventHandlerList=function(){this._list={}};Sys.EventHandlerList.prototype={addHandler:function(b,a){Array.add(this._getEvent(b,true),a)},removeHandler:function(c,b){var a=this._getEvent(c);if(!a)return;Array.remove(a,b)},getHandler:function(b){var a=this._getEvent(b);if(!a||a.length===0)return null;a=Array.clone(a);return function(c,d){for(var b=0,e=a.length;b=0;c--)$removeHandler(a,b,d[c].handler)}a._events=null}},$removeHandler=Sys.UI.DomEvent.removeHandler=function(a,e,f){var d=null,c=a._events[e];for(var b=0,g=c.length;b=0)d.className=(a.substr(0,b)+" "+a.substring(b+c.length+1,a.length)).trim()};Sys.UI.DomElement.setLocation=function(b,c,d){var a=b.style;a.position="absolute";a.left=c+"px";a.top=d+"px"};Sys.UI.DomElement.toggleCssClass=function(b,a){if(Sys.UI.DomElement.containsCssClass(b,a))Sys.UI.DomElement.removeCssClass(b,a);else Sys.UI.DomElement.addCssClass(b,a)};Sys.UI.DomElement.getVisibilityMode=function(a){return a._visibilityMode===Sys.UI.VisibilityMode.hide?Sys.UI.VisibilityMode.hide:Sys.UI.VisibilityMode.collapse};Sys.UI.DomElement.setVisibilityMode=function(a,b){Sys.UI.DomElement._ensureOldDisplayMode(a);if(a._visibilityMode!==b){a._visibilityMode=b;if(Sys.UI.DomElement.getVisible(a)===false)if(a._visibilityMode===Sys.UI.VisibilityMode.hide)a.style.display=a._oldDisplayMode;else a.style.display="none";a._visibilityMode=b}};Sys.UI.DomElement.getVisible=function(b){var a=b.currentStyle||Sys.UI.DomElement._getCurrentStyle(b);if(!a)return true;return a.visibility!=="hidden"&&a.display!=="none"};Sys.UI.DomElement.setVisible=function(a,b){if(b!==Sys.UI.DomElement.getVisible(a)){Sys.UI.DomElement._ensureOldDisplayMode(a);a.style.visibility=b?"visible":"hidden";if(b||a._visibilityMode===Sys.UI.VisibilityMode.hide)a.style.display=a._oldDisplayMode;else a.style.display="none"}};Sys.UI.DomElement._ensureOldDisplayMode=function(a){if(!a._oldDisplayMode){var b=a.currentStyle||Sys.UI.DomElement._getCurrentStyle(a);a._oldDisplayMode=b?b.display:null;if(!a._oldDisplayMode||a._oldDisplayMode==="none")switch(a.tagName.toUpperCase()){case "DIV":case "P":case "ADDRESS":case "BLOCKQUOTE":case "BODY":case "COL":case "COLGROUP":case "DD":case "DL":case "DT":case "FIELDSET":case "FORM":case "H1":case "H2":case "H3":case "H4":case "H5":case "H6":case "HR":case "IFRAME":case "LEGEND":case "OL":case "PRE":case "TABLE":case "TD":case "TH":case "TR":case "UL":a._oldDisplayMode="block";break;case "LI":a._oldDisplayMode="list-item";break;default:a._oldDisplayMode="inline"}}};Sys.UI.DomElement._getWindow=function(a){var b=a.ownerDocument||a.document||a;return b.defaultView||b.parentWindow};Sys.UI.DomElement._getCurrentStyle=function(a){if(a.nodeType===3)return null;var c=Sys.UI.DomElement._getWindow(a);if(a.documentElement)a=a.documentElement;var b=c&&a!==c&&c.getComputedStyle?c.getComputedStyle(a,null):a.currentStyle||a.style;if(!b&&Sys.Browser.agent===Sys.Browser.Safari&&a.style){var g=a.style.display,f=a.style.position;a.style.position="absolute";a.style.display="block";var e=c.getComputedStyle(a,null);a.style.display=g;a.style.position=f;b={};for(var d in e)b[d]=e[d];b.display="none"}return b};Sys.IContainer=function(){};Sys.IContainer.prototype={};Sys.IContainer.registerInterface("Sys.IContainer");Sys._ScriptLoader=function(){this._scriptsToLoad=null;this._sessions=[];this._scriptLoadedDelegate=Function.createDelegate(this,this._scriptLoadedHandler)};Sys._ScriptLoader.prototype={dispose:function(){this._stopSession();this._loading=false;if(this._events)delete this._events;this._sessions=null;this._currentSession=null;this._scriptLoadedDelegate=null},loadScripts:function(d,b,c,a){var e={allScriptsLoadedCallback:b,scriptLoadFailedCallback:c,scriptLoadTimeoutCallback:a,scriptsToLoad:this._scriptsToLoad,scriptTimeout:d};this._scriptsToLoad=null;this._sessions[this._sessions.length]=e;if(!this._loading)this._nextSession()},notifyScriptLoaded:function(){if(!this._loading)return;this._currentTask._notified++;if(Sys.Browser.agent===Sys.Browser.Safari)if(this._currentTask._notified===1)window.setTimeout(Function.createDelegate(this,function(){this._scriptLoadedHandler(this._currentTask.get_scriptElement(),true)}),0)},queueCustomScriptTag:function(a){if(!this._scriptsToLoad)this._scriptsToLoad=[];Array.add(this._scriptsToLoad,a)},queueScriptBlock:function(a){if(!this._scriptsToLoad)this._scriptsToLoad=[];Array.add(this._scriptsToLoad,{text:a})},queueScriptReference:function(a){if(!this._scriptsToLoad)this._scriptsToLoad=[];Array.add(this._scriptsToLoad,{src:a})},_createScriptElement:function(c){var a=document.createElement("script");a.type="text/javascript";for(var b in c)a[b]=c[b];return a},_loadScriptsInternal:function(){var b=this._currentSession;if(b.scriptsToLoad&&b.scriptsToLoad.length>0){var c=Array.dequeue(b.scriptsToLoad),a=this._createScriptElement(c);if(a.text&&Sys.Browser.agent===Sys.Browser.Safari){a.innerHTML=a.text;delete a.text}if(typeof c.src==="string"){this._currentTask=new Sys._ScriptLoaderTask(a,this._scriptLoadedDelegate);this._currentTask.execute()}else{document.getElementsByTagName("head")[0].appendChild(a);Sys._ScriptLoader._clearScript(a);this._loadScriptsInternal()}}else{this._stopSession();var d=b.allScriptsLoadedCallback;if(d)d(this);this._nextSession()}},_nextSession:function(){if(this._sessions.length===0){this._loading=false;this._currentSession=null;return}this._loading=true;var a=Array.dequeue(this._sessions);this._currentSession=a;if(a.scriptTimeout>0)this._timeoutCookie=window.setTimeout(Function.createDelegate(this,this._scriptLoadTimeoutHandler),a.scriptTimeout*1000);this._loadScriptsInternal()},_raiseError:function(a){var c=this._currentSession.scriptLoadFailedCallback,b=this._currentTask.get_scriptElement();this._stopSession();if(c){c(this,b,a);this._nextSession()}else{this._loading=false;throw Sys._ScriptLoader._errorScriptLoadFailed(b.src,a)}},_scriptLoadedHandler:function(a,b){if(b&&this._currentTask._notified)if(this._currentTask._notified>1)this._raiseError(true);else{Array.add(Sys._ScriptLoader._getLoadedScripts(),a.src);this._currentTask.dispose();this._currentTask=null;this._loadScriptsInternal()}else this._raiseError(false)},_scriptLoadTimeoutHandler:function(){var a=this._currentSession.scriptLoadTimeoutCallback;this._stopSession();if(a)a(this);this._nextSession()},_stopSession:function(){if(this._timeoutCookie){window.clearTimeout(this._timeoutCookie);this._timeoutCookie=null}if(this._currentTask){this._currentTask.dispose();this._currentTask=null}}};Sys._ScriptLoader.registerClass("Sys._ScriptLoader",null,Sys.IDisposable);Sys._ScriptLoader.getInstance=function(){var a=Sys._ScriptLoader._activeInstance;if(!a)a=Sys._ScriptLoader._activeInstance=new Sys._ScriptLoader;return a};Sys._ScriptLoader.isScriptLoaded=function(b){var a=document.createElement("script");a.src=b;return Array.contains(Sys._ScriptLoader._getLoadedScripts(),a.src)};Sys._ScriptLoader.readLoadedScripts=function(){if(!Sys._ScriptLoader._referencedScripts){var b=Sys._ScriptLoader._referencedScripts=[],c=document.getElementsByTagName("script");for(i=c.length-1;i>=0;i--){var d=c[i],a=d.src;if(a.length)if(!Array.contains(b,a))Array.add(b,a)}}};Sys._ScriptLoader._clearScript=function(a){if(!Sys.Debug.isDebug)a.parentNode.removeChild(a)};Sys._ScriptLoader._errorScriptLoadFailed=function(b,d){var a;if(d)a=Sys.Res.scriptLoadMultipleCallbacks;else a=Sys.Res.scriptLoadFailed;var e="Sys.ScriptLoadFailedException: "+String.format(a,b),c=Error.create(e,{name:"Sys.ScriptLoadFailedException","scriptUrl":b});c.popStackFrame();return c};Sys._ScriptLoader._getLoadedScripts=function(){if(!Sys._ScriptLoader._referencedScripts){Sys._ScriptLoader._referencedScripts=[];Sys._ScriptLoader.readLoadedScripts()}return Sys._ScriptLoader._referencedScripts};Sys._ScriptLoaderTask=function(b,a){this._scriptElement=b;this._completedCallback=a;this._notified=0};Sys._ScriptLoaderTask.prototype={get_scriptElement:function(){return this._scriptElement},dispose:function(){if(this._disposed)return;this._disposed=true;this._removeScriptElementHandlers();Sys._ScriptLoader._clearScript(this._scriptElement);this._scriptElement=null},execute:function(){this._addScriptElementHandlers();document.getElementsByTagName("head")[0].appendChild(this._scriptElement)},_addScriptElementHandlers:function(){this._scriptLoadDelegate=Function.createDelegate(this,this._scriptLoadHandler);if(Sys.Browser.agent!==Sys.Browser.InternetExplorer){this._scriptElement.readyState="loaded";$addHandler(this._scriptElement,"load",this._scriptLoadDelegate)}else $addHandler(this._scriptElement,"readystatechange",this._scriptLoadDelegate);if(this._scriptElement.addEventListener){this._scriptErrorDelegate=Function.createDelegate(this,this._scriptErrorHandler);this._scriptElement.addEventListener("error",this._scriptErrorDelegate,false)}},_removeScriptElementHandlers:function(){if(this._scriptLoadDelegate){var a=this.get_scriptElement();if(Sys.Browser.agent!==Sys.Browser.InternetExplorer)$removeHandler(a,"load",this._scriptLoadDelegate);else $removeHandler(a,"readystatechange",this._scriptLoadDelegate);if(this._scriptErrorDelegate){this._scriptElement.removeEventListener("error",this._scriptErrorDelegate,false);this._scriptErrorDelegate=null}this._scriptLoadDelegate=null}},_scriptErrorHandler:function(){if(this._disposed)return;this._completedCallback(this.get_scriptElement(),false)},_scriptLoadHandler:function(){if(this._disposed)return;var a=this.get_scriptElement();if(a.readyState!=="loaded"&&a.readyState!=="complete")return;var b=this;window.setTimeout(function(){b._completedCallback(a,true)},0)}};Sys._ScriptLoaderTask.registerClass("Sys._ScriptLoaderTask",null,Sys.IDisposable);Sys.ApplicationLoadEventArgs=function(b,a){Sys.ApplicationLoadEventArgs.initializeBase(this);this._components=b;this._isPartialLoad=a};Sys.ApplicationLoadEventArgs.prototype={get_components:function(){return this._components},get_isPartialLoad:function(){return this._isPartialLoad}};Sys.ApplicationLoadEventArgs.registerClass("Sys.ApplicationLoadEventArgs",Sys.EventArgs);Sys.HistoryEventArgs=function(a){Sys.HistoryEventArgs.initializeBase(this);this._state=a};Sys.HistoryEventArgs.prototype={get_state:function(){return this._state}};Sys.HistoryEventArgs.registerClass("Sys.HistoryEventArgs",Sys.EventArgs);Sys._Application=function(){Sys._Application.initializeBase(this);this._disposableObjects=[];this._components={};this._createdComponents=[];this._secondPassComponents=[];this._appLoadHandler=null;this._beginRequestHandler=null;this._clientId=null;this._currentEntry="";this._endRequestHandler=null;this._history=null;this._enableHistory=false;this._historyFrame=null;this._historyInitialized=false;this._historyInitialLength=0;this._historyLength=0;this._historyPointIsNew=false;this._ignoreTimer=false;this._initialState=null;this._state={};this._timerCookie=0;this._timerHandler=null;this._uniqueId=null;this._unloadHandlerDelegate=Function.createDelegate(this,this._unloadHandler);this._loadHandlerDelegate=Function.createDelegate(this,this._loadHandler);Sys.UI.DomEvent.addHandler(window,"unload",this._unloadHandlerDelegate);Sys.UI.DomEvent.addHandler(window,"load",this._loadHandlerDelegate)};Sys._Application.prototype={_creatingComponents:false,_disposing:false,get_isCreatingComponents:function(){return this._creatingComponents},get_stateString:function(){var a=window.location.hash;if(this._isSafari2()){var b=this._getHistory();if(b)a=b[window.history.length-this._historyInitialLength]}if(a.length>0&&a.charAt(0)==="#")a=a.substring(1);if(Sys.Browser.agent===Sys.Browser.Firefox)a=this._serializeState(this._deserializeState(a,true));return a},get_enableHistory:function(){return this._enableHistory},set_enableHistory:function(a){this._enableHistory=a},add_init:function(a){if(this._initialized)a(this,Sys.EventArgs.Empty);else this.get_events().addHandler("init",a)},remove_init:function(a){this.get_events().removeHandler("init",a)},add_load:function(a){this.get_events().addHandler("load",a)},remove_load:function(a){this.get_events().removeHandler("load",a)},add_navigate:function(a){this.get_events().addHandler("navigate",a)},remove_navigate:function(a){this.get_events().removeHandler("navigate",a)},add_unload:function(a){this.get_events().addHandler("unload",a)},remove_unload:function(a){this.get_events().removeHandler("unload",a)},addComponent:function(a){this._components[a.get_id()]=a},addHistoryPoint:function(c,f){this._ensureHistory();var b=this._state;for(var a in c){var d=c[a];if(d===null){if(typeof b[a]!=="undefined")delete b[a]}else b[a]=d}var e=this._serializeState(b);this._historyPointIsNew=true;this._setState(e,f);this._raiseNavigate()},beginCreateComponents:function(){this._creatingComponents=true},dispose:function(){if(!this._disposing){this._disposing=true;if(this._timerCookie){window.clearTimeout(this._timerCookie);delete this._timerCookie}if(this._endRequestHandler){Sys.WebForms.PageRequestManager.getInstance().remove_endRequest(this._endRequestHandler);delete this._endRequestHandler}if(this._beginRequestHandler){Sys.WebForms.PageRequestManager.getInstance().remove_beginRequest(this._beginRequestHandler);delete this._beginRequestHandler}if(window.pageUnload)window.pageUnload(this,Sys.EventArgs.Empty);var c=this.get_events().getHandler("unload");if(c)c(this,Sys.EventArgs.Empty);var b=Array.clone(this._disposableObjects);for(var a=0,e=b.length;a'");d.write(""+(c||document.title)+"parent.Sys.Application._onIFrameLoad(\''+a+"');");d.close()}this._ignoreTimer=false;var h=this.get_stateString();this._currentEntry=a;if(a!==h){if(this._isSafari2()){var g=this._getHistory();g[window.history.length-this._historyInitialLength+1]=a;this._setHistory(g);this._historyLength=window.history.length+1;var b=document.createElement("form");b.method="get";b.action="#"+a;document.appendChild(b);b.submit();document.removeChild(b)}else window.location.hash=a;if(typeof c!=="undefined"&&c!==null)document.title=c}}},_unloadHandler:function(){this.dispose()},_updateHiddenField:function(b){if(this._clientId){var a=document.getElementById(this._clientId);if(a)a.value=b}}};Sys._Application.registerClass("Sys._Application",Sys.Component,Sys.IContainer);Sys.Application=new Sys._Application;var $find=Sys.Application.findComponent;Type.registerNamespace("Sys.Net");Sys.Net.WebRequestExecutor=function(){this._webRequest=null;this._resultObject=null};Sys.Net.WebRequestExecutor.prototype={get_webRequest:function(){return this._webRequest},_set_webRequest:function(a){this._webRequest=a},get_started:function(){throw Error.notImplemented()},get_responseAvailable:function(){throw Error.notImplemented()},get_timedOut:function(){throw Error.notImplemented()},get_aborted:function(){throw Error.notImplemented()},get_responseData:function(){throw Error.notImplemented()},get_statusCode:function(){throw Error.notImplemented()},get_statusText:function(){throw Error.notImplemented()},get_xml:function(){throw Error.notImplemented()},get_object:function(){if(!this._resultObject)this._resultObject=Sys.Serialization.JavaScriptSerializer.deserialize(this.get_responseData());return this._resultObject},executeRequest:function(){throw Error.notImplemented()},abort:function(){throw Error.notImplemented()},getResponseHeader:function(){throw Error.notImplemented()},getAllResponseHeaders:function(){throw Error.notImplemented()}};Sys.Net.WebRequestExecutor.registerClass("Sys.Net.WebRequestExecutor");Sys.Net.XMLDOM=function(d){if(!window.DOMParser){var c=["Msxml2.DOMDocument.3.0","Msxml2.DOMDocument"];for(var b=0,f=c.length;b0)this._timer=window.setTimeout(Function.createDelegate(this,this._onTimeout),d);this._xmlHttpRequest.send(c);this._started=true},getResponseHeader:function(b){var a;try{a=this._xmlHttpRequest.getResponseHeader(b)}catch(c){}if(!a)a="";return a},getAllResponseHeaders:function(){return this._xmlHttpRequest.getAllResponseHeaders()},get_responseData:function(){return this._xmlHttpRequest.responseText},get_statusCode:function(){var a=0;try{a=this._xmlHttpRequest.status}catch(b){}return a},get_statusText:function(){return this._xmlHttpRequest.statusText},get_xml:function(){var a=this._xmlHttpRequest.responseXML;if(!a||!a.documentElement){a=Sys.Net.XMLDOM(this._xmlHttpRequest.responseText);if(!a||!a.documentElement)return null}else if(navigator.userAgent.indexOf("MSIE")!==-1)a.setProperty("SelectionLanguage","XPath");if(a.documentElement.namespaceURI==="http://www.mozilla.org/newlayout/xml/parsererror.xml"&&a.documentElement.tagName==="parsererror")return null;if(a.documentElement.firstChild&&a.documentElement.firstChild.tagName==="parsererror")return null;return a},abort:function(){if(this._aborted||this._responseAvailable||this._timedOut)return;this._aborted=true;this._clearTimer();if(this._xmlHttpRequest&&!this._responseAvailable){this._xmlHttpRequest.onreadystatechange=Function.emptyMethod;this._xmlHttpRequest.abort();this._xmlHttpRequest=null;this._webRequest.completed(Sys.EventArgs.Empty)}}};Sys.Net.XMLHttpExecutor.registerClass("Sys.Net.XMLHttpExecutor",Sys.Net.WebRequestExecutor);Sys.Net._WebRequestManager=function(){this._defaultTimeout=0;this._defaultExecutorType="Sys.Net.XMLHttpExecutor"};Sys.Net._WebRequestManager.prototype={add_invokingRequest:function(a){this._get_eventHandlerList().addHandler("invokingRequest",a)},remove_invokingRequest:function(a){this._get_eventHandlerList().removeHandler("invokingRequest",a)},add_completedRequest:function(a){this._get_eventHandlerList().addHandler("completedRequest",a)},remove_completedRequest:function(a){this._get_eventHandlerList().removeHandler("completedRequest",a)},_get_eventHandlerList:function(){if(!this._events)this._events=new Sys.EventHandlerList;return this._events},get_defaultTimeout:function(){return this._defaultTimeout},set_defaultTimeout:function(a){this._defaultTimeout=a},get_defaultExecutorType:function(){return this._defaultExecutorType},set_defaultExecutorType:function(a){this._defaultExecutorType=a},executeRequest:function(webRequest){var executor=webRequest.get_executor();if(!executor){var failed=false;try{var executorType=eval(this._defaultExecutorType);executor=new executorType}catch(a){failed=true}webRequest.set_executor(executor)}if(executor.get_aborted())return;var evArgs=new Sys.Net.NetworkRequestEventArgs(webRequest),handler=this._get_eventHandlerList().getHandler("invokingRequest");if(handler)handler(this,evArgs);if(!evArgs.get_cancel())executor.executeRequest()}};Sys.Net._WebRequestManager.registerClass("Sys.Net._WebRequestManager");Sys.Net.WebRequestManager=new Sys.Net._WebRequestManager;Sys.Net.NetworkRequestEventArgs=function(a){Sys.Net.NetworkRequestEventArgs.initializeBase(this);this._webRequest=a};Sys.Net.NetworkRequestEventArgs.prototype={get_webRequest:function(){return this._webRequest}};Sys.Net.NetworkRequestEventArgs.registerClass("Sys.Net.NetworkRequestEventArgs",Sys.CancelEventArgs);Sys.Net.WebRequest=function(){this._url="";this._headers={};this._body=null;this._userContext=null;this._httpVerb=null;this._executor=null;this._invokeCalled=false;this._timeout=0};Sys.Net.WebRequest.prototype={add_completed:function(a){this._get_eventHandlerList().addHandler("completed",a)},remove_completed:function(a){this._get_eventHandlerList().removeHandler("completed",a)},completed:function(b){var a=Sys.Net.WebRequestManager._get_eventHandlerList().getHandler("completedRequest");if(a)a(this._executor,b);a=this._get_eventHandlerList().getHandler("completed");if(a)a(this._executor,b)},_get_eventHandlerList:function(){if(!this._events)this._events=new Sys.EventHandlerList;return this._events},get_url:function(){return this._url},set_url:function(a){this._url=a},get_headers:function(){return this._headers},get_httpVerb:function(){if(this._httpVerb===null){if(this._body===null)return "GET";return "POST"}return this._httpVerb},set_httpVerb:function(a){this._httpVerb=a},get_body:function(){return this._body},set_body:function(a){this._body=a},get_userContext:function(){return this._userContext},set_userContext:function(a){this._userContext=a},get_executor:function(){return this._executor},set_executor:function(a){this._executor=a;this._executor._set_webRequest(this)},get_timeout:function(){if(this._timeout===0)return Sys.Net.WebRequestManager.get_defaultTimeout();return this._timeout},set_timeout:function(a){this._timeout=a},getResolvedUrl:function(){return Sys.Net.WebRequest._resolveUrl(this._url)},invoke:function(){Sys.Net.WebRequestManager.executeRequest(this);this._invokeCalled=true}};Sys.Net.WebRequest._resolveUrl=function(b,a){if(b&&b.indexOf("://")!==-1)return b;if(!a||a.length===0){var d=document.getElementsByTagName("base")[0];if(d&&d.href&&d.href.length>0)a=d.href;else a=document.URL}var c=a.indexOf("?");if(c!==-1)a=a.substr(0,c);c=a.indexOf("#");if(c!==-1)a=a.substr(0,c);a=a.substr(0,a.lastIndexOf("/")+1);if(!b||b.length===0)return a;if(b.charAt(0)==="/"){var e=a.indexOf("://"),g=a.indexOf("/",e+3);return a.substr(0,g)+b}else{var f=a.lastIndexOf("/");return a.substr(0,f+1)+b}};Sys.Net.WebRequest._createQueryString=function(d,b){if(!b)b=encodeURIComponent;var a=new Sys.StringBuilder,f=0;for(var c in d){var e=d[c];if(typeof e==="function")continue;var g=Sys.Serialization.JavaScriptSerializer.serialize(e);if(f!==0)a.append("&");a.append(c);a.append("=");a.append(b(g));f++}return a.toString()};Sys.Net.WebRequest._createUrl=function(a,b){if(!b)return a;var d=Sys.Net.WebRequest._createQueryString(b);if(d.length>0){var c="?";if(a&&a.indexOf("?")!==-1)c="&";return a+c+d}else return a};Sys.Net.WebRequest.registerClass("Sys.Net.WebRequest");Sys.Net.WebServiceProxy=function(){};Sys.Net.WebServiceProxy.prototype={get_timeout:function(){return this._timeout},set_timeout:function(a){if(a<0)throw Error.argumentOutOfRange("value",a,Sys.Res.invalidTimeout);this._timeout=a},get_defaultUserContext:function(){return this._userContext},set_defaultUserContext:function(a){this._userContext=a},get_defaultSucceededCallback:function(){return this._succeeded},set_defaultSucceededCallback:function(a){this._succeeded=a},get_defaultFailedCallback:function(){return this._failed},set_defaultFailedCallback:function(a){this._failed=a},get_path:function(){return this._path},set_path:function(a){this._path=a},_invoke:function(d,e,g,f,c,b,a){if(c===null||typeof c==="undefined")c=this.get_defaultSucceededCallback();if(b===null||typeof b==="undefined")b=this.get_defaultFailedCallback();if(a===null||typeof a==="undefined")a=this.get_defaultUserContext();return Sys.Net.WebServiceProxy.invoke(d,e,g,f,c,b,a,this.get_timeout())}};Sys.Net.WebServiceProxy.registerClass("Sys.Net.WebServiceProxy");Sys.Net.WebServiceProxy.invoke=function(k,a,j,d,i,c,f,h){var b=new Sys.Net.WebRequest;b.get_headers()["Content-Type"]="application/json; charset=utf-8";if(!d)d={};var g=d;if(!j||!g)g={};b.set_url(Sys.Net.WebRequest._createUrl(k+"/"+encodeURIComponent(a),g));var e=null;if(!j){e=Sys.Serialization.JavaScriptSerializer.serialize(d);if(e==="{}")e=""}b.set_body(e);b.add_completed(l);if(h&&h>0)b.set_timeout(h);b.invoke();function l(d){if(d.get_responseAvailable()){var g=d.get_statusCode(),b=null;try{var e=d.getResponseHeader("Content-Type");if(e.startsWith("application/json"))b=d.get_object();else if(e.startsWith("text/xml"))b=d.get_xml();else b=d.get_responseData()}catch(m){}var k=d.getResponseHeader("jsonerror"),h=k==="true";if(h){if(b)b=new Sys.Net.WebServiceError(false,b.Message,b.StackTrace,b.ExceptionType)}else if(e.startsWith("application/json"))b=b.d;if(g<200||g>=300||h){if(c){if(!b||!h)b=new Sys.Net.WebServiceError(false,String.format(Sys.Res.webServiceFailedNoMsg,a),"","");b._statusCode=g;c(b,f,a)}}else if(i)i(b,f,a)}else{var j;if(d.get_timedOut())j=String.format(Sys.Res.webServiceTimedOut,a);else j=String.format(Sys.Res.webServiceFailedNoMsg,a);if(c)c(new Sys.Net.WebServiceError(d.get_timedOut(),j,"",""),f,a)}}return b};Sys.Net.WebServiceProxy._generateTypedConstructor=function(a){return function(b){if(b)for(var c in b)this[c]=b[c];this.__type=a}};Sys.Net.WebServiceError=function(c,d,b,a){this._timedOut=c;this._message=d;this._stackTrace=b;this._exceptionType=a;this._statusCode=-1};Sys.Net.WebServiceError.prototype={get_timedOut:function(){return this._timedOut},get_statusCode:function(){return this._statusCode},get_message:function(){return this._message},get_stackTrace:function(){return this._stackTrace},get_exceptionType:function(){return this._exceptionType}};Sys.Net.WebServiceError.registerClass("Sys.Net.WebServiceError");Type.registerNamespace("Sys.Services");Sys.Services._ProfileService=function(){Sys.Services._ProfileService.initializeBase(this);this.properties={}};Sys.Services._ProfileService.DefaultWebServicePath="";Sys.Services._ProfileService.prototype={_defaultLoadCompletedCallback:null,_defaultSaveCompletedCallback:null,_path:"",_timeout:0,get_defaultLoadCompletedCallback:function(){return this._defaultLoadCompletedCallback},set_defaultLoadCompletedCallback:function(a){this._defaultLoadCompletedCallback=a},get_defaultSaveCompletedCallback:function(){return this._defaultSaveCompletedCallback},set_defaultSaveCompletedCallback:function(a){this._defaultSaveCompletedCallback=a},get_path:function(){return this._path||""},load:function(c,d,e,f){var b,a;if(!c){a="GetAllPropertiesForCurrentUser";b={authenticatedUserOnly:false}}else{a="GetPropertiesForCurrentUser";b={properties:this._clonePropertyNames(c),authenticatedUserOnly:false}}this._invoke(this._get_path(),a,false,b,Function.createDelegate(this,this._onLoadComplete),Function.createDelegate(this,this._onLoadFailed),[d,e,f])},save:function(d,b,c,e){var a=this._flattenProperties(d,this.properties);this._invoke(this._get_path(),"SetPropertiesForCurrentUser",false,{values:a.value,authenticatedUserOnly:false},Function.createDelegate(this,this._onSaveComplete),Function.createDelegate(this,this._onSaveFailed),[b,c,e,a.count])},_clonePropertyNames:function(e){var c=[],d={};for(var b=0;b0)a.append(",");Sys.Serialization.JavaScriptSerializer._serializeWithBuilder(b[c],a,false,g)}a.append("]")}else{if(Date.isInstanceOfType(b)){a.append('"\\/Date(');a.append(b.getTime());a.append(')\\/"');break}var d=[],f=0;for(var e in b){if(e.startsWith("$"))continue;if(e===Sys.Serialization.JavaScriptSerializer._serverTypeFieldName&&f!==0){d[f++]=d[0];d[0]=e}else d[f++]=e}if(i)d.sort();a.append("{");var j=false;for(c=0;c + /// + /// + /// + /// + /// +}; +Sys.Mvc.InsertionMode.prototype = { + replace: 0, + insertBefore: 1, + insertAfter: 2 +} +Sys.Mvc.InsertionMode.registerEnum('Sys.Mvc.InsertionMode', false); + + +//////////////////////////////////////////////////////////////////////////////// +// Sys.Mvc.AjaxContext + +Sys.Mvc.AjaxContext = function Sys_Mvc_AjaxContext(request, updateTarget, loadingElement, insertionMode) { + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + this._request = request; + this._updateTarget = updateTarget; + this._loadingElement = loadingElement; + this._insertionMode = insertionMode; +} +Sys.Mvc.AjaxContext.prototype = { + _insertionMode: 0, + _loadingElement: null, + _response: null, + _request: null, + _updateTarget: null, + + get_data: function Sys_Mvc_AjaxContext$get_data() { + /// + if (this._response) { + return this._response.get_responseData(); + } + else { + return null; + } + }, + + get_insertionMode: function Sys_Mvc_AjaxContext$get_insertionMode() { + /// + return this._insertionMode; + }, + + get_loadingElement: function Sys_Mvc_AjaxContext$get_loadingElement() { + /// + return this._loadingElement; + }, + + get_object: function Sys_Mvc_AjaxContext$get_object() { + /// + var executor = this.get_response(); + return (executor) ? executor.get_object() : null; + }, + + get_response: function Sys_Mvc_AjaxContext$get_response() { + /// + return this._response; + }, + set_response: function Sys_Mvc_AjaxContext$set_response(value) { + /// + this._response = value; + return value; + }, + + get_request: function Sys_Mvc_AjaxContext$get_request() { + /// + return this._request; + }, + + get_updateTarget: function Sys_Mvc_AjaxContext$get_updateTarget() { + /// + return this._updateTarget; + } +} + + +//////////////////////////////////////////////////////////////////////////////// +// Sys.Mvc.AsyncHyperlink + +Sys.Mvc.AsyncHyperlink = function Sys_Mvc_AsyncHyperlink() { +} +Sys.Mvc.AsyncHyperlink.handleClick = function Sys_Mvc_AsyncHyperlink$handleClick(anchor, evt, ajaxOptions) { + /// + /// + /// + /// + /// + /// + evt.preventDefault(); + Sys.Mvc.MvcHelpers._asyncRequest(anchor.href, 'post', '', anchor, ajaxOptions); +} + + +//////////////////////////////////////////////////////////////////////////////// +// Sys.Mvc.MvcHelpers + +Sys.Mvc.MvcHelpers = function Sys_Mvc_MvcHelpers() { +} +Sys.Mvc.MvcHelpers._serializeSubmitButton = function Sys_Mvc_MvcHelpers$_serializeSubmitButton(element, offsetX, offsetY) { + /// + /// + /// + /// + /// + /// + /// + if (element.disabled) { + return null; + } + var name = element.name; + if (name) { + var tagName = element.tagName.toUpperCase(); + var encodedName = encodeURIComponent(name); + var inputElement = element; + if (tagName === 'INPUT') { + var type = inputElement.type; + if (type === 'submit') { + return encodedName + '=' + encodeURIComponent(inputElement.value); + } + else if (type === 'image') { + return encodedName + '.x=' + offsetX + '&' + encodedName + '.y=' + offsetY; + } + } + else if ((tagName === 'BUTTON') && (name.length) && (inputElement.type === 'submit')) { + return encodedName + '=' + encodeURIComponent(inputElement.value); + } + } + return null; +} +Sys.Mvc.MvcHelpers._serializeForm = function Sys_Mvc_MvcHelpers$_serializeForm(form) { + /// + /// + /// + var formElements = form.elements; + var formBody = new Sys.StringBuilder(); + var count = formElements.length; + for (var i = 0; i < count; i++) { + var element = formElements[i]; + var name = element.name; + if (!name || !name.length) { + continue; + } + var tagName = element.tagName.toUpperCase(); + if (tagName === 'INPUT') { + var inputElement = element; + var type = inputElement.type; + if ((type === 'text') || (type === 'password') || (type === 'hidden') || (((type === 'checkbox') || (type === 'radio')) && element.checked)) { + formBody.append(encodeURIComponent(name)); + formBody.append('='); + formBody.append(encodeURIComponent(inputElement.value)); + formBody.append('&'); + } + } + else if (tagName === 'SELECT') { + var selectElement = element; + var optionCount = selectElement.options.length; + for (var j = 0; j < optionCount; j++) { + var optionElement = selectElement.options[j]; + if (optionElement.selected) { + formBody.append(encodeURIComponent(name)); + formBody.append('='); + formBody.append(encodeURIComponent(optionElement.value)); + formBody.append('&'); + } + } + } + else if (tagName === 'TEXTAREA') { + formBody.append(encodeURIComponent(name)); + formBody.append('='); + formBody.append(encodeURIComponent((element.value))); + formBody.append('&'); + } + } + var additionalInput = form._additionalInput; + if (additionalInput) { + formBody.append(additionalInput); + formBody.append('&'); + } + return formBody.toString(); +} +Sys.Mvc.MvcHelpers._asyncRequest = function Sys_Mvc_MvcHelpers$_asyncRequest(url, verb, body, triggerElement, ajaxOptions) { + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + if (ajaxOptions.confirm) { + if (!confirm(ajaxOptions.confirm)) { + return; + } + } + if (ajaxOptions.url) { + url = ajaxOptions.url; + } + if (ajaxOptions.httpMethod) { + verb = ajaxOptions.httpMethod; + } + if (body.length > 0 && !body.endsWith('&')) { + body += '&'; + } + body += 'X-Requested-With=XMLHttpRequest'; + var upperCaseVerb = verb.toUpperCase(); + var isGetOrPost = (upperCaseVerb === 'GET' || upperCaseVerb === 'POST'); + if (!isGetOrPost) { + body += '&'; + body += 'X-HTTP-Method-Override=' + upperCaseVerb; + } + var requestBody = ''; + if (upperCaseVerb === 'GET' || upperCaseVerb === 'DELETE') { + if (url.indexOf('?') > -1) { + if (!url.endsWith('&')) { + url += '&'; + } + url += body; + } + else { + url += '?'; + url += body; + } + } + else { + requestBody = body; + } + var request = new Sys.Net.WebRequest(); + request.set_url(url); + if (isGetOrPost) { + request.set_httpVerb(verb); + } + else { + request.set_httpVerb('POST'); + request.get_headers()['X-HTTP-Method-Override'] = upperCaseVerb; + } + request.set_body(requestBody); + if (verb.toUpperCase() === 'PUT') { + request.get_headers()['Content-Type'] = 'application/x-www-form-urlencoded;'; + } + request.get_headers()['X-Requested-With'] = 'XMLHttpRequest'; + var updateElement = null; + if (ajaxOptions.updateTargetId) { + updateElement = $get(ajaxOptions.updateTargetId); + } + var loadingElement = null; + if (ajaxOptions.loadingElementId) { + loadingElement = $get(ajaxOptions.loadingElementId); + } + var ajaxContext = new Sys.Mvc.AjaxContext(request, updateElement, loadingElement, ajaxOptions.insertionMode); + var continueRequest = true; + if (ajaxOptions.onBegin) { + continueRequest = ajaxOptions.onBegin(ajaxContext) !== false; + } + if (loadingElement) { + Sys.UI.DomElement.setVisible(ajaxContext.get_loadingElement(), true); + } + if (continueRequest) { + request.add_completed(Function.createDelegate(null, function(executor) { + Sys.Mvc.MvcHelpers._onComplete(request, ajaxOptions, ajaxContext); + })); + request.invoke(); + } +} +Sys.Mvc.MvcHelpers._onComplete = function Sys_Mvc_MvcHelpers$_onComplete(request, ajaxOptions, ajaxContext) { + /// + /// + /// + /// + /// + /// + ajaxContext.set_response(request.get_executor()); + if (ajaxOptions.onComplete && ajaxOptions.onComplete(ajaxContext) === false) { + return; + } + var statusCode = ajaxContext.get_response().get_statusCode(); + if ((statusCode >= 200 && statusCode < 300) || statusCode === 304 || statusCode === 1223) { + if (statusCode !== 204 && statusCode !== 304 && statusCode !== 1223) { + var contentType = ajaxContext.get_response().getResponseHeader('Content-Type'); + if ((contentType) && (contentType.indexOf('application/x-javascript') !== -1)) { + eval(ajaxContext.get_data()); + } + else { + Sys.Mvc.MvcHelpers.updateDomElement(ajaxContext.get_updateTarget(), ajaxContext.get_insertionMode(), ajaxContext.get_data()); + } + } + if (ajaxOptions.onSuccess) { + ajaxOptions.onSuccess(ajaxContext); + } + } + else { + if (ajaxOptions.onFailure) { + ajaxOptions.onFailure(ajaxContext); + } + } + if (ajaxContext.get_loadingElement()) { + Sys.UI.DomElement.setVisible(ajaxContext.get_loadingElement(), false); + } +} +Sys.Mvc.MvcHelpers.updateDomElement = function Sys_Mvc_MvcHelpers$updateDomElement(target, insertionMode, content) { + /// + /// + /// + /// + /// + /// + if (target) { + switch (insertionMode) { + case Sys.Mvc.InsertionMode.replace: + target.innerHTML = content; + break; + case Sys.Mvc.InsertionMode.insertBefore: + if (content && content.length > 0) { + target.innerHTML = content + target.innerHTML.trimStart(); + } + break; + case Sys.Mvc.InsertionMode.insertAfter: + if (content && content.length > 0) { + target.innerHTML = target.innerHTML.trimEnd() + content; + } + break; + } + } +} + + +//////////////////////////////////////////////////////////////////////////////// +// Sys.Mvc.AsyncForm + +Sys.Mvc.AsyncForm = function Sys_Mvc_AsyncForm() { +} +Sys.Mvc.AsyncForm.handleClick = function Sys_Mvc_AsyncForm$handleClick(form, evt) { + /// + /// + /// + /// + var additionalInput = Sys.Mvc.MvcHelpers._serializeSubmitButton(evt.target, evt.offsetX, evt.offsetY); + form._additionalInput = additionalInput; +} +Sys.Mvc.AsyncForm.handleSubmit = function Sys_Mvc_AsyncForm$handleSubmit(form, evt, ajaxOptions) { + /// + /// + /// + /// + /// + /// + evt.preventDefault(); + var body = Sys.Mvc.MvcHelpers._serializeForm(form); + Sys.Mvc.MvcHelpers._asyncRequest(form.action, form.method || 'post', body, form, ajaxOptions); +} + + +Sys.Mvc.AjaxContext.registerClass('Sys.Mvc.AjaxContext'); +Sys.Mvc.AsyncHyperlink.registerClass('Sys.Mvc.AsyncHyperlink'); +Sys.Mvc.MvcHelpers.registerClass('Sys.Mvc.MvcHelpers'); +Sys.Mvc.AsyncForm.registerClass('Sys.Mvc.AsyncForm'); + +// ---- Do not remove this footer ---- +// Generated using Script# v0.5.0.0 (http://projects.nikhilk.net) +// ----------------------------------- diff --git a/ShowOff/Scripts/MicrosoftMvcAjax.js b/ShowOff/Scripts/MicrosoftMvcAjax.js new file mode 100644 index 0000000..1b6f16e --- /dev/null +++ b/ShowOff/Scripts/MicrosoftMvcAjax.js @@ -0,0 +1,25 @@ +//---------------------------------------------------------- +// Copyright (C) Microsoft Corporation. All rights reserved. +//---------------------------------------------------------- +// MicrosoftMvcAjax.js + +Type.registerNamespace('Sys.Mvc');Sys.Mvc.$create_AjaxOptions=function(){return {};} +Sys.Mvc.InsertionMode=function(){};Sys.Mvc.InsertionMode.prototype = {replace:0,insertBefore:1,insertAfter:2} +Sys.Mvc.InsertionMode.registerEnum('Sys.Mvc.InsertionMode',false);Sys.Mvc.AjaxContext=function(request,updateTarget,loadingElement,insertionMode){this.$3=request;this.$4=updateTarget;this.$1=loadingElement;this.$0=insertionMode;} +Sys.Mvc.AjaxContext.prototype={$0:0,$1:null,$2:null,$3:null,$4:null,get_data:function(){if(this.$2){return this.$2.get_responseData();}else{return null;}},get_insertionMode:function(){return this.$0;},get_loadingElement:function(){return this.$1;},get_object:function(){var $0=this.get_response();return ($0)?$0.get_object():null;},get_response:function(){return this.$2;},set_response:function(value){this.$2=value;return value;},get_request:function(){return this.$3;},get_updateTarget:function(){return this.$4;}} +Sys.Mvc.AsyncHyperlink=function(){} +Sys.Mvc.AsyncHyperlink.handleClick=function(anchor,evt,ajaxOptions){evt.preventDefault();Sys.Mvc.MvcHelpers.$2(anchor.href,'post','',anchor,ajaxOptions);} +Sys.Mvc.MvcHelpers=function(){} +Sys.Mvc.MvcHelpers.$0=function($p0,$p1,$p2){if($p0.disabled){return null;}var $0=$p0.name;if($0){var $1=$p0.tagName.toUpperCase();var $2=encodeURIComponent($0);var $3=$p0;if($1==='INPUT'){var $4=$3.type;if($4==='submit'){return $2+'='+encodeURIComponent($3.value);}else if($4==='image'){return $2+'.x='+$p1+'&'+$2+'.y='+$p2;}}else if(($1==='BUTTON')&&($0.length)&&($3.type==='submit')){return $2+'='+encodeURIComponent($3.value);}}return null;} +Sys.Mvc.MvcHelpers.$1=function($p0){var $0=$p0.elements;var $1=new Sys.StringBuilder();var $2=$0.length;for(var $4=0;$4<$2;$4++){var $5=$0[$4];var $6=$5.name;if(!$6||!$6.length){continue;}var $7=$5.tagName.toUpperCase();if($7==='INPUT'){var $8=$5;var $9=$8.type;if(($9==='text')||($9==='password')||($9==='hidden')||((($9==='checkbox')||($9==='radio'))&&$5.checked)){$1.append(encodeURIComponent($6));$1.append('=');$1.append(encodeURIComponent($8.value));$1.append('&');}}else if($7==='SELECT'){var $A=$5;var $B=$A.options.length;for(var $C=0;$C<$B;$C++){var $D=$A.options[$C];if($D.selected){$1.append(encodeURIComponent($6));$1.append('=');$1.append(encodeURIComponent($D.value));$1.append('&');}}}else if($7==='TEXTAREA'){$1.append(encodeURIComponent($6));$1.append('=');$1.append(encodeURIComponent(($5.value)));$1.append('&');}}var $3=$p0._additionalInput;if($3){$1.append($3);$1.append('&');}return $1.toString();} +Sys.Mvc.MvcHelpers.$2=function($p0,$p1,$p2,$p3,$p4){if($p4.confirm){if(!confirm($p4.confirm)){return;}}if($p4.url){$p0=$p4.url;}if($p4.httpMethod){$p1=$p4.httpMethod;}if($p2.length>0&&!$p2.endsWith('&')){$p2+='&';}$p2+='X-Requested-With=XMLHttpRequest';var $0=$p1.toUpperCase();var $1=($0==='GET'||$0==='POST');if(!$1){$p2+='&';$p2+='X-HTTP-Method-Override='+$0;}var $2='';if($0==='GET'||$0==='DELETE'){if($p0.indexOf('?')>-1){if(!$p0.endsWith('&')){$p0+='&';}$p0+=$p2;}else{$p0+='?';$p0+=$p2;}}else{$2=$p2;}var $3=new Sys.Net.WebRequest();$3.set_url($p0);if($1){$3.set_httpVerb($p1);}else{$3.set_httpVerb('POST');$3.get_headers()['X-HTTP-Method-Override']=$0;}$3.set_body($2);if($p1.toUpperCase()==='PUT'){$3.get_headers()['Content-Type']='application/x-www-form-urlencoded;';}$3.get_headers()['X-Requested-With']='XMLHttpRequest';var $4=null;if($p4.updateTargetId){$4=$get($p4.updateTargetId);}var $5=null;if($p4.loadingElementId){$5=$get($p4.loadingElementId);}var $6=new Sys.Mvc.AjaxContext($3,$4,$5,$p4.insertionMode);var $7=true;if($p4.onBegin){$7=$p4.onBegin($6)!==false;}if($5){Sys.UI.DomElement.setVisible($6.get_loadingElement(),true);}if($7){$3.add_completed(Function.createDelegate(null,function($p1_0){ +Sys.Mvc.MvcHelpers.$3($3,$p4,$6);}));$3.invoke();}} +Sys.Mvc.MvcHelpers.$3=function($p0,$p1,$p2){$p2.set_response($p0.get_executor());if($p1.onComplete&&$p1.onComplete($p2)===false){return;}var $0=$p2.get_response().get_statusCode();if(($0>=200&&$0<300)||$0===304||$0===1223){if($0!==204&&$0!==304&&$0!==1223){var $1=$p2.get_response().getResponseHeader('Content-Type');if(($1)&&($1.indexOf('application/x-javascript')!==-1)){eval($p2.get_data());}else{Sys.Mvc.MvcHelpers.updateDomElement($p2.get_updateTarget(),$p2.get_insertionMode(),$p2.get_data());}}if($p1.onSuccess){$p1.onSuccess($p2);}}else{if($p1.onFailure){$p1.onFailure($p2);}}if($p2.get_loadingElement()){Sys.UI.DomElement.setVisible($p2.get_loadingElement(),false);}} +Sys.Mvc.MvcHelpers.updateDomElement=function(target,insertionMode,content){if(target){switch(insertionMode){case 0:target.innerHTML=content;break;case 1:if(content&&content.length>0){target.innerHTML=content+target.innerHTML.trimStart();}break;case 2:if(content&&content.length>0){target.innerHTML=target.innerHTML.trimEnd()+content;}break;}}} +Sys.Mvc.AsyncForm=function(){} +Sys.Mvc.AsyncForm.handleClick=function(form,evt){var $0=Sys.Mvc.MvcHelpers.$0(evt.target,evt.offsetX,evt.offsetY);form._additionalInput = $0;} +Sys.Mvc.AsyncForm.handleSubmit=function(form,evt,ajaxOptions){evt.preventDefault();var $0=Sys.Mvc.MvcHelpers.$1(form);Sys.Mvc.MvcHelpers.$2(form.action,form.method||'post',$0,form,ajaxOptions);} +Sys.Mvc.AjaxContext.registerClass('Sys.Mvc.AjaxContext');Sys.Mvc.AsyncHyperlink.registerClass('Sys.Mvc.AsyncHyperlink');Sys.Mvc.MvcHelpers.registerClass('Sys.Mvc.MvcHelpers');Sys.Mvc.AsyncForm.registerClass('Sys.Mvc.AsyncForm'); +// ---- Do not remove this footer ---- +// Generated using Script# v0.5.0.0 (http://projects.nikhilk.net) +// ----------------------------------- diff --git a/ShowOff/Scripts/MicrosoftMvcValidation.debug.js b/ShowOff/Scripts/MicrosoftMvcValidation.debug.js new file mode 100644 index 0000000..b48bb2f --- /dev/null +++ b/ShowOff/Scripts/MicrosoftMvcValidation.debug.js @@ -0,0 +1,874 @@ +//!---------------------------------------------------------- +//! Copyright (C) Microsoft Corporation. All rights reserved. +//!---------------------------------------------------------- +//! MicrosoftMvcValidation.js + + +Type.registerNamespace('Sys.Mvc'); + +//////////////////////////////////////////////////////////////////////////////// +// Sys.Mvc.Validation + +Sys.Mvc.$create_Validation = function Sys_Mvc_Validation() { return {}; } + + +//////////////////////////////////////////////////////////////////////////////// +// Sys.Mvc.JsonValidationField + +Sys.Mvc.$create_JsonValidationField = function Sys_Mvc_JsonValidationField() { return {}; } + + +//////////////////////////////////////////////////////////////////////////////// +// Sys.Mvc.JsonValidationOptions + +Sys.Mvc.$create_JsonValidationOptions = function Sys_Mvc_JsonValidationOptions() { return {}; } + + +//////////////////////////////////////////////////////////////////////////////// +// Sys.Mvc.JsonValidationRule + +Sys.Mvc.$create_JsonValidationRule = function Sys_Mvc_JsonValidationRule() { return {}; } + + +//////////////////////////////////////////////////////////////////////////////// +// Sys.Mvc.ValidationContext + +Sys.Mvc.$create_ValidationContext = function Sys_Mvc_ValidationContext() { return {}; } + + +//////////////////////////////////////////////////////////////////////////////// +// Sys.Mvc.NumberValidator + +Sys.Mvc.NumberValidator = function Sys_Mvc_NumberValidator() { +} +Sys.Mvc.NumberValidator.create = function Sys_Mvc_NumberValidator$create(rule) { + /// + /// + /// + return Function.createDelegate(new Sys.Mvc.NumberValidator(), new Sys.Mvc.NumberValidator().validate); +} +Sys.Mvc.NumberValidator.prototype = { + + validate: function Sys_Mvc_NumberValidator$validate(value, context) { + /// + /// + /// + /// + /// + if (Sys.Mvc._validationUtil.stringIsNullOrEmpty(value)) { + return true; + } + var n = Number.parseLocale(value); + return (!isNaN(n)); + } +} + + +//////////////////////////////////////////////////////////////////////////////// +// Sys.Mvc.FormContext + +Sys.Mvc.FormContext = function Sys_Mvc_FormContext(formElement, validationSummaryElement) { + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + this._errors = []; + this.fields = new Array(0); + this._formElement = formElement; + this._validationSummaryElement = validationSummaryElement; + formElement[Sys.Mvc.FormContext._formValidationTag] = this; + if (validationSummaryElement) { + var ulElements = validationSummaryElement.getElementsByTagName('ul'); + if (ulElements.length > 0) { + this._validationSummaryULElement = ulElements[0]; + } + } + this._onClickHandler = Function.createDelegate(this, this._form_OnClick); + this._onSubmitHandler = Function.createDelegate(this, this._form_OnSubmit); +} +Sys.Mvc.FormContext._Application_Load = function Sys_Mvc_FormContext$_Application_Load() { + var allFormOptions = window.mvcClientValidationMetadata; + if (allFormOptions) { + while (allFormOptions.length > 0) { + var thisFormOptions = allFormOptions.pop(); + Sys.Mvc.FormContext._parseJsonOptions(thisFormOptions); + } + } +} +Sys.Mvc.FormContext._getFormElementsWithName = function Sys_Mvc_FormContext$_getFormElementsWithName(formElement, name) { + /// + /// + /// + /// + /// + var allElementsWithNameInForm = []; + var allElementsWithName = document.getElementsByName(name); + for (var i = 0; i < allElementsWithName.length; i++) { + var thisElement = allElementsWithName[i]; + if (Sys.Mvc.FormContext._isElementInHierarchy(formElement, thisElement)) { + Array.add(allElementsWithNameInForm, thisElement); + } + } + return allElementsWithNameInForm; +} +Sys.Mvc.FormContext.getValidationForForm = function Sys_Mvc_FormContext$getValidationForForm(formElement) { + /// + /// + /// + return formElement[Sys.Mvc.FormContext._formValidationTag]; +} +Sys.Mvc.FormContext._isElementInHierarchy = function Sys_Mvc_FormContext$_isElementInHierarchy(parent, child) { + /// + /// + /// + /// + /// + while (child) { + if (parent === child) { + return true; + } + child = child.parentNode; + } + return false; +} +Sys.Mvc.FormContext._parseJsonOptions = function Sys_Mvc_FormContext$_parseJsonOptions(options) { + /// + /// + /// + var formElement = $get(options.FormId); + var validationSummaryElement = (!Sys.Mvc._validationUtil.stringIsNullOrEmpty(options.ValidationSummaryId)) ? $get(options.ValidationSummaryId) : null; + var formContext = new Sys.Mvc.FormContext(formElement, validationSummaryElement); + formContext.enableDynamicValidation(); + formContext.replaceValidationSummary = options.ReplaceValidationSummary; + for (var i = 0; i < options.Fields.length; i++) { + var field = options.Fields[i]; + var fieldElements = Sys.Mvc.FormContext._getFormElementsWithName(formElement, field.FieldName); + var validationMessageElement = (!Sys.Mvc._validationUtil.stringIsNullOrEmpty(field.ValidationMessageId)) ? $get(field.ValidationMessageId) : null; + var fieldContext = new Sys.Mvc.FieldContext(formContext); + Array.addRange(fieldContext.elements, fieldElements); + fieldContext.validationMessageElement = validationMessageElement; + fieldContext.replaceValidationMessageContents = field.ReplaceValidationMessageContents; + for (var j = 0; j < field.ValidationRules.length; j++) { + var rule = field.ValidationRules[j]; + var validator = Sys.Mvc.ValidatorRegistry.getValidator(rule); + if (validator) { + var validation = Sys.Mvc.$create_Validation(); + validation.fieldErrorMessage = rule.ErrorMessage; + validation.validator = validator; + Array.add(fieldContext.validations, validation); + } + } + fieldContext.enableDynamicValidation(); + Array.add(formContext.fields, fieldContext); + } + return formContext; +} +Sys.Mvc.FormContext.prototype = { + _onClickHandler: null, + _onSubmitHandler: null, + _submitButtonClicked: null, + _validationSummaryElement: null, + _validationSummaryULElement: null, + _formElement: null, + replaceValidationSummary: false, + + addError: function Sys_Mvc_FormContext$addError(message) { + /// + /// + this.addErrors([ message ]); + }, + + addErrors: function Sys_Mvc_FormContext$addErrors(messages) { + /// + /// + if (!Sys.Mvc._validationUtil.arrayIsNullOrEmpty(messages)) { + Array.addRange(this._errors, messages); + this._onErrorCountChanged(); + } + }, + + clearErrors: function Sys_Mvc_FormContext$clearErrors() { + Array.clear(this._errors); + this._onErrorCountChanged(); + }, + + _displayError: function Sys_Mvc_FormContext$_displayError() { + if (this._validationSummaryElement) { + if (this._validationSummaryULElement) { + Sys.Mvc._validationUtil.removeAllChildren(this._validationSummaryULElement); + for (var i = 0; i < this._errors.length; i++) { + var liElement = document.createElement('li'); + Sys.Mvc._validationUtil.setInnerText(liElement, this._errors[i]); + this._validationSummaryULElement.appendChild(liElement); + } + } + Sys.UI.DomElement.removeCssClass(this._validationSummaryElement, Sys.Mvc.FormContext._validationSummaryValidCss); + Sys.UI.DomElement.addCssClass(this._validationSummaryElement, Sys.Mvc.FormContext._validationSummaryErrorCss); + } + }, + + _displaySuccess: function Sys_Mvc_FormContext$_displaySuccess() { + var validationSummaryElement = this._validationSummaryElement; + if (validationSummaryElement) { + var validationSummaryULElement = this._validationSummaryULElement; + if (validationSummaryULElement) { + validationSummaryULElement.innerHTML = ''; + } + Sys.UI.DomElement.removeCssClass(validationSummaryElement, Sys.Mvc.FormContext._validationSummaryErrorCss); + Sys.UI.DomElement.addCssClass(validationSummaryElement, Sys.Mvc.FormContext._validationSummaryValidCss); + } + }, + + enableDynamicValidation: function Sys_Mvc_FormContext$enableDynamicValidation() { + Sys.UI.DomEvent.addHandler(this._formElement, 'click', this._onClickHandler); + Sys.UI.DomEvent.addHandler(this._formElement, 'submit', this._onSubmitHandler); + }, + + _findSubmitButton: function Sys_Mvc_FormContext$_findSubmitButton(element) { + /// + /// + /// + if (element.disabled) { + return null; + } + var name = element.name; + if (name) { + var tagName = element.tagName.toUpperCase(); + var encodedName = encodeURIComponent(name); + var inputElement = element; + if (tagName === 'INPUT') { + var type = inputElement.type; + if (type === 'submit' || type === 'image') { + return inputElement; + } + } + else if ((tagName === 'BUTTON') && (name.length) && (inputElement.type === 'submit')) { + return inputElement; + } + } + return null; + }, + + _form_OnClick: function Sys_Mvc_FormContext$_form_OnClick(e) { + /// + /// + this._submitButtonClicked = this._findSubmitButton(e.target); + }, + + _form_OnSubmit: function Sys_Mvc_FormContext$_form_OnSubmit(e) { + /// + /// + var form = e.target; + var submitButton = this._submitButtonClicked; + if (submitButton && submitButton.disableValidation) { + return; + } + var errorMessages = this.validate('submit'); + if (!Sys.Mvc._validationUtil.arrayIsNullOrEmpty(errorMessages)) { + e.preventDefault(); + } + }, + + _onErrorCountChanged: function Sys_Mvc_FormContext$_onErrorCountChanged() { + if (!this._errors.length) { + this._displaySuccess(); + } + else { + this._displayError(); + } + }, + + validate: function Sys_Mvc_FormContext$validate(eventName) { + /// + /// + /// + var fields = this.fields; + var errors = []; + for (var i = 0; i < fields.length; i++) { + var field = fields[i]; + var thisErrors = field.validate(eventName); + if (thisErrors) { + Array.addRange(errors, thisErrors); + } + } + if (this.replaceValidationSummary) { + this.clearErrors(); + this.addErrors(errors); + } + return errors; + } +} + + +//////////////////////////////////////////////////////////////////////////////// +// Sys.Mvc.FieldContext + +Sys.Mvc.FieldContext = function Sys_Mvc_FieldContext(formContext) { + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + this._errors = []; + this.elements = new Array(0); + this.validations = new Array(0); + this.formContext = formContext; + this._onBlurHandler = Function.createDelegate(this, this._element_OnBlur); + this._onChangeHandler = Function.createDelegate(this, this._element_OnChange); + this._onInputHandler = Function.createDelegate(this, this._element_OnInput); + this._onPropertyChangeHandler = Function.createDelegate(this, this._element_OnPropertyChange); +} +Sys.Mvc.FieldContext.prototype = { + _onBlurHandler: null, + _onChangeHandler: null, + _onInputHandler: null, + _onPropertyChangeHandler: null, + defaultErrorMessage: null, + formContext: null, + replaceValidationMessageContents: false, + validationMessageElement: null, + + addError: function Sys_Mvc_FieldContext$addError(message) { + /// + /// + this.addErrors([ message ]); + }, + + addErrors: function Sys_Mvc_FieldContext$addErrors(messages) { + /// + /// + if (!Sys.Mvc._validationUtil.arrayIsNullOrEmpty(messages)) { + Array.addRange(this._errors, messages); + this._onErrorCountChanged(); + } + }, + + clearErrors: function Sys_Mvc_FieldContext$clearErrors() { + Array.clear(this._errors); + this._onErrorCountChanged(); + }, + + _displayError: function Sys_Mvc_FieldContext$_displayError() { + var validationMessageElement = this.validationMessageElement; + if (validationMessageElement) { + if (this.replaceValidationMessageContents) { + Sys.Mvc._validationUtil.setInnerText(validationMessageElement, this._errors[0]); + } + Sys.UI.DomElement.removeCssClass(validationMessageElement, Sys.Mvc.FieldContext._validationMessageValidCss); + Sys.UI.DomElement.addCssClass(validationMessageElement, Sys.Mvc.FieldContext._validationMessageErrorCss); + } + var elements = this.elements; + for (var i = 0; i < elements.length; i++) { + var element = elements[i]; + Sys.UI.DomElement.removeCssClass(element, Sys.Mvc.FieldContext._inputElementValidCss); + Sys.UI.DomElement.addCssClass(element, Sys.Mvc.FieldContext._inputElementErrorCss); + } + }, + + _displaySuccess: function Sys_Mvc_FieldContext$_displaySuccess() { + var validationMessageElement = this.validationMessageElement; + if (validationMessageElement) { + if (this.replaceValidationMessageContents) { + Sys.Mvc._validationUtil.setInnerText(validationMessageElement, ''); + } + Sys.UI.DomElement.removeCssClass(validationMessageElement, Sys.Mvc.FieldContext._validationMessageErrorCss); + Sys.UI.DomElement.addCssClass(validationMessageElement, Sys.Mvc.FieldContext._validationMessageValidCss); + } + var elements = this.elements; + for (var i = 0; i < elements.length; i++) { + var element = elements[i]; + Sys.UI.DomElement.removeCssClass(element, Sys.Mvc.FieldContext._inputElementErrorCss); + Sys.UI.DomElement.addCssClass(element, Sys.Mvc.FieldContext._inputElementValidCss); + } + }, + + _element_OnBlur: function Sys_Mvc_FieldContext$_element_OnBlur(e) { + /// + /// + if (e.target[Sys.Mvc.FieldContext._hasTextChangedTag] || e.target[Sys.Mvc.FieldContext._hasValidationFiredTag]) { + this.validate('blur'); + } + }, + + _element_OnChange: function Sys_Mvc_FieldContext$_element_OnChange(e) { + /// + /// + e.target[Sys.Mvc.FieldContext._hasTextChangedTag] = true; + }, + + _element_OnInput: function Sys_Mvc_FieldContext$_element_OnInput(e) { + /// + /// + e.target[Sys.Mvc.FieldContext._hasTextChangedTag] = true; + if (e.target[Sys.Mvc.FieldContext._hasValidationFiredTag]) { + this.validate('input'); + } + }, + + _element_OnPropertyChange: function Sys_Mvc_FieldContext$_element_OnPropertyChange(e) { + /// + /// + if (e.rawEvent.propertyName === 'value') { + e.target[Sys.Mvc.FieldContext._hasTextChangedTag] = true; + if (e.target[Sys.Mvc.FieldContext._hasValidationFiredTag]) { + this.validate('input'); + } + } + }, + + enableDynamicValidation: function Sys_Mvc_FieldContext$enableDynamicValidation() { + var elements = this.elements; + for (var i = 0; i < elements.length; i++) { + var element = elements[i]; + if (Sys.Mvc._validationUtil.elementSupportsEvent(element, 'onpropertychange')) { + Sys.UI.DomEvent.addHandler(element, 'propertychange', this._onPropertyChangeHandler); + } + else { + Sys.UI.DomEvent.addHandler(element, 'input', this._onInputHandler); + } + Sys.UI.DomEvent.addHandler(element, 'change', this._onChangeHandler); + Sys.UI.DomEvent.addHandler(element, 'blur', this._onBlurHandler); + } + }, + + _getErrorString: function Sys_Mvc_FieldContext$_getErrorString(validatorReturnValue, fieldErrorMessage) { + /// + /// + /// + /// + /// + var fallbackErrorMessage = fieldErrorMessage || this.defaultErrorMessage; + if (Boolean.isInstanceOfType(validatorReturnValue)) { + return (validatorReturnValue) ? null : fallbackErrorMessage; + } + if (String.isInstanceOfType(validatorReturnValue)) { + return ((validatorReturnValue).length) ? validatorReturnValue : fallbackErrorMessage; + } + return null; + }, + + _getStringValue: function Sys_Mvc_FieldContext$_getStringValue() { + /// + var elements = this.elements; + return (elements.length > 0) ? elements[0].value : null; + }, + + _markValidationFired: function Sys_Mvc_FieldContext$_markValidationFired() { + var elements = this.elements; + for (var i = 0; i < elements.length; i++) { + var element = elements[i]; + element[Sys.Mvc.FieldContext._hasValidationFiredTag] = true; + } + }, + + _onErrorCountChanged: function Sys_Mvc_FieldContext$_onErrorCountChanged() { + if (!this._errors.length) { + this._displaySuccess(); + } + else { + this._displayError(); + } + }, + + validate: function Sys_Mvc_FieldContext$validate(eventName) { + /// + /// + /// + var validations = this.validations; + var errors = []; + var value = this._getStringValue(); + for (var i = 0; i < validations.length; i++) { + var validation = validations[i]; + var context = Sys.Mvc.$create_ValidationContext(); + context.eventName = eventName; + context.fieldContext = this; + context.validation = validation; + var retVal = validation.validator(value, context); + var errorMessage = this._getErrorString(retVal, validation.fieldErrorMessage); + if (!Sys.Mvc._validationUtil.stringIsNullOrEmpty(errorMessage)) { + Array.add(errors, errorMessage); + } + } + this._markValidationFired(); + this.clearErrors(); + this.addErrors(errors); + return errors; + } +} + + +//////////////////////////////////////////////////////////////////////////////// +// Sys.Mvc.RangeValidator + +Sys.Mvc.RangeValidator = function Sys_Mvc_RangeValidator(minimum, maximum) { + /// + /// + /// + /// + /// + /// + /// + /// + this._minimum = minimum; + this._maximum = maximum; +} +Sys.Mvc.RangeValidator.create = function Sys_Mvc_RangeValidator$create(rule) { + /// + /// + /// + var min = rule.ValidationParameters['minimum']; + var max = rule.ValidationParameters['maximum']; + return Function.createDelegate(new Sys.Mvc.RangeValidator(min, max), new Sys.Mvc.RangeValidator(min, max).validate); +} +Sys.Mvc.RangeValidator.prototype = { + _minimum: null, + _maximum: null, + + validate: function Sys_Mvc_RangeValidator$validate(value, context) { + /// + /// + /// + /// + /// + if (Sys.Mvc._validationUtil.stringIsNullOrEmpty(value)) { + return true; + } + var n = Number.parseLocale(value); + return (!isNaN(n) && this._minimum <= n && n <= this._maximum); + } +} + + +//////////////////////////////////////////////////////////////////////////////// +// Sys.Mvc.RegularExpressionValidator + +Sys.Mvc.RegularExpressionValidator = function Sys_Mvc_RegularExpressionValidator(pattern) { + /// + /// + /// + /// + this._pattern = pattern; +} +Sys.Mvc.RegularExpressionValidator.create = function Sys_Mvc_RegularExpressionValidator$create(rule) { + /// + /// + /// + var pattern = rule.ValidationParameters['pattern']; + return Function.createDelegate(new Sys.Mvc.RegularExpressionValidator(pattern), new Sys.Mvc.RegularExpressionValidator(pattern).validate); +} +Sys.Mvc.RegularExpressionValidator.prototype = { + _pattern: null, + + validate: function Sys_Mvc_RegularExpressionValidator$validate(value, context) { + /// + /// + /// + /// + /// + if (Sys.Mvc._validationUtil.stringIsNullOrEmpty(value)) { + return true; + } + var regExp = new RegExp(this._pattern); + var matches = regExp.exec(value); + return (!Sys.Mvc._validationUtil.arrayIsNullOrEmpty(matches) && matches[0].length === value.length); + } +} + + +//////////////////////////////////////////////////////////////////////////////// +// Sys.Mvc.RequiredValidator + +Sys.Mvc.RequiredValidator = function Sys_Mvc_RequiredValidator() { +} +Sys.Mvc.RequiredValidator.create = function Sys_Mvc_RequiredValidator$create(rule) { + /// + /// + /// + return Function.createDelegate(new Sys.Mvc.RequiredValidator(), new Sys.Mvc.RequiredValidator().validate); +} +Sys.Mvc.RequiredValidator._isRadioInputElement = function Sys_Mvc_RequiredValidator$_isRadioInputElement(element) { + /// + /// + /// + if (element.tagName.toUpperCase() === 'INPUT') { + var inputType = (element.type).toUpperCase(); + if (inputType === 'RADIO') { + return true; + } + } + return false; +} +Sys.Mvc.RequiredValidator._isSelectInputElement = function Sys_Mvc_RequiredValidator$_isSelectInputElement(element) { + /// + /// + /// + if (element.tagName.toUpperCase() === 'SELECT') { + return true; + } + return false; +} +Sys.Mvc.RequiredValidator._isTextualInputElement = function Sys_Mvc_RequiredValidator$_isTextualInputElement(element) { + /// + /// + /// + if (element.tagName.toUpperCase() === 'INPUT') { + var inputType = (element.type).toUpperCase(); + switch (inputType) { + case 'TEXT': + case 'PASSWORD': + case 'FILE': + return true; + } + } + if (element.tagName.toUpperCase() === 'TEXTAREA') { + return true; + } + return false; +} +Sys.Mvc.RequiredValidator._validateRadioInput = function Sys_Mvc_RequiredValidator$_validateRadioInput(elements) { + /// + /// + /// + for (var i = 0; i < elements.length; i++) { + var element = elements[i]; + if (element.checked) { + return true; + } + } + return false; +} +Sys.Mvc.RequiredValidator._validateSelectInput = function Sys_Mvc_RequiredValidator$_validateSelectInput(optionElements) { + /// + /// + /// + for (var i = 0; i < optionElements.length; i++) { + var element = optionElements[i]; + if (element.selected) { + if (!Sys.Mvc._validationUtil.stringIsNullOrEmpty(element.value)) { + return true; + } + } + } + return false; +} +Sys.Mvc.RequiredValidator._validateTextualInput = function Sys_Mvc_RequiredValidator$_validateTextualInput(element) { + /// + /// + /// + return (!Sys.Mvc._validationUtil.stringIsNullOrEmpty(element.value)); +} +Sys.Mvc.RequiredValidator.prototype = { + + validate: function Sys_Mvc_RequiredValidator$validate(value, context) { + /// + /// + /// + /// + /// + var elements = context.fieldContext.elements; + if (!elements.length) { + return true; + } + var sampleElement = elements[0]; + if (Sys.Mvc.RequiredValidator._isTextualInputElement(sampleElement)) { + return Sys.Mvc.RequiredValidator._validateTextualInput(sampleElement); + } + if (Sys.Mvc.RequiredValidator._isRadioInputElement(sampleElement)) { + return Sys.Mvc.RequiredValidator._validateRadioInput(elements); + } + if (Sys.Mvc.RequiredValidator._isSelectInputElement(sampleElement)) { + return Sys.Mvc.RequiredValidator._validateSelectInput((sampleElement).options); + } + return true; + } +} + + +//////////////////////////////////////////////////////////////////////////////// +// Sys.Mvc.StringLengthValidator + +Sys.Mvc.StringLengthValidator = function Sys_Mvc_StringLengthValidator(minLength, maxLength) { + /// + /// + /// + /// + /// + /// + /// + /// + this._minLength = minLength; + this._maxLength = maxLength; +} +Sys.Mvc.StringLengthValidator.create = function Sys_Mvc_StringLengthValidator$create(rule) { + /// + /// + /// + var minLength = rule.ValidationParameters['minimumLength']; + var maxLength = rule.ValidationParameters['maximumLength']; + return Function.createDelegate(new Sys.Mvc.StringLengthValidator(minLength, maxLength), new Sys.Mvc.StringLengthValidator(minLength, maxLength).validate); +} +Sys.Mvc.StringLengthValidator.prototype = { + _maxLength: 0, + _minLength: 0, + + validate: function Sys_Mvc_StringLengthValidator$validate(value, context) { + /// + /// + /// + /// + /// + if (Sys.Mvc._validationUtil.stringIsNullOrEmpty(value)) { + return true; + } + return (this._minLength <= value.length && value.length <= this._maxLength); + } +} + + +//////////////////////////////////////////////////////////////////////////////// +// Sys.Mvc._validationUtil + +Sys.Mvc._validationUtil = function Sys_Mvc__validationUtil() { +} +Sys.Mvc._validationUtil.arrayIsNullOrEmpty = function Sys_Mvc__validationUtil$arrayIsNullOrEmpty(array) { + /// + /// + /// + return (!array || !array.length); +} +Sys.Mvc._validationUtil.stringIsNullOrEmpty = function Sys_Mvc__validationUtil$stringIsNullOrEmpty(value) { + /// + /// + /// + return (!value || !value.length); +} +Sys.Mvc._validationUtil.elementSupportsEvent = function Sys_Mvc__validationUtil$elementSupportsEvent(element, eventAttributeName) { + /// + /// + /// + /// + /// + return (eventAttributeName in element); +} +Sys.Mvc._validationUtil.removeAllChildren = function Sys_Mvc__validationUtil$removeAllChildren(element) { + /// + /// + while (element.firstChild) { + element.removeChild(element.firstChild); + } +} +Sys.Mvc._validationUtil.setInnerText = function Sys_Mvc__validationUtil$setInnerText(element, innerText) { + /// + /// + /// + /// + var textNode = document.createTextNode(innerText); + Sys.Mvc._validationUtil.removeAllChildren(element); + element.appendChild(textNode); +} + + +//////////////////////////////////////////////////////////////////////////////// +// Sys.Mvc.ValidatorRegistry + +Sys.Mvc.ValidatorRegistry = function Sys_Mvc_ValidatorRegistry() { + /// + /// +} +Sys.Mvc.ValidatorRegistry.getValidator = function Sys_Mvc_ValidatorRegistry$getValidator(rule) { + /// + /// + /// + var creator = Sys.Mvc.ValidatorRegistry.validators[rule.ValidationType]; + return (creator) ? creator(rule) : null; +} +Sys.Mvc.ValidatorRegistry._getDefaultValidators = function Sys_Mvc_ValidatorRegistry$_getDefaultValidators() { + /// + return { required: Function.createDelegate(null, Sys.Mvc.RequiredValidator.create), stringLength: Function.createDelegate(null, Sys.Mvc.StringLengthValidator.create), regularExpression: Function.createDelegate(null, Sys.Mvc.RegularExpressionValidator.create), range: Function.createDelegate(null, Sys.Mvc.RangeValidator.create), number: Function.createDelegate(null, Sys.Mvc.NumberValidator.create) }; +} + + +Sys.Mvc.NumberValidator.registerClass('Sys.Mvc.NumberValidator'); +Sys.Mvc.FormContext.registerClass('Sys.Mvc.FormContext'); +Sys.Mvc.FieldContext.registerClass('Sys.Mvc.FieldContext'); +Sys.Mvc.RangeValidator.registerClass('Sys.Mvc.RangeValidator'); +Sys.Mvc.RegularExpressionValidator.registerClass('Sys.Mvc.RegularExpressionValidator'); +Sys.Mvc.RequiredValidator.registerClass('Sys.Mvc.RequiredValidator'); +Sys.Mvc.StringLengthValidator.registerClass('Sys.Mvc.StringLengthValidator'); +Sys.Mvc._validationUtil.registerClass('Sys.Mvc._validationUtil'); +Sys.Mvc.ValidatorRegistry.registerClass('Sys.Mvc.ValidatorRegistry'); +Sys.Mvc.FormContext._validationSummaryErrorCss = 'validation-summary-errors'; +Sys.Mvc.FormContext._validationSummaryValidCss = 'validation-summary-valid'; +Sys.Mvc.FormContext._formValidationTag = '__MVC_FormValidation'; +Sys.Mvc.FieldContext._hasTextChangedTag = '__MVC_HasTextChanged'; +Sys.Mvc.FieldContext._hasValidationFiredTag = '__MVC_HasValidationFired'; +Sys.Mvc.FieldContext._inputElementErrorCss = 'input-validation-error'; +Sys.Mvc.FieldContext._inputElementValidCss = 'input-validation-valid'; +Sys.Mvc.FieldContext._validationMessageErrorCss = 'field-validation-error'; +Sys.Mvc.FieldContext._validationMessageValidCss = 'field-validation-valid'; +Sys.Mvc.ValidatorRegistry.validators = Sys.Mvc.ValidatorRegistry._getDefaultValidators(); + +// ---- Do not remove this footer ---- +// Generated using Script# v0.5.0.0 (http://projects.nikhilk.net) +// ----------------------------------- + +// register validation +Sys.Application.add_load(function() { + Sys.Application.remove_load(arguments.callee); + Sys.Mvc.FormContext._Application_Load(); +}); diff --git a/ShowOff/Scripts/MicrosoftMvcValidation.js b/ShowOff/Scripts/MicrosoftMvcValidation.js new file mode 100644 index 0000000..62e6412 --- /dev/null +++ b/ShowOff/Scripts/MicrosoftMvcValidation.js @@ -0,0 +1,54 @@ +//---------------------------------------------------------- +// Copyright (C) Microsoft Corporation. All rights reserved. +//---------------------------------------------------------- +// MicrosoftMvcValidation.js + +Type.registerNamespace('Sys.Mvc');Sys.Mvc.$create_Validation=function(){return {};} +Sys.Mvc.$create_JsonValidationField=function(){return {};} +Sys.Mvc.$create_JsonValidationOptions=function(){return {};} +Sys.Mvc.$create_JsonValidationRule=function(){return {};} +Sys.Mvc.$create_ValidationContext=function(){return {};} +Sys.Mvc.NumberValidator=function(){} +Sys.Mvc.NumberValidator.create=function(rule){return Function.createDelegate(new Sys.Mvc.NumberValidator(),new Sys.Mvc.NumberValidator().validate);} +Sys.Mvc.NumberValidator.prototype={validate:function(value,context){if(Sys.Mvc._ValidationUtil.$1(value)){return true;}var $0=Number.parseLocale(value);return (!isNaN($0));}} +Sys.Mvc.FormContext=function(formElement,validationSummaryElement){this.$5=[];this.fields=new Array(0);this.$9=formElement;this.$7=validationSummaryElement;formElement['__MVC_FormValidation'] = this;if(validationSummaryElement){var $0=validationSummaryElement.getElementsByTagName('ul');if($0.length>0){this.$8=$0[0];}}this.$3=Function.createDelegate(this,this.$D);this.$4=Function.createDelegate(this,this.$E);} +Sys.Mvc.FormContext._Application_Load=function(){var $0=window.mvcClientValidationMetadata;if($0){while($0.length>0){var $1=$0.pop();Sys.Mvc.FormContext.$12($1);}}} +Sys.Mvc.FormContext.$F=function($p0,$p1){var $0=[];var $1=document.getElementsByName($p1);for(var $2=0;$2<$1.length;$2++){var $3=$1[$2];if(Sys.Mvc.FormContext.$10($p0,$3)){Array.add($0,$3);}}return $0;} +Sys.Mvc.FormContext.getValidationForForm=function(formElement){return formElement['__MVC_FormValidation'];} +Sys.Mvc.FormContext.$10=function($p0,$p1){while($p1){if($p0===$p1){return true;}$p1=$p1.parentNode;}return false;} +Sys.Mvc.FormContext.$12=function($p0){var $0=$get($p0.FormId);var $1=(!Sys.Mvc._ValidationUtil.$1($p0.ValidationSummaryId))?$get($p0.ValidationSummaryId):null;var $2=new Sys.Mvc.FormContext($0,$1);$2.enableDynamicValidation();$2.replaceValidationSummary=$p0.ReplaceValidationSummary;for(var $3=0;$3<$p0.Fields.length;$3++){var $4=$p0.Fields[$3];var $5=Sys.Mvc.FormContext.$F($0,$4.FieldName);var $6=(!Sys.Mvc._ValidationUtil.$1($4.ValidationMessageId))?$get($4.ValidationMessageId):null;var $7=new Sys.Mvc.FieldContext($2);Array.addRange($7.elements,$5);$7.validationMessageElement=$6;$7.replaceValidationMessageContents=$4.ReplaceValidationMessageContents;for(var $8=0;$8<$4.ValidationRules.length;$8++){var $9=$4.ValidationRules[$8];var $A=Sys.Mvc.ValidatorRegistry.getValidator($9);if($A){var $B=Sys.Mvc.$create_Validation();$B.fieldErrorMessage=$9.ErrorMessage;$B.validator=$A;Array.add($7.validations,$B);}}$7.enableDynamicValidation();Array.add($2.fields,$7);}return $2;} +Sys.Mvc.FormContext.prototype={$3:null,$4:null,$6:null,$7:null,$8:null,$9:null,replaceValidationSummary:false,addError:function(message){this.addErrors([message]);},addErrors:function(messages){if(!Sys.Mvc._ValidationUtil.$0(messages)){Array.addRange(this.$5,messages);this.$11();}},clearErrors:function(){Array.clear(this.$5);this.$11();},$A:function(){if(this.$7){if(this.$8){Sys.Mvc._ValidationUtil.$3(this.$8);for(var $0=0;$00)?$0[0].value:null;},$13:function(){var $0=this.elements;for(var $1=0;$1<$0.length;$1++){var $2=$0[$1];$2['__MVC_HasValidationFired'] = true;}},$14:function(){if(!this.$A.length){this.$C();}else{this.$B();}},validate:function(eventName){var $0=this.validations;var $1=[];var $2=this.$12();for(var $3=0;$3<$0.length;$3++){var $4=$0[$3];var $5=Sys.Mvc.$create_ValidationContext();$5.eventName=eventName;$5.fieldContext=this;$5.validation=$4;var $6=$4.validator($2,$5);var $7=this.$11($6,$4.fieldErrorMessage);if(!Sys.Mvc._ValidationUtil.$1($7)){Array.add($1,$7);}}this.$13();this.clearErrors();this.addErrors($1);return $1;}} +Sys.Mvc.RangeValidator=function(minimum,maximum){this.$0=minimum;this.$1=maximum;} +Sys.Mvc.RangeValidator.create=function(rule){var $0=rule.ValidationParameters['minimum'];var $1=rule.ValidationParameters['maximum'];return Function.createDelegate(new Sys.Mvc.RangeValidator($0,$1),new Sys.Mvc.RangeValidator($0,$1).validate);} +Sys.Mvc.RangeValidator.prototype={$0:null,$1:null,validate:function(value,context){if(Sys.Mvc._ValidationUtil.$1(value)){return true;}var $0=Number.parseLocale(value);return (!isNaN($0)&&this.$0<=$0&&$0<=this.$1);}} +Sys.Mvc.RegularExpressionValidator=function(pattern){this.$0=pattern;} +Sys.Mvc.RegularExpressionValidator.create=function(rule){var $0=rule.ValidationParameters['pattern'];return Function.createDelegate(new Sys.Mvc.RegularExpressionValidator($0),new Sys.Mvc.RegularExpressionValidator($0).validate);} +Sys.Mvc.RegularExpressionValidator.prototype={$0:null,validate:function(value,context){if(Sys.Mvc._ValidationUtil.$1(value)){return true;}var $0=new RegExp(this.$0);var $1=$0.exec(value);return (!Sys.Mvc._ValidationUtil.$0($1)&&$1[0].length===value.length);}} +Sys.Mvc.RequiredValidator=function(){} +Sys.Mvc.RequiredValidator.create=function(rule){return Function.createDelegate(new Sys.Mvc.RequiredValidator(),new Sys.Mvc.RequiredValidator().validate);} +Sys.Mvc.RequiredValidator.$0=function($p0){if($p0.tagName.toUpperCase()==='INPUT'){var $0=($p0.type).toUpperCase();if($0==='RADIO'){return true;}}return false;} +Sys.Mvc.RequiredValidator.$1=function($p0){if($p0.tagName.toUpperCase()==='SELECT'){return true;}return false;} +Sys.Mvc.RequiredValidator.$2=function($p0){if($p0.tagName.toUpperCase()==='INPUT'){var $0=($p0.type).toUpperCase();switch($0){case 'TEXT':case 'PASSWORD':case 'FILE':return true;}}if($p0.tagName.toUpperCase()==='TEXTAREA'){return true;}return false;} +Sys.Mvc.RequiredValidator.$3=function($p0){for(var $0=0;$0<$p0.length;$0++){var $1=$p0[$0];if($1.checked){return true;}}return false;} +Sys.Mvc.RequiredValidator.$4=function($p0){for(var $0=0;$0<$p0.length;$0++){var $1=$p0[$0];if($1.selected){if(!Sys.Mvc._ValidationUtil.$1($1.value)){return true;}}}return false;} +Sys.Mvc.RequiredValidator.$5=function($p0){return (!Sys.Mvc._ValidationUtil.$1($p0.value));} +Sys.Mvc.RequiredValidator.prototype={validate:function(value,context){var $0=context.fieldContext.elements;if(!$0.length){return true;}var $1=$0[0];if(Sys.Mvc.RequiredValidator.$2($1)){return Sys.Mvc.RequiredValidator.$5($1);}if(Sys.Mvc.RequiredValidator.$0($1)){return Sys.Mvc.RequiredValidator.$3($0);}if(Sys.Mvc.RequiredValidator.$1($1)){return Sys.Mvc.RequiredValidator.$4(($1).options);}return true;}} +Sys.Mvc.StringLengthValidator=function(minLength,maxLength){this.$1=minLength;this.$0=maxLength;} +Sys.Mvc.StringLengthValidator.create=function(rule){var $0=rule.ValidationParameters['minimumLength'];var $1=rule.ValidationParameters['maximumLength'];return Function.createDelegate(new Sys.Mvc.StringLengthValidator($0,$1),new Sys.Mvc.StringLengthValidator($0,$1).validate);} +Sys.Mvc.StringLengthValidator.prototype={$0:0,$1:0,validate:function(value,context){if(Sys.Mvc._ValidationUtil.$1(value)){return true;}return (this.$1<=value.length&&value.length<=this.$0);}} +Sys.Mvc._ValidationUtil=function(){} +Sys.Mvc._ValidationUtil.$0=function($p0){return (!$p0||!$p0.length);} +Sys.Mvc._ValidationUtil.$1=function($p0){return (!$p0||!$p0.length);} +Sys.Mvc._ValidationUtil.$2=function($p0,$p1){return ($p1 in $p0);} +Sys.Mvc._ValidationUtil.$3=function($p0){while($p0.firstChild){$p0.removeChild($p0.firstChild);}} +Sys.Mvc._ValidationUtil.$4=function($p0,$p1){var $0=document.createTextNode($p1);Sys.Mvc._ValidationUtil.$3($p0);$p0.appendChild($0);} +Sys.Mvc.ValidatorRegistry=function(){} +Sys.Mvc.ValidatorRegistry.getValidator=function(rule){var $0=Sys.Mvc.ValidatorRegistry.validators[rule.ValidationType];return ($0)?$0(rule):null;} +Sys.Mvc.ValidatorRegistry.$0=function(){return {required:Function.createDelegate(null,Sys.Mvc.RequiredValidator.create),stringLength:Function.createDelegate(null,Sys.Mvc.StringLengthValidator.create),regularExpression:Function.createDelegate(null,Sys.Mvc.RegularExpressionValidator.create),range:Function.createDelegate(null,Sys.Mvc.RangeValidator.create),number:Function.createDelegate(null,Sys.Mvc.NumberValidator.create)};} +Sys.Mvc.NumberValidator.registerClass('Sys.Mvc.NumberValidator');Sys.Mvc.FormContext.registerClass('Sys.Mvc.FormContext');Sys.Mvc.FieldContext.registerClass('Sys.Mvc.FieldContext');Sys.Mvc.RangeValidator.registerClass('Sys.Mvc.RangeValidator');Sys.Mvc.RegularExpressionValidator.registerClass('Sys.Mvc.RegularExpressionValidator');Sys.Mvc.RequiredValidator.registerClass('Sys.Mvc.RequiredValidator');Sys.Mvc.StringLengthValidator.registerClass('Sys.Mvc.StringLengthValidator');Sys.Mvc._ValidationUtil.registerClass('Sys.Mvc._ValidationUtil');Sys.Mvc.ValidatorRegistry.registerClass('Sys.Mvc.ValidatorRegistry');Sys.Mvc.ValidatorRegistry.validators=Sys.Mvc.ValidatorRegistry.$0(); +// ---- Do not remove this footer ---- +// Generated using Script# v0.5.0.0 (http://projects.nikhilk.net) +// ----------------------------------- +Sys.Application.add_load(function(){Sys.Application.remove_load(arguments.callee);Sys.Mvc.FormContext._Application_Load();}); \ No newline at end of file diff --git a/ShowOff/Scripts/jcarousellite_1.0.1.js b/ShowOff/Scripts/jcarousellite_1.0.1.js new file mode 100644 index 0000000..07b82a6 --- /dev/null +++ b/ShowOff/Scripts/jcarousellite_1.0.1.js @@ -0,0 +1,341 @@ +/** + * jCarouselLite - jQuery plugin to navigate images/any content in a carousel style widget. + * @requires jQuery v1.2 or above + * + * http://gmarwaha.com/jquery/jcarousellite/ + * + * Copyright (c) 2007 Ganeshji Marwaha (gmarwaha.com) + * Dual licensed under the MIT and GPL licenses: + * http://www.opensource.org/licenses/mit-license.php + * http://www.gnu.org/licenses/gpl.html + * + * Version: 1.0.1 + * Note: Requires jquery 1.2 or above from version 1.0.1 + */ + +/** + * Creates a carousel-style navigation widget for images/any-content from a simple HTML markup. + * + * The HTML markup that is used to build the carousel can be as simple as... + * + * + * + * As you can see, this snippet is nothing but a simple div containing an unordered list of images. + * You don't need any special "class" attribute, or a special "css" file for this plugin. + * I am using a class attribute just for the sake of explanation here. + * + * To navigate the elements of the carousel, you need some kind of navigation buttons. + * For example, you will need a "previous" button to go backward, and a "next" button to go forward. + * This need not be part of the carousel "div" itself. It can be any element in your page. + * Lets assume that the following elements in your document can be used as next, and prev buttons... + * + * + * + * + * Now, all you need to do is call the carousel component on the div element that represents it, and pass in the + * navigation buttons as options. + * + * $(".carousel").jCarouselLite({ + * btnNext: ".next", + * btnPrev: ".prev" + * }); + * + * That's it, you would have now converted your raw div, into a magnificient carousel. + * + * There are quite a few other options that you can use to customize it though. + * Each will be explained with an example below. + * + * @param an options object - You can specify all the options shown below as an options object param. + * + * @option btnPrev, btnNext : string - no defaults + * @example + * $(".carousel").jCarouselLite({ + * btnNext: ".next", + * btnPrev: ".prev" + * }); + * @desc Creates a basic carousel. Clicking "btnPrev" navigates backwards and "btnNext" navigates forward. + * + * @option btnGo - array - no defaults + * @example + * $(".carousel").jCarouselLite({ + * btnNext: ".next", + * btnPrev: ".prev", + * btnGo: [".0", ".1", ".2"] + * }); + * @desc If you don't want next and previous buttons for navigation, instead you prefer custom navigation based on + * the item number within the carousel, you can use this option. Just supply an array of selectors for each element + * in the carousel. The index of the array represents the index of the element. What i mean is, if the + * first element in the array is ".0", it means that when the element represented by ".0" is clicked, the carousel + * will slide to the first element and so on and so forth. This feature is very powerful. For example, i made a tabbed + * interface out of it by making my navigation elements styled like tabs in css. As the carousel is capable of holding + * any content, not just images, you can have a very simple tabbed navigation in minutes without using any other plugin. + * The best part is that, the tab will "slide" based on the provided effect. :-) + * + * @option mouseWheel : boolean - default is false + * @example + * $(".carousel").jCarouselLite({ + * mouseWheel: true + * }); + * @desc The carousel can also be navigated using the mouse wheel interface of a scroll mouse instead of using buttons. + * To get this feature working, you have to do 2 things. First, you have to include the mouse-wheel plugin from brandon. + * Second, you will have to set the option "mouseWheel" to true. That's it, now you will be able to navigate your carousel + * using the mouse wheel. Using buttons and mouseWheel or not mutually exclusive. You can still have buttons for navigation + * as well. They complement each other. To use both together, just supply the options required for both as shown below. + * @example + * $(".carousel").jCarouselLite({ + * btnNext: ".next", + * btnPrev: ".prev", + * mouseWheel: true + * }); + * + * @option auto : number - default is null, meaning autoscroll is disabled by default + * @example + * $(".carousel").jCarouselLite({ + * auto: 800, + * speed: 500 + * }); + * @desc You can make your carousel auto-navigate itself by specfying a millisecond value in this option. + * The value you specify is the amount of time between 2 slides. The default is null, and that disables auto scrolling. + * Specify this value and magically your carousel will start auto scrolling. + * + * @option speed : number - 200 is default + * @example + * $(".carousel").jCarouselLite({ + * btnNext: ".next", + * btnPrev: ".prev", + * speed: 800 + * }); + * @desc Specifying a speed will slow-down or speed-up the sliding speed of your carousel. Try it out with + * different speeds like 800, 600, 1500 etc. Providing 0, will remove the slide effect. + * + * @option easing : string - no easing effects by default. + * @example + * $(".carousel").jCarouselLite({ + * btnNext: ".next", + * btnPrev: ".prev", + * easing: "bounceout" + * }); + * @desc You can specify any easing effect. Note: You need easing plugin for that. Once specified, + * the carousel will slide based on the provided easing effect. + * + * @option vertical : boolean - default is false + * @example + * $(".carousel").jCarouselLite({ + * btnNext: ".next", + * btnPrev: ".prev", + * vertical: true + * }); + * @desc Determines the direction of the carousel. true, means the carousel will display vertically. The next and + * prev buttons will slide the items vertically as well. The default is false, which means that the carousel will + * display horizontally. The next and prev items will slide the items from left-right in this case. + * + * @option circular : boolean - default is true + * @example + * $(".carousel").jCarouselLite({ + * btnNext: ".next", + * btnPrev: ".prev", + * circular: false + * }); + * @desc Setting it to true enables circular navigation. This means, if you click "next" after you reach the last + * element, you will automatically slide to the first element and vice versa. If you set circular to false, then + * if you click on the "next" button after you reach the last element, you will stay in the last element itself + * and similarly for "previous" button and first element. + * + * @option visible : number - default is 3 + * @example + * $(".carousel").jCarouselLite({ + * btnNext: ".next", + * btnPrev: ".prev", + * visible: 4 + * }); + * @desc This specifies the number of items visible at all times within the carousel. The default is 3. + * You are even free to experiment with real numbers. Eg: "3.5" will have 3 items fully visible and the + * last item half visible. This gives you the effect of showing the user that there are more images to the right. + * + * @option start : number - default is 0 + * @example + * $(".carousel").jCarouselLite({ + * btnNext: ".next", + * btnPrev: ".prev", + * start: 2 + * }); + * @desc You can specify from which item the carousel should start. Remember, the first item in the carousel + * has a start of 0, and so on. + * + * @option scrool : number - default is 1 + * @example + * $(".carousel").jCarouselLite({ + * btnNext: ".next", + * btnPrev: ".prev", + * scroll: 2 + * }); + * @desc The number of items that should scroll/slide when you click the next/prev navigation buttons. By + * default, only one item is scrolled, but you may set it to any number. Eg: setting it to "2" will scroll + * 2 items when you click the next or previous buttons. + * + * @option beforeStart, afterEnd : function - callbacks + * @example + * $(".carousel").jCarouselLite({ + * btnNext: ".next", + * btnPrev: ".prev", + * beforeStart: function(a) { + * alert("Before animation starts:" + a); + * }, + * afterEnd: function(a) { + * alert("After animation ends:" + a); + * } + * }); + * @desc If you wanted to do some logic in your page before the slide starts and after the slide ends, you can + * register these 2 callbacks. The functions will be passed an argument that represents an array of elements that + * are visible at the time of callback. + * + * + * @cat Plugins/Image Gallery + * @author Ganeshji Marwaha/ganeshread@gmail.com + */ + +(function($) { // Compliant with jquery.noConflict() +$.fn.jCarouselLite = function(o) { + o = $.extend({ + btnPrev: null, + btnNext: null, + btnGo: null, + mouseWheel: false, + auto: null, + + speed: 200, + easing: null, + + vertical: false, + circular: true, + visible: 3, + start: 0, + scroll: 1, + + beforeStart: null, + afterEnd: null + }, o || {}); + + return this.each(function() { // Returns the element collection. Chainable. + + var running = false, animCss=o.vertical?"top":"left", sizeCss=o.vertical?"height":"width"; + var div = $(this), ul = $("ul", div), tLi = $("li", ul), tl = tLi.size(), v = o.visible; + + if(o.circular) { + ul.prepend(tLi.slice(tl-v-1+1).clone()) + .append(tLi.slice(0,v).clone()); + o.start += v; + } + + var li = $("li", ul), itemLength = li.size(), curr = o.start; + div.css("visibility", "visible"); + + li.css({overflow: "hidden", float: o.vertical ? "none" : "left"}); + ul.css({margin: "0", padding: "0", position: "relative", "list-style-type": "none", "z-index": "1"}); + div.css({overflow: "hidden", position: "relative", "z-index": "2", left: "0px"}); + + var liSize = o.vertical ? height(li) : width(li); // Full li size(incl margin)-Used for animation + var ulSize = liSize * itemLength; // size of full ul(total length, not just for the visible items) + var divSize = liSize * v; // size of entire div(total length for just the visible items) + + li.css({width: li.width(), height: li.height()}); + ul.css(sizeCss, ulSize+"px").css(animCss, -(curr*liSize)); + + div.css(sizeCss, divSize+"px"); // Width of the DIV. length of visible images + + if(o.btnPrev) + $(o.btnPrev).click(function() { + return go(curr-o.scroll); + }); + + if(o.btnNext) + $(o.btnNext).click(function() { + return go(curr+o.scroll); + }); + + if(o.btnGo) + $.each(o.btnGo, function(i, val) { + $(val).click(function() { + return go(o.circular ? o.visible+i : i); + }); + }); + + if(o.mouseWheel && div.mousewheel) + div.mousewheel(function(e, d) { + return d>0 ? go(curr-o.scroll) : go(curr+o.scroll); + }); + + if(o.auto) + setInterval(function() { + go(curr+o.scroll); + }, o.auto+o.speed); + + function vis() { + return li.slice(curr).slice(0,v); + }; + + function go(to) { + if(!running) { + + if(o.beforeStart) + o.beforeStart.call(this, vis()); + + if(o.circular) { // If circular we are in first or last, then goto the other end + if(to<=o.start-v-1) { // If first, then goto last + ul.css(animCss, -((itemLength-(v*2))*liSize)+"px"); + // If "scroll" > 1, then the "to" might not be equal to the condition; it can be lesser depending on the number of elements. + curr = to==o.start-v-1 ? itemLength-(v*2)-1 : itemLength-(v*2)-o.scroll; + } else if(to>=itemLength-v+1) { // If last, then goto first + ul.css(animCss, -( (v) * liSize ) + "px" ); + // If "scroll" > 1, then the "to" might not be equal to the condition; it can be greater depending on the number of elements. + curr = to==itemLength-v+1 ? v+1 : v+o.scroll; + } else curr = to; + } else { // If non-circular and to points to first or last, we just return. + if(to<0 || to>itemLength-v) return; + else curr = to; + } // If neither overrides it, the curr will still be "to" and we can proceed. + + running = true; + + ul.animate( + animCss == "left" ? { left: -(curr*liSize) } : { top: -(curr*liSize) } , o.speed, o.easing, + function() { + if(o.afterEnd) + o.afterEnd.call(this, vis()); + running = false; + } + ); + // Disable buttons when the carousel reaches the last/first, and enable when not + if(!o.circular) { + $(o.btnPrev + "," + o.btnNext).removeClass("disabled"); + $( (curr-o.scroll<0 && o.btnPrev) + || + (curr+o.scroll > itemLength-v && o.btnNext) + || + [] + ).addClass("disabled"); + } + + } + return false; + }; + }); +}; + +function css(el, prop) { + return parseInt($.css(el[0], prop)) || 0; +}; +function width(el) { + return el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight'); +}; +function height(el) { + return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom'); +}; + +})(jQuery); \ No newline at end of file diff --git a/ShowOff/Scripts/jquery-1.3.2-vsdoc.js b/ShowOff/Scripts/jquery-1.3.2-vsdoc.js new file mode 100644 index 0000000..27aefb8 --- /dev/null +++ b/ShowOff/Scripts/jquery-1.3.2-vsdoc.js @@ -0,0 +1,6255 @@ +/* + * This file has been commented to support Visual Studio Intellisense. + * You should not use this file at runtime inside the browser--it is only + * intended to be used only for design-time IntelliSense. Please use the + * standard jQuery library for all production use. + * + * Comment version: 1.3.2a + */ + +/* + * jQuery JavaScript Library v1.3.2 + * + * Copyright (c) 2009 John Resig, http://jquery.com/ + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009) + * Revision: 6246 + */ + +(function(){ + +var + // Will speed up references to window, and allows munging its name. + window = this, + // Will speed up references to undefined, and allows munging its name. + undefined, + // Map over jQuery in case of overwrite + _jQuery = window.jQuery, + // Map over the $ in case of overwrite + _$ = window.$, + + jQuery = window.jQuery = window.$ = function(selector, context) { + /// + /// 1: $(expression, context) - This function accepts a string containing a CSS selector which is then used to match a set of elements. + /// 2: $(html) - Create DOM elements on-the-fly from the provided String of raw HTML. + /// 3: $(elements) - Wrap jQuery functionality around a single or multiple DOM Element(s). + /// 4: $(callback) - A shorthand for $(document).ready(). + /// + /// + /// 1: expression - An expression to search with. + /// 2: html - A string of HTML to create on the fly. + /// 3: elements - DOM element(s) to be encapsulated by a jQuery object. + /// 4: callback - The function to execute when the DOM is ready. + /// + /// + /// 1: context - A DOM Element, Document or jQuery to use as context. + /// + /// + /// The DOM node context originally passed to jQuery() (if none was passed then context will be equal to the document). + /// + /// + /// A selector representing selector originally passed to jQuery(). + /// + /// + + // The jQuery object is actually just the init constructor 'enhanced' + return new jQuery.fn.init( selector, context ); + }, + + // A simple way to check for HTML strings or ID strings + // (both of which we optimize for) + quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/, + // Is it a simple selector + isSimple = /^.[^:#\[\.,]*$/; + +jQuery.fn = jQuery.prototype = { + init: function( selector, context ) { + /// + /// 1: $(expression, context) - This function accepts a string containing a CSS selector which is then used to match a set of elements. + /// 2: $(html) - Create DOM elements on-the-fly from the provided String of raw HTML. + /// 3: $(elements) - Wrap jQuery functionality around a single or multiple DOM Element(s). + /// 4: $(callback) - A shorthand for $(document).ready(). + /// + /// + /// 1: expression - An expression to search with. + /// 2: html - A string of HTML to create on the fly. + /// 3: elements - DOM element(s) to be encapsulated by a jQuery object. + /// 4: callback - The function to execute when the DOM is ready. + /// + /// + /// 1: context - A DOM Element, Document or jQuery to use as context. + /// + /// + + // Make sure that a selection was provided + selector = selector || document; + + // Handle $(DOMElement) + if ( selector.nodeType ) { + this[0] = selector; + this.length = 1; + this.context = selector; + return this; + } + // Handle HTML strings + if (typeof selector === "string") { + // Are we dealing with HTML string or an ID? + var match = quickExpr.exec(selector); + + // Verify a match, and that no context was specified for #id + if (match && (match[1] || !context)) { + + // HANDLE: $(html) -> $(array) + if (match[1]) + selector = jQuery.clean([match[1]], context); + + // HANDLE: $("#id") + else { + var elem = document.getElementById(match[3]); + + // Handle the case where IE and Opera return items + // by name instead of ID + if (elem && elem.id != match[3]) + return jQuery().find(selector); + + // Otherwise, we inject the element directly into the jQuery object + var ret = jQuery(elem || []); + ret.context = document; + ret.selector = selector; + return ret; + } + + // HANDLE: $(expr, [context]) + // (which is just equivalent to: $(content).find(expr) + } else + return jQuery(context).find(selector); + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( jQuery.isFunction( selector ) ) + return jQuery( document ).ready( selector ); + + // Make sure that old selector state is passed along + if ( selector.selector && selector.context ) { + this.selector = selector.selector; + this.context = selector.context; + } + + return this.setArray(jQuery.isArray( selector ) ? + selector : + jQuery.makeArray(selector)); + }, + + // Start with an empty selector + selector: "", + + // The current version of jQuery being used + jquery: "1.3.2", + + // The number of elements contained in the matched element set + size: function() { + /// + /// The number of elements currently matched. + /// Part of Core + /// + /// + + return this.length; + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + /// + /// Access a single matched element. num is used to access the + /// Nth element matched. + /// Part of Core + /// + /// + /// + /// Access the element in the Nth position. + /// + + return num == undefined ? + + // Return a 'clean' array + Array.prototype.slice.call( this ) : + + // Return just the object + this[ num ]; + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems, name, selector ) { + /// + /// Set the jQuery object to an array of elements, while maintaining + /// the stack. + /// Part of Core + /// + /// + /// + /// An array of elements + /// + + // Build a new jQuery matched element set + var ret = jQuery( elems ); + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + + ret.context = this.context; + + if ( name === "find" ) + ret.selector = this.selector + (this.selector ? " " : "") + selector; + else if ( name ) + ret.selector = this.selector + "." + name + "(" + selector + ")"; + + // Return the newly-formed element set + return ret; + }, + + // Force the current matched set of elements to become + // the specified array of elements (destroying the stack in the process) + // You should use pushStack() in order to do this, but maintain the stack + setArray: function( elems ) { + /// + /// Set the jQuery object to an array of elements. This operation is + /// completely destructive - be sure to use .pushStack() if you wish to maintain + /// the jQuery stack. + /// Part of Core + /// + /// + /// + /// An array of elements + /// + + // Resetting the length to 0, then using the native Array push + // is a super-fast way to populate an object with array-like properties + this.length = 0; + Array.prototype.push.apply( this, elems ); + + return this; + }, + + // Execute a callback for every element in the matched set. + // (You can seed the arguments with an array of args, but this is + // only used internally.) + each: function( callback, args ) { + /// + /// Execute a function within the context of every matched element. + /// This means that every time the passed-in function is executed + /// (which is once for every element matched) the 'this' keyword + /// points to the specific element. + /// Additionally, the function, when executed, is passed a single + /// argument representing the position of the element in the matched + /// set. + /// Part of Core + /// + /// + /// + /// A function to execute + /// + + return jQuery.each( this, callback, args ); + }, + + // Determine the position of an element within + // the matched set of elements + index: function( elem ) { + /// + /// Searches every matched element for the object and returns + /// the index of the element, if found, starting with zero. + /// Returns -1 if the object wasn't found. + /// Part of Core + /// + /// + /// + /// Object to search for + /// + + // Locate the position of the desired element + return jQuery.inArray( + // If it receives a jQuery object, the first element is used + elem && elem.jquery ? elem[0] : elem + , this ); + }, + + attr: function( name, value, type ) { + /// + /// Set a single property to a computed value, on all matched elements. + /// Instead of a value, a function is provided, that computes the value. + /// Part of DOM/Attributes + /// + /// + /// + /// The name of the property to set. + /// + /// + /// A function returning the value to set. + /// + + var options = name; + + // Look for the case where we're accessing a style value + if ( typeof name === "string" ) + if ( value === undefined ) + return this[0] && jQuery[ type || "attr" ]( this[0], name ); + + else { + options = {}; + options[ name ] = value; + } + + // Check to see if we're setting style values + return this.each(function(i){ + // Set all the styles + for ( name in options ) + jQuery.attr( + type ? + this.style : + this, + name, jQuery.prop( this, options[ name ], type, i, name ) + ); + }); + }, + + css: function( key, value ) { + /// + /// Set a single style property to a value, on all matched elements. + /// If a number is provided, it is automatically converted into a pixel value. + /// Part of CSS + /// + /// + /// + /// The name of the property to set. + /// + /// + /// The value to set the property to. + /// + + // ignore negative width and height values + if ( (key == 'width' || key == 'height') && parseFloat(value) < 0 ) + value = undefined; + return this.attr( key, value, "curCSS" ); + }, + + text: function( text ) { + /// + /// Set the text contents of all matched elements. + /// Similar to html(), but escapes HTML (replace "<" and ">" with their + /// HTML entities). + /// Part of DOM/Attributes + /// + /// + /// + /// The text value to set the contents of the element to. + /// + + if ( typeof text !== "object" && text != null ) + return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) ); + + var ret = ""; + + jQuery.each( text || this, function(){ + jQuery.each( this.childNodes, function(){ + if ( this.nodeType != 8 ) + ret += this.nodeType != 1 ? + this.nodeValue : + jQuery.fn.text( [ this ] ); + }); + }); + + return ret; + }, + + wrapAll: function( html ) { + /// + /// Wrap all matched elements with a structure of other elements. + /// This wrapping process is most useful for injecting additional + /// stucture into a document, without ruining the original semantic + /// qualities of a document. + /// This works by going through the first element + /// provided and finding the deepest ancestor element within its + /// structure - it is that element that will en-wrap everything else. + /// This does not work with elements that contain text. Any necessary text + /// must be added after the wrapping is done. + /// Part of DOM/Manipulation + /// + /// + /// + /// A DOM element that will be wrapped around the target. + /// + + if ( this[0] ) { + // The elements to wrap the target around + var wrap = jQuery( html, this[0].ownerDocument ).clone(); + + if ( this[0].parentNode ) + wrap.insertBefore( this[0] ); + + wrap.map(function(){ + var elem = this; + + while ( elem.firstChild ) + elem = elem.firstChild; + + return elem; + }).append(this); + } + + return this; + }, + + wrapInner: function( html ) { + /// + /// Wraps the inner child contents of each matched elemenht (including text nodes) with an HTML structure. + /// + /// + /// A string of HTML or a DOM element that will be wrapped around the target contents. + /// + /// + + return this.each(function(){ + jQuery( this ).contents().wrapAll( html ); + }); + }, + + wrap: function( html ) { + /// + /// Wrap all matched elements with a structure of other elements. + /// This wrapping process is most useful for injecting additional + /// stucture into a document, without ruining the original semantic + /// qualities of a document. + /// This works by going through the first element + /// provided and finding the deepest ancestor element within its + /// structure - it is that element that will en-wrap everything else. + /// This does not work with elements that contain text. Any necessary text + /// must be added after the wrapping is done. + /// Part of DOM/Manipulation + /// + /// + /// + /// A DOM element that will be wrapped around the target. + /// + + return this.each(function(){ + jQuery( this ).wrapAll( html ); + }); + }, + + append: function() { + /// + /// Append content to the inside of every matched element. + /// This operation is similar to doing an appendChild to all the + /// specified elements, adding them into the document. + /// Part of DOM/Manipulation + /// + /// + /// + /// Content to append to the target + /// + + return this.domManip(arguments, true, function(elem){ + if (this.nodeType == 1) + this.appendChild( elem ); + }); + }, + + prepend: function() { + /// + /// Prepend content to the inside of every matched element. + /// This operation is the best way to insert elements + /// inside, at the beginning, of all matched elements. + /// Part of DOM/Manipulation + /// + /// + /// + /// Content to prepend to the target. + /// + + return this.domManip(arguments, true, function(elem){ + if (this.nodeType == 1) + this.insertBefore( elem, this.firstChild ); + }); + }, + + before: function() { + /// + /// Insert content before each of the matched elements. + /// Part of DOM/Manipulation + /// + /// + /// + /// Content to insert before each target. + /// + + return this.domManip(arguments, false, function(elem){ + this.parentNode.insertBefore( elem, this ); + }); + }, + + after: function() { + /// + /// Insert content after each of the matched elements. + /// Part of DOM/Manipulation + /// + /// + /// + /// Content to insert after each target. + /// + + return this.domManip(arguments, false, function(elem){ + this.parentNode.insertBefore( elem, this.nextSibling ); + }); + }, + + end: function() { + /// + /// End the most recent 'destructive' operation, reverting the list of matched elements + /// back to its previous state. After an end operation, the list of matched elements will + /// revert to the last state of matched elements. + /// If there was no destructive operation before, an empty set is returned. + /// Part of DOM/Traversing + /// + /// + + return this.prevObject || jQuery( [] ); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: [].push, + sort: [].sort, + splice: [].splice, + + find: function( selector ) { + /// + /// Searches for all elements that match the specified expression. + /// This method is a good way to find additional descendant + /// elements with which to process. + /// All searching is done using a jQuery expression. The expression can be + /// written using CSS 1-3 Selector syntax, or basic XPath. + /// Part of DOM/Traversing + /// + /// + /// + /// An expression to search with. + /// + /// + + if ( this.length === 1 ) { + var ret = this.pushStack( [], "find", selector ); + ret.length = 0; + jQuery.find( selector, this[0], ret ); + return ret; + } else { + return this.pushStack( jQuery.unique(jQuery.map(this, function(elem){ + return jQuery.find( selector, elem ); + })), "find", selector ); + } + }, + + clone: function( events ) { + /// + /// Clone matched DOM Elements and select the clones. + /// This is useful for moving copies of the elements to another + /// location in the DOM. + /// Part of DOM/Manipulation + /// + /// + /// + /// (Optional) Set to false if you don't want to clone all descendant nodes, in addition to the element itself. + /// + + // Do the clone + var ret = this.map(function(){ + if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) { + // IE copies events bound via attachEvent when + // using cloneNode. Calling detachEvent on the + // clone will also remove the events from the orignal + // In order to get around this, we use innerHTML. + // Unfortunately, this means some modifications to + // attributes in IE that are actually only stored + // as properties will not be copied (such as the + // the name attribute on an input). + var html = this.outerHTML; + if ( !html ) { + var div = this.ownerDocument.createElement("div"); + div.appendChild( this.cloneNode(true) ); + html = div.innerHTML; + } + + return jQuery.clean([html.replace(/ jQuery\d+="(?:\d+|null)"/g, "").replace(/^\s*/, "")])[0]; + } else + return this.cloneNode(true); + }); + + // Copy the events from the original to the clone + if ( events === true ) { + var orig = this.find("*").andSelf(), i = 0; + + ret.find("*").andSelf().each(function(){ + if ( this.nodeName !== orig[i].nodeName ) + return; + + var events = jQuery.data( orig[i], "events" ); + + for ( var type in events ) { + for ( var handler in events[ type ] ) { + jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data ); + } + } + + i++; + }); + } + + // Return the cloned set + return ret; + }, + + filter: function( selector ) { + /// + /// Removes all elements from the set of matched elements that do not + /// pass the specified filter. This method is used to narrow down + /// the results of a search. + /// }) + /// Part of DOM/Traversing + /// + /// + /// + /// A function to use for filtering + /// + /// + + return this.pushStack( + jQuery.isFunction( selector ) && + jQuery.grep(this, function(elem, i){ + return selector.call( elem, i ); + }) || + + jQuery.multiFilter( selector, jQuery.grep(this, function(elem){ + return elem.nodeType === 1; + }) ), "filter", selector ); + }, + + closest: function( selector ) { + /// + /// Get a set of elements containing the closest parent element that matches the specified selector, the starting element included. + /// + /// + /// + /// An expression to filter the elements with. + /// + /// + + var pos = jQuery.expr.match.POS.test( selector ) ? jQuery(selector) : null, + closer = 0; + + return this.map(function(){ + var cur = this; + while ( cur && cur.ownerDocument ) { + if ( pos ? pos.index(cur) > -1 : jQuery(cur).is(selector) ) { + jQuery.data(cur, "closest", closer); + return cur; + } + cur = cur.parentNode; + closer++; + } + }); + }, + + not: function( selector ) { + /// + /// Removes any elements inside the array of elements from the set + /// of matched elements. This method is used to remove one or more + /// elements from a jQuery object. + /// Part of DOM/Traversing + /// + /// + /// A set of elements to remove from the jQuery set of matched elements. + /// + /// + + if ( typeof selector === "string" ) + // test special case where just one selector is passed in + if ( isSimple.test( selector ) ) + return this.pushStack( jQuery.multiFilter( selector, this, true ), "not", selector ); + else + selector = jQuery.multiFilter( selector, this ); + + var isArrayLike = selector.length && selector[selector.length - 1] !== undefined && !selector.nodeType; + return this.filter(function() { + return isArrayLike ? jQuery.inArray( this, selector ) < 0 : this != selector; + }); + }, + + add: function( selector ) { + /// + /// Adds one or more Elements to the set of matched elements. + /// Part of DOM/Traversing + /// + /// + /// One or more Elements to add + /// + /// + + return this.pushStack( jQuery.unique( jQuery.merge( + this.get(), + typeof selector === "string" ? + jQuery( selector ) : + jQuery.makeArray( selector ) + ))); + }, + + is: function( selector ) { + /// + /// Checks the current selection against an expression and returns true, + /// if at least one element of the selection fits the given expression. + /// Does return false, if no element fits or the expression is not valid. + /// filter(String) is used internally, therefore all rules that apply there + /// apply here, too. + /// Part of DOM/Traversing + /// + /// + /// + /// The expression with which to filter + /// + + return !!selector && jQuery.multiFilter( selector, this ).length > 0; + }, + + hasClass: function( selector ) { + /// + /// Checks the current selection against a class and returns whether at least one selection has a given class. + /// + /// The class to check against + /// True if at least one element in the selection has the class, otherwise false. + + return !!selector && this.is( "." + selector ); + }, + + val: function( value ) { + /// + /// Set the value of every matched element. + /// Part of DOM/Attributes + /// + /// + /// + /// Set the property to the specified value. + /// + + if ( value === undefined ) { + var elem = this[0]; + + if ( elem ) { + if( jQuery.nodeName( elem, 'option' ) ) + return (elem.attributes.value || {}).specified ? elem.value : elem.text; + + // We need to handle select boxes special + if ( jQuery.nodeName( elem, "select" ) ) { + var index = elem.selectedIndex, + values = [], + options = elem.options, + one = elem.type == "select-one"; + + // Nothing was selected + if ( index < 0 ) + return null; + + // Loop through all the selected options + for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) { + var option = options[ i ]; + + if ( option.selected ) { + // Get the specifc value for the option + value = jQuery(option).val(); + + // We don't need an array for one selects + if ( one ) + return value; + + // Multi-Selects return an array + values.push( value ); + } + } + + return values; + } + + // Everything else, we just grab the value + return (elem.value || "").replace(/\r/g, ""); + + } + + return undefined; + } + + if ( typeof value === "number" ) + value += ''; + + return this.each(function(){ + if ( this.nodeType != 1 ) + return; + + if ( jQuery.isArray(value) && /radio|checkbox/.test( this.type ) ) + this.checked = (jQuery.inArray(this.value, value) >= 0 || + jQuery.inArray(this.name, value) >= 0); + + else if ( jQuery.nodeName( this, "select" ) ) { + var values = jQuery.makeArray(value); + + jQuery( "option", this ).each(function(){ + this.selected = (jQuery.inArray( this.value, values ) >= 0 || + jQuery.inArray( this.text, values ) >= 0); + }); + + if ( !values.length ) + this.selectedIndex = -1; + + } else + this.value = value; + }); + }, + + html: function( value ) { + /// + /// Set the html contents of every matched element. + /// This property is not available on XML documents. + /// Part of DOM/Attributes + /// + /// + /// + /// Set the html contents to the specified value. + /// + + return value === undefined ? + (this[0] ? + this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g, "") : + null) : + this.empty().append( value ); + }, + + replaceWith: function( value ) { + /// + /// Replaces all matched element with the specified HTML or DOM elements. + /// + /// + /// The content with which to replace the matched elements. + /// + /// The element that was just replaced. + + return this.after( value ).remove(); + }, + + eq: function( i ) { + /// + /// Reduce the set of matched elements to a single element. + /// The position of the element in the set of matched elements + /// starts at 0 and goes to length - 1. + /// Part of Core + /// + /// + /// + /// pos The index of the element that you wish to limit to. + /// + + return this.slice( i, +i + 1 ); + }, + + slice: function() { + /// + /// Selects a subset of the matched elements. Behaves exactly like the built-in Array slice method. + /// + /// Where to start the subset (0-based). + /// Where to end the subset (not including the end element itself). + /// If omitted, ends at the end of the selection + /// The sliced elements + + return this.pushStack( Array.prototype.slice.apply( this, arguments ), + "slice", Array.prototype.slice.call(arguments).join(",") ); + }, + + map: function( callback ) { + /// + /// This member is internal. + /// + /// + /// + + return this.pushStack( jQuery.map(this, function(elem, i){ + return callback.call( elem, i, elem ); + })); + }, + + andSelf: function() { + /// + /// Adds the previous selection to the current selection. + /// + /// + + return this.add( this.prevObject ); + }, + + domManip: function( args, table, callback ) { + /// + /// Args + /// + /// + /// Insert TBODY in TABLEs if one is not found. + /// + /// + /// If dir<0, process args in reverse order. + /// + /// + /// The function doing the DOM manipulation. + /// + /// + /// + /// Part of Core + /// + + if ( this[0] ) { + var fragment = (this[0].ownerDocument || this[0]).createDocumentFragment(), + scripts = jQuery.clean( args, (this[0].ownerDocument || this[0]), fragment ), + first = fragment.firstChild; + + if ( first ) + for ( var i = 0, l = this.length; i < l; i++ ) + callback.call( root(this[i], first), this.length > 1 || i > 0 ? + fragment.cloneNode(true) : fragment ); + + if ( scripts ) + jQuery.each( scripts, evalScript ); + } + + return this; + + function root( elem, cur ) { + return table && jQuery.nodeName(elem, "table") && jQuery.nodeName(cur, "tr") ? + (elem.getElementsByTagName("tbody")[0] || + elem.appendChild(elem.ownerDocument.createElement("tbody"))) : + elem; + } + } +}; + +// Give the init function the jQuery prototype for later instantiation +jQuery.fn.init.prototype = jQuery.fn; + +function evalScript( i, elem ) { + /// + /// This method is internal. + /// + /// + + if ( elem.src ) + jQuery.ajax({ + url: elem.src, + async: false, + dataType: "script" + }); + + else + jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" ); + + if ( elem.parentNode ) + elem.parentNode.removeChild( elem ); +} + +function now(){ + /// + /// Gets the current date. + /// + /// The current date. + return +new Date; +} + +jQuery.extend = jQuery.fn.extend = function() { + /// + /// Extend one object with one or more others, returning the original, + /// modified, object. This is a great utility for simple inheritance. + /// jQuery.extend(settings, options); + /// var settings = jQuery.extend({}, defaults, options); + /// Part of JavaScript + /// + /// + /// The object to extend + /// + /// + /// The object that will be merged into the first. + /// + /// + /// (optional) More objects to merge into the first + /// + /// + + // copy reference to target object + var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !jQuery.isFunction(target) ) + target = {}; + + // extend jQuery itself if only one argument is passed + if ( length == i ) { + target = this; + --i; + } + + for ( ; i < length; i++ ) + // Only deal with non-null/undefined values + if ( (options = arguments[ i ]) != null ) + // Extend the base object + for ( var name in options ) { + var src = target[ name ], copy = options[ name ]; + + // Prevent never-ending loop + if ( target === copy ) + continue; + + // Recurse if we're merging object values + if ( deep && copy && typeof copy === "object" && !copy.nodeType ) + target[ name ] = jQuery.extend( deep, + // Never move original objects, clone them + src || ( copy.length != null ? [ ] : { } ) + , copy ); + + // Don't bring in undefined values + else if ( copy !== undefined ) + target[ name ] = copy; + + } + + // Return the modified object + return target; +}; + +// exclude the following css properties to add px +var exclude = /z-?index|font-?weight|opacity|zoom|line-?height/i, + // cache defaultView + defaultView = document.defaultView || {}, + toString = Object.prototype.toString; + +jQuery.extend({ + noConflict: function( deep ) { + /// + /// Run this function to give control of the $ variable back + /// to whichever library first implemented it. This helps to make + /// sure that jQuery doesn't conflict with the $ object + /// of other libraries. + /// By using this function, you will only be able to access jQuery + /// using the 'jQuery' variable. For example, where you used to do + /// $("div p"), you now must do jQuery("div p"). + /// Part of Core + /// + /// + + window.$ = _$; + + if ( deep ) + window.jQuery = _jQuery; + + return jQuery; + }, + + // See test/unit/core.js for details concerning isFunction. + // Since version 1.3, DOM methods and functions like alert + // aren't supported. They return false on IE (#2968). + isFunction: function( obj ) { + /// + /// Determines if the parameter passed is a function. + /// + /// The object to check + /// True if the parameter is a function; otherwise false. + + return toString.call(obj) === "[object Function]"; + }, + + isArray: function(obj) { + /// + /// Determine if the parameter passed is an array. + /// + /// Object to test whether or not it is an array. + /// True if the parameter is a function; otherwise false. + + return toString.call(obj) === "[object Array]"; + }, + + // check if an element is in a (or is an) XML document + isXMLDoc: function( elem ) { + /// + /// Determines if the parameter passed is an XML document. + /// + /// The object to test + /// True if the parameter is an XML document; otherwise false. + + return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" || + !!elem.ownerDocument && jQuery.isXMLDoc(elem.ownerDocument); + }, + + // Evalulates a script in a global context + globalEval: function( data ) { + /// + /// Internally evaluates a script in a global context. + /// + /// + + if ( data && /\S/.test(data) ) { + // Inspired by code by Andrea Giammarchi + // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html + var head = document.getElementsByTagName("head")[0] || document.documentElement, + script = document.createElement("script"); + + script.type = "text/javascript"; + if ( jQuery.support.scriptEval ) + script.appendChild( document.createTextNode( data ) ); + else + script.text = data; + + // Use insertBefore instead of appendChild to circumvent an IE6 bug. + // This arises when a base node is used (#2709). + head.insertBefore( script, head.firstChild ); + head.removeChild( script ); + } + }, + + nodeName: function( elem, name ) { + /// + /// Checks whether the specified element has the specified DOM node name. + /// + /// The element to examine + /// The node name to check + /// True if the specified node name matches the node's DOM node name; otherwise false + + return elem.nodeName && elem.nodeName.toUpperCase() == name.toUpperCase(); + }, + + // args is for internal usage only + each: function( object, callback, args ) { + /// + /// A generic iterator function, which can be used to seemlessly + /// iterate over both objects and arrays. This function is not the same + /// as $().each() - which is used to iterate, exclusively, over a jQuery + /// object. This function can be used to iterate over anything. + /// The callback has two arguments:the key (objects) or index (arrays) as first + /// the first, and the value as the second. + /// Part of JavaScript + /// + /// + /// The object, or array, to iterate over. + /// + /// + /// The function that will be executed on every object. + /// + /// + + var name, i = 0, length = object.length; + + if ( args ) { + if ( length === undefined ) { + for ( name in object ) + if ( callback.apply( object[ name ], args ) === false ) + break; + } else + for ( ; i < length; ) + if ( callback.apply( object[ i++ ], args ) === false ) + break; + + // A special, fast, case for the most common use of each + } else { + if ( length === undefined ) { + for ( name in object ) + if ( callback.call( object[ name ], name, object[ name ] ) === false ) + break; + } else + for ( var value = object[0]; + i < length && callback.call( value, i, value ) !== false; value = object[++i] ){} + } + + return object; + }, + + prop: function( elem, value, type, i, name ) { + /// + /// This method is internal. + /// + /// + // This member is not documented within the jQuery API: http://docs.jquery.com/action/edit/Internals/jQuery.prop + + // Handle executable functions + if ( jQuery.isFunction( value ) ) + value = value.call( elem, i ); + + // Handle passing in a number to a CSS property + return typeof value === "number" && type == "curCSS" && !exclude.test( name ) ? + value + "px" : + value; + }, + + className: { + // internal only, use addClass("class") + add: function( elem, classNames ) { + /// + /// Internal use only; use addClass('class') + /// + /// + + jQuery.each((classNames || "").split(/\s+/), function(i, className){ + if ( elem.nodeType == 1 && !jQuery.className.has( elem.className, className ) ) + elem.className += (elem.className ? " " : "") + className; + }); + }, + + // internal only, use removeClass("class") + remove: function( elem, classNames ) { + /// + /// Internal use only; use removeClass('class') + /// + /// + + if (elem.nodeType == 1) + elem.className = classNames !== undefined ? + jQuery.grep(elem.className.split(/\s+/), function(className){ + return !jQuery.className.has( classNames, className ); + }).join(" ") : + ""; + }, + + // internal only, use hasClass("class") + has: function( elem, className ) { + /// + /// Internal use only; use hasClass('class') + /// + /// + + return elem && jQuery.inArray(className, (elem.className || elem).toString().split(/\s+/)) > -1; + } + }, + + // A method for quickly swapping in/out CSS properties to get correct calculations + swap: function( elem, options, callback ) { + /// + /// Swap in/out style options. + /// + + var old = {}; + // Remember the old values, and insert the new ones + for ( var name in options ) { + old[ name ] = elem.style[ name ]; + elem.style[ name ] = options[ name ]; + } + + callback.call( elem ); + + // Revert the old values + for ( var name in options ) + elem.style[ name ] = old[ name ]; + }, + + css: function( elem, name, force, extra ) { + /// + /// This method is internal only. + /// + /// + // This method is undocumented in jQuery API: http://docs.jquery.com/action/edit/Internals/jQuery.css + + if ( name == "width" || name == "height" ) { + var val, props = { position: "absolute", visibility: "hidden", display:"block" }, which = name == "width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ]; + + function getWH() { + val = name == "width" ? elem.offsetWidth : elem.offsetHeight; + + if ( extra === "border" ) + return; + + jQuery.each( which, function() { + if ( !extra ) + val -= parseFloat(jQuery.curCSS( elem, "padding" + this, true)) || 0; + if ( extra === "margin" ) + val += parseFloat(jQuery.curCSS( elem, "margin" + this, true)) || 0; + else + val -= parseFloat(jQuery.curCSS( elem, "border" + this + "Width", true)) || 0; + }); + } + + if ( elem.offsetWidth !== 0 ) + getWH(); + else + jQuery.swap( elem, props, getWH ); + + return Math.max(0, Math.round(val)); + } + + return jQuery.curCSS( elem, name, force ); + }, + + curCSS: function( elem, name, force ) { + /// + /// This method is internal only. + /// + /// + // This method is undocumented in jQuery API: http://docs.jquery.com/action/edit/Internals/jQuery.curCSS + + var ret, style = elem.style; + + // We need to handle opacity special in IE + if ( name == "opacity" && !jQuery.support.opacity ) { + ret = jQuery.attr( style, "opacity" ); + + return ret == "" ? + "1" : + ret; + } + + // Make sure we're using the right name for getting the float value + if ( name.match( /float/i ) ) + name = styleFloat; + + if ( !force && style && style[ name ] ) + ret = style[ name ]; + + else if ( defaultView.getComputedStyle ) { + + // Only "float" is needed here + if ( name.match( /float/i ) ) + name = "float"; + + name = name.replace( /([A-Z])/g, "-$1" ).toLowerCase(); + + var computedStyle = defaultView.getComputedStyle( elem, null ); + + if ( computedStyle ) + ret = computedStyle.getPropertyValue( name ); + + // We should always get a number back from opacity + if ( name == "opacity" && ret == "" ) + ret = "1"; + + } else if ( elem.currentStyle ) { + var camelCase = name.replace(/\-(\w)/g, function(all, letter){ + return letter.toUpperCase(); + }); + + ret = elem.currentStyle[ name ] || elem.currentStyle[ camelCase ]; + + // From the awesome hack by Dean Edwards + // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 + + // If we're not dealing with a regular pixel number + // but a number that has a weird ending, we need to convert it to pixels + if ( !/^\d+(px)?$/i.test( ret ) && /^\d/.test( ret ) ) { + // Remember the original values + var left = style.left, rsLeft = elem.runtimeStyle.left; + + // Put in the new values to get a computed value out + elem.runtimeStyle.left = elem.currentStyle.left; + style.left = ret || 0; + ret = style.pixelLeft + "px"; + + // Revert the changed values + style.left = left; + elem.runtimeStyle.left = rsLeft; + } + } + + return ret; + }, + + clean: function( elems, context, fragment ) { + /// + /// This method is internal only. + /// + /// + // This method is undocumented in the jQuery API: http://docs.jquery.com/action/edit/Internals/jQuery.clean + + + context = context || document; + + // !context.createElement fails in IE with an error but returns typeof 'object' + if ( typeof context.createElement === "undefined" ) + context = context.ownerDocument || context[0] && context[0].ownerDocument || document; + + // If a single string is passed in and it's a single tag + // just do a createElement and skip the rest + if ( !fragment && elems.length === 1 && typeof elems[0] === "string" ) { + var match = /^<(\w+)\s*\/?>$/.exec(elems[0]); + if ( match ) + return [ context.createElement( match[1] ) ]; + } + + var ret = [], scripts = [], div = context.createElement("div"); + + jQuery.each(elems, function(i, elem){ + if ( typeof elem === "number" ) + elem += ''; + + if ( !elem ) + return; + + // Convert html string into DOM nodes + if ( typeof elem === "string" ) { + // Fix "XHTML"-style tags in all browsers + elem = elem.replace(/(<(\w+)[^>]*?)\/>/g, function(all, front, tag){ + return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i) ? + all : + front + ">"; + }); + + // Trim whitespace, otherwise indexOf won't work as expected + var tags = elem.replace(/^\s+/, "").substring(0, 10).toLowerCase(); + + var wrap = + // option or optgroup + !tags.indexOf("", "" ] || + + !tags.indexOf("", "" ] || + + tags.match(/^<(thead|tbody|tfoot|colg|cap)/) && + [ 1, "", "
" ] || + + !tags.indexOf("", "" ] || + + // matched above + (!tags.indexOf("", "" ] || + + !tags.indexOf("", "" ] || + + // IE can't serialize and + + + + + diff --git a/ShowOff/Views/Web.config b/ShowOff/Views/Web.config new file mode 100644 index 0000000..e7c3846 --- /dev/null +++ b/ShowOff/Views/Web.config @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ShowOff/Web.config b/ShowOff/Web.config new file mode 100644 index 0000000..4754b6f --- /dev/null +++ b/ShowOff/Web.config @@ -0,0 +1,173 @@ + + + + + + +
+ +
+
+
+
+ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/lib/moq/Moq.chm b/lib/moq/Moq.chm new file mode 100644 index 0000000..69560a1 Binary files /dev/null and b/lib/moq/Moq.chm differ diff --git a/lib/moq/Moq.dll b/lib/moq/Moq.dll new file mode 100644 index 0000000..7cab162 Binary files /dev/null and b/lib/moq/Moq.dll differ diff --git a/lib/moq/Moq.pdb b/lib/moq/Moq.pdb new file mode 100644 index 0000000..3964e06 Binary files /dev/null and b/lib/moq/Moq.pdb differ diff --git a/lib/moq/Moq.xml b/lib/moq/Moq.xml new file mode 100644 index 0000000..54caa92 --- /dev/null +++ b/lib/moq/Moq.xml @@ -0,0 +1,3467 @@ + + + + Moq + + + + + A that returns an empty default value + for invocations that do not have setups or return values, with loose mocks. + This is the default behavior for a mock. + + + + + Interface to be implemented by classes that determine the + default value of non-expected invocations. + + + + + Provides a value for the given member and arguments. + + The member to provide a default + value for. + Optional arguments passed in + to the call that requires a default value. + + + + Implements the fluent API. + + + + + Defines the Callback verb and overloads. + + + + + Helper interface used to hide the base + members from the fluent API to make it much cleaner + in Visual Studio intellisense. + + + + + + + + + + + + + + + + + Specifies a callback to invoke when the method is called. + + Callback method to invoke. + + The following example specifies a callback to set a boolean + value that can be used later: + + bool called = false; + mock.Setup(x => x.Execute()) + .Callback(() => called = true); + + + + + + Specifies a callback to invoke when the method is called that receives the original + arguments. + + Argument type of the invoked method. + Callback method to invoke. + + Invokes the given callback with the concrete invocation argument value. + + Notice how the specific string argument is retrieved by simply declaring + it as part of the lambda expression for the callback: + + + mock.Setup(x => x.Execute(It.IsAny<string>())) + .Callback((string command) => Console.WriteLine(command)); + + + + + + Specifies a callback to invoke when the method is called that receives the original + arguments. + + Type of the first argument of the invoked method. + Type of the second argument of the invoked method. + Callback method to invoke. + + Invokes the given callback with the concrete invocation arguments values. + + Notice how the specific arguments are retrieved by simply declaring + them as part of the lambda expression for the callback: + + + mock.Setup(x => x.Execute( + It.IsAny<string>(), + It.IsAny<string>())) + .Callback((string arg1, string arg2) => Console.WriteLine(arg1 + arg2)); + + + + + + Specifies a callback to invoke when the method is called that receives the original + arguments. + + Type of the first argument of the invoked method. + Type of the second argument of the invoked method. + Type of the third argument of the invoked method. + Callback method to invoke. + + Invokes the given callback with the concrete invocation arguments values. + + Notice how the specific arguments are retrieved by simply declaring + them as part of the lambda expression for the callback: + + + mock.Setup(x => x.Execute( + It.IsAny<string>(), + It.IsAny<string>(), + It.IsAny<int>())) + .Callback((string arg1, string arg2, int arg3) => Console.WriteLine(arg1 + arg2 + arg3)); + + + + + + Specifies a callback to invoke when the method is called that receives the original + arguments. + + Type of the first argument of the invoked method. + Type of the second argument of the invoked method. + Type of the third argument of the invoked method. + Type of the fourth argument of the invoked method. + Callback method to invoke. + + Invokes the given callback with the concrete invocation arguments values. + + Notice how the specific arguments are retrieved by simply declaring + them as part of the lambda expression for the callback: + + + mock.Setup(x => x.Execute( + It.IsAny<string>(), + It.IsAny<string>(), + It.IsAny<int>(), + It.IsAny<bool>())) + .Callback((string arg1, string arg2, int arg3, bool arg4) => Console.WriteLine(arg1 + arg2 + arg3 + arg4)); + + + + + + Defines occurrence members to constraint setups. + + + + + The expected invocation can happen at most once. + + + + var mock = new Mock<ICommand>(); + mock.Setup(foo => foo.Execute("ping")) + .AtMostOnce(); + + + + + + The expected invocation can happen at most specified number of times. + + The number of times to accept calls. + + + var mock = new Mock<ICommand>(); + mock.Setup(foo => foo.Execute("ping")) + .AtMost( 5 ); + + + + + + Defines the Raises verb. + + + + + Specifies the event that will be raised + when the setup is met. + + An expression that represents an event attach or detach action. + The event arguments to pass for the raised event. + + The following example shows how to raise an event when + the setup is met: + + var mock = new Mock<IContainer>(); + + mock.Setup(add => add.Add(It.IsAny<string>(), It.IsAny<object>())) + .Raises(add => add.Added += null, EventArgs.Empty); + + + + + + Specifies the event that will be raised + when the setup is matched. + + An expression that represents an event attach or detach action. + A function that will build the + to pass when raising the event. + + + + + Specifies the event that will be raised + when the setup is matched. + + An expression that represents an event attach or detach action. + A function that will build the + to pass when raising the event. + Type of the argument received by the expected invocation. + + + + + Specifies the event that will be raised + when the setup is matched. + + An expression that represents an event attach or detach action. + A function that will build the + to pass when raising the event. + Type of the first argument received by the expected invocation. + Type of the second argument received by the expected invocation. + + + + + Specifies the event that will be raised + when the setup is matched. + + An expression that represents an event attach or detach action. + A function that will build the + to pass when raising the event. + Type of the first argument received by the expected invocation. + Type of the second argument received by the expected invocation. + Type of the third argument received by the expected invocation. + + + + + Specifies the event that will be raised + when the setup is matched. + + An expression that represents an event attach or detach action. + A function that will build the + to pass when raising the event. + Type of the first argument received by the expected invocation. + Type of the second argument received by the expected invocation. + Type of the third argument received by the expected invocation. + Type of the fourth argument received by the expected invocation. + + + + + Specifies the custom event that will be raised + when the setup is matched. + + An expression that represents an event attach or detach action. + The arguments to pass to the custom delegate (non EventHandler-compatible). + + + + Defines the Raises verb. + + + + + Specifies the mocked event that will be raised + when the setup is met. + + The mocked event, retrieved from + or . + + The event args to pass when raising the event. + + The following example shows how to raise an event when + the setup is met: + + var mock = new Mock<IContainer>(); + // create handler to associate with the event to raise + var handler = mock.CreateEventHandler(); + // associate the handler with the event to raise + mock.Object.Added += handler; + // setup the invocation and the handler to raise + mock.Setup(add => add.Add(It.IsAny<string>(), It.IsAny<object>())) + .Raises(handler, EventArgs.Empty); + + + + + + Specifies the mocked event that will be raised + when the setup is matched. + + The mocked event, retrieved from + or . + + A function that will build the + to pass when raising the event. + + + + + Specifies the mocked event that will be raised + when the setup is matched. + + The mocked event, retrieved from + or . + + A function that will build the + to pass when raising the event. + Type of the argument received by the expected invocation. + + + + + Specifies the mocked event that will be raised + when the setup is matched. + + The mocked event, retrieved from + or . + + A function that will build the + to pass when raising the event. + Type of the first argument received by the expected invocation. + Type of the second argument received by the expected invocation. + + + + + Specifies the mocked event that will be raised + when the setup is matched. + + The mocked event, retrieved from + or . + + A function that will build the + to pass when raising the event. + Type of the first argument received by the expected invocation. + Type of the second argument received by the expected invocation. + Type of the third argument received by the expected invocation. + + + + + Specifies the mocked event that will be raised + when the setup is matched. + + The mocked event, retrieved from + or . + + A function that will build the + to pass when raising the event. + Type of the first argument received by the expected invocation. + Type of the second argument received by the expected invocation. + Type of the third argument received by the expected invocation. + Type of the fourth argument received by the expected invocation. + + + + + Defines the Verifiable verb. + + + + + Marks the expectation as verifiable, meaning that a call + to will check if this particular + expectation was met. + + + The following example marks the expectation as verifiable: + + mock.Expect(x => x.Execute("ping")) + .Returns(true) + .Verifiable(); + + + + + + Marks the expectation as verifiable, meaning that a call + to will check if this particular + expectation was met, and specifies a message for failures. + + + The following example marks the expectation as verifiable: + + mock.Expect(x => x.Execute("ping")) + .Returns(true) + .Verifiable("Ping should be executed always!"); + + + + + + Marks a method as a matcher, which allows complete replacement + of the built-in class with your own argument + matching rules. + + + This feature has been deprecated in favor of the new + and simpler . + + + The argument matching is used to determine whether a concrete + invocation in the mock matches a given setup. This + matching mechanism is fully extensible. + + + There are two parts of a matcher: the compiler matcher + and the runtime matcher. + + + Compiler matcher + Used to satisfy the compiler requirements for the + argument. Needs to be a method optionally receiving any arguments + you might need for the matching, but with a return type that + matches that of the argument. + + Let's say I want to match a lists of orders that contains + a particular one. I might create a compiler matcher like the following: + + + public static class Orders + { + [Matcher] + public static IEnumerable<Order> Contains(Order order) + { + return null; + } + } + + Now we can invoke this static method instead of an argument in an + invocation: + + var order = new Order { ... }; + var mock = new Mock<IRepository<Order>>(); + + mock.Setup(x => x.Save(Orders.Contains(order))) + .Throws<ArgumentException>(); + + Note that the return value from the compiler matcher is irrelevant. + This method will never be called, and is just used to satisfy the + compiler and to signal Moq that this is not a method that we want + to be invoked at runtime. + + + + Runtime matcher + + The runtime matcher is the one that will actually perform evaluation + when the test is run, and is defined by convention to have the + same signature as the compiler matcher, but where the return + value is the first argument to the call, which contains the + object received by the actual invocation at runtime: + + public static bool Contains(IEnumerable<Order> orders, Order order) + { + return orders.Contains(order); + } + + At runtime, the mocked method will be invoked with a specific + list of orders. This value will be passed to this runtime + matcher as the first argument, while the second argument is the + one specified in the setup (x.Save(Orders.Contains(order))). + + The boolean returned determines whether the given argument has been + matched. If all arguments to the expected method are matched, then + the setup matches and is evaluated. + + + + + + Using this extensible infrastructure, you can easily replace the entire + set of matchers with your own. You can also avoid the + typical (and annoying) lengthy expressions that result when you have + multiple arguments that use generics. + + + The following is the complete example explained above: + + public static class Orders + { + [Matcher] + public static IEnumerable<Order> Contains(Order order) + { + return null; + } + + public static bool Contains(IEnumerable<Order> orders, Order order) + { + return orders.Contains(order); + } + } + + And the concrete test using this matcher: + + var order = new Order { ... }; + var mock = new Mock<IRepository<Order>>(); + + mock.Setup(x => x.Save(Orders.Contains(order))) + .Throws<ArgumentException>(); + + // use mock, invoke Save, and have the matcher filter. + + + + + + Casts the expression to a lambda expression, removing + a cast if there's any. + + + + + Casts the body of the lambda expression to a . + + If the body is not a method call. + + + + Converts the body of the lambda expression into the referenced by it. + + + + + Checks whether the body of the lambda expression is a property access. + + + + + Checks whether the expression is a property access. + + + + + Checks whether the body of the lambda expression is a property indexer, which is true + when the expression is an whose + has + equal to . + + + + + Checks whether the expression is a property indexer, which is true + when the expression is an whose + has + equal to . + + + + + Creates an expression that casts the given expression to the + type. + + + + + TODO: remove this code when https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=331583 + is fixed. + + + + + Base class for visitors of expression trees. + + + Provides the functionality of the internal visitor base class that + comes with Linq. + Matt's comments on the implementation: + + In this variant there is only one visitor class that dispatches calls to the general + Visit function out to specific VisitXXX methods corresponding to different node types. + Note not every node type gets it own method, for example all binary operators are + treated in one VisitBinary method. The nodes themselves do not directly participate + in the visitation process. They are treated as just data. + The reason for this is that the quantity of visitors is actually open ended. + You can write your own. Therefore no semantics of visiting is coupled into the node classes. + It’s all in the visitors. The default visit behavior for node XXX is baked into the base + class’s version of VisitXXX. + + + Another variant is that all VisitXXX methods return a node. + The Expression tree nodes are immutable. In order to change the tree you must construct + a new one. The default VisitXXX methods will construct a new node if any of its sub-trees change. + If no changes are made then the same node is returned. That way if you make a change + to a node (by making a new node) deep down in a tree, the rest of the tree is rebuilt + automatically for you. + + See: http://blogs.msdn.com/mattwar/archive/2007/07/31/linq-building-an-iqueryable-provider-part-ii.aspx. + + Matt Warren: http://blogs.msdn.com/mattwar + Documented by InSTEDD: http://www.instedd.org + + + + Default constructor used by derived visitors. + + + + + Visits the , determining which + of the concrete Visit methods to call. + + + + + Visits the generic , determining and + calling the appropriate Visit method according to the + , which will result + in calls to , + or . + + + + + + + Visits the initializer by + calling the for the + . + + + + + Visits the expression by + calling with the expression. + + + + + Visits the by calling + with the , + and + expressions. + + + + + Visits the by calling + with the + expression. + + + + + Visits the , by default returning the + same without further behavior. + + + + + Visits the by calling + with the , + and + expressions. + + + + + Visits the returning it + by default without further behavior. + + + + + Visits the by calling + with the + expression. + + + + + Visits the by calling + with the expression, + and then with the . + + + + + + + Visits the by iterating + the list and visiting each in it. + + + + + + + Visits the by calling + with the expression. + + + + + + + Visits the by calling + with the . + + + + + + + Visits the by calling + with the + . + + + + + + + Visits the by + calling for each in the + collection. + + + + + + + Visits the by + calling for each + in the collection. + + + + + + + Visits the by calling + with the expression. + + + + + + + Visits the by calling + with the + expressions. + + + + + + + Visits the by calling + with the + expression, then with the + . + + + + + Visits the by calling + with the + expression, and then with the + . + + + + + + + Visits the by calling + with the + expressions. + + + + + + + Visits the by calling + with the + expressions. + + + + + + + Provides partial evaluation of subtrees, whenever they can be evaluated locally. + + Matt Warren: http://blogs.msdn.com/mattwar + Documented by InSTEDD: http://www.instedd.org + + + + Performs evaluation and replacement of independent sub-trees + + The root of the expression tree. + A function that decides whether a given expression + node can be part of the local function. + A new tree with sub-trees evaluated and replaced. + + + + Performs evaluation and replacement of independent sub-trees + + The root of the expression tree. + A new tree with sub-trees evaluated and replaced. + + + + Evaluates and replaces sub-trees when first candidate is reached (top-down) + + + + + Performs bottom-up analysis to determine which nodes can possibly + be part of an evaluated sub-tree. + + + + + Checks an argument to ensure it isn't null. + + The argument value to check. + The name of the argument. + + + + Checks a string argument to ensure it isn't null or empty. + + The argument value to check. + The name of the argument. + + + + Checks an argument to ensure it is in the specified range including the edges. + + Type of the argument to check, it must be an type. + + The argument value to check. + The minimun allowed value for the argument. + The maximun allowed value for the argument. + The name of the argument. + + + + Checks an argument to ensure it is in the specified range excluding the edges. + + Type of the argument to check, it must be an type. + + The argument value to check. + The minimun allowed value for the argument. + The maximun allowed value for the argument. + The name of the argument. + + + + Defines the Returns verb for property get setups. + + Mocked type. + Type of the property. + + + + Specifies the value to return. + + The value to return, or . + + Return a true value from the property getter call: + + mock.SetupGet(x => x.Suspended) + .Returns(true); + + + + + + Specifies a function that will calculate the value to return for the property. + + The function that will calculate the return value. + + Return a calculated value when the property is retrieved: + + mock.SetupGet(x => x.Suspended) + .Returns(() => returnValues[0]); + + The lambda expression to retrieve the return value is lazy-executed, + meaning that its value may change depending on the moment the property + is retrieved and the value the returnValues array has at + that moment. + + + + + Defines the Callback verb for property getter setups. + + + Mocked type. + Type of the property. + + + + Specifies a callback to invoke when the property is retrieved. + + Callback method to invoke. + + Invokes the given callback with the property value being set. + + mock.SetupGet(x => x.Suspended) + .Callback(() => called = true) + .Returns(true); + + + + + + Implements the fluent API. + + + + + Implements the fluent API. + + + + + Defines the Returns verb. + + Mocked type. + Type of the return value from the expression. + + + + Specifies the value to return. + + The value to return, or . + + Return a true value from the method call: + + mock.Setup(x => x.Execute("ping")) + .Returns(true); + + + + + + Specifies a function that will calculate the value to return from the method. + + The function that will calculate the return value. + + Return a calculated value when the method is called: + + mock.Setup(x => x.Execute("ping")) + .Returns(() => returnValues[0]); + + The lambda expression to retrieve the return value is lazy-executed, + meaning that its value may change depending on the moment the method + is executed and the value the returnValues array has at + that moment. + + + + + Specifies a function that will calculate the value to return from the method, + retrieving the arguments for the invocation. + + Type of the argument of the invoked method. + The function that will calculate the return value. + + Return a calculated value which is evaluated lazily at the time of the invocation. + + The lookup list can change between invocations and the setup + will return different values accordingly. Also, notice how the specific + string argument is retrieved by simply declaring it as part of the lambda + expression: + + + mock.Setup(x => x.Execute(It.IsAny<string>())) + .Returns((string command) => returnValues[command]); + + + + + + Specifies a function that will calculate the value to return from the method, + retrieving the arguments for the invocation. + + Type of the first argument of the invoked method. + Type of the second argument of the invoked method. + The function that will calculate the return value. + + Return a calculated value which is evaluated lazily at the time of the invocation. + + The return value is calculated from the value of the actual method invocation arguments. + Notice how the arguments are retrieved by simply declaring them as part of the lambda + expression: + + + mock.Setup(x => x.Execute( + It.IsAny<string>(), + It.IsAny<string>())) + .Returns((string arg1, string arg2) => arg1 + arg2); + + + + + + Specifies a function that will calculate the value to return from the method, + retrieving the arguments for the invocation. + + Type of the first argument of the invoked method. + Type of the second argument of the invoked method. + Type of the third argument of the invoked method. + The function that will calculate the return value. + + Return a calculated value which is evaluated lazily at the time of the invocation. + + The return value is calculated from the value of the actual method invocation arguments. + Notice how the arguments are retrieved by simply declaring them as part of the lambda + expression: + + + mock.Setup(x => x.Execute( + It.IsAny<string>(), + It.IsAny<string>(), + It.IsAny<int>())) + .Returns((string arg1, string arg2, int arg3) => arg1 + arg2 + arg3); + + + + + + Specifies a function that will calculate the value to return from the method, + retrieving the arguments for the invocation. + + Type of the first argument of the invoked method. + Type of the second argument of the invoked method. + Type of the third argument of the invoked method. + Type of the fourth argument of the invoked method. + The function that will calculate the return value. + + Return a calculated value which is evaluated lazily at the time of the invocation. + + The return value is calculated from the value of the actual method invocation arguments. + Notice how the arguments are retrieved by simply declaring them as part of the lambda + expression: + + + mock.Setup(x => x.Execute( + It.IsAny<string>(), + It.IsAny<string>(), + It.IsAny<int>(), + It.IsAny<bool>())) + .Returns((string arg1, string arg2, int arg3, bool arg4) => arg1 + arg2 + arg3 + arg4); + + + + + + Defines the Throws verb. + + + + + Specifies the exception to throw when the method is invoked. + + Exception instance to throw. + + This example shows how to throw an exception when the method is + invoked with an empty string argument: + + mock.Setup(x => x.Execute("")) + .Throws(new ArgumentException()); + + + + + + Specifies the type of exception to throw when the method is invoked. + + Type of exception to instantiate and throw when the setup is matched. + + This example shows how to throw an exception when the method is + invoked with an empty string argument: + + mock.Setup(x => x.Execute("")) + .Throws<ArgumentException>(); + + + + + + Implements the fluent API. + + + + + Implements the fluent API. + + + + + Defines the Callback verb and overloads for callbacks on + setups that return a value. + + Mocked type. + Type of the return value of the setup. + + + + Specifies a callback to invoke when the method is called. + + Callback method to invoke. + + The following example specifies a callback to set a boolean + value that can be used later: + + bool called = false; + mock.Setup(x => x.Execute()) + .Callback(() => called = true) + .Returns(true); + + Note that in the case of value-returning methods, after the Callback + call you can still specify the return value. + + + + + Specifies a callback to invoke when the method is called that receives the original + arguments. + + Type of the argument of the invoked method. + Callback method to invoke. + + Invokes the given callback with the concrete invocation argument value. + + Notice how the specific string argument is retrieved by simply declaring + it as part of the lambda expression for the callback: + + + mock.Setup(x => x.Execute(It.IsAny<string>())) + .Callback((string command) => Console.WriteLine(command)) + .Returns(true); + + + + + + Specifies a callback to invoke when the method is called that receives the original + arguments. + + Type of the first argument of the invoked method. + Type of the second argument of the invoked method. + Callback method to invoke. + + Invokes the given callback with the concrete invocation arguments values. + + Notice how the specific arguments are retrieved by simply declaring + them as part of the lambda expression for the callback: + + + mock.Setup(x => x.Execute( + It.IsAny<string>(), + It.IsAny<string>())) + .Callback((string arg1, string arg2) => Console.WriteLine(arg1 + arg2)) + .Returns(true); + + + + + + Specifies a callback to invoke when the method is called that receives the original + arguments. + + Type of the first argument of the invoked method. + Type of the second argument of the invoked method. + Type of the third argument of the invoked method. + Callback method to invoke. + + Invokes the given callback with the concrete invocation arguments values. + + Notice how the specific arguments are retrieved by simply declaring + them as part of the lambda expression for the callback: + + + mock.Setup(x => x.Execute( + It.IsAny<string>(), + It.IsAny<string>(), + It.IsAny<int>())) + .Callback((string arg1, string arg2, int arg3) => Console.WriteLine(arg1 + arg2 + arg3)) + .Returns(true); + + + + + + Specifies a callback to invoke when the method is called that receives the original + arguments. + + Type of the first argument of the invoked method. + Type of the second argument of the invoked method. + Type of the third argument of the invoked method. + Type of the fourth argument of the invoked method. + Callback method to invoke. + + Invokes the given callback with the concrete invocation arguments values. + + Notice how the specific arguments are retrieved by simply declaring + them as part of the lambda expression for the callback: + + + mock.Setup(x => x.Execute( + It.IsAny<string>(), + It.IsAny<string>(), + It.IsAny<int>(), + It.IsAny<bool>())) + .Callback((string arg1, string arg2, int arg3, bool arg4) => Console.WriteLine(arg1 + arg2 + arg3 + arg4)) + .Returns(true); + + + + + + Implemented by all generated mock object instances. + + + + + Implemented by all generated mock object instances. + + + + + Reference the Mock that contains this as the mock.Object value. + + + + + Reference the Mock that contains this as the mock.Object value. + + + + + Implements the actual interception and method invocation for + all mocks. + + + + + Get an eventInfo for a given event name. Search type ancestors depth first if necessary. + + Name of the event, with the set_ or get_ prefix already removed + + + + Given a type return all of its ancestors, both types and interfaces. + + The type to find immediate ancestors of + + + + Implements the fluent API. + + + + + Defines the Never verb. + + + + + The expected invocation is never expected to happen. + + + + var mock = new Mock<ICommand>(); + mock.Setup(foo => foo.Execute("ping")) + .Never(); + + + + is always verified inmediately as + the invocations are performed, like strict mocks do + with unexpected invocations. + + + + + Implements the fluent API. + + + + + Implements the fluent API. + + + + + Implements the fluent API. + + + + + Defines the Callback verb for property setter setups. + + Type of the property. + + + + Specifies a callback to invoke when the property is set that receives the + property value being set. + + Callback method to invoke. + + Invokes the given callback with the property value being set. + + mock.SetupSet(x => x.Suspended) + .Callback((bool state) => Console.WriteLine(state)); + + + + + + Allows the specification of a matching condition for an + argument in a method invocation, rather than a specific + argument value. "It" refers to the argument being matched. + + This class allows the setup to match a method invocation + with an arbitrary value, with a value in a specified range, or + even one that matches a given predicate. + + + + + Matches any value of the given type. + + Typically used when the actual argument value for a method + call is not relevant. + + + // Throws an exception for a call to Remove with any string value. + mock.Setup(x => x.Remove(It.IsAny<string>())).Throws(new InvalidOperationException()); + + Type of the value. + + + + Matches any value that satisfies the given predicate. + Type of the argument to check.The predicate used to match the method argument. + Allows the specification of a predicate to perform matching + of method call arguments. + + This example shows how to return the value 1 whenever the argument to the + Do method is an even number. + + mock.Setup(x => x.Do(It.Is<int>(i => i % 2 == 0))) + .Returns(1); + + This example shows how to throw an exception if the argument to the + method is a negative number: + + mock.Setup(x => x.GetUser(It.Is<int>(i => i < 0))) + .Throws(new ArgumentException()); + + + + + + Matches any value that is in the range specified. + Type of the argument to check.The lower bound of the range.The upper bound of the range. + The kind of range. See . + + The following example shows how to expect a method call + with an integer argument within the 0..100 range. + + mock.Setup(x => x.HasInventory( + It.IsAny<string>(), + It.IsInRange(0, 100, Range.Inclusive))) + .Returns(false); + + + + + + Matches a string argument if it matches the given regular expression pattern. + The pattern to use to match the string argument value. + The following example shows how to expect a call to a method where the + string argument matches the given regular expression: + + mock.Setup(x => x.Check(It.IsRegex("[a-z]+"))).Returns(1); + + + + + + Matches a string argument if it matches the given regular expression pattern. + The pattern to use to match the string argument value.The options used to interpret the pattern. + The following example shows how to expect a call to a method where the + string argument matches the given regular expression, in a case insensitive way: + + mock.Setup(x => x.Check(It.IsRegex("[a-z]+", RegexOptions.IgnoreCase))).Returns(1); + + + + + + Matcher to treat static functions as matchers. + + mock.Setup(x => x.StringMethod(A.MagicString())); + + pbulic static class A + { + [Matcher] + public static string MagicString() { return null; } + public static bool MagicString(string arg) + { + return arg == "magic"; + } + } + + Will success if: mock.Object.StringMethod("magic"); + and fail with any other call. + + + + + We need this non-generics base class so that + we can use from + generic code. + + + + + Base class for mocks and static helper class with methods that + apply to mocked objects, such as to + retrieve a from an object instance. + + + + + Retrieves the mock object for the given object instance. + + Type of the mock to retrieve. Can be omitted as it's inferred + from the object instance passed in as the instance. + The instance of the mocked object.The mock associated with the mocked object. + The received instance + was not created by Moq. + + The following example shows how to add a new setup to an object + instance which is not the original but rather + the object associated with it: + + // Typed instance, not the mock, is retrieved from some test API. + HttpContextBase context = GetMockContext(); + + // context.Request is the typed object from the "real" API + // so in order to add a setup to it, we need to get + // the mock that "owns" it + Mock<HttpRequestBase> request = Mock.Get(context.Request); + mock.Setup(req => req.AppRelativeCurrentExecutionFilePath) + .Returns(tempUrl); + + + + + + Returns the mocked object value. + + + + + Verifies that all verifiable expectations have been met. + + This example sets up an expectation and marks it as verifiable. After + the mock is used, a Verify() call is issued on the mock + to ensure the method in the setup was invoked: + + var mock = new Mock<IWarehouse>(); + this.Setup(x => x.HasInventory(TALISKER, 50)).Verifiable().Returns(true); + ... + // other test code + ... + // Will throw if the test code has didn't call HasInventory. + this.Verify(); + + Not all verifiable expectations were met. + + + + Verifies all expectations regardless of whether they have + been flagged as verifiable. + + This example sets up an expectation without marking it as verifiable. After + the mock is used, a call is issued on the mock + to ensure that all expectations are met: + + var mock = new Mock<IWarehouse>(); + this.Setup(x => x.HasInventory(TALISKER, 50)).Returns(true); + ... + // other test code + ... + // Will throw if the test code has didn't call HasInventory, even + // that expectation was not marked as verifiable. + this.VerifyAll(); + + At least one expectation was not met. + + + + Gets the interceptor target for the given expression and root mock, + building the intermediate hierarchy of mock objects if necessary. + + + + + Creates a handler that can be associated to an event receiving + the given and can be used + to raise the event. + + Type of + data passed in to the event. + + This example shows how to invoke an event with a custom event arguments + class in a view that will cause its corresponding presenter to + react by changing its state: + + var mockView = new Mock<IOrdersView>(); + var mockedEvent = mockView.CreateEventHandler<OrderEventArgs>(); + + var presenter = new OrdersPresenter(mockView.Object); + + // Check that the presenter has no selection by default + Assert.Null(presenter.SelectedOrder); + + // Create a mock event handler of the appropriate type + var handler = mockView.CreateEventHandler<OrderEventArgs>(); + // Associate it with the event we want to raise + mockView.Object.Cancel += handler; + // Finally raise the event with a specific arguments data + handler.Raise(new OrderEventArgs { Order = new Order("moq", 500) }); + + // Now the presenter reacted to the event, and we have a selected order + Assert.NotNull(presenter.SelectedOrder); + Assert.Equal("moq", presenter.SelectedOrder.ProductName); + + + + + + Creates a handler that can be associated to an event receiving + a generic and can be used + to raise the event. + + This example shows how to invoke a generic event in a view that will + cause its corresponding presenter to react by changing its state: + + var mockView = new Mock<IOrdersView>(); + var mockedEvent = mockView.CreateEventHandler(); + + var presenter = new OrdersPresenter(mockView.Object); + + // Check that the presenter is not in the "Canceled" state + Assert.False(presenter.IsCanceled); + + // Create a mock event handler of the appropriate type + var handler = mockView.CreateEventHandler(); + // Associate it with the event we want to raise + mockView.Object.Cancel += handler; + // Finally raise the event + handler.Raise(EventArgs.Empty); + + // Now the presenter reacted to the event, and changed its state + Assert.True(presenter.IsCanceled); + + + + + + Base class for mocks and static helper class with methods that + apply to mocked objects, such as to + retrieve a from an object instance. + + + + + Behavior of the mock, according to the value set in the constructor. + + + + + Whether the base member virtual implementation will be called + for mocked classes if no setup is matched. Defaults to . + + + + + Specifies the behavior to use when returning default values for + unexpected invocations on loose mocks. + + + + + Gets the mocked object instance, which is of the mocked type . + + + + + Retrieves the type of the mocked object, its generic type argument. + This is used in the auto-mocking of hierarchy access. + + + + + Specifies the class that will determine the default + value to return when invocations are made that + have no setups and need to return a default + value (for loose mocks). + + + + + Exposes the list of extra interfaces implemented by the mock. + + + + + Options to customize the behavior of the mock. + + + + + Causes the mock to always throw + an exception for invocations that don't have a + corresponding setup. + + + + + Will never throw exceptions, returning default + values when necessary (null for reference types, + zero for value types or empty enumerables and arrays). + + + + + Default mock behavior, which equals . + + + + + Represents a generic event that has been mocked and can + be rised. + + + + + Provided solely to allow the interceptor to determine when the attached + handler is coming from this mocked event so we can assign the + corresponding EventInfo for it. + + + + + Raises the associated event with the given + event argument data. + + + + + Raises the associated event with the given + event argument data. + + + + + Provides support for attaching a to + a generic event. + + Event to convert. + + + + Event raised whenever the mocked event is rised. + + + + + Exception thrown by mocks when setups are not matched, + the mock is not properly setup, etc. + + + A distinct exception type is provided so that exceptions + thrown by the mock can be differentiated in tests that + expect other exceptions to be thrown (i.e. ArgumentException). + + Richer exception hierarchy/types are not provided as + tests typically should not catch or expect exceptions + from the mocks. These are typically the result of changes + in the tested class or its collaborators implementation, and + result in fixes in the mock setup so that they dissapear and + allow the test to pass. + + + + + + Supports the serialization infrastructure. + + Serialization information. + Streaming context. + + + + Supports the serialization infrastructure. + + Serialization information. + Streaming context. + + + + Made internal as it's of no use for + consumers, but it's important for + our own tests. + + + + + Used by the mock factory to accumulate verification + failures. + + + + + Supports the serialization infrastructure. + + + + + Utility factory class to use to construct multiple + mocks when consistent verification is + desired for all of them. + + + If multiple mocks will be created during a test, passing + the desired (if different than the + or the one + passed to the factory constructor) and later verifying each + mock can become repetitive and tedious. + + This factory class helps in that scenario by providing a + simplified creation of multiple mocks with a default + (unless overriden by calling + ) and posterior verification. + + + + The following is a straightforward example on how to + create and automatically verify strict mocks using a : + + var factory = new MockFactory(MockBehavior.Strict); + + var foo = factory.Create<IFoo>(); + var bar = factory.Create<IBar>(); + + // no need to call Verifiable() on the setup + // as we'll be validating all of them anyway. + foo.Setup(f => f.Do()); + bar.Setup(b => b.Redo()); + + // exercise the mocks here + + factory.VerifyAll(); + // At this point all setups are already checked + // and an optional MockException might be thrown. + // Note also that because the mocks are strict, any invocation + // that doesn't have a matching setup will also throw a MockException. + + The following examples shows how to setup the factory + to create loose mocks and later verify only verifiable setups: + + var factory = new MockFactory(MockBehavior.Loose); + + var foo = factory.Create<IFoo>(); + var bar = factory.Create<IBar>(); + + // this setup will be verified when we verify the factory + foo.Setup(f => f.Do()).Verifiable(); + + // this setup will NOT be verified + foo.Setup(f => f.Calculate()); + + // this setup will be verified when we verify the factory + bar.Setup(b => b.Redo()).Verifiable(); + + // exercise the mocks here + // note that because the mocks are Loose, members + // called in the interfaces for which no matching + // setups exist will NOT throw exceptions, + // and will rather return default values. + + factory.Verify(); + // At this point verifiable setups are already checked + // and an optional MockException might be thrown. + + The following examples shows how to setup the factory with a + default strict behavior, overriding that default for a + specific mock: + + var factory = new MockFactory(MockBehavior.Strict); + + // this particular one we want loose + var foo = factory.Create<IFoo>(MockBehavior.Loose); + var bar = factory.Create<IBar>(); + + // specify setups + + // exercise the mocks here + + factory.Verify(); + + + + + + + Initializes the factory with the given + for newly created mocks from the factory. + + The behavior to use for mocks created + using the factory method if not overriden + by using the overload. + + + + Creates a new mock with the default + specified at factory construction time. + + Type to mock. + A new . + + + var factory = new MockFactory(MockBehavior.Strict); + + var foo = factory.Create<IFoo>(); + // use mock on tests + + factory.VerifyAll(); + + + + + + Creates a new mock with the default + specified at factory construction time and with the + the given constructor arguments for the class. + + + The mock will try to find the best match constructor given the + constructor arguments, and invoke that to initialize the instance. + This applies only to classes, not interfaces. + + Type to mock. + Constructor arguments for mocked classes. + A new . + + + var factory = new MockFactory(MockBehavior.Default); + + var mock = factory.Create<MyBase>("Foo", 25, true); + // use mock on tests + + factory.Verify(); + + + + + + Creates a new mock with the given . + + Type to mock. + Behavior to use for the mock, which overrides + the default behavior specified at factory construction time. + A new . + + The following example shows how to create a mock with a different + behavior to that specified as the default for the factory: + + var factory = new MockFactory(MockBehavior.Strict); + + var foo = factory.Create<IFoo>(MockBehavior.Loose); + + + + + + Creates a new mock with the given + and with the the given constructor arguments for the class. + + + The mock will try to find the best match constructor given the + constructor arguments, and invoke that to initialize the instance. + This applies only to classes, not interfaces. + + Type to mock. + Behavior to use for the mock, which overrides + the default behavior specified at factory construction time. + Constructor arguments for mocked classes. + A new . + + The following example shows how to create a mock with a different + behavior to that specified as the default for the factory, passing + constructor arguments: + + var factory = new MockFactory(MockBehavior.Default); + + var mock = factory.Create<MyBase>(MockBehavior.Strict, "Foo", 25, true); + + + + + + Implements creation of a new mock within the factory. + + Type to mock. + The behavior for the new mock. + Optional arguments for the construction of the mock. + + + + Verifies all verifiable expectations on all mocks created + by this factory. + + + One or more mocks had expectations that were not satisfied. + + + + Verifies all verifiable expectations on all mocks created + by this factory. + + + One or more mocks had expectations that were not satisfied. + + + + Invokes for each mock + in , and accumulates the resulting + that might be + thrown from the action. + + The action to execute against + each mock. + + + + Whether the base member virtual implementation will be called + for mocked classes if no setup is matched. Defaults to . + + + + + Specifies the behavior to use when returning default values for + unexpected invocations on loose mocks. + + + + + Gets the mocks that have been created by this factory and + that will get verified together. + + + + + A strongly-typed resource class, for looking up localized strings, etc. + + + + + Returns the cached ResourceManager instance used by this class. + + + + + Overrides the current thread's CurrentUICulture property for all + resource lookups using this strongly typed resource class. + + + + + Looks up a localized string similar to Mock type has already been initialized by accessing its Object property. Adding interfaces must be done before that.. + + + + + Looks up a localized string similar to Value cannot be an empty string.. + + + + + Looks up a localized string similar to Can only add interfaces to the mock.. + + + + + Looks up a localized string similar to Can't set return value for void method {0}.. + + + + + Looks up a localized string similar to Constructor arguments cannot be passed for interface mocks.. + + + + + Looks up a localized string similar to A matching constructor for the given arguments was not found on the mocked type.. + + + + + Looks up a localized string similar to Expression {0} involves a field access, which is not supported. Use properties instead.. + + + + + Looks up a localized string similar to Type to mock must be an interface or an abstract or non-sealed class. . + + + + + Looks up a localized string similar to Cannot retrieve a mock with the given object type {0} as it's not the main type of the mock or any of its additional interfaces. + Please cast the argument to one of the supported types: {1}. + Remember that there's no generics covariance in the CLR, so your object must be one of these types in order for the call to succeed.. + + + + + Looks up a localized string similar to Member {0}.{1} does not exist.. + + + + + Looks up a localized string similar to Method {0}.{1} is public. Use strong-typed Expect overload instead: + mock.Setup(x => x.{1}()); + . + + + + + Looks up a localized string similar to {0} invocation failed with mock behavior {1}. + {2}. + + + + + Looks up a localized string similar to Expected only {0} calls to {1}.. + + + + + Looks up a localized string similar to Expected only one call to {0}.. + + + + + Looks up a localized string similar to {0} + Invocation was performed on the mock less than {2} times: {1}. + + + + + Looks up a localized string similar to {0} + Invocation was not performed on the mock: {1}. + + + + + Looks up a localized string similar to {0} + Invocation was performed on the mock more than {3} times: {1}. + + + + + Looks up a localized string similar to {0} + Invocation was performed on the mock more than once: {1}. + + + + + Looks up a localized string similar to {0} + Invocation was performed on the mock less or equal than {2} times or more or equal than {3} times: {1}. + + + + + Looks up a localized string similar to {0} + Invocation was performed on the mock less than {2} times or more than {3} times: {1}. + + + + + Looks up a localized string similar to {0} + Invocation was not performed on the mock {2} times: {1}. + + + + + Looks up a localized string similar to {0} + Invocation should not have been performed on the mock: {1}. + + + + + Looks up a localized string similar to {0} + Invocation was performed more than once on the mock: {1}. + + + + + Looks up a localized string similar to All invocations on the mock must have a corresponding setup.. + + + + + Looks up a localized string similar to Object instance was not created by Moq.. + + + + + Looks up a localized string similar to Property {0}.{1} does not exist.. + + + + + Looks up a localized string similar to Property {0}.{1} is write-only.. + + + + + Looks up a localized string similar to Property {0}.{1} is read-only.. + + + + + Looks up a localized string similar to Cannot raise a mocked event unless it has been associated (attached) to a concrete event in a mocked object.. + + + + + Looks up a localized string similar to Invocation needs to return a value and therefore must have a corresponding setup that provides it.. + + + + + Looks up a localized string similar to A lambda expression is expected as the argument to It.Is<T>.. + + + + + Looks up a localized string similar to Invocation {0} should not have been made.. + + + + + Looks up a localized string similar to Expression is not a method invocation: {0}. + + + + + Looks up a localized string similar to Expression is not a property access: {0}. + + + + + Looks up a localized string similar to Expression is not a property setter invocation.. + + + + + Looks up a localized string similar to Invalid setup on a non-overridable member: + {0}. + + + + + Looks up a localized string similar to Type {0} does not implement required interface {1}. + + + + + Looks up a localized string similar to Type {0} does not from required type {1}. + + + + + Looks up a localized string similar to To specify a setup for public property {0}.{1}, use the typed overloads, such as: + mock.Setup(x => x.{1}).Returns(value); + mock.SetupGet(x => x.{1}).Returns(value); //equivalent to previous one + mock.SetupSet(x => x.{1}).Callback(callbackDelegate); + . + + + + + Looks up a localized string similar to Expression {0} is not supported.. + + + + + Looks up a localized string similar to Only property accesses are supported in intermediate invocations on a setup. Unsupported expression {0}.. + + + + + Looks up a localized string similar to Expression contains intermediate property access {0}.{1} which is of type {2} and cannot be mocked. Unsupported expression {3}.. + + + + + Looks up a localized string similar to Setter expression cannot use argument matchers that receive parameters.. + + + + + Looks up a localized string similar to Member {0} is not supported for protected mocking.. + + + + + Looks up a localized string similar to Setter expression can only use static custom matchers.. + + + + + Looks up a localized string similar to To specify a setup for protected property {0}.{1}, use: + mock.Setup<{2}>(x => x.{1}).Returns(value); + mock.SetupGet(x => x.{1}).Returns(value); //equivalent to previous one + mock.SetupSet(x => x.{1}).Callback(callbackDelegate);. + + + + + Looks up a localized string similar to The following setups were not matched: + {0}. + + + + + Allows setups to be specified for protected members by using their + name as a string, rather than strong-typing them which is not possible + due to their visibility. + + + + + Specifies a setup for a void method invocation with the given + , optionally specifying + arguments for the method call. + + Name of the void method to be invoke. + Optional arguments for the invocation. If argument matchers are used, + remember to use rather than . + + + + Specifies a setup for an invocation on a property or a non void method with the given + , optionally specifying + arguments for the method call. + + Name of the method or property to be invoke. + Optional arguments for the invocation. If argument matchers are used, + remember to use rather than . + Return type of the method or property. + + + + Specifies a setup for an invocation on a property getter with the given + . + + Name of the property. + Type of the property. + + + + Specifies a setup for an invocation on a property setter with the given + . + + Name of the property. + Type of the property. + + + + Allows the specification of a matching condition for an + argument in a protected member setup, rather than a specific + argument value. "ItExpr" refers to the argument being matched. + + + Use this variant of argument matching instead of + for protected setups. + This class allows the setup to match a method invocation + with an arbitrary value, with a value in a specified range, or + even one that matches a given predicate, or null. + + + + + Matches a null value of the given type. + + + Required for protected mocks as the null value cannot be used + directly as it prevents proper method overload selection. + + + + // Throws an exception for a call to Remove with a null string value. + mock.Protected() + .Setup("Remove", ItExpr.IsNull<string>()) + .Throws(new InvalidOperationException()); + + + Type of the value. + + + + Matches any value of the given type. + + + Typically used when the actual argument value for a method + call is not relevant. + + + + // Throws an exception for a call to Remove with any string value. + mock.Protected() + .Setup("Remove", ItExpr.IsAny<string>()) + .Throws(new InvalidOperationException()); + + + Type of the value. + + + + Matches any value that satisfies the given predicate. + + Type of the argument to check. + The predicate used to match the method argument. + + Allows the specification of a predicate to perform matching + of method call arguments. + + + This example shows how to return the value 1 whenever the argument to the + Do method is an even number. + + mock.Protected() + .Setup("Do", ItExpr.Is<int>(i => i % 2 == 0)) + .Returns(1); + + This example shows how to throw an exception if the argument to the + method is a negative number: + + mock.Protected() + .Setup("GetUser", ItExpr.Is<int>(i => i < 0)) + .Throws(new ArgumentException()); + + + + + + Matches any value that is in the range specified. + + Type of the argument to check. + The lower bound of the range. + The upper bound of the range. + The kind of range. See . + + The following example shows how to expect a method call + with an integer argument within the 0..100 range. + + mock.Protected() + .Setup("HasInventory", + ItExpr.IsAny<string>(), + ItExpr.IsInRange(0, 100, Range.Inclusive)) + .Returns(false); + + + + + + Matches a string argument if it matches the given regular expression pattern. + + The pattern to use to match the string argument value. + + The following example shows how to expect a call to a method where the + string argument matches the given regular expression: + + mock.Protected() + .Setup("Check", ItExpr.IsRegex("[a-z]+")) + .Returns(1); + + + + + + Matches a string argument if it matches the given regular expression pattern. + + The pattern to use to match the string argument value. + The options used to interpret the pattern. + + The following example shows how to expect a call to a method where the + string argument matches the given regular expression, in a case insensitive way: + + mock.Protected() + .Setup("Check", ItExpr.IsRegex("[a-z]+", RegexOptions.IgnoreCase)) + .Returns(1); + + + + + + Enables the Protected() method on , + allowing setups to be set for protected members by using their + name as a string, rather than strong-typing them which is not possible + due to their visibility. + + + + + Enable protected setups for the mock. + + Mocked object type. Typically omitted as it can be inferred from the mock instance. + The mock to set the protected setups on. + + + + + + + + + + + + Kind of range to use in a filter specified through + . + + + + + The range includes the to and + from values. + + + + + The range does not include the to and + from values. + + + + + Determines the way default values are generated + calculated for loose mocks. + + + + + Default behavior, which generates empty values for + value types (i.e. default(int)), empty array and + enumerables, and nulls for all other reference types. + + + + + Whenever the default value generated by + is null, replaces this value with a mock (if the type + can be mocked). + + + For sealed classes, a null value will be generated. + + + + + Allows creation custom value matchers that can be used on setups and verification, + completely replacing the built-in class with your own argument + matching rules. + + + + + Provided for the sole purpose of rendering the delegate passed to the + matcher constructor if no friendly render lambda is provided. + + + + + Allows creation custom value matchers that can be used on setups and verification, + completely replacing the built-in class with your own argument + matching rules. + Type of the value to match. + The argument matching is used to determine whether a concrete + invocation in the mock matches a given setup. This + matching mechanism is fully extensible. + + Creating a custom matcher is straightforward. You just need to create a method + that returns a value from a call to with + your matching condition and optional friendly render expression: + + public Order IsBigOrder() + { + return Match<Order>.Create( + o => o.GrandTotal >= 5000, + /* a friendly expression to render on failures */ + () => IsBigOrder()); + } + + This method can be used in any mock setup invocation: + + mock.Setup(m => m.Submit(IsBigOrder()).Throws<UnauthorizedAccessException>(); + + At runtime, Moq knows that the return value was a matcher and + evaluates your predicate with the actual value passed into your predicate. + + Another example might be a case where you want to match a lists of orders + that contains a particular one. You might create matcher like the following: + + + public static class Orders + { + public static IEnumerable<Order> Contains(Order order) + { + return Match<IEnumerable<Order>>.Create(orders => orders.Contains(order)); + } + } + + Now we can invoke this static method instead of an argument in an + invocation: + + var order = new Order { ... }; + var mock = new Mock<IRepository<Order>>(); + + mock.Setup(x => x.Save(Orders.Contains(order))) + .Throws<ArgumentException>(); + + + + + + Initializes the match with the condition that + will be checked in order to match invocation + values. + The condition to match against actual values. + + + + + + + + + + + + This method is used to set an expression as the last matcher invoked, + which is used in the SetupSet to allow matchers in the prop = value + delegate expression. This delegate is executed in "fluent" mode in + order to capture the value being set, and construct the corresponding + methodcall. + This is also used in the MatcherFactory for each argument expression. + This method ensures that when we execute the delegate, we + also track the matcher that was invoked, so that when we create the + methodcall we build the expression using it, rather than the null/default + value returned from the actual invocation. + + + + + Provides a mock implementation of . + + Any interface type can be used for mocking, but for classes, only abstract and virtual members can be mocked. + + The behavior of the mock with regards to the setups and the actual calls is determined + by the optional that can be passed to the + constructor. + + Type to mock, which can be an interface or a class. + The following example shows establishing setups with specific values + for method invocations: + + // Arrange + var order = new Order(TALISKER, 50); + var mock = new Mock<IWarehouse>(); + + mock.Setup(x => x.HasInventory(TALISKER, 50)).Returns(true); + + // Act + order.Fill(mock.Object); + + // Assert + Assert.True(order.IsFilled); + + The following example shows how to use the class + to specify conditions for arguments instead of specific values: + + // Arrange + var order = new Order(TALISKER, 50); + var mock = new Mock<IWarehouse>(); + + // shows how to expect a value within a range + mock.Setup(x => x.HasInventory( + It.IsAny<string>(), + It.IsInRange(0, 100, Range.Inclusive))) + .Returns(false); + + // shows how to throw for unexpected calls. + mock.Setup(x => x.Remove( + It.IsAny<string>(), + It.IsAny<int>())) + .Throws(new InvalidOperationException()); + + // Act + order.Fill(mock.Object); + + // Assert + Assert.False(order.IsFilled); + + + + + + Ctor invoked by AsTInterface exclusively. + + + + + Initializes an instance of the mock with default behavior. + + var mock = new Mock<IFormatProvider>(); + + + + + Initializes an instance of the mock with default behavior and with + the given constructor arguments for the class. (Only valid when is a class) + + The mock will try to find the best match constructor given the constructor arguments, and invoke that + to initialize the instance. This applies only for classes, not interfaces. + + var mock = new Mock<MyProvider>(someArgument, 25); + Optional constructor arguments if the mocked type is a class. + + + + Initializes an instance of the mock with the specified behavior. + + var mock = new Mock<IFormatProvider>(MockBehavior.Relaxed); + Behavior of the mock. + + + + Initializes an instance of the mock with a specific behavior with + the given constructor arguments for the class. + + The mock will try to find the best match constructor given the constructor arguments, and invoke that + to initialize the instance. This applies only to classes, not interfaces. + + var mock = new Mock<MyProvider>(someArgument, 25); + Behavior of the mock.Optional constructor arguments if the mocked type is a class. + + + + Returns the mocked object value. + + + + + Specifies a setup on the mocked type for a call to + to a void method. + + If more than one setup is specified for the same method or property, + the latest one wins and is the one that will be executed. + Lambda expression that specifies the expected method invocation. + + var mock = new Mock<IProcessor>(); + mock.Setup(x => x.Execute("ping")); + + + + + + Specifies a setup on the mocked type for a call to + to a value returning method. + Type of the return value. Typically omitted as it can be inferred from the expression. + If more than one setup is specified for the same method or property, + the latest one wins and is the one that will be executed. + Lambda expression that specifies the method invocation. + + mock.Setup(x => x.HasInventory("Talisker", 50)).Returns(true); + + + + + + Specifies a setup on the mocked type for a call to + to a property getter. + + If more than one setup is set for the same property getter, + the latest one wins and is the one that will be executed. + Type of the property. Typically omitted as it can be inferred from the expression.Lambda expression that specifies the property getter. + + mock.SetupGet(x => x.Suspended) + .Returns(true); + + + + + + Specifies a setup on the mocked type for a call to + to a property setter. + + If more than one setup is set for the same property setter, + the latest one wins and is the one that will be executed. + + This overloads allows the use of a callback already + typed for the property type. + + Type of the property. Typically omitted as it can be inferred from the expression.Lambda expression that sets a property to a value. + + mock.SetupSet(x => x.Suspended = true); + + + + + + Specifies a setup on the mocked type for a call to + to a property setter. + + If more than one setup is set for the same property setter, + the latest one wins and is the one that will be executed. + Lambda expression that sets a property to a value. + + mock.SetupSet(x => x.Suspended = true); + + + + + + Specifies that the given property should have "property behavior", + meaning that setting its value will cause it to be saved and + later returned when the property is requested. (this is also + known as "stubbing"). + + Type of the property, inferred from the property + expression (does not need to be specified). + Property expression to stub. + If you have an interface with an int property Value, you might + stub it using the following straightforward call: + + var mock = new Mock<IHaveValue>(); + mock.Stub(v => v.Value); + + After the Stub call has been issued, setting and + retrieving the object value will behave as expected: + + IHaveValue v = mock.Object; + + v.Value = 5; + Assert.Equal(5, v.Value); + + + + + + Specifies that the given property should have "property behavior", + meaning that setting its value will cause it to be saved and + later returned when the property is requested. This overload + allows setting the initial value for the property. (this is also + known as "stubbing"). + + Type of the property, inferred from the property + expression (does not need to be specified). + Property expression to stub.Initial value for the property. + If you have an interface with an int property Value, you might + stub it using the following straightforward call: + + var mock = new Mock<IHaveValue>(); + mock.SetupProperty(v => v.Value, 5); + + After the SetupProperty call has been issued, setting and + retrieving the object value will behave as expected: + + IHaveValue v = mock.Object; + // Initial value was stored + Assert.Equal(5, v.Value); + + // New value set which changes the initial value + v.Value = 6; + Assert.Equal(6, v.Value); + + + + + + Specifies that the all properties on the mock should have "property behavior", + meaning that setting its value will cause it to be saved and + later returned when the property is requested. (this is also + known as "stubbing"). The default value for each property will be the + one generated as specified by the property for the mock. + + If the mock is set to , + the mocked default values will also get all properties setup recursively. + + + + + Verifies that a specific invocation matching the given expression was performed on the mock. Use + in conjuntion with the default . + + This example assumes that the mock has been used, and later we want to verify that a given + invocation with specific parameters was performed: + + var mock = new Mock<IProcessor>(); + // exercise mock + //... + // Will throw if the test code didn't call Execute with a "ping" string argument. + mock.Verify(proc => proc.Execute("ping")); + + The invocation was not performed on the mock.Expression to verify. + + + + Verifies that a specific invocation matching the given expression was performed on the mock. Use + in conjuntion with the default . + + The invocation was not call the times specified by + . + Expression to verify.The number of times a method is allowed to be called. + + + + Verifies that a specific invocation matching the given expression was performed on the mock, + specifying a failure error message. Use in conjuntion with the default + . + + This example assumes that the mock has been used, and later we want to verify that a given + invocation with specific parameters was performed: + + var mock = new Mock<IProcessor>(); + // exercise mock + //... + // Will throw if the test code didn't call Execute with a "ping" string argument. + mock.Verify(proc => proc.Execute("ping")); + + The invocation was not performed on the mock.Expression to verify.Message to show if verification fails. + + + + Verifies that a specific invocation matching the given expression was performed on the mock, + specifying a failure error message. Use in conjuntion with the default + . + + The invocation was not call the times specified by + . + Expression to verify.The number of times a method is allowed to be called.Message to show if verification fails. + + + + Verifies that a specific invocation matching the given expression was performed on the mock. Use + in conjuntion with the default . + + This example assumes that the mock has been used, and later we want to verify that a given + invocation with specific parameters was performed: + + var mock = new Mock<IWarehouse>(); + // exercise mock + //... + // Will throw if the test code didn't call HasInventory. + mock.Verify(warehouse => warehouse.HasInventory(TALISKER, 50)); + + The invocation was not performed on the mock.Expression to verify.Type of return value from the expression. + + + + Verifies that a specific invocation matching the given + expression was performed on the mock. Use in conjuntion + with the default . + + The invocation was not call the times specified by + . + Expression to verify.The number of times a method is allowed to be called.Type of return value from the expression. + + + + Verifies that a specific invocation matching the given + expression was performed on the mock, specifying a failure + error message. + + This example assumes that the mock has been used, + and later we want to verify that a given invocation + with specific parameters was performed: + + var mock = new Mock<IWarehouse>(); + // exercise mock + //... + // Will throw if the test code didn't call HasInventory. + mock.Verify(warehouse => warehouse.HasInventory(TALISKER, 50), "When filling orders, inventory has to be checked"); + + The invocation was not performed on the mock.Expression to verify.Message to show if verification fails.Type of return value from the expression. + + + + Verifies that a specific invocation matching the given + expression was performed on the mock, specifying a failure + error message. + + The invocation was not call the times specified by + . + Expression to verify.The number of times a method is allowed to be called.Message to show if verification fails.Type of return value from the expression. + + + + Verifies that a property was read on the mock. + + This example assumes that the mock has been used, + and later we want to verify that a given property + was retrieved from it: + + var mock = new Mock<IWarehouse>(); + // exercise mock + //... + // Will throw if the test code didn't retrieve the IsClosed property. + mock.VerifyGet(warehouse => warehouse.IsClosed); + + The invocation was not performed on the mock.Expression to verify. + Type of the property to verify. Typically omitted as it can + be inferred from the expression's return type. + + + + + Verifies that a property was read on the mock. + + The invocation was not call the times specified by + . + The number of times a method is allowed to be called.Expression to verify. + Type of the property to verify. Typically omitted as it can + be inferred from the expression's return type. + + + + + Verifies that a property was read on the mock, specifying a failure + error message. + + This example assumes that the mock has been used, + and later we want to verify that a given property + was retrieved from it: + + var mock = new Mock<IWarehouse>(); + // exercise mock + //... + // Will throw if the test code didn't retrieve the IsClosed property. + mock.VerifyGet(warehouse => warehouse.IsClosed); + + The invocation was not performed on the mock.Expression to verify.Message to show if verification fails. + Type of the property to verify. Typically omitted as it can + be inferred from the expression's return type. + + + + + Verifies that a property was read on the mock, specifying a failure + error message. + + The invocation was not call the times specified by + . + The number of times a method is allowed to be called.Expression to verify.Message to show if verification fails. + Type of the property to verify. Typically omitted as it can + be inferred from the expression's return type. + + + + + Verifies that a property was set on the mock. + + This example assumes that the mock has been used, + and later we want to verify that a given property + was set on it: + + var mock = new Mock<IWarehouse>(); + // exercise mock + //... + // Will throw if the test code didn't set the IsClosed property. + mock.VerifySet(warehouse => warehouse.IsClosed = true); + + The invocation was not performed on the mock.Expression to verify. + + + + Verifies that a property was set on the mock. + + The invocation was not call the times specified by + . + The number of times a method is allowed to be called.Expression to verify. + + + + Verifies that a property was set on the mock, specifying + a failure message. + + This example assumes that the mock has been used, + and later we want to verify that a given property + was set on it: + + var mock = new Mock<IWarehouse>(); + // exercise mock + //... + // Will throw if the test code didn't set the IsClosed property. + mock.VerifySet(warehouse => warehouse.IsClosed = true, "Warehouse should always be closed after the action"); + + The invocation was not performed on the mock.Expression to verify.Message to show if verification fails. + + + + Verifies that a property was set on the mock, specifying + a failure message. + + The invocation was not call the times specified by + . + The number of times a method is allowed to be called.Expression to verify.Message to show if verification fails. + + + + Adds an interface implementation to the mock, + allowing setups to be specified for it. + + This method can only be called before the first use + of the mock property, at which + point the runtime type has already been generated + and no more interfaces can be added to it. + + Also, must be an + interface and not a class, which must be specified + when creating the mock instead. + + + The mock type + has already been generated by accessing the property. + + The specified + is not an interface. + + The following example creates a mock for the main interface + and later adds to it to verify + it's called by the consumer code: + + var mock = new Mock<IProcessor>(); + mock.Setup(x => x.Execute("ping")); + + // add IDisposable interface + var disposable = mock.As<IDisposable>(); + disposable.Setup(d => d.Dispose()).Verifiable(); + + Type of interface to cast the mock to. + + + + Raises the event referenced in using + the given and arguments. + + The argument is + invalid for the target event invocation, or the is + not an event attach or detach expression. + + The following example shows how to raise a event: + + var mock = new Mock<IViewModel>(); + + mock.Raise(x => x.PropertyChanged -= null, new PropertyChangedEventArgs("Name")); + + + This example shows how to invoke an event with a custom event arguments + class in a view that will cause its corresponding presenter to + react by changing its state: + + var mockView = new Mock<IOrdersView>(); + var presenter = new OrdersPresenter(mockView.Object); + + // Check that the presenter has no selection by default + Assert.Null(presenter.SelectedOrder); + + // Raise the event with a specific arguments data + mockView.Raise(v => v.SelectionChanged += null, new OrderEventArgs { Order = new Order("moq", 500) }); + + // Now the presenter reacted to the event, and we have a selected order + Assert.NotNull(presenter.SelectedOrder); + Assert.Equal("moq", presenter.SelectedOrder.ProductName); + + + + + + Raises the event referenced in using + the given and arguments + for a non-EventHandler typed event. + + The arguments are + invalid for the target event invocation, or the is + not an event attach or detach expression. + + The following example shows how to raise a custom event that does not adhere to + the standard EventHandler: + + var mock = new Mock<IViewModel>(); + + mock.Raise(x => x.MyEvent -= null, "Name", bool, 25); + + + + + + Obsolete. + + + + + Obsolete. + + + + + Obsolete. + + + + + Obsolete. + + + + + Obsolete. + + + + + Exposes the mocked object instance. + + + + + Provides legacy API members as extensions so that + existing code continues to compile, but new code + doesn't see then. + + + + + Obsolete. + + + + + Obsolete. + + + + + Obsolete. + + + + + Tracks the current mock and interception context. + + + + + Having an active fluent mock context means that the invocation + is being performed in "trial" mode, just to gather the + target method and arguments that need to be matched later + when the actual invocation is made. + + + + + A that returns an empty default value + for non-mockeable types, and mocks for all other types (interfaces and + non-sealed classes) that can be mocked. + + + + + Provides a typed for a + specific type of . + + The type of event arguments required by the event. + + The mocked event can either be a or custom + event handler which follows .NET practice of providing object sender, EventArgs args + kind of signature. + + + + + Raises the associated event with the given + event argument data. + + Data to pass to the event. + + + + Provides support for attaching a to + a generic event. + + Event to convert. + + + + Provided solely to allow the interceptor to determine when the attached + handler is coming from this mocked event so we can assign the + corresponding EventInfo for it. + + + + + Provides additional methods on mocks. + + + Provided as extension methods as they confuse the compiler + with the overloads taking Action. + + + + + Specifies a setup on the mocked type for a call to + to a property setter, regardless of its value. + + + If more than one setup is set for the same property setter, + the latest one wins and is the one that will be executed. + + Type of the property. Typically omitted as it can be inferred from the expression. + Type of the mock. + The target mock for the setup. + Lambda expression that specifies the property setter. + + + mock.SetupSet(x => x.Suspended); + + + + This method is not legacy, but must be on an extension method to avoid + confusing the compiler with the new Action syntax. + + + + + Verifies that a property has been set on the mock, regarless of its value. + + + This example assumes that the mock has been used, + and later we want to verify that a given invocation + with specific parameters was performed: + + var mock = new Mock<IWarehouse>(); + // exercise mock + //... + // Will throw if the test code didn't set the IsClosed property. + mock.VerifySet(warehouse => warehouse.IsClosed); + + + The invocation was not performed on the mock. + Expression to verify. + The mock instance. + Mocked type. + Type of the property to verify. Typically omitted as it can + be inferred from the expression's return type. + + + + Verifies that a property has been set on the mock, specifying a failure + error message. + + + This example assumes that the mock has been used, + and later we want to verify that a given invocation + with specific parameters was performed: + + var mock = new Mock<IWarehouse>(); + // exercise mock + //... + // Will throw if the test code didn't set the IsClosed property. + mock.VerifySet(warehouse => warehouse.IsClosed); + + + The invocation was not performed on the mock. + Expression to verify. + Message to show if verification fails. + The mock instance. + Mocked type. + Type of the property to verify. Typically omitted as it can + be inferred from the expression's return type. + + + + Verifies that a property has been set on the mock, regardless + of the value but only the specified number of times. + + + This example assumes that the mock has been used, + and later we want to verify that a given invocation + with specific parameters was performed: + + var mock = new Mock<IWarehouse>(); + // exercise mock + //... + // Will throw if the test code didn't set the IsClosed property. + mock.VerifySet(warehouse => warehouse.IsClosed); + + + The invocation was not performed on the mock. + The invocation was not call the times specified by + . + The mock instance. + Mocked type. + The number of times a method is allowed to be called. + Expression to verify. + Type of the property to verify. Typically omitted as it can + be inferred from the expression's return type. + + + + Verifies that a property has been set on the mock, regardless + of the value but only the specified number of times, and specifying a failure + error message. + + + This example assumes that the mock has been used, + and later we want to verify that a given invocation + with specific parameters was performed: + + var mock = new Mock<IWarehouse>(); + // exercise mock + //... + // Will throw if the test code didn't set the IsClosed property. + mock.VerifySet(warehouse => warehouse.IsClosed); + + + The invocation was not performed on the mock. + The invocation was not call the times specified by + . + The mock instance. + Mocked type. + The number of times a method is allowed to be called. + Message to show if verification fails. + Expression to verify. + Type of the property to verify. Typically omitted as it can + be inferred from the expression's return type. + + + + Legacy Stub stuff, moved to the core API. + + + + + Obsolete. Use . + + + + + Obsolete. Use . + + + + + Obsolete. Use . + + + + + Defines the number of invocations allowed by a mocked method. + + + + + Specifies that a mocked method should be invoked times as minimum. + + The minimun number of times. + An object defining the allowed number of invocations. + + + + Specifies that a mocked method should be invoked one time as minimum. + + An object defining the allowed number of invocations. + + + + Specifies that a mocked method should be invoked time as maximun. + + The maximun number of times. + An object defining the allowed number of invocations. + + + + Specifies that a mocked method should be invoked one time as maximun. + + An object defining the allowed number of invocations. + + + + Specifies that a mocked method should be invoked between and + times. + + The minimun number of times. + The maximun number of times. + The kind of range. See . + An object defining the allowed number of invocations. + + + + Specifies that a mocked method should be invoked exactly times. + + The times that a method or property can be called. + An object defining the allowed number of invocations. + + + + Specifies that a mocked method should not be invoked. + + An object defining the allowed number of invocations. + + + + Specifies that a mocked method should be invoked exactly one time. + + An object defining the allowed number of invocations. + + + diff --git a/lib/nhib/Antlr3.Runtime.dll b/lib/nhib/Antlr3.Runtime.dll new file mode 100644 index 0000000..637fc3e Binary files /dev/null and b/lib/nhib/Antlr3.Runtime.dll differ diff --git a/lib/nhib/Castle.Core.dll b/lib/nhib/Castle.Core.dll new file mode 100644 index 0000000..dacd378 Binary files /dev/null and b/lib/nhib/Castle.Core.dll differ diff --git a/lib/nhib/Castle.DynamicProxy2.dll b/lib/nhib/Castle.DynamicProxy2.dll new file mode 100644 index 0000000..1226cc3 Binary files /dev/null and b/lib/nhib/Castle.DynamicProxy2.dll differ diff --git a/lib/nhib/FluentNHibernate.dll b/lib/nhib/FluentNHibernate.dll new file mode 100644 index 0000000..a041814 Binary files /dev/null and b/lib/nhib/FluentNHibernate.dll differ diff --git a/lib/nhib/FluentNHibernate.pdb b/lib/nhib/FluentNHibernate.pdb new file mode 100644 index 0000000..dc5ddd8 Binary files /dev/null and b/lib/nhib/FluentNHibernate.pdb differ diff --git a/lib/nhib/Iesi.Collections.dll b/lib/nhib/Iesi.Collections.dll new file mode 100644 index 0000000..32f2332 Binary files /dev/null and b/lib/nhib/Iesi.Collections.dll differ diff --git a/lib/nhib/NHibernate.ByteCode.Castle.dll b/lib/nhib/NHibernate.ByteCode.Castle.dll new file mode 100644 index 0000000..2070f67 Binary files /dev/null and b/lib/nhib/NHibernate.ByteCode.Castle.dll differ diff --git a/lib/nhib/NHibernate.dll b/lib/nhib/NHibernate.dll new file mode 100644 index 0000000..f45b6b6 Binary files /dev/null and b/lib/nhib/NHibernate.dll differ diff --git a/lib/nhib/log4net.dll b/lib/nhib/log4net.dll new file mode 100644 index 0000000..ffc57e1 Binary files /dev/null and b/lib/nhib/log4net.dll differ