Пример #1
0
        public async Task <IActionResult> GetAssetResults(string searchToken)
        {
            if (String.IsNullOrWhiteSpace(searchToken))
            {
                return(BadRequest());
            }

            string accessIpAddress = HttpContext?.Connection?.RemoteIpAddress?.ToString();

            if (string.IsNullOrWhiteSpace(accessIpAddress))
            {
                return(BadRequest());
            }

            try
            {
                const int MaxSearchResults = 50;
                var       assets           = await _assetService.GetAssetResultsAsync(searchToken, MaxSearchResults);

                return(new OkObjectResult(AssetFactory.ConvertAssetSearch(assets)));
            }
            catch (Exception ex)
            {
                // LOG through SERVICE TODO
                var t = new TelemetryClient();
                t.TrackException(ex);
                return(BadRequest());
            }
        }
        public void CreateAssetSearchViewModel_InvalidKeysShouldGetException(int id)
        {
            Asset asset = new Note()
            {
                Id = id, ProjectForeignKey = 1
            };

            try
            {
                AssetFactory.CreateAssetSearchViewModel(asset);
            }
            catch (ArgumentException)
            {
                Assert.True(true);
            }

            asset = new Credential()
            {
                Id = 1, ProjectForeignKey = id
            };
            try
            {
                AssetFactory.CreateAssetSearchViewModel(asset);
            }
            catch (ArgumentException)
            {
                Assert.True(true);
            }
        }
Пример #3
0
        static void WriteFileInfo(SerializedFile container, StreamWriter sw)
        {
            sw.WriteLine($"  File: {container.Name}");
            sw.WriteLine($"	File.Collection: {container.Collection}");
            sw.WriteLine($"	File.Platform: {container.Platform}");
            sw.WriteLine($"	File.Version: {container.Version}");
            foreach (var dep in container.Dependencies)
            {
                sw.WriteLine($"	File.Dependency: {dep}");
                sw.WriteLine($"	  Dependency.AssetPath: {dep.AssetPath}");
                sw.WriteLine($"	  Dependency.FilePath: {dep.FilePath}");
                sw.WriteLine($"	  Dependency.FilePathOrigin: {dep.FilePathOrigin}");
            }
            sw.WriteLine($"	File.Metadata: {container.Metadata.Entries.Count}");
            var factory = new AssetFactory();

            foreach (var entry in container.Metadata.Entries)
            {
                var       info      = entry.Value;
                AssetInfo assetInfo = new AssetInfo(container, info.PathID, info.ClassID);
                Object    asset     = factory.CreateAsset(assetInfo);
                if (asset == null)
                {
                    sw.WriteLine($"	  Unimplemented Asset: {info.ClassID}, {info.ScriptID}, {info.TypeID}, {info.PathID}, {info.IsStripped}");
                }
            }
        }
Пример #4
0
        private static void AddTargetAssets(IUnitTestGeneratorOptions options, KeyValuePair <Project, Tuple <HashSet <TargetAsset>, HashSet <IReferencedAssembly> > > pair)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            foreach (var targetAsset in pair.Value.Item1)
            {
                var asset = AssetFactory.Create(targetAsset);
                if (asset != null)
                {
                    var targetProjectFileName = pair.Key.FileName;
                    var targetProjectPath     = Path.GetDirectoryName(targetProjectFileName);

                    if (string.IsNullOrWhiteSpace(targetProjectPath))
                    {
                        continue;
                    }

#pragma warning disable VSTHRD010
                    if (!pair.Key.ProjectItems.OfType <ProjectItem>().Any(x => string.Equals(x.Name, asset.AssetFileName, StringComparison.OrdinalIgnoreCase)))
#pragma warning restore VSTHRD010
                    {
                        var nameSpace = VsProjectHelper.GetProjectRootNamespace(pair.Key);
                        var fileName  = Path.Combine(targetProjectPath, asset.AssetFileName);
                        File.WriteAllText(fileName, asset.Content(nameSpace, options.GenerationOptions.FrameworkType));
                        pair.Key.ProjectItems.AddFromFile(fileName);
                    }
                }
            }
        }
        public static void CanCallCreate()
        {
            var assetType = TargetAsset.PropertyTester;
            var result    = AssetFactory.Create(assetType);

            Assert.That(result, Is.InstanceOf <IAsset>());
        }
Пример #6
0
        public GameLoader(SignalBus signalBus, AssetFactory assetFactory)
        {
            this.signalBus    = signalBus;
            this.assetFactory = assetFactory;

            LoadGame().Forget();
        }
Пример #7
0
        static void WriteFileInfo(SerializedFile container, StreamWriter sw)
        {
            sw.WriteLine($"  File: {container.Name}");
            sw.WriteLine($"	File.Collection: {container.Collection}");
            sw.WriteLine($"	File.Platform: {container.Platform}");
            sw.WriteLine($"	File.Version: {container.Version}");
            foreach (var dep in container.Dependencies)
            {
                sw.WriteLine($"	File.Dependency: {dep}");
                sw.WriteLine($"	  Dependency.AssetPath: {dep.AssetPath}");
                sw.WriteLine($"	  Dependency.FilePath: {dep.FilePath}");
                sw.WriteLine($"	  Dependency.FilePathOrigin: {dep.FilePathOrigin}");
            }
            if (container.Metadata.Hierarchy != null)
            {
                var SerializeTypeTrees = Util.GetMember <bool>(container.Metadata.Hierarchy, "SerializeTypeTrees");
                var Types = Util.GetMember <IReadOnlyList <object> >(container.Metadata.Hierarchy, "Types");
                var Name  = Util.GetMember <string>(container.Metadata.Hierarchy, "Name");
                sw.WriteLine($"	File.Metadata.Hierarchy:");
                sw.WriteLine($"		Hierarchy.Name: {Name}");
                sw.WriteLine($"		Hierarchy.SerializeTypeTrees: {SerializeTypeTrees}");
                sw.WriteLine($"		Hierarchy.Types: {Types.Count}");
                if (Types.Count > 0)
                {
                    sw.WriteLine($"			ClassID, IsStrippedType, ScriptID, ScriptHash, TypeHash, NodeCount");
                }
                foreach (var type in Types)
                {
                    var ClassID        = Util.GetMember <ClassIDType>(type, "ClassID");
                    var IsStrippedType = Util.GetMember <bool>(type, "IsStrippedType");
                    var ScriptID       = Util.GetMember <short>(type, "ScriptID");
                    var Tree           = Util.GetMember <object>(type, "Tree");
                    var ScriptHash     = Util.GetMember <Hash128>(type, "ScriptHash");
                    var TypeHash       = Util.GetMember <Hash128>(type, "TypeHash");
                    var nodeCount      = Tree == null ? "Null" : Util.GetMember <IReadOnlyList <object> >(Tree, "Nodes").Count.ToString();
                    sw.WriteLine($"			{ClassID}, {IsStrippedType}, {ScriptID}, {HashToString(ScriptHash)}, {HashToString(TypeHash)}, {nodeCount}");
                }
            }
            else
            {
                sw.WriteLine($"	File.Metadata.Hierarchy: Null");
            }
            sw.WriteLine($"	File.Metadata.Entries: {container.Metadata.Entries.Count}");

            var factory = new AssetFactory();

            foreach (var entry in container.Metadata.Entries)
            {
                var       info      = entry.Value;
                AssetInfo assetInfo = new AssetInfo(container, info.PathID, info.ClassID);
                Object    asset     = factory.CreateAsset(assetInfo);
                if (asset == null)
                {
                    sw.WriteLine($"	  Unimplemented Asset: {info.ClassID}, {info.ScriptID}, {info.TypeID}, {info.PathID}, {info.IsStripped}");
                }
            }
        }
Пример #8
0
        public async Task Mobi7ParserShouldExtractNavigationStream()
        {
            await using var stream      = AssetFactory.GetAsset("pg42324.mobi");
            await using var rawMlStream = new MobiMetadata(stream).GetRawMlStream();

            var parser        = new Mobi7Parser();
            var contentStream = await parser.GetNavigationStream(rawMlStream);

            Assert.IsNotNull(contentStream);
            Assert.AreEqual(4133, contentStream.Length);
        }
        public void ConvertAssetSearch_ShouldNotFailOnNullArgument()
        {
            try
            {
                AssetFactory.ConvertAssetSearch(null);
            }
            catch (NullReferenceException)
            {
                Assert.False(true);
            }

            Assert.True(true);
        }
Пример #10
0
    public void Awake()
    {
        // We don't care about checking for null. If no player, the game
        // won't work anyway.
        player = FetchUtils.FetchGameObjectByTag(Tags.PLAYER).GetComponent <RogueController>();

        factory = new AssetFactory();
        factory.LoadAll();

        builder = new DungeonBuilder(factory, transform);

        // Now create the first dungeon
        GenerateDungeon();
    }
Пример #11
0
        public ICommandResult Create(AssetCommand command)
        {
            try
            {
                if (command.IsValid())
                {
                    var brandResult = this.brandRepository.GetById(new Guid(command.BrandId));

                    if (brandResult is null)
                    {
                        AddNotification("BrandID", "Brand not found");
                        return(new UnsuccessfulCommandResult(StatusCodeResult.NotFound,
                                                             "Please, check the properties before creating the user", this.Notifications));
                    }

                    var brand = BrandFactory.Create(brandResult);
                    var asset = AssetFactory.Create(command, brand);

                    this.assetRepository.Save(asset);

                    return(new SuccessfulCommandResult("Asset was saved with successful", new
                    {
                        id = asset.Id,
                        Name = asset.Name,
                        Description = asset.Description,
                        Registry = asset.Registry,
                        Brand = new
                        {
                            id = asset.Brand.Id,
                            Name = asset.Brand.Name,
                        }
                    }));
                }

                return(new UnsuccessfulCommandResult(StatusCodeResult.BadRequest,
                                                     "Please, check the properties before creating the asset", command.Notifications));
            }
            catch (Exception ex)
            {
                return(new UnsuccessfulCommandResult(StatusCodeResult.InternalServerError,
                                                     "There was an error saving the user, please contact your system administrator.",
                                                     ex.Message));
            }
        }
Пример #12
0
        public Form()
        {
            InitializeComponent();
            int k = 0;

            this.Load    += delegate { factory = new AssetFactory(); };
            this.MouseUp += (s, e) =>
            {
                this.Controls.Add(
                    new Prefab(
                        sprite: factory.GetAsset((Texture2D)(k++)),
                        x: e.X - 50,
                        y: e.Y - 65
                        )
                    .SimpleImage
                    );
                k %= 3;
            };
        }
Пример #13
0
        public void UpdateAsset(int buildingId, int mediaId)
        {
            //check if child media node already exists in the db
            var dbassetExisting = _buildingAssetRepo.GetById(mediaId);

            if (dbassetExisting != null)
            {
                dbassetExisting.BuildingId = buildingId;
                dbassetExisting.MediaId    = mediaId;
                dbassetExisting.TypeId     = (int)AssetMediaType.Image;

                //just update to make sure it's referenced to correct buildign and media
                _buildingAssetRepo.Update(dbassetExisting.Id, dbassetExisting);
            }
            else
            {
                //re-add each media to db asset table
                _buildingAssetRepo.Insert((BuildingAsset)AssetFactory.CreateAsset(AssetType.Building, buildingId, mediaId, AssetMediaType.Image));
            }
        }
Пример #14
0
        public async Task MobiReaderShouldParseAnnotationsAndTableOfContent()
        {
            await using var stream = AssetFactory.GetAsset("pg42324.mobi");
            var annotations = new List <Annotation>
            {
                new(
                    "Nothing is so painful to the human mind as a great and sudden change.",
                    new DocumentReference(),
                    AnnotationType.Highlight,
                    new AnnotationContext
                {
                    PageNumber = 380,
                    SerializedLocation = "line://925-994"
                },
                    DateTime.MinValue)
            };

            var document = await this.reader.Read(
                stream,
                new ReaderOptions(),
                _ => annotations);

            Assert.AreEqual(1, document.Annotations.Count());
        }
Пример #15
0
        /// <summary>
        /// Gets an active alarm based on the parameters passed in
        /// </summary>
        private AlarmModel GetActiveAlarmDetails(int customerID, ActiveAlarm alarm, DateTime localTime)
        {
            var alarmModel = new AlarmModel();

            if (alarm != null)
            {
                //Get the meter map for this alarm
                MeterMap metermap =
                    PemsEntities.MeterMaps.FirstOrDefault(
                        x =>
                        x.Areaid == alarm.AreaID && x.Customerid == alarm.CustomerID &&
                        x.MeterId == alarm.MeterId);

                //Asset / Location Information
                alarmModel.EventSource  = alarm.EventSource;
                alarmModel.Latitude     = alarm.Meter == null ? 0 : alarm.Meter.Latitude ?? 0;
                alarmModel.Longitude    = alarm.Meter == null ? 0 : alarm.Meter.Longitude ?? 0;
                alarmModel.MeterGroupId = alarm.Meter == null ? 0 : alarm.Meter.MeterGroup ?? 0;
                alarmModel.AssetClass   = alarm.Meter == null ? AssetClass.Unknown : AssetFactory.GetAssetClass(alarm.Meter.MeterGroup);
                alarmModel.AssetType    = alarm.Meter == null ? string.Empty : (new AssetFactory(ConnectionStringName)).GetAssetTypeDescription(alarm.Meter.MeterGroup, customerID);
                alarmModel.CustomerId   = customerID;
                //name ans state are based on class
                OperationalStatu opStatus = null;

                if (alarmModel.AssetClass == AssetClass.Sensor)
                {
                    alarmModel.AssetName         = PemsEntities.Sensors.FirstOrDefault(x => x.SensorID == metermap.SensorID) == null? "": PemsEntities.Sensors.FirstOrDefault(x => x.SensorID == metermap.SensorID).SensorName;
                    opStatus                     = PemsEntities.OperationalStatus.FirstOrDefault(x => x.OperationalStatusId == metermap.Sensor.OperationalStatus);
                    alarmModel.OperationalStatus = opStatus == null ? "" : opStatus.OperationalStatusDesc ?? "";
                }
                else if (alarmModel.AssetClass == AssetClass.Gateway)
                {
                    alarmModel.AssetName         = PemsEntities.Gateways.FirstOrDefault(x => x.GateWayID == metermap.GatewayID) == null ? "" : PemsEntities.Gateways.FirstOrDefault(x => x.GateWayID == metermap.GatewayID).Description;
                    opStatus                     = PemsEntities.OperationalStatus.FirstOrDefault(x => x.OperationalStatusId == metermap.Gateway.OperationalStatus);
                    alarmModel.OperationalStatus = opStatus == null ? "" : opStatus.OperationalStatusDesc ?? "";
                }
                //everything else falls under meter for now
                else
                {
                    alarmModel.AssetName         = alarm.Meter == null ? "" : alarm.Meter.MeterName;
                    opStatus                     = PemsEntities.OperationalStatus.FirstOrDefault(x => x.OperationalStatusId == metermap.Meter.OperationalStatusID);
                    alarmModel.OperationalStatus = opStatus == null ? "" : opStatus.OperationalStatusDesc ?? "";
                }
                alarmModel.AssetID      = alarm.Meter.MeterId;
                alarmModel.Area         = PemsEntities.Areas.FirstOrDefault(x => x.CustomerID == metermap.Customerid && x.AreaID == metermap.AreaId2) == null ? "" : PemsEntities.Areas.FirstOrDefault(x => x.CustomerID == metermap.Customerid && x.AreaID == metermap.AreaId2).AreaName;
                alarmModel.AreaId       = metermap.AreaId2; //alarm.Meter.Area.AreaID;
                alarmModel.Zone         = metermap.Zone == null ? string.Empty : PemsEntities.Zones.FirstOrDefault(x => x.ZoneId == metermap.ZoneId && metermap.Customerid == x.customerID) == null ? string.Empty : PemsEntities.Zones.FirstOrDefault(x => x.ZoneId == metermap.ZoneId && metermap.Customerid == x.customerID).ZoneName;
                alarmModel.Suburb       = metermap == null? string.Empty: metermap.CustomGroup11 == null ? string.Empty : metermap.CustomGroup11.DisplayName;
                alarmModel.Street       = alarm.Meter.Location;
                alarmModel.BaysAffected = alarm.Meter.MaxBaysEnabled ?? 0;

                //Alarm / Meter information
                alarmModel.AlarmID                = alarm.AlarmUID ?? 0;
                alarmModel.AlarmCode              = alarm.EventCode1.EventCode1;
                alarmModel.AlarmDesription        = alarm.EventCode1.EventDescAbbrev;
                alarmModel.AlarmDesriptionVerbose = alarm.EventCode1.EventDescVerbose;
                alarmModel.ServiceTargetTime      = alarm.SLADue ?? DateTime.MinValue;
                alarmModel.AlarmStatus            = "Open";
                var alarmStatus = PemsEntities.AlarmStatus.FirstOrDefault(x => x.AlarmStatusId == 2);
                if (alarmStatus != null)
                {
                    alarmModel.AlarmStatus = alarmStatus.AlarmStatusDesc;
                }
                alarmModel.TimeNotified = alarm.TimeOfNotification;
                alarmModel             = DetermineSlaValues(alarmModel, alarm, localTime);
                alarmModel.TimeOccured = alarm.TimeOfOccurrance;
                //Time Types here

                AddTimeTypes(alarm, alarmModel);
                alarmModel.TimeType1     = alarm.TimeType1 ?? 0;
                alarmModel.TimeType2     = alarm.TimeType2 ?? 0;
                alarmModel.TimeType3     = alarm.TimeType3 ?? 0;
                alarmModel.TimeType4     = alarm.TimeType4 ?? 0;
                alarmModel.TimeType5     = alarm.TimeType5 ?? 0;
                alarmModel.AlarmSource   = PemsEntities.EventSources.FirstOrDefault(x => x.EventSourceCode == alarm.EventSource).EventSourceDesc;
                alarmModel.AlarmSeverity = alarm.EventCode1.AlarmTier1 == null ? string.Empty : alarm.EventCode1.AlarmTier1.TierDesc;
                alarmModel.EntryNotes    = alarm.Notes;
                alarmModel.IsClosed      = false;
                alarmModel.CustomerId    = customerID;
                //Closure Information -  this alarm hasnt been closed, so most of them are not needed
                //closed by is current user
                alarmModel.ClosedBy     = WebSecurity.CurrentUserId;
                alarmModel.ClosedByName = WebSecurity.CurrentUserName;
            }

            alarmModel.ResolutionCodes = GetResolutionCodes();
            alarmModel.TechnicianIDs   = GetAlarmTechnicians();
            return(alarmModel);
        }
Пример #16
0
 static void CreateAsset()
 {
     AssetFactory.CreateAssetInProjectWindow <CommentAsset>("Packages/net.peeweek.gameplay-ingredients/Icons/Misc/ic-comment.png", "New Comment.asset");
 }
Пример #17
0
        static void WriteFileInfo(SerializedFile container, StreamWriter sw)
        {
            sw.WriteLine($"  File: {container.Name}");
            sw.WriteLine($"	File.Collection: {container.Collection}");
            sw.WriteLine($"	File.Platform: {container.Platform}");
            sw.WriteLine($"	File.Version: {container.Version}");
            foreach (var dep in container.Dependencies)
            {
                sw.WriteLine($"	File.Dependency: {dep}");
                sw.WriteLine($"	  Dependency.AssetPath: {dep.AssetPath}");
                sw.WriteLine($"	  Dependency.FilePath: {dep.FilePath}");
                sw.WriteLine($"	  Dependency.FilePathOrigin: {dep.FilePathOrigin}");
            }
            if (container.Metadata != null)
            {
                var SerializeTypeTrees = container.Metadata.Hierarchy.SerializeTypeTrees;
                var Types    = container.Metadata.Hierarchy.Types;
                var Version  = container.Metadata.Hierarchy.Version;
                var Platform = container.Metadata.Hierarchy.Platform;
                var Unknown  = container.Metadata.Hierarchy.Unknown;
                sw.WriteLine($"	File.Metadata.Hierarchy:");
                sw.WriteLine($"		Hierarchy.Version: {Version}");
                sw.WriteLine($"		Hierarchy.Platform: {Platform}");
                sw.WriteLine($"		Hierarchy.SerializeTypeTrees: {SerializeTypeTrees}");
                sw.WriteLine($"		Hierarchy.Unknown: {Unknown}");
                sw.WriteLine($"		Hierarchy.Types: {Types.Length}");
                if (Types.Length > 0)
                {
                    sw.WriteLine("			{0,-18}, {1}, {2}, {3,-32}, {4,-32}, {5}",
                                 "ClassId", "IsStrippedType", "ScriptID", "ScriptHash", "TypeHash", "NodeCount");
                }
                foreach (var type in Types)
                {
                    var ClassID        = Util.GetMember <ClassIDType>(type, "ClassID");
                    var IsStrippedType = Util.GetMember <bool>(type, "IsStrippedType");
                    var ScriptID       = Util.GetMember <short>(type, "ScriptID");
                    var Tree           = Util.GetMember <object>(type, "Tree");
                    var ScriptHash     = Util.GetMember <Hash128>(type, "ScriptHash");
                    var TypeHash       = Util.GetMember <Hash128>(type, "TypeHash");
                    var nodeCount      = Tree == null ? "Null" : Util.GetMember <IList>(Tree, "Nodes").Count.ToString();
                    sw.WriteLine("			{0,-18}, {1,14}, {2,8}, {3}, {4}, {5}",
                                 ClassID.ToString(), IsStrippedType, ScriptID, HashToString(ScriptHash), HashToString(TypeHash), nodeCount);
                }
            }
            else
            {
                sw.WriteLine($"	File.Metadata.Hierarchy: Null");
            }
            sw.WriteLine($"	File.Metadata.Entries: {container.Metadata.Entries.Length}");

            var factory = new AssetFactory();

            foreach (var entry in container.Metadata.Entries)
            {
                AssetInfo assetInfo = new AssetInfo(container, entry.PathID, entry.ClassID);
                Object    asset     = factory.CreateAsset(assetInfo);
                if (asset == null)
                {
                    sw.WriteLine($"	  Unimplemented Asset: {entry.ClassID}, {entry.ScriptID}, {entry.TypeID}, {entry.PathID}, {entry.IsStripped}");
                }
            }
        }
Пример #18
0
 public AssetConverter(AssetFactory assetFactory, IServiceProvider services)
     : base(services, typeof(TAsset) != typeof(Asset))
 {
     _assetFactory = assetFactory;
 }
Пример #19
0
        /// <summary>
        /// Method to upload the media/asset files for a building or apartment
        /// Building assets are images
        /// Apartment assets are files (excel,csv,pdf, etc)
        /// </summary>
        /// <param name="files"></param>
        /// <param name="buildingId"></param>
        /// <param name="parentId"></param>
        /// <param name="apartmentId"></param>
        /// <returns></returns>
        public IList <IMedia> UploadMediaFiles(HttpFileCollectionBase files, int buildingId, int parentId, int apartmentId = -1)
        {
            IList <IMedia> media = new List <IMedia>();

            foreach (var fileKey in files)
            {
                var fileContent = files[fileKey.ToString()];
                if (fileContent != null && fileContent.ContentLength > 0)
                {
                    fileContent.InputStream.Position = 0;
                    var    binaryReader = new BinaryReader(fileContent.InputStream);
                    byte[] binData      = binaryReader.ReadBytes(fileContent.ContentLength);
                    var    fileName     = Path.GetFileName(fileContent.FileName);

                    var mediaType = "File"; //default

                    //check if supported
                    var isImageSupported = IMAGEFORMATS_SUPPORTED.Any(x => fileContent.FileName.EndsWith(x, System.StringComparison.OrdinalIgnoreCase));
                    var isFileSupported  = FILEFORMATS_SUPPORTED.Any(x => fileContent.FileName.EndsWith(x, System.StringComparison.OrdinalIgnoreCase));

                    if (isImageSupported)
                    {
                        mediaType = "Image";
                    }

                    if (isFileSupported)
                    {
                        mediaType = "File";
                    }

                    if (!isImageSupported && !isFileSupported)
                    {
                        continue;
                    }

                    if (binData != null && binData.Length > 0)
                    {
                        var propertyTypeAlias = "umbracoFile";
                        var newMedia          = _mediaService.CreateMedia(fileName, parentId, mediaType);
                        if (newMedia != null)
                        {
                            newMedia.SetValue(propertyTypeAlias, fileContent);
                            _mediaService.Save(newMedia);

                            //add to repository to building asset by default
                            if (apartmentId <= 0)
                            {
                                _buildingAssetRepo.Insert((BuildingAsset)AssetFactory.CreateAsset(AssetType.Building, buildingId, newMedia.Id, AssetMediaType.Image));
                            }
                            else
                            {
                                _apartmentAssetRepo.Insert((ApartmentAsset)AssetFactory.CreateAsset(AssetType.Apartment, apartmentId, newMedia.Id, AssetMediaType.File));
                            }

                            //add newly added media to list
                            media.Add(newMedia);
                        }
                    }
                }
            }
            return(media);
        }
        public static async Task AssertTestGeneration(string resourceName, TestFrameworkTypes testFrameworkTypes, MockingFrameworkType mockingFrameworkType)
        {
            var classAsText = TestClasses.ResourceManager.GetString(resourceName, TestClasses.Culture);

            var tree = CSharpSyntaxTree.ParseText(classAsText, new CSharpParseOptions(LanguageVersion.Latest));

            var assemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location);
            var references   = new List <MetadataReference>
            {
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(INotifyPropertyChanged).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Expression).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Brush).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Stream).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Form).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(SqlConnection).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Window).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(UIElement).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(DependencyObject).Assembly.Location),
                MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.dll")),
                MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Core.dll")),
                MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Runtime.dll")),
                MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Threading.Tasks.dll")),
            };

            references.AddRange(GetReferences(mockingFrameworkType));
            references.AddRange(GetReferences(testFrameworkTypes));

            var compilation = CSharpCompilation.Create(
                "MyTest",
                syntaxTrees: new[] { tree },
                references: references);

            var semanticModel = compilation.GetSemanticModel(tree);

            IUnitTestGeneratorOptions options = Substitute.For <IUnitTestGeneratorOptions>();

            options.GenerationOptions.FrameworkType.Returns(testFrameworkTypes);
            options.GenerationOptions.MockingFrameworkType.Returns(mockingFrameworkType);
            options.GenerationOptions.TestFileNaming.Returns("{0}Tests");
            options.GenerationOptions.TestTypeNaming.Returns("{0}Tests");
            options.GenerationOptions.TestProjectNaming.Returns("{0}.Tests");
            var core = await CoreGenerator.Generate(semanticModel, null, null, false, options, x => "Tests").ConfigureAwait(true);

            Assert.IsNotNull(core);
            Console.WriteLine(core.FileContent);
            Assert.IsNotNull(core.FileContent);

            var generatedTree = CSharpSyntaxTree.ParseText(core.FileContent, new CSharpParseOptions(LanguageVersion.Latest));

            var syntaxTrees = new List <SyntaxTree> {
                tree, generatedTree
            };

            if (core.RequiredAssets.Any(x => x == TargetAsset.PropertyTester))
            {
                var testerAsset    = AssetFactory.Create(TargetAsset.PropertyTester);
                var propertyTester = testerAsset.Content("Tests", testFrameworkTypes);
                syntaxTrees.Add(CSharpSyntaxTree.ParseText(propertyTester, new CSharpParseOptions(LanguageVersion.Latest)));
            }

            var validateCompilation = CSharpCompilation.Create(
                "MyTest",
                syntaxTrees: syntaxTrees,
                references: references,
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            var stream       = new MemoryStream();
            var result       = validateCompilation.Emit(stream);
            var streamLength = stream.Length;

            stream.Dispose();

            Assert.IsTrue(result.Success, string.Join(",", result.Diagnostics.Select(x => x.Location.GetLineSpan().StartLinePosition.Line + ": " + x.GetMessage())));
            Assert.That(streamLength, Is.GreaterThan(0));
        }
Пример #21
0
        public void Construct_ValidInput(string targetDirectory, IEnumerable <Asset> expected)
        {
            IEnumerable <Asset> actual = AssetFactory.Construct(targetDirectory);

            Assert.That(actual, Is.EqualTo(expected));
        }
Пример #22
0
 public void setFactory <DATA, ASSET>(AssetType type, AssetFactory <DATA, ASSET> factory)
     where DATA : IAssetData
     where ASSET : IAsset <DATA>
 {
     //factory("",
 }
Пример #23
0
 public DungeonBuilder(AssetFactory factory, Transform parent)
 {
     this.factory = factory;
     this.parent  = parent;
     algo         = new NaiveAlgorithm();
 }
Пример #24
0
        /// <summary>
        /// Gets details of a historic alarm
        /// </summary>
        private AlarmModel GetHistoricalAlarmDetails(int customerID, HistoricalAlarm alarm)
        {
            var alarmModel = new AlarmModel();

            if (alarm != null)
            {
                //Get the meter map for this alarm
                var metermap =
                    PemsEntities.MeterMaps.FirstOrDefault(x => x.Areaid == alarm.AreaID && x.Customerid == alarm.CustomerID && x.MeterId == alarm.MeterId);
                var alarmEventCode = PemsEntities.EventCodes.FirstOrDefault(x => x.EventCode1 == alarm.EventCode && x.CustomerID == customerID);
                //Asset / Location Information
                alarmModel.Latitude     = alarm.Meter == null ? 0 : alarm.Meter.Latitude ?? 0;
                alarmModel.Longitude    = alarm.Meter == null ? 0 : alarm.Meter.Longitude ?? 0;
                alarmModel.MeterGroupId = alarm.Meter == null ? 0 : alarm.Meter.MeterGroup ?? 0;
                alarmModel.AssetClass   = alarm.Meter == null ? AssetClass.Unknown : AssetFactory.GetAssetClass(alarm.Meter.MeterGroup);
                alarmModel.AssetType    = alarm.Meter == null ? string.Empty : (new AssetFactory(ConnectionStringName)).GetAssetTypeDescription(alarm.Meter.MeterGroup, customerID);

                OperationalStatu opStatus = null;
                //name ans state are based on class
                if (alarmModel.AssetClass == AssetClass.Sensor)
                {
                    alarmModel.AssetName         = PemsEntities.Sensors.FirstOrDefault(x => x.SensorID == metermap.SensorID) == null ? "" : PemsEntities.Sensors.FirstOrDefault(x => x.SensorID == metermap.SensorID).SensorName;
                    opStatus                     = PemsEntities.OperationalStatus.FirstOrDefault(x => x.OperationalStatusId == metermap.Sensor.OperationalStatus);
                    alarmModel.OperationalStatus = opStatus == null ? "" : opStatus.OperationalStatusDesc ?? "";
                }
                else if (alarmModel.AssetClass == AssetClass.Gateway)
                {
                    alarmModel.AssetName         = PemsEntities.Gateways.FirstOrDefault(x => x.GateWayID == metermap.GatewayID) == null ? "" : PemsEntities.Gateways.FirstOrDefault(x => x.GateWayID == metermap.GatewayID).Description;
                    opStatus                     = PemsEntities.OperationalStatus.FirstOrDefault(x => x.OperationalStatusId == metermap.Gateway.OperationalStatus);
                    alarmModel.OperationalStatus = opStatus == null ? "" : opStatus.OperationalStatusDesc ?? "";
                }
                //everything else falls under meter for now
                else
                {
                    alarmModel.AssetName         = alarm.Meter == null ? "" : alarm.Meter.MeterName;
                    opStatus                     = PemsEntities.OperationalStatus.FirstOrDefault(x => x.OperationalStatusId == metermap.Meter.OperationalStatusID);
                    alarmModel.OperationalStatus = opStatus == null ? "" : opStatus.OperationalStatusDesc ?? "";
                }
                alarmModel.AssetID      = alarm.Meter.MeterId;
                alarmModel.Area         = PemsEntities.Areas.FirstOrDefault(x => x.CustomerID == metermap.Customerid && x.AreaID == metermap.AreaId2) == null ? "" : PemsEntities.Areas.FirstOrDefault(x => x.AreaID == metermap.AreaId2 && x.CustomerID == metermap.Customerid).AreaName; //alarm.Meter.Area.AreaName;
                alarmModel.AreaId       = metermap.AreaId2;                                                                                                                                                                                                                                // alarm.Meter.Area.AreaID;
                alarmModel.Zone         = metermap.Zone == null ? string.Empty : PemsEntities.Zones.FirstOrDefault(x => x.ZoneId == metermap.ZoneId && metermap.Customerid == x.customerID) == null ? string.Empty : PemsEntities.Zones.FirstOrDefault(x => x.ZoneId == metermap.ZoneId && metermap.Customerid == x.customerID).ZoneName;
                alarmModel.Suburb       = metermap == null ? string.Empty : metermap.CustomGroup11 == null ? string.Empty : metermap.CustomGroup11.DisplayName;
                alarmModel.Street       = alarm.Meter.Location;
                alarmModel.BaysAffected = alarm.Meter.MaxBaysEnabled ?? 0;

                //Alarm / Meter information
                alarmModel.AlarmID                = alarm.AlarmUID ?? 0;
                alarmModel.AlarmCode              = alarmEventCode == null ? 0 : alarmEventCode.EventCode1;
                alarmModel.AlarmDesription        = alarmEventCode == null ? string.Empty : alarmEventCode.EventDescAbbrev;
                alarmModel.AlarmDesriptionVerbose = alarmEventCode == null ? string.Empty : alarmEventCode.EventDescVerbose;
                alarmModel.ServiceTargetTime      = alarm.SLADue ?? DateTime.MinValue;
                alarmModel.AlarmStatus            = "Closed";
                var alarmStatus = PemsEntities.AlarmStatus.FirstOrDefault(x => x.AlarmStatusId == 3);
                if (alarmStatus != null)
                {
                    alarmModel.AlarmStatus = alarmStatus.AlarmStatusDesc;
                }
                alarmModel.TimeNotified = alarm.TimeOfNotification;
                alarmModel.TimeCleared  = alarm.TimeOfClearance ?? DateTime.MinValue;

                //SLA Values
                //calculation for historical alarm time remaining: Service Target time - Time Cleared. NOTE, this is different for active alarms. using time cleared instead of current local time
                //set the defaults
                alarmModel.TimeRemainingTillTargetTime        = 0;
                alarmModel.TimeRemainingTillTargetTimeDisplay = Constants.TimeFormats.timeFormatToDisplay_HHH_MM;

                if (alarm.SLADue.HasValue)
                {
                    if (!String.IsNullOrEmpty(alarm.SLADue.Value.ToString()))
                    {
                        TimeSpan diffTime = (alarm.SLADue.Value - alarm.TimeOfClearance.Value);
                        if (diffTime.TotalHours > 0)
                        {
                            alarmModel.TimeRemainingTillTargetTimeDisplay = FormatHelper.FormatTimeFromMinutes(Math.Round(diffTime.TotalMinutes, 0), (int)PEMSEnums.PEMSEnumsTimeFormats.timeFormat_HHH_MM);
                        }
                    }
                }
                else
                {
                    alarmModel.TimeRemainingTillTargetTimeDisplay = FormatHelper.FormatTimeFromMinutes(0, (int)PEMSEnums.PEMSEnumsTimeFormats.timeFormat_HHH_MM);
                }

                //Target Service Designation - note, we are NOT regenerating this, just using what is assigned to the
                alarmModel.ServiceDesignation   = "N/A";
                alarmModel.ServiceDesignationId = -1;
                if (alarm.TargetServiceDesignation1 != null)
                {
                    alarmModel.ServiceDesignation   = alarm.TargetServiceDesignation1.TargetServiceDesignationDesc;
                    alarmModel.ServiceDesignationId = alarm.TargetServiceDesignation1.TargetServiceDesignationId;
                }

                alarmModel.TimeOccured = alarm.TimeOfOccurrance;
                AddTimeTypes(alarm, alarmModel);
                alarmModel.TimeType1     = alarm.TimeType1 ?? 0;
                alarmModel.TimeType2     = alarm.TimeType2 ?? 0;
                alarmModel.TimeType3     = alarm.TimeType3 ?? 0;
                alarmModel.TimeType4     = alarm.TimeType4 ?? 0;
                alarmModel.TimeType5     = alarm.TimeType5 ?? 0;
                alarmModel.AlarmSource   = PemsEntities.EventSources.FirstOrDefault(x => x.EventSourceCode == alarm.EventSource).EventSourceDesc;
                alarmModel.AlarmSeverity = alarmEventCode == null ? string.Empty : alarmEventCode.AlarmTier1 == null ? string.Empty : alarmEventCode.AlarmTier1.TierDesc;
                alarmModel.EntryNotes    = alarm.Notes;
                alarmModel.CustomerId    = customerID;
                //Closure Information
                var maintenanceEvent = PemsEntities.SFMeterMaintenanceEvents.FirstOrDefault(
                    x => x.AreaId == alarm.Meter.AreaID && x.CustomerId == customerID && x.MeterId == alarm.MeterId && x.WorkOrderID == alarm.WorkOrderId);
                alarmModel.ResolutionCode     = maintenanceEvent == null ? 1 : maintenanceEvent.MaintenanceCode;
                alarmModel.ResolutionCodeDesc = maintenanceEvent == null
                                                    ? ""
                                                    : PemsEntities.MaintenanceCodes.FirstOrDefault(x => x.MaintenanceCode1 == maintenanceEvent.MaintenanceCode) == null
                                                          ? ""
                                                          : PemsEntities.MaintenanceCodes.FirstOrDefault(x => x.MaintenanceCode1 == maintenanceEvent.MaintenanceCode).Description;

                //RJH: Set ClosureNotification = TimeCleared if no maintenance event.
                alarmModel.ClosureNotification = maintenanceEvent == null ? alarmModel.TimeCleared : maintenanceEvent.EventDateTime;

                alarmModel.TechnicianID = maintenanceEvent == null ? -1 : maintenanceEvent.TechnicianId;
                if (alarmModel.TechnicianID > 0)
                {
                    alarmModel.TechnicianName =
                        PemsEntities.TechnicianDetails.FirstOrDefault(x => x.TechnicianId == alarmModel.TechnicianID) ==
                        null
                            ? ""
                            : PemsEntities.TechnicianDetails.FirstOrDefault(
                            x => x.TechnicianId == alarmModel.TechnicianID).Name;
                }
                alarmModel.ClosureNotes = alarm.ClosureNote;
                alarmModel.ClosedBy     = alarm.ClearedByUserId ?? 0;
                if (alarm.ClearedByUserId != null)
                {
                    var user = (new UserFactory()).GetUserById(alarm.ClearedByUserId.Value);
                    if (user != null)
                    {
                        alarmModel.ClosedByName = user.Username;
                    }
                }
                alarmModel.IsClosed = true;
            }

            alarmModel.ResolutionCodes = GetResolutionCodes();
            alarmModel.TechnicianIDs   = GetAlarmTechnicians();

            return(alarmModel);
        }