private static Tuple<string, YamlNode> GetUpdateAttribute(JProperty prop) { var propValueType = prop.Value.Type; var value = string.Empty; if (propValueType == JTokenType.Object || propValueType == JTokenType.Array) { if (propValueType == JTokenType.Array) { var nodes = new YamlSequenceNode(); foreach(var item in prop.Value as JArray) { var asset = new Asset(item as dynamic); var yamlNode = GetNodes(asset); nodes.Add(yamlNode); } return new Tuple<string, YamlNode>(prop.Name, nodes); } return new Tuple<string, YamlNode>(prop.Name, new YamlScalarNode(string.Empty)); } else { value = (prop.Value as JValue).Value.ToString(); return new Tuple<string, YamlNode>(prop.Name, new YamlScalarNode(value)); } }
public static YamlNode GetNodes(Asset source) { var root = new YamlMappingNode(); var assetType = source.AssetType; root.Add("asset", assetType); JObject obj = JObject.FromObject(source.GetChangesDto()); obj.Remove("AssetType"); YamlMappingNode attributes = new YamlMappingNode(); var tuples = (from prop in ( from token in JToken.FromObject(obj) where token.Type == JTokenType.Property select token as JProperty ) select GetUpdateAttribute(prop) ); foreach (var tuple in tuples) { attributes.Add(tuple.Item1, tuple.Item2); } root.Add("attributes", attributes); return root; }
public override void runAssetFile(Asset asset) { foreach (var obj in asset.ObjectInfos) { ulong oldSize = 0; mSizeDic.TryGetValue(obj.classID, out oldSize); mSizeDic[obj.classID] = oldSize + obj.length; totalSize += obj.length; var typeTree = typeTreeDatabase.GetType(asset.AssetVersion, obj.classID); if (typeTree != null) { try { SerializeObject sobj = new SerializeObject(typeTree, obj.data); var property = sobj.FindProperty("m_Resource.m_Size"); if (property != null) { ulong resSize = (ulong)property.Value; totalSize += resSize; mSizeDic[obj.classID] += resSize; } } catch { Debug.LogError("Can't Create SerializeObject.TypeVerion:{0},TypeClassID:{1},TypeName:{2}", typeTree.version, obj.classID, typeTree.type); } } } }
// Register is always used for someone not in the database, only first time User or first time Asset use this method public async Task<AccountResult> RegisterUser(RegistrationModelBase model) { UserProfile profile; User user = null; switch (model.Type) { case IdentityTypes.USER: profile = new UserProfile(model as UserRegistrationModel); user = new User(model as UserRegistrationModel, profile); break; case IdentityTypes.BIKE_MESSENGER: case IdentityTypes.CNG_DRIVER: profile = new AssetProfile(model as AssetRegistrationModel); user = new Asset(model as AssetRegistrationModel, profile as AssetProfile); break; case IdentityTypes.ENTERPRISE: var enterpriseProfile = new EnterpriseUserProfile(model as EnterpriseUserRegistrationModel); user = new EnterpriseUser(model as EnterpriseUserRegistrationModel, enterpriseProfile); break; } var identityResult = await accountManager.CreateAsync(user, model.Password); var creationResult = new AccountResult(identityResult, user); return creationResult; }
public static void AddDefaultExtractSettingsToAsset(Asset asset, string siteRootParentAssetId) { // Get starting path for all other paths var parentAssetId = int.Parse(siteRootParentAssetId); var parentAsset = Asset.LoadDirect(parentAssetId); var basePath = parentAsset.AssetPath.ToString(); // Get paths needed by the site builder tool var pro_library_folder = Asset.LoadDirect(basePath + "/Project/Library").GetLink(LinkType.Internal); if (string.IsNullOrEmpty(pro_library_folder)) pro_library_folder = Asset.LoadDirect(basePath + "/Project/Client Library").GetLink(LinkType.Internal); var pro_model_folder = Asset.LoadDirect(basePath + "/Project/Models").GetLink(LinkType.Internal); var pro_nav_wrap_location = Asset.LoadDirect(basePath + "/Project/Templates/MasterPage").GetLink(LinkType.Internal); var pro_project_folder = Asset.LoadDirect(basePath + "/Project").GetLink(LinkType.Internal); var pro_site_root_folder = Asset.LoadDirect(basePath + "/Site Root").GetLink(LinkType.Internal); var pro_template_folder = Asset.LoadDirect(basePath + "/Project/Templates").GetLink(LinkType.Internal); var fields = new Dictionary<string, string>(); fields.Add("export_site_option", "yes"); fields.Add("extract_type", "project"); fields.Add("include_binaries", "true"); fields.Add("include_contents", "true"); fields.Add("include_wrappers", "true"); fields.Add("pro_library_folder", pro_library_folder); fields.Add("pro_model_folder", pro_model_folder); fields.Add("pro_nav_wrap_location", pro_nav_wrap_location); fields.Add("pro_project_folder", pro_project_folder); fields.Add("pro_site_root_folder", pro_site_root_folder); fields.Add("pro_template_folder", pro_template_folder); asset.SaveContent(fields); }
public Date(Entry entry) { StartDate = entry.Date.ToString("yyyy,M,d"); Headline = entry.Title; Text = entry.Text; Asset = new Asset(entry.Asset); }
public AssetProperties(Asset asset) { foreach (AssetValue val in asset) { //is this one supposed to be different from the others? "DisplayName vs Name" if (val.DisplayName.Equals("Color") && val.ValueType == AssetValueTypeEnum.kAssetValueTypeColor) { color = ((ColorAssetValue) val).Value; } /* //I am unable to find any reference to gloss in the API, and I've found the value changes from material to material else if (val.Name.Equals("generic_glossiness") && val.ValueType == AssetValueTypeEnum.kAssetValueTypeFloat) { generic_glossiness = ((FloatAssetValue)val).Value; } */ //opacity is a double else if (val.DisplayName.Equals("Transparency") && val.ValueType == AssetValueTypeEnum.kAssetValueTypeFloat) { transparency = ((FloatAssetValue) val).Value; } else if (val.DisplayName.Equals("Translucency") && val.ValueType == AssetValueTypeEnum.kAssetValueTypeFloat) { translucency = ((FloatAssetValue) val).Value; } else if (val.ValueType == AssetValueTypeEnum.kAssetValueTextureType) { AssetTexture tex = ((TextureAssetValue) val).Value; } else if (val.Name.Contains("reflectivity") && val.Name.Contains("0deg") && val.ValueType == AssetValueTypeEnum.kAssetValueTypeFloat) { specular = ((FloatAssetValue) val).Value; } } }
public void Update(Asset entity, bool commit) { if (entity == null) throw new ArgumentNullException("entity"); _db.SaveChanges(); }
public void Asset_Received(AssetDownload trans, Asset asset) { var Running = ExportCommand.Exporting; var item = SourceItem; UUID itemID = item.UUID; //if (trans.AssetID != item.AssetUUID) return; if (!trans.Success) { Error = "" + trans.Status; if (waiting != null) waiting.Set(); lock (Running.TaskAssetWaiting) { ExportTaskAsset exportTaskAsset; if (!Running.CompletedTaskItem.Contains(itemID)) { Request(); return; } } } Running.Assets_OnReceived(trans, asset); //AddRelated(item.AssetUUID, item.AssetType); Running.TaskItemComplete(O.ID, itemID, asset.AssetID, asset.AssetType); if (waiting != null) waiting.Set(); }
public bool AddReference(Asset asset) { if (asset == null) throw new ArgumentNullException("asset"); //if (string.IsNullOrEmpty(asset)) // throw new ArgumentException("Argument cannot be null or empty.", "asset"); //AssetIdentifier aid = AssetIdentifier.Parse(asset); //Debug.Assert(aid.ToString().Equals(asset, StringComparison.Ordinal), // "AssetIdentifier '{0}' failed to roundtrip.", asset); //if (aid.AssetId[aid.AssetId.Length - 1] == ']') // aid = new AssetIdentifier(aid.AssetId.Substring(0, aid.AssetId.LastIndexOf('[')), // aid.Version); //object resolve = this.AssetResolver.Resolve(aid); //Debug.Assert(resolve != null); //Debug.Assert(!string.IsNullOrWhiteSpace(aid.AssetId)); if (this._references.Add(asset)) { TraceSources.GeneratorSource.TraceEvent(TraceEventType.Verbose, 1, "Reference: {0}", asset.Id); return true; } return false; }
/// <summary> /// Create asset description from asset. /// </summary> /// <param name="asset"></param> public AssetDesc ( Asset asset ) { Path = asset.AssetPath; Type = asset.GetType().Name; Parameters = new List<KeyValuePair<string,string>>(); foreach ( var prop in asset.GetType().GetProperties() ) { if (!prop.CanWrite || !prop.CanRead) { continue; } if (prop.IsList()) { var list = prop.GetList( asset ); var type = prop.GetListElementType(); foreach ( var element in list ) { var conv = TypeDescriptor.GetConverter( type ); var value = conv.ConvertToInvariantString( element ); Parameters.Add( new KeyValuePair<string,string>(prop.Name, value) ); } } else { var conv = TypeDescriptor.GetConverter( prop.PropertyType ); var value = conv.ConvertToInvariantString( prop.GetValue( asset ) ); Parameters.Add( new KeyValuePair<string,string>(prop.Name, value) ); } } }
public string outputBase(Asset asset, OutputContext context, string name, string index = "") { StringBuilder sbContent = new StringBuilder(); sbContent.Append(componentMarkup); String markup = ComponentLibraryHelper.updateMarkupForPreviewPublish(context, sbContent.ToString()); return markup; }
public static Dictionary<UFile, ObjectId> GetAllHashes(Asset asset) { var hashes = TryGet(asset, AbsoluteSourceHashesKey); var result = new Dictionary<UFile, ObjectId>(); hashes?.ForEach(x => result.Add(x.Key, x.Value)); return result; }
public Asset CreateAsset(Asset info) { try { string sqlCommand = @"INSERT INTO ""ASSET"" (""ASSETNO"",""ASSETCATEGORYID"",""ASSETNAME"",""STORAGE"",""STATE"",""DEPRECIATIONYEAR"",""UNITPRICE"",""BRAND"",""MANAGEMODE"",""FINANCECATEGORY"",""SUPPLIERID"",""PURCHASEDATE"",""EXPIREDDATE"",""ASSETSPECIFICATION"",""STORAGEFLAG"",""SUBCOMPANY"",""CONTRACTID"",""CONTRACTDETAILID"") VALUES (:Assetno,:Assetcategoryid,:Assetname,:Storage,:State,:Depreciationyear,:Unitprice,:Brand,:Managemode,:Financecategory,:Supplierid,:Purchasedate,:Expireddate,:Assetspecification,:Storageflag,:Subcompany,:Contractid,:Contractdetailid)"; this.Database.AddInParameter(":Assetno", info.Assetno);//DBType:VARCHAR2 this.Database.AddInParameter(":Assetcategoryid", info.Assetcategoryid);//DBType:VARCHAR2 this.Database.AddInParameter(":Assetname", info.Assetname);//DBType:NVARCHAR2 this.Database.AddInParameter(":Storage", info.Storage);//DBType:NVARCHAR2 this.Database.AddInParameter(":State", info.State);//DBType:NUMBER this.Database.AddInParameter(":Depreciationyear", info.Depreciationyear);//DBType:NUMBER this.Database.AddInParameter(":Unitprice", info.Unitprice);//DBType:NUMBER this.Database.AddInParameter(":Brand", info.Brand);//DBType:NVARCHAR2 this.Database.AddInParameter(":Managemode", info.Managemode);//DBType:NUMBER this.Database.AddInParameter(":Financecategory", info.Financecategory);//DBType:NUMBER this.Database.AddInParameter(":Supplierid", info.Supplierid);//DBType:NVARCHAR2 this.Database.AddInParameter(":Purchasedate", info.Purchasedate);//DBType:DATE this.Database.AddInParameter(":Expireddate", info.Expireddate);//DBType:DATE this.Database.AddInParameter(":Assetspecification", info.Assetspecification);//DBType:NVARCHAR2 this.Database.AddInParameter(":Storageflag", info.Storageflag);//DBType:NVARCHAR2 this.Database.AddInParameter(":Subcompany", info.Subcompany);//DBType:VARCHAR2 this.Database.AddInParameter(":Contractid", info.Contractid);//DBType:VARCHAR2 this.Database.AddInParameter(":Contractdetailid", info.Contractdetailid);//DBType:VARCHAR2 this.Database.ExecuteNonQuery(sqlCommand); } finally { this.Database.ClearParameter(); } return info; }
public Date(Entry entry) { startDate = entry.Date.ToString("yyyy,M,d"); headline = entry.Title; text = entry.Text; asset = new Asset(entry.Asset); }
public Sorter(Dictionary<string, Asset> assets) { List<Asset> list = new List<Asset>(); foreach (Asset asset in assets.Values) { foreach (string provides in asset.Provides) { var newAsset = new Asset() { Name = asset.Path }; newAsset.Provides.Add(provides); newAsset.Requires.AddRange(asset.Requires); list.Add(newAsset); } } this.GenericSorter(list); foreach (int i in this.result) { if (!Sorted.Contains(list[i].Name)) { Sorted.Add(list[i].Name); } } }
public void Add(Asset asset) { AssertAssetIsValid(asset); var assetItem = listService.CreateItem(); unitOfWork.AddInsert(asset, assetItem); }
public Asset GetParent(Asset asset) { Asset ret; switch (asset.Type) { case AssetType.Namespace: NamespaceInfo nsInfo = (NamespaceInfo)asset.Target; ret = ReflectionServices.GetAsset(nsInfo.Assembly); break; case AssetType.Type: Type type = (Type)asset.Target; if (type.IsNested) ret = ReflectionServices.GetAsset(type.DeclaringType); else ret = ReflectionServices.GetAsset(type.Assembly, type.Namespace); break; case AssetType.Method: case AssetType.Field: case AssetType.Event: case AssetType.Property: Type parent = ((MemberInfo)asset.Target).ReflectedType; ret = ReflectionServices.GetAsset(parent); break; case AssetType.Assembly: ret = null; break; default: throw new ArgumentException(string.Format("Cannot find parent of asset of type {0}", asset.Type)); } return ret; }
public void Save(Asset asset) { if(asset.IsValid()) { AssetRepo.Save(asset); } }
void onAsset(AssetDownload transfer,Asset asset) { Logger.Log("Asset retrieved id "+asset.AssetID.ToString(),Helpers.LogLevel.Debug); Logger.Log("target_asset"+this.target_asset.ToString(),Helpers.LogLevel.Debug); if(asset.AssetID!=target_asset) return; new TryGetImage(this.image,asset.AssetID,false); }
public static IEnumerable<Asset> GetAssetHierarchy(this IAssetExplorer assetExplorer, Asset asset) { do { yield return asset; asset = assetExplorer.GetParent(asset); } while (asset != null); }
public void Remove(Asset entity, bool commit) { if (entity == null) throw new ArgumentNullException("entity"); _entities.Remove(entity); _db.SaveChanges(); }
public Dictionary<UFile, bool> GetSourceFiles(Asset asset) { sourceFiles = new Dictionary<UFile, bool>(); Visit(asset); var result = sourceFiles; sourceFiles = null; return result; }
public AssetsModel(Asset asset) { this.Id = asset.Id; this.Name = asset.Name; this.Description = asset.Description; this.Cost = asset.Cost; this.AddedByUser = asset.AddedByUser; }
public void ValidateSingleFieldByAttribute() { Asset asset = new Asset(AssetType(DefectTypeName)); IAttributeDefinition defectNameDef = asset.AssetType.GetAttributeDefinition(TitleAttributeName); Assert.IsFalse(validator.Validate(asset, defectNameDef)); asset.LoadAttributeValue(defectNameDef, "Valid defect name"); Assert.IsTrue(validator.Validate(asset, defectNameDef)); }
public void Remove(Asset asset) { if (asset == null) throw new ArgumentNullException("asset"); var assetItem = GetAssetItemBySerialNumber(asset.SerialNumber); if (assetItem != null) assetItem.Delete(); }
public void AddAsset(string xnaName, AssetType xnaType) { Asset a = new Asset(); a.xnaName = xnaName; a.assetType = xnaType; a.id = _asset_list.Count; _asset_list.Add(a); }
public void LoadRequiredFields() { Asset asset = new Asset(AssetType(DefectTypeName)); IAttributeDefinition defectNameDef = asset.AssetType.GetAttributeDefinition(TitleAttributeName); Assert.IsTrue(validator.IsRequired(defectNameDef)); IAttributeDefinition defectParentDef = asset.AssetType.GetAttributeDefinition(ParentAttributeName); Assert.IsFalse(validator.IsRequired(defectParentDef)); }
public Dictionary<MemberPath, UFile> GetSourceMembers(Asset asset) { sourceMembers = new Dictionary<MemberPath, UFile>(); Visit(asset); var result = sourceMembers; sourceMembers = null; return result; }
public void Add(Asset asset) { if (asset == null) throw new ArgumentNullException("asset"); var assetItem = listService.CreateItem(); assetItem.Update(asset); }
public ActionResult Edit(ContextHelpRefDataViewModel model, string button) { if (model != null && ModelState.IsValid) { if (button.ToLower().Equals("update")) { var help = _contextHelpRefDataService.GetById(model.Id); help.Title = model.Title; help.HelpText = model.HelpText; // Update Help if (model.HelpVideoFile != null) { var folder = SettingsHelper.HelpVideoFileLocation; var fullPath = string.Empty; try { // If the folder doesn't exist then create if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } var originalFullFileName = model.HelpVideoFile.FileName; var fileName = Guid.NewGuid(); var fileExtension = Path.GetExtension(originalFullFileName); fullPath = Path.Combine(folder, fileName + fileExtension); model.HelpVideoFile.SaveAs(fullPath); var asset = new Asset { OriginalFileName = Path.GetFileNameWithoutExtension(originalFullFileName), FileName = fileName.ToString(), FileExtension = fileExtension, FullPath = fullPath, MimeType = MimeMapping.GetMimeMapping(fullPath), ContextHelpRefDatas = new List <ContextHelpRefData> { help } }; _assetRepository.Insert(asset); help.Asset = asset; _contextHelpRefDataService.Update(help); } catch (Exception) { // Tidy up the file if it has not been deleted if (System.IO.File.Exists(fullPath)) { System.IO.File.Delete(fullPath); } throw; } } else { _contextHelpRefDataService.Update(help); } } } return(RedirectToAction("Index", "Help", new { helpKey = model?.Key ?? "homepage" })); }
// GET: Assets/Edit/5 public ActionResult Edit(Guid?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Asset asset = db.Assets.Include("Address").Include("Appliances").SingleOrDefault(a => a.ID == id); if (asset == null) { return(HttpNotFound()); } List <Appliance> availableAppliances = db.Appliances.Where(a => a.BelongsToAsset == null).ToList(); var selectableAppliances = new Dictionary <string, List <SelectListItem> >(); var selectListAppliances = new Dictionary <string, SelectList>(); // create selectableAppliances from ApplianceType enum foreach (ApplianceType applianceType in Enum.GetValues(typeof(ApplianceType))) { List <SelectListItem> newList = new List <SelectListItem>(); selectableAppliances.Add(applianceType.ToString(), newList); newList.Add( new SelectListItem() { Text = "Nothing", Value = NULL } ); } // add currently associated appliances to lists foreach (Appliance a in asset.Appliances) { selectableAppliances[a.Type.ToString()].Add( new SelectListItem() { Text = a.Name, Value = a.ID.ToString() } ); } // populate selectableAppliances foreach (Appliance a in availableAppliances) { List <SelectListItem> currentList; if (selectableAppliances.TryGetValue(a.Type.ToString(), out currentList)) { currentList.Add( new SelectListItem() { Text = a.Name.ToString(), Value = a.ID.ToString() } ); } } // populate selectListAppliances from selectableAppliances foreach (KeyValuePair <string, List <SelectListItem> > e in selectableAppliances) { Appliance def = asset.Appliances.SingleOrDefault(a => a.Type.ToString() == e.Key); string defaultValue = (def == null) ? NULL : def.ID.ToString(); selectListAppliances.Add(e.Key, new SelectList(e.Value, "Value", "Text", defaultValue)); } ViewBag.AppLists = selectListAppliances; return(View(asset)); }
/// <summary> /// Initializes Asset object /// </summary> /// <param name="asset">an Asset object</param> public RenderAppearanceDescriptor(Asset asset) { m_asset = asset; GetAssetProperties(); }
/// <summary> /// Run the sample async. /// </summary> /// <param name="config">The parm is of type ConfigWrapper. This class reads values from local configuration file.</param> /// <returns></returns> // <RunAsync> private static async Task RunAsync(ConfigWrapper config) { IAzureMediaServicesClient client = await CreateMediaServicesClientAsync(config); // Set the polling interval for long running operations to 2 seconds. // The default value is 30 seconds for the .NET client SDK client.LongRunningOperationRetryTimeout = 2; // Creating a unique suffix so that we don't have name collisions if you run the sample // multiple times without cleaning up. string uniqueness = Guid.NewGuid().ToString("N"); string jobName = $"job-{uniqueness}"; string locatorName = $"locator-{uniqueness}"; string outputAssetName = $"output-{uniqueness}"; // Ensure that you have the desired encoding Transform. This is really a one time setup operation. Transform transform = await GetOrCreateTransformAsync(client, config.ResourceGroup, config.AccountName, AdaptiveStreamingTransformName); // Output from the encoding Job must be written to an Asset, so let's create one Asset outputAsset = await CreateOutputAssetAsync(client, config.ResourceGroup, config.AccountName, outputAssetName); Job job = await SubmitJobAsync(client, config.ResourceGroup, config.AccountName, AdaptiveStreamingTransformName, outputAsset.Name, jobName); // In this demo code, we will poll for Job status // Polling is not a recommended best practice for production applications because of the latency it introduces. // Overuse of this API may trigger throttling. Developers should instead use Event Grid. job = await WaitForJobToFinishAsync(client, config.ResourceGroup, config.AccountName, AdaptiveStreamingTransformName, jobName); if (job.State == JobState.Finished) { Console.WriteLine("Job finished."); if (!Directory.Exists(OutputFolderName)) { Directory.CreateDirectory(OutputFolderName); } // Generate a new random token signing key to use RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); rng.GetBytes(TokenSigningKey); //Create the content key policy that configures how the content key is delivered to end clients // via the Key Delivery component of Azure Media Services. ContentKeyPolicy policy = await GetOrCreateContentKeyPolicyAsync(client, config.ResourceGroup, config.AccountName, ContentKeyPolicyName); StreamingLocator locator = await CreateStreamingLocatorAsync(client, config.ResourceGroup, config.AccountName, outputAsset.Name, locatorName, ContentKeyPolicyName); // We are using the ContentKeyIdentifierClaim in the ContentKeyPolicy which means that the token presented // to the Key Delivery Component must have the identifier of the content key in it. Since we didn't specify // a content key when creating the StreamingLocator, the system created a random one for us. In order to // generate our test token we must get the ContentKeyId to put in the ContentKeyIdentifierClaim claim. string keyIdentifier = locator.ContentKeys.First().Id.ToString(); string token = GetTokenAsync(Issuer, Audience, keyIdentifier, TokenSigningKey); string dashPath = await GetDASHStreamingUrlAsync(client, config.ResourceGroup, config.AccountName, locator.Name); Console.WriteLine("Copy and paste the following URL in your browser to play back the file in the Azure Media Player."); Console.WriteLine("Note, the player is set to use the AES token and the Bearer token is specified. "); Console.WriteLine(); Console.WriteLine($"https://ampdemo.azureedge.net/?url={dashPath}&aes=true&aestoken=Bearer%3D{token}"); Console.WriteLine(); } Console.WriteLine("When finished press enter to cleanup."); Console.Out.Flush(); Console.ReadLine(); Console.WriteLine("Cleaning up..."); await CleanUpAsync(client, config.ResourceGroup, config.AccountName, AdaptiveStreamingTransformName, ContentKeyPolicyName); }
/// <summary> /// Create a Pak. /// </summary> /// <param name="MapFrom"></param> /// <param name="MapTo"></param> private void CreatePak(string Name, List <string> Assets) { string CookedDir = Path.Combine(Params.BaseStageDirectory, "HTML5"); string PakPath = Path.Combine(new string[] { Path.GetDirectoryName(Params.RawProjectPath.FullName), "Binaries", "HTML5", Params.ShortProjectName, "Content", "Paks" }); if (!Directory.Exists(PakPath)) { Directory.CreateDirectory(PakPath); } Assets.Add(Name); List <string> Files = new List <string>(); foreach (string Asset in Assets) { string GameDir = "/Game/"; if (Asset.StartsWith(GameDir)) { string PathOnDiskasset = CommandUtils.CombinePaths(CookedDir, Params.ShortProjectName, "Content", Asset.Remove(0, GameDir.Length) + ".uasset"); string PathOnDiskmap = CommandUtils.CombinePaths(CookedDir, Params.ShortProjectName, "Content", Asset.Remove(0, GameDir.Length) + ".umap"); if (File.Exists(PathOnDiskmap)) { Files.Add(PathOnDiskmap); } else if (File.Exists(PathOnDiskasset)) { Files.Add(PathOnDiskasset); } else { System.Console.WriteLine(Asset + " not found, skipping !!"); } } } // we have all the files. Dictionary <string, string> UnrealPakResponseFile = new Dictionary <string, string>(); // create response file structure. foreach (string file in Files) { string MountPoint = file.Remove(0, CookedDir.Length + 1); UnrealPakResponseFile[file] = "../../../" + MountPoint; } RunUnrealPak(UnrealPakResponseFile, PakPath + "\\" + Name + ".pak", null, "", true); }
/// <summary> /// adds a fixed asset Adds an asset to the system /// </summary> /// <exception cref="Xero.NetStandard.OAuth2.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="xeroTenantId">Xero identifier for Tenant</param> /// <param name="asset">Fixed asset you are creating</param> /// <returns>Task of Asset</returns> public async System.Threading.Tasks.Task <Asset> CreateAssetAsync(string accessToken, string xeroTenantId, Asset asset) { Xero.NetStandard.OAuth2.Client.ApiResponse <Asset> localVarResponse = await CreateAssetAsyncWithHttpInfo(accessToken, xeroTenantId, asset); return(localVarResponse.Data); }
public WitnessUpdateOperation(string owner, string url, PublicKeyType blockSigningKey, ChainProperties17 props, Asset fee) { Owner = owner; Url = url; BlockSigningKey = blockSigningKey; Props = props; Fee = fee; }
protected override async Task LoadContent() { await base.LoadContent(); var image1 = new ImageElement { Source = new UIImage(Asset.Load <Texture>("BorderButtonCentered")) { Region = new Rectangle(256, 128, 512, 256), Borders = new Vector4(0.125f, 0.125f, 0.25f, 0.25f) }, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center }; var image2 = new ImageElement { Source = new UIImage(Asset.Load <Texture>("uv")) { Region = new Rectangle(0, 0, 512, 512) }, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center }; var image3 = new ImageElement { Source = new UIImage(Asset.Load <Texture>("uv")) { Region = new Rectangle(512, 0, 512, 512) }, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center }; var image4 = new ImageElement { Source = new UIImage(Asset.Load <Texture>("uv")) { Region = new Rectangle(0, 512, 512, 512) }, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center }; var image5 = new ImageElement { Source = new UIImage(Asset.Load <Texture>("uv")) { Region = new Rectangle(512, 512, 512, 512) }, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center }; stackPanel = new StackPanel { Orientation = Orientation.Vertical }; stackPanel.Children.Add(image1); stackPanel.Children.Add(image2); stackPanel.Children.Add(image3); stackPanel.Children.Add(image4); stackPanel.Children.Add(image5); UIComponent.RootElement = new ScrollViewer { Content = stackPanel }; }
public override int Import() { //SqlDataReader sdr = GetImportDataFromSproc("spGetConversationsForImport"); SqlDataReader sdr = GetImportDataFromDBTable("Conversations"); int importCount = 0; while (sdr.Read()) { try { //CHECK DATA: Conversation must have an author. if (_config.V1Configurations.MigrateUnauthoredConversationsAsAdmin == false && String.IsNullOrEmpty(sdr["Author"].ToString())) { UpdateImportStatus("Conversations", sdr["AssetOID"].ToString(), ImportStatuses.FAILED, "Conversation author attribute is required."); continue; } IAssetType assetType = _metaAPI.GetAssetType("Expression"); Asset asset = _dataAPI.New(assetType, null); IAttributeDefinition authoredAtAttribute = assetType.GetAttributeDefinition("AuthoredAt"); asset.SetAttributeValue(authoredAtAttribute, sdr["AuthoredAt"].ToString()); IAttributeDefinition contentAttribute = assetType.GetAttributeDefinition("Content"); asset.SetAttributeValue(contentAttribute, sdr["Content"].ToString()); string memberOid = string.Empty; if (_config.V1Configurations.MigrateUnauthoredConversationsAsAdmin == true && String.IsNullOrEmpty(sdr["Author"].ToString())) { memberOid = "Member:20"; } else { memberOid = GetNewAssetOIDFromDB(sdr["Author"].ToString(), "Members"); } IAttributeDefinition authorAttribute = assetType.GetAttributeDefinition("Author"); asset.SetAttributeValue(authorAttribute, memberOid); //NOTE: Only works with 13.2 or greater of VersionOne, should be able to remove for earlier versions //BelongsTo gets set for the 1st Conversation/Expression, After that, InReplyTo gets set and BelongsTo is "Related" into it automagicly string belongsTo = string.Empty; //asset.SetAttributeValue(belongsToAttribute, GetConversationBelongsTo(memberOid, sdr["Conversation"].ToString(), sdr["NewConversatiionOID"].ToString())); if (String.IsNullOrEmpty(sdr["InReplyTo"].ToString()) == true) { IAttributeDefinition belongsToAttribute = assetType.GetAttributeDefinition("BelongsTo"); belongsTo = GetConversationBelongsTo(memberOid, sdr); asset.SetAttributeValue(belongsToAttribute, belongsTo); } else { string inReplyTo = GetNewAssetOIDFromDB(sdr["InReplyTo"].ToString(), "Conversations"); IAttributeDefinition inReplyToAttribute = assetType.GetAttributeDefinition("InReplyTo"); asset.SetAttributeValue(inReplyToAttribute, inReplyTo); } //NOTE: Need to switch on V1 version. Right now handles 11.3 to 11.4+. Used to be BaseAssets, is now Mentions. //HACK: Modified to support Rally migration, needs refactoring. if (String.IsNullOrEmpty(sdr["Mentions"].ToString()) == false) { AddMultiValueRelation(assetType, asset, "Mentions", sdr["Mentions"].ToString()); //AddRallyMentionsValue(assetType, asset, sdr["BaseAssetType"].ToString(), sdr["Mentions"].ToString()); } else if (String.IsNullOrEmpty(sdr["BaseAssets"].ToString()) == false) { AddMultiValueRelation(assetType, asset, "Mentions", sdr["BaseAssets"].ToString()); } _dataAPI.Save(asset); UpdateNewAssetOIDInDB("Conversations", sdr["AssetOID"].ToString(), asset.Oid.Momentless.ToString()); UpdateImportStatus("Conversations", sdr["AssetOID"].ToString(), ImportStatuses.IMPORTED, "Conversation imported."); importCount++; } catch (Exception ex) { if (_config.V1Configurations.LogExceptions == true) { UpdateImportStatus("Conversations", sdr["AssetOID"].ToString(), ImportStatuses.FAILED, ex.Message); continue; } else { throw ex; } } } sdr.Close(); //SetConversationDependencies();Not Needed since InReplyTo gets set automagically through DB Relation return(importCount); }
/// <summary> /// Returns a new SpriteTexture instance. /// </summary> /// <param name="texture">Texture sheet.</param> /// <param name="rect">Source rectangle of the texture sheet.</param> public SpriteTexture(Asset <Texture2D> texture, Rectangle rect) { textureAsset = texture; SourceRectangle = rect; }
public override void Update(GameTime gameTime) { if (assetsToLoad.Count > 0) { Asset asset = assetsToLoad.Pop(); switch (asset.Item1) { case "Fleet Textures": for (int faction = 0; faction < Constants.FleetTexture.Length; faction++) { Assets.FleetTextures[faction] = new Texture2D[Constants.FleetStateLimit[faction]]; for (int state = 0; state < Constants.FleetStateLimit[faction]; state++) { Assets.FleetTextures[faction][state] = Loader.LoadPNG("spr_fleet_" + Constants.FleetTexture[faction] + "_" + state); } } break; case "Background": Assets.Background = Loader.LoadPNG("background/bg_space"); break; case "Planet Climate Textures": for (int i = 1; i < Assets.PlanetTypeTextures.Length; i++) { Assets.PlanetTypeTextures[i] = Loader.LoadPNG("ui/planet" + i); } break; case "Planet Textures": for (int i = 0; i < Assets.PlanetTextures.Length; i++) { Assets.PlanetTextures[i] = Loader.LoadPNG("spr_planets_" + i); } break; case "System Textures": for (int i = 0; i < Assets.SystemTextures.Length; i++) { Assets.SystemTextures[i] = Loader.LoadPNG("spr_star_" + i); } break; case "Button Textures": for (int i = 0; i < 4; i++) { Assets.ButtonTextures.Add("ui_but_" + i, Loader.LoadPNG("spr_ui_but_" + (i + 1) + "_0")); } Assets.ButtonTextures.Add("pin_button", Loader.LoadPNG("spr_pin_button")); Assets.ButtonTextures.Add("new_game", Loader.LoadPNG("spr_mm_butts_0")); Assets.ButtonTextures.Add("load_game", Loader.LoadPNG("spr_mm_butts_1")); Assets.ButtonTextures.Add("about", Loader.LoadPNG("spr_mm_butts_2")); Assets.ButtonTextures.Add("exit", Loader.LoadPNG("spr_mm_butts_3")); Assets.ButtonTextures.Add("back", Loader.LoadPNG("spr_mm_butts_4")); Assets.ButtonTextures.Add("space_marine", Loader.LoadPNG("spr_master_splash_0")); Assets.ButtonTextures.Add("textbox", Loader.LoadPNG("spr_new_banner_0")); Assets.ButtonTextures.Add("creation_arrow_right", Loader.LoadPNG("spr_creation_arrow_1")); Assets.ButtonTextures.Add("creation_arrow_left", Loader.LoadPNG("spr_creation_arrow_0")); break; case "UI Textures": Assets.UITextures.Add("mapframe", Loader.LoadPNG("spr_new_ui_1")); Assets.UITextures.Add("systemscreen1", Loader.LoadPNG("spr_star_screen_1")); Assets.UITextures.Add("systemscreen2", Loader.LoadPNG("spr_star_screen_2")); Assets.UITextures.Add("systemscreen3", Loader.LoadPNG("spr_star_screen_3")); Assets.UITextures.Add("systemscreen4", Loader.LoadPNG("spr_star_screen_4")); Assets.UITextures.Add("planetscreen", Loader.LoadPNG("spr_planet_screen_1")); // modified texture by removing extra space Assets.UITextures.Add("title_splash", Loader.LoadPNG("ui/title_splash")); Assets.UITextures.Add("spr_rock_bg_0", Loader.LoadPNG("ui/spr_rock_bg_0")); Assets.UITextures.Add("force_background", Loader.LoadPNG("ui/force_background_r")); Assets.UITextures.Add("ledger_background", Loader.LoadPNG("ui/force_background")); // combat Assets.UITextures.Add("bg_combat_grass", Loader.LoadPNG("combat/Zelda Textures/Zelda Texture - Grass 11x Scale")); Assets.UITextures.Add("gc_spacemarine", Loader.LoadPNG("combat/troop/groundcombat_spacemarine")); // spr_mar_collision_0 Assets.UITextures.Add("gc_squadleader", Loader.LoadPNG("combat/troop/groundcombat_squadleader")); Assets.UITextures.Add("order_move_arrow", Loader.LoadPNG("combat/order_move_arrow")); // Move this to a different loading stage //Assets.UITextures.Add("", Loader.LoadPNG("")); Assets.UITextures.Add("campaign_picker", Loader.LoadPNG("spr_popup_medium_0")); // Move this to the UI folder, you utter beefbroth. Assets.UITextures.Add("faction_creator_background", Loader.LoadPNG("spr_settings_bg_0")); Assets.UITextures.Add("black_background", Loader.LoadPNG("background/black_background")); break; case "Fonts": break; case "Faction Icons": Assets.UITextures.Add("faction_icon_selected", Loader.LoadPNG("factions/spr_icon_old_0")); for (int i = 1; i < 10; i++) { Assets.IconTextures.Add("founding_chapter_" + i, Loader.LoadPNG("factions/spr_icon_old_" + i)); } Assets.IconTextures.Add("successor_chapter_1", Loader.LoadPNG("factions/spr_icon_old_11")); Assets.IconTextures.Add("successor_chapter_2", Loader.LoadPNG("factions/spr_icon_old_12")); Assets.IconTextures.Add("successor_chapter_3", Loader.LoadPNG("factions/spr_icon_old_13")); Assets.IconTextures.Add("successor_chapter_4", Loader.LoadPNG("factions/spr_icon_old_15")); break; default: throw new Exception($"Asset type {asset.Item1} is not recognized"); } progress += asset.Item2; } else { Debug.WriteLine("Switching to game state"); gameManager.ChangeState(new MenuState(gameManager, gameManager.GraphicsDevice, gameManager.Content)); } }
public Subsystem(XmlNode xmlNode, Asset asset) { }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation($"AMS v3 Function - MonitorBlobContainerCopyStatus was triggered!"); string requestBody = new StreamReader(req.Body).ReadToEnd(); dynamic data = JsonConvert.DeserializeObject(requestBody); // Validate input objects if (data.assetName == null) { return(new BadRequestObjectResult("Please pass assetName in the input object")); } string assetName = data.assetName; List <string> fileNames = null; if (data.fileNames != null) { fileNames = ((JArray)data.fileNames).ToObject <List <string> >(); } bool copyStatus = true; JArray blobCopyStatusList = new JArray(); MediaServicesConfigWrapper amsconfig = new MediaServicesConfigWrapper(); Asset asset = null; try { IAzureMediaServicesClient client = MediaServicesHelper.CreateMediaServicesClientAsync(amsconfig); // Get the Asset asset = client.Assets.Get(amsconfig.ResourceGroup, amsconfig.AccountName, assetName); if (asset == null) { return(new BadRequestObjectResult("Asset not found")); } // Setup blob container var response = client.Assets.ListContainerSas(amsconfig.ResourceGroup, amsconfig.AccountName, assetName, permissions: AssetContainerPermission.Read, expiryTime: DateTime.UtcNow.AddHours(4).ToUniversalTime()); var sasUri = new Uri(response.AssetContainerSasUrls.First()); CloudBlobContainer destinationBlobContainer = new CloudBlobContainer(sasUri); //string blobPrefix = null; //bool useFlatBlobListing = true; //BlobContinuationToken blobContinuationToken = null; log.LogInformation("Checking CopyStatus of all blobs in the source container..."); var blobList = BlobStorageHelper.ListBlobs(destinationBlobContainer); foreach (var blob in blobList) { if (fileNames != null) { bool found = false; foreach (var fileName in fileNames) { if (fileName == blob.Name) { found = true; break; } } if (found == false) { break; } } if (blob.CopyState.Status == CopyStatus.Aborted || blob.CopyState.Status == CopyStatus.Failed) { // Log the copy status description for diagnostics and restart copy blob.StartCopyAsync(blob.CopyState.Source); copyStatus = false; } else if (blob.CopyState.Status == CopyStatus.Pending) { // We need to continue waiting for this pending copy // However, let us log copy state for diagnostics copyStatus = false; } // else we completed this pending copy string blobName = blob.Name as string; int blobCopyStatus = (int)(blob.CopyState.Status); JObject o = new JObject(); o["blobName"] = blobName; o["blobCopyStatus"] = blobCopyStatus; blobCopyStatusList.Add(o); } } catch (ApiErrorException e) { log.LogError($"ERROR: AMS API call failed with error code: {e.Body.Error.Code} and message: {e.Body.Error.Message}"); return(new BadRequestObjectResult("AMS API call error: " + e.Message + "\nError Code: " + e.Body.Error.Code + "\nMessage: " + e.Body.Error.Message)); } catch (Exception e) { log.LogError($"ERROR: Exception with message: {e.Message}"); return(new BadRequestObjectResult("Error: " + e.Message)); } JObject result = new JObject(); result["copyStatus"] = copyStatus; result["blobCopyStatusList"] = blobCopyStatusList; return((ActionResult) new OkObjectResult(result)); }
/// <summary> /// adds a fixed asset Adds an asset to the system /// </summary> /// <exception cref="Xero.NetStandard.OAuth2.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="xeroTenantId">Xero identifier for Tenant</param> /// <param name="asset">Fixed asset you are creating</param> /// <returns>Task of ApiResponse (Asset)</returns> public async System.Threading.Tasks.Task <Xero.NetStandard.OAuth2.Client.ApiResponse <Asset> > CreateAssetAsyncWithHttpInfo(string accessToken, string xeroTenantId, Asset asset) { // verify the required parameter 'xeroTenantId' is set if (xeroTenantId == null) { throw new Xero.NetStandard.OAuth2.Client.ApiException(400, "Missing required parameter 'xeroTenantId' when calling AssetApi->CreateAsset"); } // verify the required parameter 'asset' is set if (asset == null) { throw new Xero.NetStandard.OAuth2.Client.ApiException(400, "Missing required parameter 'asset' when calling AssetApi->CreateAsset"); } Xero.NetStandard.OAuth2.Client.RequestOptions requestOptions = new Xero.NetStandard.OAuth2.Client.RequestOptions(); String[] @contentTypes = new String[] { "application/json" }; // to determine the Accept header String[] @accepts = new String[] { "application/json" }; foreach (var cType in @contentTypes) { requestOptions.HeaderParameters.Add("Content-Type", cType); } foreach (var accept in @accepts) { requestOptions.HeaderParameters.Add("Accept", accept); } if (xeroTenantId != null) { requestOptions.HeaderParameters.Add("Xero-Tenant-Id", Xero.NetStandard.OAuth2.Client.ClientUtils.ParameterToString(xeroTenantId)); // header parameter } requestOptions.Data = asset; // authentication (OAuth2) required // oauth required if (!String.IsNullOrEmpty(accessToken)) { requestOptions.HeaderParameters.Add("Authorization", "Bearer " + accessToken); } // make the HTTP request var response = await this.AsynchronousClient.PostAsync <Asset>("/Assets", requestOptions, this.Configuration); if (this.ExceptionFactory != null) { Exception exception = this.ExceptionFactory("CreateAsset", response); if (exception != null) { throw exception; } } return(response); }
protected override async Task LoadContent() { await base.LoadContent(); // create pipeline CreatePipeline(); // setup the scene var material = Asset.Load <Material>("BasicMaterial"); teapotEntity = new Entity() { new ModelComponent() { Model = new Model() { material, new Mesh() { Draw = GeometricPrimitive.Teapot.New(GraphicsDevice).ToMeshDraw(), MaterialIndex = 0, } } } }; Entities.Add(teapotEntity); var textureCube = Asset.Load <Texture>("uv_cube"); var staticCubemapEntity = new Entity() { new CubemapSourceComponent(textureCube) { InfluenceRadius = 2f, IsDynamic = false }, new TransformationComponent() { Translation = Vector3.UnitZ } }; Entities.Add(staticCubemapEntity); dynamicCubemapEntity = new Entity() { new CubemapSourceComponent(textureCube) { InfluenceRadius = 0.5f, IsDynamic = false }, new TransformationComponent() { Translation = Vector3.Zero } }; Entities.Add(dynamicCubemapEntity); var mainCamera = new Entity() { new CameraComponent { AspectRatio = 8 / 4.8f, FarPlane = 20, NearPlane = 1, VerticalFieldOfView = 0.6f, Target = teapotEntity, TargetUp = Vector3.UnitY, }, new TransformationComponent { Translation = new Vector3(4, 3, 0) } }; Entities.Add(mainCamera); RenderSystem.Pipeline.SetCamera(mainCamera.Get <CameraComponent>()); Script.Add(GameScript1); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); dynamic data; try { data = JsonConvert.DeserializeObject(new StreamReader(req.Body).ReadToEnd()); } catch (Exception ex) { return(IrdetoHelpers.ReturnErrorException(log, ex)); } var assetName = (string)data.assetName; if (assetName == null) { return(IrdetoHelpers.ReturnErrorException(log, "Error - please pass assetName in the JSON")); } // Azure region management var azureRegions = new List <string>(); if ((string)data.azureRegion != null) { azureRegions = ((string)data.azureRegion).Split(',').ToList(); } else { azureRegions.Add((string)null); } // semaphore file (json structure) VodSemaphore semaphore = null; if (data.semaphore != null) { semaphore = VodSemaphore.FromJson((string)data.semaphore); } // init default var streamingLocatorGuid = Guid.NewGuid(); // same locator for the two ouputs if 2 live event namle created var uniquenessLocator = streamingLocatorGuid.ToString().Substring(0, 13); var streamingLocatorName = "locator-" + uniquenessLocator; string uniquenessPolicyName = Guid.NewGuid().ToString().Substring(0, 13); // useDRM init var useDRM = true; if (data.useDRM != null) { useDRM = (bool)data.useDRM; } else if (semaphore != null & semaphore.ClearStream != null) { useDRM = !(bool)semaphore.ClearStream; } // Default content id and semaphare value string irdetoContentId = null; if (semaphore != null && semaphore.DrmContentId != null) // semaphore data has higher priority { irdetoContentId = semaphore.DrmContentId; } else if (data.defaultIrdetoContentId != null) { irdetoContentId = (string)data.defaultIrdetoContentId; } DateTime?startTime = null; DateTime?endTime = null; try { if (semaphore != null && semaphore.StartTime != null) { startTime = DateTime.ParseExact(semaphore.StartTime, AssetEntry.DateFormat, System.Globalization.CultureInfo.InvariantCulture); } if (semaphore != null && semaphore.EndTime != null) { endTime = DateTime.ParseExact(semaphore.EndTime, AssetEntry.DateFormat, System.Globalization.CultureInfo.InvariantCulture); } } catch (Exception ex) { return(IrdetoHelpers.ReturnErrorException(log, ex)); } var cencKey = new StreamingLocatorContentKey(); var cbcsKey = new StreamingLocatorContentKey(); if (useDRM) { try { ConfigWrapper config = new ConfigWrapper(new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddEnvironmentVariables() .Build(), null); MediaServicesHelpers.LogInformation(log, "Irdeto call..."); cencKey = await IrdetoHelpers.GenerateAndRegisterCENCKeyToIrdeto(irdetoContentId, config); cbcsKey = await IrdetoHelpers.GenerateAndRegisterCBCSKeyToIrdeto(irdetoContentId, config); MediaServicesHelpers.LogInformation(log, "Irdeto call done."); } catch (Exception ex) { return(IrdetoHelpers.ReturnErrorException(log, ex, "Irdeto response error")); } } var clientTasks = new List <Task <AssetEntry> >(); foreach (var region in azureRegions) { var task = Task <AssetEntry> .Run(async() => { Asset asset = null; StreamingPolicy streamingPolicy = null; ConfigWrapper config = new ConfigWrapper(new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddEnvironmentVariables() .Build(), region ); MediaServicesHelpers.LogInformation(log, "config loaded.", region); MediaServicesHelpers.LogInformation(log, "connecting to AMS account : " + config.AccountName, region); var client = await MediaServicesHelpers.CreateMediaServicesClientAsync(config); // Set the polling interval for long running operations to 2 seconds. // The default value is 30 seconds for the .NET client SDK client.LongRunningOperationRetryTimeout = 2; if (useDRM) { MediaServicesHelpers.LogInformation(log, "Trying to read streaming policy from Cosmos.", region); string streamingPolicyName = null; // Load streaming policy info from Cosmos try { var info = await CosmosHelpers.ReadStreamingPolicyDocument(new StreamingPolicyInfo() { Project = policyProject, AMSAccountName = config.AccountName }); if (info == null) { log.LogWarning("Streaming policy not read from Cosmos."); } else { streamingPolicyName = info.StreamingPolicyName; } } catch (Exception ex) { throw new Exception("Error reading Cosmos DB", ex); } // STREAMING POLICY CREATION if (streamingPolicyName == null) // not found in Cosmos let's create a new one { MediaServicesHelpers.LogInformation(log, "Creating streaming policy.", region); try { streamingPolicy = await IrdetoHelpers.CreateStreamingPolicyIrdeto(config, client, uniquenessPolicyName); } catch (Exception ex) { throw new Exception("Streaming policy creation error", ex); } try { if (!await CosmosHelpers.CreateOrUpdatePolicyDocument(new StreamingPolicyInfo() { Project = policyProject, AMSAccountName = config.AccountName, StreamingPolicyName = streamingPolicy.Name })) { log.LogWarning("Cosmos access not configured or error."); } } catch (Exception ex) { throw new Exception("Streaming policy write error to Cosmos", ex); } } else { MediaServicesHelpers.LogInformation(log, "Getting streaming policy in AMS.", region); try { streamingPolicy = await client.StreamingPolicies.GetAsync(config.ResourceGroup, config.AccountName, streamingPolicyName); } catch (Exception ex) { throw new Exception("Error when getting streaming policy " + streamingPolicy, ex); } } } // let's get the asset try { MediaServicesHelpers.LogInformation(log, "Getting asset.", region); asset = await client.Assets.GetAsync(config.ResourceGroup, config.AccountName, assetName); } catch (Exception ex) { throw new Exception("Error when retreving asset by name", ex); } // Locator creation try { StreamingLocator locator = null; if (useDRM) { locator = await IrdetoHelpers.SetupDRMAndCreateLocatorWithNewKeys(config, streamingPolicy.Name, streamingLocatorName, client, asset, cencKey, cbcsKey, streamingLocatorGuid, irdetoContentId, startTime, endTime); } else // no DRM { locator = await IrdetoHelpers.CreateClearLocator(config, streamingLocatorName, client, asset, streamingLocatorGuid, startTime, endTime); } MediaServicesHelpers.LogInformation(log, "locator : " + locator.Name, region); } catch (Exception ex) { throw new Exception("Error when creating the locator", ex); } // let's build info for the live event and output AssetEntry assetEntry = await GenerateInfoHelpers.GenerateAssetInformation(config, client, asset, semaphore, irdetoContentId, region); if (!await CosmosHelpers.CreateOrUpdateAssetDocument(assetEntry)) { log.LogWarning("Cosmos access not configured."); } return(assetEntry); }); clientTasks.Add(task); } try { Task.WaitAll(clientTasks.ToArray()); } catch (Exception ex) { return(IrdetoHelpers.ReturnErrorException(log, ex)); } return(new OkObjectResult( JsonConvert.SerializeObject(new AssetInfo { Success = true, Assets = clientTasks.Select(i => i.Result).ToList() }, Formatting.Indented) )); }
public override void Unload() { glowmask = null; }
protected override void OnShow(Node node, Asset asset) { App.UI.Root.SetDefaultStyle(ResourceCache.GetXmlFile("UI/DefaultStyle.xml")); App.UI.LoadLayoutToElement(App.UI.Root, ResourceCache, asset.RelativePathToAsset); }
public ActionResult Edit([Bind(Include = "ID,IsOccuppied,Name,Type,AskingRent,Address")] Asset asset) { List <Appliance> appliancesOld = db.Appliances.Include("BelongsToAsset").Where(a => a.BelongsToAsset.ID == asset.ID).ToList(); List <Appliance> appliancesSelected = new List <Appliance>(); Asset thisAsset = db.Assets.Find(asset.ID); // update all properties thisAsset.Name = asset.Name; thisAsset.Type = asset.Type; thisAsset.Address = asset.Address; thisAsset.AskingRent = asset.AskingRent; // add newly selected appliances foreach (ApplianceType applianceType in Enum.GetValues(typeof(ApplianceType))) { Guid appID; Appliance selectedApp; // skip if appliance type was not selected if (Request[applianceType.ToString()] == NULL) { continue; } appID = Guid.Parse(Request[applianceType.ToString()]); selectedApp = db.Appliances.Find(appID); // skip if selected appliance non-existent in database if (selectedApp == null) { continue; } // add to selected appliances // used for removing unselected appliances appliancesSelected.Add(selectedApp); // add appliance if (!appliancesOld.Contains(selectedApp)) { selectedApp.BelongsToAsset = thisAsset; } else { appliancesOld.Remove(selectedApp); } } // remove unselected appliances foreach (Appliance oldApp in appliancesOld) { oldApp.BelongsToAsset = null; } if (ModelState.IsValid) { //db.Entry(asset).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } return(View(asset)); }
/// <inheritdoc /> public string PresentAsset(Asset asset) => asset == null ? "null" : AssetToken + PresentJson(asset).ToString(Formatting.Indented);
void FindTextureBitmapPaths(Document doc) { // Find materials FilteredElementCollector fec = new FilteredElementCollector(doc); fec.OfClass(typeof(Material)); IEnumerable<Material> targetMaterials = fec.Cast<Material>().Where<Material>(mtl => targetMaterialNames.Contains(mtl.Name)); foreach (Material material in targetMaterials) { // Get appearance asset for read ElementId appearanceAssetId = material .AppearanceAssetId; AppearanceAssetElement appearanceAssetElem = doc.GetElement(appearanceAssetId) as AppearanceAssetElement; Asset asset = appearanceAssetElem .GetRenderingAsset(); // Walk through all first level assets to find // connected Bitmap properties. Note: it is // possible to have multilevel connected // properties with Bitmaps in the leaf nodes. // So this would need to be recursive. int size = asset.Size; for (int assetIdx = 0; assetIdx < size; assetIdx++) { //AssetProperty aProperty = asset[assetIdx]; // 2018 AssetProperty aProperty = asset.Get(assetIdx); // 2019 if (aProperty.NumberOfConnectedProperties < 1) continue; // Find first connected property. // Should work for all current (2018) schemas. // Safer code would loop through all connected // properties based on the number provided. Asset connectedAsset = aProperty .GetConnectedProperty(0) as Asset; // We are only checking for bitmap connected assets. if (connectedAsset.Name == "UnifiedBitmapSchema") { // This line is 2018.1 & up because of the // property reference to UnifiedBitmap // .UnifiedbitmapBitmap. In earlier versions, // you can still reference the string name // instead: "unifiedbitmap_Bitmap" //AssetPropertyString path = connectedAsset[ // 2018 // UnifiedBitmap.UnifiedbitmapBitmap] // as AssetPropertyString; AssetPropertyString path = connectedAsset // 2019 .FindByName(UnifiedBitmap.UnifiedbitmapBitmap) as AssetPropertyString; // This will be a relative path to the // built -in materials folder, addiitonal // render appearance folder, or an // absolute path. TaskDialog.Show("Connected bitmap", String.Format("{0} from {2}: {1}", aProperty.Name, path.Value, connectedAsset.LibraryName)); } } } }
private void Bind(int page, bool updateAuditLog) { AssetFinder finder = SavedUserAssetSearch.AssetFinder; EntityList <Asset> assets = Asset.FindMany(finder, page - 1, PageSize); if (assets.Count == 0) { NoSearchResultsPanel.Visible = true; SearchResultListRepeater.Visible = false; SearchResultThumbnailsDataList.Visible = false; } else { // Hide the no results panel; we have some assets NoSearchResultsPanel.Visible = false; // Update page size SavedUserAssetSearch.PageSize = PageSize; // Update page SavedUserAssetSearch.Page = page; // Show filters panel if a search term was entered, we're on page 1, and have more than the specified number of results if (!StringUtils.IsBlank(finder.GeneralKeyword) && (page == 1) && (ShowFiltersCount > 0) && (assets.PagingInfo.TotalRecords > ShowFiltersCount)) { PageHeader pageHeader = (PageHeader)SiteUtils.FindControlRecursive(Page, "PageHeader1"); pageHeader.ToggleSearchVisibility(SavedUserAssetSearch.FilterOpen, SavedUserAssetSearch.CategoriesOpen); string message = string.Format("Your search has returned more than {0} results. Use the filters above to refine your search.", ShowFiltersCount); LargeSearchResultFeedbackLabel.SetErrorMessage(message); LargeSearchResultFeedbackLabel.Pinned = true; } else { LargeSearchResultFeedbackLabel.Visible = false; LargeSearchResultFeedbackLabel.Pinned = false; } // Log which assets were returned as part of this search if (updateAuditLog) { int index = 0; foreach (Asset asset in assets) { index++; AuditLogManager.LogAssetInSearchResult(SavedUserAssetSearch.AuditAssetSearchId, asset.AssetId.GetValueOrDefault()); AuditLogManager.LogAssetAction(asset, CurrentUser, AuditAssetAction.ReturnedInSearch, string.Format("Search Criteria: {0}. Total assets: {1}. Displayed on page: {2}, asset number: {3}", finder.GeneralKeyword, assets.PagingInfo.TotalRecords, assets.PagingInfo.CurrentPage + 1, index)); } } // The current view is thumbnails, so ensure we have at last a single row and toggle // the relevant data controls (ie. hide the list repeater and show the thumbnail datalist) if (SavedUserAssetSearch.SearchResultsView == SearchResultsView.Thumbnails) { // In thumbnail view, we need to make sure we have at least one row of assets, or the // layout gets really messed up. Here, we're doing a check, and adding in empty assets // to pad out the asset list to at least a single row. while (assets.Count < SearchResultThumbnailsDataList.RepeatColumns) { assets.Add(Asset.Empty); } SearchResultListRepeater.Visible = false; SearchResultThumbnailsDataList.Visible = true; SearchResultThumbnailsDataList.DataSource = assets; SearchResultThumbnailsDataList.DataBind(); } else { SearchResultListRepeater.Visible = true; SearchResultThumbnailsDataList.Visible = false; SearchResultListRepeater.DataSource = assets; SearchResultListRepeater.DataBind(); } } TopPager.CurrentPage = assets.PagingInfo.CurrentPage + 1; TopPager.PageSize = assets.PagingInfo.PageSize; TopPager.PageCount = assets.PagingInfo.TotalPages; TopPager.ItemCount = assets.PagingInfo.TotalRecords; BottomPager.CurrentPage = TopPager.CurrentPage; BottomPager.PageSize = TopPager.PageSize; BottomPager.PageCount = TopPager.PageCount; BottomPager.ItemCount = TopPager.ItemCount; CurrentPage = page; TotalPages = assets.PagingInfo.TotalPages; AssetCount = assets.PagingInfo.TotalRecords; }
private static Tuple<Type, Object> GetTypeAndValue(AssetProperty assetProperty, int level) { Object theValue; Type valueType; //For each AssetProperty, it has different type and value //must deal with it separately try { if (assetProperty is AssetPropertyBoolean) { AssetPropertyBoolean property = assetProperty as AssetPropertyBoolean; valueType = typeof(AssetPropertyBoolean); theValue = property.Value; } else if (assetProperty is AssetPropertyDistance) { AssetPropertyDistance property = assetProperty as AssetPropertyDistance; valueType = typeof(AssetPropertyDistance); theValue = property.Value; } else if (assetProperty is AssetPropertyDouble) { AssetPropertyDouble property = assetProperty as AssetPropertyDouble; valueType = typeof(AssetPropertyDouble); theValue = property.Value; } else if (assetProperty is AssetPropertyDoubleArray2d) { //Default, it is supported by PropertyGrid to display Double [] //Try to convert DoubleArray to Double [] AssetPropertyDoubleArray2d property = assetProperty as AssetPropertyDoubleArray2d; valueType = typeof(AssetPropertyDoubleArray2d); theValue = GetSystemArrayAsString(property.Value); } else if (assetProperty is AssetPropertyDoubleArray3d) { AssetPropertyDoubleArray3d property = assetProperty as AssetPropertyDoubleArray3d; valueType = typeof(AssetPropertyDoubleArray3d); //theValue = GetSystemArrayAsString( property.Value ); // 2017 theValue = Util.DoubleArrayString(property.GetValueAsDoubles()); // 2018 } else if (assetProperty is AssetPropertyDoubleArray4d) { AssetPropertyDoubleArray4d property = assetProperty as AssetPropertyDoubleArray4d; valueType = typeof(AssetPropertyDoubleArray4d); //theValue = GetSystemArrayAsString( property.Value ); // 2017 theValue = Util.DoubleArrayString(property.GetValueAsDoubles()); // 2018 } else if (assetProperty is AssetPropertyDoubleMatrix44) { AssetPropertyDoubleMatrix44 property = assetProperty as AssetPropertyDoubleMatrix44; valueType = typeof(AssetPropertyDoubleMatrix44); theValue = GetSystemArrayAsString(property.Value); } else if (assetProperty is AssetPropertyEnum) { AssetPropertyEnum property = assetProperty as AssetPropertyEnum; valueType = typeof(AssetPropertyEnum); theValue = property.Value; } else if (assetProperty is AssetPropertyFloat) { AssetPropertyFloat property = assetProperty as AssetPropertyFloat; valueType = typeof(AssetPropertyFloat); theValue = property.Value; } else if (assetProperty is AssetPropertyInteger) { AssetPropertyInteger property = assetProperty as AssetPropertyInteger; valueType = typeof(AssetPropertyInteger); theValue = property.Value; } else if (assetProperty is AssetPropertyReference) { AssetPropertyReference property = assetProperty as AssetPropertyReference; valueType = typeof(AssetPropertyReference); theValue = "REFERENCE"; //property.Type; } else if (assetProperty is AssetPropertyString) { AssetPropertyString property = assetProperty as AssetPropertyString; valueType = typeof(AssetPropertyString); theValue = property.Value; } else if (assetProperty is AssetPropertyTime) { AssetPropertyTime property = assetProperty as AssetPropertyTime; valueType = typeof(AssetPropertyTime); theValue = property.Value; } else { valueType = typeof(String); theValue = "Unprocessed asset type: " + assetProperty.GetType().Name; } if (assetProperty.NumberOfConnectedProperties > 0) { String result = ""; result = theValue.ToString(); TaskDialog.Show("Connected properties found", assetProperty.Name + ": " + assetProperty.NumberOfConnectedProperties); IList<AssetProperty> properties = assetProperty.GetAllConnectedProperties(); foreach (AssetProperty property in properties) { if (property is Asset) { // Nested? Asset asset = property as Asset; int size = asset.Size; for (int i = 0; i < size; i++) { //AssetProperty subproperty = asset[i]; // 2018 AssetProperty subproperty = asset.Get(i); // 2019 Tuple<Type, Object> valueAndType = GetTypeAndValue(subproperty, level + 1); String indent = ""; if (level > 0) { for (int iLevel = 1; iLevel <= level; iLevel++) indent += " "; } result += "\n " + indent + "- connected: name: " + subproperty.Name + " | type: " + valueAndType.Item1.Name + " | value: " + valueAndType.Item2.ToString(); } } } theValue = result; } } catch { return null; } return new Tuple<Type, Object>(valueType, theValue); }
void GetElementMaterialInfo( Document doc ) { FilteredElementCollector collector = new FilteredElementCollector( doc ) .WhereElementIsNotElementType() .OfClass( typeof( Material ) ); try { foreach( Material material in collector ) { if( material.Name.Equals( "Air" ) ) { AppearanceAssetElement appearanceElement = doc.GetElement( material.AppearanceAssetId ) as AppearanceAssetElement; Asset appearanceAsset = appearanceElement .GetRenderingAsset(); List<AssetProperty> assetProperties = new List<AssetProperty>(); PropertySetElement physicalPropSet = doc.GetElement( material.StructuralAssetId ) as PropertySetElement; PropertySetElement thermalPropSet = doc.GetElement( material.ThermalAssetId ) as PropertySetElement; ThermalAsset thermalAsset = thermalPropSet .GetThermalAsset(); StructuralAsset physicalAsset = physicalPropSet .GetStructuralAsset(); ICollection<Parameter> physicalParameters = physicalPropSet.GetOrderedParameters(); ICollection<Parameter> thermalParameters = thermalPropSet.GetOrderedParameters(); // Appearance Asset for( int i = 0; i < appearanceAsset.Size; i++ ) { AssetProperty property = appearanceAsset[ i ]; assetProperties.Add( property ); } foreach( AssetProperty assetProp in assetProperties ) { Type type = assetProp.GetType(); object assetPropValue = null; var prop = type.GetProperty( "Value" ); if( prop != null && prop.GetIndexParameters().Length == 0 ) { assetPropValue = prop.GetValue( assetProp ); } } // Physical (Structural) Asset foreach( Parameter p in physicalParameters ) { // Work with parameters here // The only parameter not in the orderedParameters // that is needed is the Asset name, which you // can get by 'physicalAsset.Name'. } // Thermal Asset foreach( Parameter p in thermalParameters ) { //Work with parameters here //The only parameter not in the orderedParameters // that is needed is the Asset name, shich you // can get by 'thermalAsset.Name'. } } } } catch( Exception e ) { Console.WriteLine( e.ToString() ); } }
protected DeriveAssetTestBase(Asset baseAsset, Asset derivedAsset) { Container = new AssetPropertyGraphContainer(new PackageSession(), new AssetNodeContainer()); BaseAssetItem = new AssetItem("MyAsset", baseAsset); DerivedAssetItem = new AssetItem("MyDerivedAsset", derivedAsset); }
public Subsystem(XmlNode xmlNode, Dependency deps, Asset asset) { }
public async Task <string> ImportAssetExcelAsync(ExcelWorksheet worksheet, int userID) { string result = "Import fail " + worksheet.Name.Trim(); using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, new System.TimeSpan(0, 60, 0))) { try { var colCount = worksheet.Dimension.End.Column; var rowCount = worksheet.Dimension.End.Row; string locationCode = worksheet.Cells[1, 3].Value.ToString().Trim(); Location location = _locationService.GetLocationByCode(locationCode); if (location == null) { result = "Do not exist current location code: " + locationCode + ". Please check again or create new!"; return(result); } for (int i = 3; i <= rowCount; i++) { result = "Error at cell " + i; string areaCode = worksheet.Cells[i, 2].Value.ToString(); Area area = _areaService.GetAreaByCode(areaCode); if (area == null) { result = result + " in area collum do not exist current area code:" + areaCode + ". Please check again or create new!"; return(result); } string assetname = worksheet.Cells[i, 3].Value.ToString(); string assetTypeName = worksheet.Cells[i, 4].Value.ToString(); string description = worksheet.Cells[i, 8].Value.ToString(); bool active = false; if (worksheet.Cells[i, 9].Value.ToString().Equals("1")) { active = true; } string assetCode = worksheet.Cells[i, 7].Value.ToString(); int quantity = Int32.Parse(worksheet.Cells[i, 5].Value.ToString().Trim()); DateTime startDate = DateTime.Now; try { startDate = Convert.ToDateTime(worksheet.Cells[i, 6].Value.ToString()); } catch (Exception e) { //set default date startDate = Convert.ToDateTime("1900-01-01"); } AssetType assetTypes = _assetTypeService.GetAssetTypeByName(assetTypeName); if (assetTypes == null) { result = result + "in Assettype collum do not exist current type import: " + assetTypeName; return(result); } // check asset is exist or not / if exist update asset Asset asset = _assetService.GetAssetByCode(assetCode); if (asset == null) { Asset newAsset = new Asset(); newAsset.Name = assetname; newAsset.AssetCode = assetCode; newAsset.Description = description; newAsset.Quantity = quantity; newAsset.StartDate = startDate; newAsset.AssetTypeID = assetTypes.ID; newAsset.ApplicationUserID = userID; newAsset.AreaID = area.ID; newAsset.Active = active; _assetService.Add(newAsset); asset = newAsset; _assetService.SaveChanges(); } else { asset.AssetCode = assetCode; asset.Name = assetname; asset.Description = description; asset.Quantity = quantity; asset.StartDate = startDate; asset.AssetTypeID = assetTypes.ID; asset.AreaID = area.ID; asset.Active = active; _assetService.Update(asset); _assetService.SaveChanges(); } for (int j = 10; j <= colCount; j++) { string attributeName = worksheet.Cells[2, j].Value.ToString().Trim(); AssetTypeAttribute assetAttribute = _attributeService.GetAttributeByName(attributeName, assetTypes.ID); string value = ""; try { if (worksheet.Cells[i, j].Value == null) { value = "N/A"; } value = worksheet.Cells[i, j].Value.ToString().Trim(); } catch (Exception e) { value = "N/A"; } AssetAttributeValue insertValue = _attributeValueService.SearchAttributeValue(asset.ID, assetAttribute.ID); if (insertValue != null) { insertValue.Value = value; _attributeValueService.Update(insertValue); } else { insertValue = new AssetAttributeValue(); insertValue.Value = value; insertValue.AssetID = asset.ID; insertValue.AssetAttributeID = assetAttribute.ID; insertValue.Active = true; _attributeValueService.Add(insertValue); } } result = result + " in Attribute value table."; } _attributeValueService.SaveChanges(); result = "Error in Commplete transison."; scope.Complete(); result = "Import successfull!"; return(result); } catch (Exception) { return(result); } } }
[OnImportsSatisfied] // <= required, but may result in double initialisation... public void Compose() { Asset.Compose(); RegisterMessageHandler(); Configure(); }
protected override async Task LoadContent() { await base.LoadContent(); var random = new Random(0); var uiImages = Asset.Load <UIImageGroup>("UIImages"); var img1 = new ImageElement { Source = new UIImage(Asset.Load <Texture>("uv")) }; var img2 = new ImageElement { Source = uiImages["GameScreenLeft"] }; var img3 = new ImageElement { Source = uiImages["GameScreenRight"] }; stackPanel1 = new StackPanel { Orientation = Orientation.Vertical, ItemVirtualizationEnabled = true }; stackPanel1.Children.Add(img1); stackPanel1.Children.Add(img2); stackPanel1.Children.Add(img3); stackPanel2 = new StackPanel { Orientation = Orientation.Vertical, ItemVirtualizationEnabled = true }; for (var i = 0; i < 1000; i++) { stackPanel2.Children.Add(new Button { Name = "" + i, Height = 75, Content = new TextBlock { Text = "button number " + i, Font = Asset.Load <SpriteFont>("MicrosoftSansSerif15") } }); } stackPanel3 = new StackPanel { Orientation = Orientation.Vertical, ItemVirtualizationEnabled = true, VerticalAlignment = VerticalAlignment.Center }; for (var i = 0; i < 103; i++) { stackPanel3.Children.Add(new Button { Name = "" + i, Height = 50 + 500 * random.NextFloat(), Content = new TextBlock { Text = "random button number " + i, Font = Asset.Load <SpriteFont>("MicrosoftSansSerif15") } }); } stackPanel4 = new StackPanel { Orientation = Orientation.Vertical, ItemVirtualizationEnabled = true }; for (var i = 0; i < 5; i++) { stackPanel4.Children.Add(new Button { Name = "" + i, Height = i * 30, Content = new TextBlock { Text = "random button number " + i, Font = Asset.Load <SpriteFont>("MicrosoftSansSerif15") } }); } currentStackPanel = stackPanel1; scrollViewer = new ScrollViewer { Name = "sv", Content = currentStackPanel, ScrollMode = ScrollingMode.Vertical }; UI.RootElement = scrollViewer; }
private static void SetDictionary(Asset asset, ShadowObjectPropertyKey key, Dictionary<UFile, ObjectId> dictionary) { var shadow = ShadowObject.GetOrCreate(asset); shadow[key] = dictionary; }