context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// MemberResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; namespace Twilio.Rest.IpMessaging.V1.Service.Channel { public class MemberResource : Resource { private static Request BuildFetchRequest(FetchMemberOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.IpMessaging, "/v1/Services/" + options.PathServiceSid + "/Channels/" + options.PathChannelSid + "/Members/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch Member parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Member </returns> public static MemberResource Fetch(FetchMemberOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch Member parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Member </returns> public static async System.Threading.Tasks.Task<MemberResource> FetchAsync(FetchMemberOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// fetch /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathChannelSid"> The channel_sid </param> /// <param name="pathSid"> The sid </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Member </returns> public static MemberResource Fetch(string pathServiceSid, string pathChannelSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchMemberOptions(pathServiceSid, pathChannelSid, pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathChannelSid"> The channel_sid </param> /// <param name="pathSid"> The sid </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Member </returns> public static async System.Threading.Tasks.Task<MemberResource> FetchAsync(string pathServiceSid, string pathChannelSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchMemberOptions(pathServiceSid, pathChannelSid, pathSid); return await FetchAsync(options, client); } #endif private static Request BuildCreateRequest(CreateMemberOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.IpMessaging, "/v1/Services/" + options.PathServiceSid + "/Channels/" + options.PathChannelSid + "/Members", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// create /// </summary> /// <param name="options"> Create Member parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Member </returns> public static MemberResource Create(CreateMemberOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildCreateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="options"> Create Member parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Member </returns> public static async System.Threading.Tasks.Task<MemberResource> CreateAsync(CreateMemberOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildCreateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// create /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathChannelSid"> The channel_sid </param> /// <param name="identity"> The identity </param> /// <param name="roleSid"> The role_sid </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Member </returns> public static MemberResource Create(string pathServiceSid, string pathChannelSid, string identity, string roleSid = null, ITwilioRestClient client = null) { var options = new CreateMemberOptions(pathServiceSid, pathChannelSid, identity){RoleSid = roleSid}; return Create(options, client); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathChannelSid"> The channel_sid </param> /// <param name="identity"> The identity </param> /// <param name="roleSid"> The role_sid </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Member </returns> public static async System.Threading.Tasks.Task<MemberResource> CreateAsync(string pathServiceSid, string pathChannelSid, string identity, string roleSid = null, ITwilioRestClient client = null) { var options = new CreateMemberOptions(pathServiceSid, pathChannelSid, identity){RoleSid = roleSid}; return await CreateAsync(options, client); } #endif private static Request BuildReadRequest(ReadMemberOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.IpMessaging, "/v1/Services/" + options.PathServiceSid + "/Channels/" + options.PathChannelSid + "/Members", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// read /// </summary> /// <param name="options"> Read Member parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Member </returns> public static ResourceSet<MemberResource> Read(ReadMemberOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<MemberResource>.FromJson("members", response.Content); return new ResourceSet<MemberResource>(page, options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="options"> Read Member parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Member </returns> public static async System.Threading.Tasks.Task<ResourceSet<MemberResource>> ReadAsync(ReadMemberOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<MemberResource>.FromJson("members", response.Content); return new ResourceSet<MemberResource>(page, options, client); } #endif /// <summary> /// read /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathChannelSid"> The channel_sid </param> /// <param name="identity"> The identity </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Member </returns> public static ResourceSet<MemberResource> Read(string pathServiceSid, string pathChannelSid, List<string> identity = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadMemberOptions(pathServiceSid, pathChannelSid){Identity = identity, PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathChannelSid"> The channel_sid </param> /// <param name="identity"> The identity </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Member </returns> public static async System.Threading.Tasks.Task<ResourceSet<MemberResource>> ReadAsync(string pathServiceSid, string pathChannelSid, List<string> identity = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadMemberOptions(pathServiceSid, pathChannelSid){Identity = identity, PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<MemberResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<MemberResource>.FromJson("members", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<MemberResource> NextPage(Page<MemberResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.IpMessaging) ); var response = client.Request(request); return Page<MemberResource>.FromJson("members", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<MemberResource> PreviousPage(Page<MemberResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.IpMessaging) ); var response = client.Request(request); return Page<MemberResource>.FromJson("members", response.Content); } private static Request BuildDeleteRequest(DeleteMemberOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Delete, Rest.Domain.IpMessaging, "/v1/Services/" + options.PathServiceSid + "/Channels/" + options.PathChannelSid + "/Members/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// delete /// </summary> /// <param name="options"> Delete Member parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Member </returns> public static bool Delete(DeleteMemberOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="options"> Delete Member parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Member </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteMemberOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #endif /// <summary> /// delete /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathChannelSid"> The channel_sid </param> /// <param name="pathSid"> The sid </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Member </returns> public static bool Delete(string pathServiceSid, string pathChannelSid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteMemberOptions(pathServiceSid, pathChannelSid, pathSid); return Delete(options, client); } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathChannelSid"> The channel_sid </param> /// <param name="pathSid"> The sid </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Member </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathServiceSid, string pathChannelSid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteMemberOptions(pathServiceSid, pathChannelSid, pathSid); return await DeleteAsync(options, client); } #endif private static Request BuildUpdateRequest(UpdateMemberOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.IpMessaging, "/v1/Services/" + options.PathServiceSid + "/Channels/" + options.PathChannelSid + "/Members/" + options.PathSid + "", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// update /// </summary> /// <param name="options"> Update Member parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Member </returns> public static MemberResource Update(UpdateMemberOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// update /// </summary> /// <param name="options"> Update Member parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Member </returns> public static async System.Threading.Tasks.Task<MemberResource> UpdateAsync(UpdateMemberOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// update /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathChannelSid"> The channel_sid </param> /// <param name="pathSid"> The sid </param> /// <param name="roleSid"> The role_sid </param> /// <param name="lastConsumedMessageIndex"> The last_consumed_message_index </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Member </returns> public static MemberResource Update(string pathServiceSid, string pathChannelSid, string pathSid, string roleSid = null, int? lastConsumedMessageIndex = null, ITwilioRestClient client = null) { var options = new UpdateMemberOptions(pathServiceSid, pathChannelSid, pathSid){RoleSid = roleSid, LastConsumedMessageIndex = lastConsumedMessageIndex}; return Update(options, client); } #if !NET35 /// <summary> /// update /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathChannelSid"> The channel_sid </param> /// <param name="pathSid"> The sid </param> /// <param name="roleSid"> The role_sid </param> /// <param name="lastConsumedMessageIndex"> The last_consumed_message_index </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Member </returns> public static async System.Threading.Tasks.Task<MemberResource> UpdateAsync(string pathServiceSid, string pathChannelSid, string pathSid, string roleSid = null, int? lastConsumedMessageIndex = null, ITwilioRestClient client = null) { var options = new UpdateMemberOptions(pathServiceSid, pathChannelSid, pathSid){RoleSid = roleSid, LastConsumedMessageIndex = lastConsumedMessageIndex}; return await UpdateAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a MemberResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> MemberResource object represented by the provided JSON </returns> public static MemberResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<MemberResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The sid /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The account_sid /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The channel_sid /// </summary> [JsonProperty("channel_sid")] public string ChannelSid { get; private set; } /// <summary> /// The service_sid /// </summary> [JsonProperty("service_sid")] public string ServiceSid { get; private set; } /// <summary> /// The identity /// </summary> [JsonProperty("identity")] public string Identity { get; private set; } /// <summary> /// The date_created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The date_updated /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// The role_sid /// </summary> [JsonProperty("role_sid")] public string RoleSid { get; private set; } /// <summary> /// The last_consumed_message_index /// </summary> [JsonProperty("last_consumed_message_index")] public int? LastConsumedMessageIndex { get; private set; } /// <summary> /// The last_consumption_timestamp /// </summary> [JsonProperty("last_consumption_timestamp")] public DateTime? LastConsumptionTimestamp { get; private set; } /// <summary> /// The url /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } private MemberResource() { } } }
using UnityEngine; using UnityEditor; using System; using System.Xml; using System.IO; using System.Collections; using System.Collections.Generic; [CustomEditor(typeof(GameControlTB))] public class GameControlEditor : Editor { GameControlTB gc; UnitControl uc; string[] turnModeLabel=new string[0]; string[] turnModeTooltip=new string[0]; string[] moveOrderLabel=new string[0]; string[] moveOrderTooltip=new string[0]; string[] loadModeLabel=new string[0]; string[] loadModeTooltip=new string[0]; string[] moveAPRuleLabel=new string[0]; string[] moveAPRuleTooltip=new string[0]; string[] attackAPRuleLabel=new string[0]; string[] attackAPRuleTooltip=new string[0]; int[] intVal=new int[10]; void Awake () { gc=(GameControlTB)target; uc=gc.gameObject.GetComponent<UnitControl>(); InitLabel(); if(gc.playerFactionID==null || gc.playerFactionID.Count==0){ gc.playerFactionID=new List<int>(); gc.playerFactionID.Add(0); } } void InitLabel(){ int enumLength = Enum.GetValues(typeof(_TurnMode)).Length; turnModeLabel=new string[enumLength]; for(int i=0; i<enumLength; i++) turnModeLabel[i]=((_TurnMode)i).ToString(); turnModeTooltip=new string[enumLength]; turnModeTooltip[0]="Each faction take turn to move all its unit in each round"; turnModeTooltip[1]="Each faction take turn to move a single unit in each round"; turnModeTooltip[2]="Each faction take turn to move a single unit in each turn\nThe round is completed when all unit has moved"; turnModeTooltip[3]="All units (regardless of faction) take turn to move according to the stats (TurnPriority)\nThe round is completed when all unit has moved"; turnModeTooltip[4]="All units (regardless of faction) take turn to move according to the stats (TurnPriority)\nUnit with higher stats may get to move more than 1 turn in a round\nThe round is completed when all unit has moved"; turnModeTooltip[5]="All units (regardless of faction) take turn to move according to the stats (TurnPriority)\nUnit with higher stats may get to move more more\nThere is no round mechanic"; enumLength = Enum.GetValues(typeof(_MoveOrder)).Length; moveOrderLabel=new string[enumLength]; for(int i=0; i<enumLength; i++) moveOrderLabel[i]=((_MoveOrder)i).ToString(); moveOrderTooltip=new string[enumLength]; moveOrderTooltip[0]="Randomise move order for the unit\nunit switching is enabled"; moveOrderTooltip[1]="Randomise move order for the unit\nunit switching is disabled"; moveOrderTooltip[2]="Arrange the move order based on unit's stats (TurnPriority)\nunit switching is not allowed"; enumLength = Enum.GetValues(typeof(_LoadMode)).Length; loadModeLabel=new string[enumLength]; for(int i=0; i<enumLength; i++) loadModeLabel[i]=((_LoadMode)i).ToString(); loadModeTooltip=new string[enumLength]; loadModeTooltip[0]="Use data carried from previous progress\nUpon complete this level, the data will be saved and carry to subsequent scene"; loadModeTooltip[1]="Use temporary data set in any previous scene, if there's any\nThis data will not be carried forward."; loadModeTooltip[2]="Use data set in UnitControl\nThis data will not be carried forward."; enumLength = Enum.GetValues(typeof(_MovementAPCostRule)).Length; moveAPRuleLabel=new string[enumLength]; for(int i=0; i<enumLength; i++) moveAPRuleLabel[i]=((_MovementAPCostRule)i).ToString(); moveAPRuleTooltip=new string[enumLength]; moveAPRuleTooltip[0]="Unit's movement doesn't cost any AP"; moveAPRuleTooltip[1]="Unit's movement cost just one AP regardless of how far the unit move"; moveAPRuleTooltip[2]="Each movement across a tile cost the unit one AP"; enumLength = Enum.GetValues(typeof(_AttackAPCostRule)).Length; attackAPRuleLabel=new string[enumLength]; for(int i=0; i<enumLength; i++) attackAPRuleLabel[i]=((_AttackAPCostRule)i).ToString(); attackAPRuleTooltip=new string[enumLength]; attackAPRuleTooltip[0]="Unit's attack doesn't cost any AP"; attackAPRuleTooltip[1]="Each attack cost the unit one AP"; for(int i=0; i<intVal.Length; i++){ intVal[i]=i; } } GUIContent cont; GUIContent[] contL; public override void OnInspectorGUI(){ gc = (GameControlTB)target; //DrawDefaultInspector(); EditorGUILayout.Space(); EditorGUILayout.Space(); int turnMode=(int)gc.turnMode; cont=new GUIContent("Turn Mode:", "Turn mode to be used in this scene"); contL=new GUIContent[turnModeLabel.Length]; for(int i=0; i<contL.Length; i++) contL[i]=new GUIContent(turnModeLabel[i], turnModeTooltip[i]); turnMode = EditorGUILayout.IntPopup(cont, turnMode, contL, intVal); gc.turnMode=(_TurnMode)turnMode; if(turnMode<=2){ int moveOrder=(int)gc.moveOrder; cont=new GUIContent("Move Order:", "Unit move order to be used in this scene"); contL=new GUIContent[moveOrderLabel.Length]; for(int i=0; i<contL.Length; i++) contL[i]=new GUIContent(moveOrderLabel[i], moveOrderTooltip[i]); moveOrder = EditorGUILayout.IntPopup(cont, moveOrder, contL, intVal); gc.moveOrder=(_MoveOrder)moveOrder; } int loadMode=(int)gc.loadMode; cont=new GUIContent("Data Load Mode:", "Data loading mode to be used in this scene"); contL=new GUIContent[loadModeLabel.Length]; for(int i=0; i<contL.Length; i++) contL[i]=new GUIContent(loadModeLabel[i], loadModeTooltip[i]); loadMode = EditorGUILayout.IntPopup(cont, loadMode, contL, intVal); gc.loadMode=(_LoadMode)loadMode; cont=new GUIContent("Enable Perk Menu:", "check to enable PerkMenu to be brought out in the scene"); EditorGUILayout.BeginHorizontal(""); //EditorGUILayout.LabelField(cont); gc.enablePerkMenu=EditorGUILayout.Toggle(cont, gc.enablePerkMenu); EditorGUILayout.EndHorizontal(); //cont=new GUIContent("PlayerFactionID:", "Numerial ID to identify player's units\nAny unit with similar unitID will be able to control by player\nif no unit with similar unitID is in the scene, the whole game will be run by AI"); //gc.playerFactionID[0]=EditorGUILayout.IntField(cont, gc.playerFactionID[0]); EditorGUILayout.Space(); EditorGUILayout.Space(); cont=new GUIContent("HotSeat Mode:", "check to enable local hot seat multiplayer\nenable multiple player faction"); EditorGUILayout.BeginHorizontal(""); //EditorGUILayout.LabelField(cont); gc.hotseat=EditorGUILayout.Toggle(cont, gc.hotseat); EditorGUILayout.EndHorizontal(); if(gc.hotseat){ gc.enableFogOfWar=false; if(gc.playerFactionID.Count==1){ int ID=gc.playerFactionID[0]; int newID=0; if(ID==0) newID=1; gc.playerFactionID.Add(newID); uc.playerUnits.Add(new PlayerUnits(newID)); } for(int i=0; i<gc.playerFactionID.Count; i++){ EditorGUILayout.BeginHorizontal(""); cont=new GUIContent("PlayerFactionID - "+i+":", "Numerial ID to identify player's units\nAny unit with similar unitID will be able to control by player\nif no unit with similar unitID is in the scene, the whole game will be run by AI"); int ID=gc.playerFactionID[i]; ID=EditorGUILayout.IntField(cont, ID, GUILayout.MaxHeight(16)); if(!gc.playerFactionID.Contains(ID)){ gc.playerFactionID[i]=ID; uc.playerUnits[i].factionID=ID; } if(GUILayout.Button("Remove", GUILayout.MaxHeight(16))){ if(gc.playerFactionID.Count>2){ gc.playerFactionID.RemoveAt(i); uc.playerUnits.RemoveAt(i); } } EditorGUILayout.EndHorizontal(); } if(GUILayout.Button("Add more player", GUILayout.MaxHeight(16))){ int newID=0; while(gc.playerFactionID.Contains(newID)) newID+=1; gc.playerFactionID.Add(newID); uc.playerUnits.Add(new PlayerUnits(newID)); } } else{ if(gc.playerFactionID.Count>1){ //int ID=gc.playerFactionID[0]; //gc.playerFactionID=new List<int>(); //gc.playerFactionID.Add(ID); for(int i=0; i<gc.playerFactionID.Count-1; i++){ gc.playerFactionID.RemoveAt(1); uc.playerUnits.RemoveAt(1); } } cont=new GUIContent("PlayerFactionID:", "Numerial ID to identify player's units\nAny unit with similar unitID will be able to control by player\nif no unit with similar unitID is in the scene, the whole game will be run by AI"); gc.playerFactionID[0]=EditorGUILayout.IntField(cont, gc.playerFactionID[0]); uc.playerUnits[0].factionID=gc.playerFactionID[0]; } EditorGUILayout.Space(); EditorGUILayout.Space(); int moveRule=(int)gc.movementAPCostRule; cont=new GUIContent("Movement AP Rule:", "The AP cost of unit's movement"); contL=new GUIContent[moveAPRuleLabel.Length]; for(int i=0; i<contL.Length; i++) contL[i]=new GUIContent(moveAPRuleLabel[i], moveAPRuleTooltip[i]); moveRule = EditorGUILayout.IntPopup(cont, moveRule, contL, intVal, GUILayout.ExpandWidth(true)); gc.movementAPCostRule=(_MovementAPCostRule)moveRule; /* if(gc.movementAPCostRule==_MovementAPCostRule.PerMove){ cont=new GUIContent("AP Cost Per Move:", "AP cost for unit to move"); gc.movementAPCost=EditorGUILayout.IntField(cont, gc.movementAPCost); } else if(gc.movementAPCostRule==_MovementAPCostRule.PerTile){ cont=new GUIContent("AP Cost Per Move:", "AP cost for unit to move across each tile"); gc.movementAPCost=EditorGUILayout.IntField(cont, gc.movementAPCost); } */ int attackRule=(int)gc.attackAPCostRule; cont=new GUIContent("Attack AP Rule:", "The AP cost of unit's attack"); contL=new GUIContent[attackAPRuleLabel.Length]; for(int i=0; i<contL.Length; i++) contL[i]=new GUIContent(attackAPRuleLabel[i], attackAPRuleTooltip[i]); attackRule = EditorGUILayout.IntPopup(cont, attackRule, contL, intVal, GUILayout.ExpandWidth(true)); gc.attackAPCostRule=(_AttackAPCostRule)attackRule; /* if(gc.attackAPCostRule==_AttackAPCostRule.PerAttack){ cont=new GUIContent("AP Cost Per Attack:", "AP cost for unit to perform each attack"); gc.attackAPCost=EditorGUILayout.IntField(cont, gc.attackAPCost); } */ cont=new GUIContent("Win Point Reward:", "point reward for winning this battle"); gc.winPointReward=EditorGUILayout.IntField(cont, gc.winPointReward); cont=new GUIContent("Next Scene:", "the name of next scene to be load"); gc.nextScene=EditorGUILayout.TextField(cont, gc.nextScene); cont=new GUIContent("Main Menu:", "the name of the main menu scene"); gc.mainMenu=EditorGUILayout.TextField(cont, gc.mainMenu); cont=new GUIContent("Enable Unit Placement:", "check to enable player to hand place the starting unit before the battle start"); EditorGUILayout.BeginHorizontal(""); EditorGUILayout.LabelField(cont, GUILayout.MinWidth(180)); gc.enableUnitPlacement=EditorGUILayout.Toggle(gc.enableUnitPlacement, GUILayout.ExpandWidth(true)); EditorGUILayout.EndHorizontal(); cont=new GUIContent("Enable Counter Attack:", "check to enable unit to perform counter attack in range (only when attacker is within attack range)"); EditorGUILayout.BeginHorizontal(""); EditorGUILayout.LabelField(cont, GUILayout.MinWidth(180)); gc.enableCounterAttack=EditorGUILayout.Toggle(gc.enableCounterAttack, GUILayout.ExpandWidth(true)); EditorGUILayout.EndHorizontal(); cont=new GUIContent("Full AP On Start:", "check to start unit at full AP"); EditorGUILayout.BeginHorizontal(""); EditorGUILayout.LabelField(cont, GUILayout.MinWidth(180)); gc.fullAPOnStart=EditorGUILayout.Toggle(gc.fullAPOnStart, GUILayout.ExpandWidth(true)); EditorGUILayout.EndHorizontal(); cont=new GUIContent("Restore AP On New Round:", "check to restore unit AP to full at every new round"); EditorGUILayout.BeginHorizontal(""); EditorGUILayout.LabelField(cont, GUILayout.MinWidth(180)); gc.fullAPOnNewRound=EditorGUILayout.Toggle(gc.fullAPOnNewRound, GUILayout.ExpandWidth(true)); EditorGUILayout.EndHorizontal(); cont=new GUIContent("Enable Cover System:", "check to use cover system\nunit behind an obstacle will gain bonus defense against attack from other side of cover"); EditorGUILayout.BeginHorizontal(""); EditorGUILayout.LabelField(cont, GUILayout.MinWidth(180)); gc.enableCover=EditorGUILayout.Toggle(gc.enableCover, GUILayout.ExpandWidth(true)); EditorGUILayout.EndHorizontal(); if(gc.enableCover){ cont=new GUIContent("- Half Cover Bonus:", "hit penalty when attacking a target behind a half cover\ntakes value from 0-1"); gc.coverBonusHalf=EditorGUILayout.FloatField(cont, gc.coverBonusHalf); cont=new GUIContent("- Full Cover Bonus:", "hit penalty when attacking a target behind a full cover\ntakes value from 0-1"); gc.coverBonusFull=EditorGUILayout.FloatField(cont, gc.coverBonusFull); cont=new GUIContent("- Flanking Crit Bonus:", "critical bonus gain when attacking a unit with no cover\ntakes value from 0-1"); gc.exposedCritBonus=EditorGUILayout.FloatField(cont, gc.exposedCritBonus); gc.coverBonusHalf=Mathf.Clamp(gc.coverBonusHalf, 0f, 1f); gc.coverBonusFull=Mathf.Clamp(gc.coverBonusFull, 0f, 1f); } cont=new GUIContent("Enable Fog of War:", "check to enable fog of war\nunit cannot see enemies beyond sight and out of line-of sight"); EditorGUILayout.BeginHorizontal(""); EditorGUILayout.LabelField(cont, GUILayout.MinWidth(180)); gc.enableFogOfWar=EditorGUILayout.Toggle(gc.enableFogOfWar, GUILayout.ExpandWidth(true)); EditorGUILayout.EndHorizontal(); if(gc.enableFogOfWar) gc.hotseat=false; cont=new GUIContent("Allow Movement After Attack:", "check to allow unit to move after attack"); EditorGUILayout.BeginHorizontal(""); EditorGUILayout.LabelField(cont, GUILayout.MinWidth(180)); gc.allowMovementAfterAttack=EditorGUILayout.Toggle(gc.allowMovementAfterAttack, GUILayout.ExpandWidth(true)); EditorGUILayout.EndHorizontal(); cont=new GUIContent("Allow Ability After Attack:", "check to allow unit to use ability after attack"); EditorGUILayout.BeginHorizontal(""); EditorGUILayout.LabelField(cont, GUILayout.MinWidth(180)); gc.allowAbilityAfterAttack=EditorGUILayout.Toggle(gc.allowAbilityAfterAttack, GUILayout.ExpandWidth(true)); EditorGUILayout.EndHorizontal(); /* if(gc.turnMode==_TurnMode.FactionSingleUnitPerTurnSingle){ cont=new GUIContent("Allow Unit Switching:", "check to allow player to switch unit in play when in FactionBasedSingleUnit turn-mode"); EditorGUILayout.BeginHorizontal(""); EditorGUILayout.LabelField(cont, GUILayout.MinWidth(230)); gc.allowUnitSwitching=EditorGUILayout.Toggle(gc.allowUnitSwitching); EditorGUILayout.EndHorizontal(); } */ cont=new GUIContent("Action Cam Frequency:", "The rate at which action-cam will be used. value from 0-1. 0 being no action-cam, 1 being always action-cam"); gc.actionCamFrequency=EditorGUILayout.FloatField(cont, gc.actionCamFrequency); if(GUI.changed){ EditorUtility.SetDirty(gc); } } }
// ------------------------------------------------------------------------------------------------------------------- // Generated code, do not edit // Command Line: DomGen "D:\Sony\poleary\components\wws_sled\SLED\SledShared\Resources\Schemas\SledProjectFiles.xsd" "SledSchema.cs" "sled" "Sce.Sled.Shared.Dom" // ------------------------------------------------------------------------------------------------------------------- using Sce.Atf.Dom; namespace Sce.Sled.Shared.Dom { /// <summary> /// SledSchema Class /// </summary> public static class SledSchema { /// <summary> /// Namespace /// </summary> public const string NS = "sled"; /// <summary> /// Initialize /// </summary> /// <param name="typeCollection"></param> public static void Initialize(XmlSchemaTypeCollection typeCollection) { SledProjectFilesType.Type = typeCollection.GetNodeType("SledProjectFilesType"); SledProjectFilesType.nameAttribute = SledProjectFilesType.Type.GetAttributeInfo("name"); SledProjectFilesType.expandedAttribute = SledProjectFilesType.Type.GetAttributeInfo("expanded"); SledProjectFilesType.assetdirectoryAttribute = SledProjectFilesType.Type.GetAttributeInfo("assetdirectory"); SledProjectFilesType.guidAttribute = SledProjectFilesType.Type.GetAttributeInfo("guid"); SledProjectFilesType.FilesChild = SledProjectFilesType.Type.GetChildInfo("Files"); SledProjectFilesType.FoldersChild = SledProjectFilesType.Type.GetChildInfo("Folders"); SledProjectFilesType.LanguagesChild = SledProjectFilesType.Type.GetChildInfo("Languages"); SledProjectFilesType.WatchesChild = SledProjectFilesType.Type.GetChildInfo("Watches"); SledProjectFilesType.RootsChild = SledProjectFilesType.Type.GetChildInfo("Roots"); SledProjectFilesType.UserSettingsChild = SledProjectFilesType.Type.GetChildInfo("UserSettings"); SledProjectFilesEmptyType.Type = typeCollection.GetNodeType("SledProjectFilesEmptyType"); SledProjectFilesEmptyType.nameAttribute = SledProjectFilesEmptyType.Type.GetAttributeInfo("name"); SledProjectFilesFolderType.Type = typeCollection.GetNodeType("SledProjectFilesFolderType"); SledProjectFilesFolderType.nameAttribute = SledProjectFilesFolderType.Type.GetAttributeInfo("name"); SledProjectFilesFolderType.expandedAttribute = SledProjectFilesFolderType.Type.GetAttributeInfo("expanded"); SledProjectFilesFolderType.FilesChild = SledProjectFilesFolderType.Type.GetChildInfo("Files"); SledProjectFilesFolderType.FoldersChild = SledProjectFilesFolderType.Type.GetChildInfo("Folders"); SledProjectFilesBaseType.Type = typeCollection.GetNodeType("SledProjectFilesBaseType"); SledProjectFilesBaseType.nameAttribute = SledProjectFilesBaseType.Type.GetAttributeInfo("name"); SledProjectFilesBaseType.expandedAttribute = SledProjectFilesBaseType.Type.GetAttributeInfo("expanded"); SledProjectFilesFileType.Type = typeCollection.GetNodeType("SledProjectFilesFileType"); SledProjectFilesFileType.nameAttribute = SledProjectFilesFileType.Type.GetAttributeInfo("name"); SledProjectFilesFileType.expandedAttribute = SledProjectFilesFileType.Type.GetAttributeInfo("expanded"); SledProjectFilesFileType.pathAttribute = SledProjectFilesFileType.Type.GetAttributeInfo("path"); SledProjectFilesFileType.guidAttribute = SledProjectFilesFileType.Type.GetAttributeInfo("guid"); SledProjectFilesFileType.BreakpointsChild = SledProjectFilesFileType.Type.GetChildInfo("Breakpoints"); SledProjectFilesFileType.FunctionsChild = SledProjectFilesFileType.Type.GetChildInfo("Functions"); SledProjectFilesFileType.AttributesChild = SledProjectFilesFileType.Type.GetChildInfo("Attributes"); SledProjectFilesBreakpointType.Type = typeCollection.GetNodeType("SledProjectFilesBreakpointType"); SledProjectFilesBreakpointType.lineAttribute = SledProjectFilesBreakpointType.Type.GetAttributeInfo("line"); SledProjectFilesBreakpointType.enabledAttribute = SledProjectFilesBreakpointType.Type.GetAttributeInfo("enabled"); SledProjectFilesBreakpointType.conditionAttribute = SledProjectFilesBreakpointType.Type.GetAttributeInfo("condition"); SledProjectFilesBreakpointType.conditionenabledAttribute = SledProjectFilesBreakpointType.Type.GetAttributeInfo("conditionenabled"); SledProjectFilesBreakpointType.conditionresultAttribute = SledProjectFilesBreakpointType.Type.GetAttributeInfo("conditionresult"); SledProjectFilesBreakpointType.usefunctionenvironmentAttribute = SledProjectFilesBreakpointType.Type.GetAttributeInfo("usefunctionenvironment"); SledFunctionBaseType.Type = typeCollection.GetNodeType("SledFunctionBaseType"); SledFunctionBaseType.nameAttribute = SledFunctionBaseType.Type.GetAttributeInfo("name"); SledFunctionBaseType.line_definedAttribute = SledFunctionBaseType.Type.GetAttributeInfo("line_defined"); SledAttributeBaseType.Type = typeCollection.GetNodeType("SledAttributeBaseType"); SledAttributeBaseType.nameAttribute = SledAttributeBaseType.Type.GetAttributeInfo("name"); SledProjectFilesLanguageType.Type = typeCollection.GetNodeType("SledProjectFilesLanguageType"); SledProjectFilesLanguageType.languageAttribute = SledProjectFilesLanguageType.Type.GetAttributeInfo("language"); SledProjectFilesLanguageType.versionAttribute = SledProjectFilesLanguageType.Type.GetAttributeInfo("version"); SledProjectFilesWatchType.Type = typeCollection.GetNodeType("SledProjectFilesWatchType"); SledProjectFilesWatchType.nameAttribute = SledProjectFilesWatchType.Type.GetAttributeInfo("name"); SledProjectFilesWatchType.expandedAttribute = SledProjectFilesWatchType.Type.GetAttributeInfo("expanded"); SledProjectFilesWatchType.language_pluginAttribute = SledProjectFilesWatchType.Type.GetAttributeInfo("language_plugin"); SledProjectFilesRootType.Type = typeCollection.GetNodeType("SledProjectFilesRootType"); SledProjectFilesRootType.directoryAttribute = SledProjectFilesRootType.Type.GetAttributeInfo("directory"); SledProjectFilesUserSettingsType.Type = typeCollection.GetNodeType("SledProjectFilesUserSettingsType"); SledProjectFilesUserSettingsType.nameAttribute = SledProjectFilesUserSettingsType.Type.GetAttributeInfo("name"); SledProjectFilesUserSettingsType.expandedAttribute = SledProjectFilesUserSettingsType.Type.GetAttributeInfo("expanded"); SledSyntaxErrorListType.Type = typeCollection.GetNodeType("SledSyntaxErrorListType"); SledSyntaxErrorListType.nameAttribute = SledSyntaxErrorListType.Type.GetAttributeInfo("name"); SledSyntaxErrorListType.ErrorsChild = SledSyntaxErrorListType.Type.GetChildInfo("Errors"); SledSyntaxErrorType.Type = typeCollection.GetNodeType("SledSyntaxErrorType"); SledSyntaxErrorType.lineAttribute = SledSyntaxErrorType.Type.GetAttributeInfo("line"); SledSyntaxErrorType.errorAttribute = SledSyntaxErrorType.Type.GetAttributeInfo("error"); SledFindResultsListType.Type = typeCollection.GetNodeType("SledFindResultsListType"); SledFindResultsListType.nameAttribute = SledFindResultsListType.Type.GetAttributeInfo("name"); SledFindResultsListType.FindResultsChild = SledFindResultsListType.Type.GetChildInfo("FindResults"); SledFindResultsType.Type = typeCollection.GetNodeType("SledFindResultsType"); SledFindResultsType.nameAttribute = SledFindResultsType.Type.GetAttributeInfo("name"); SledFindResultsType.fileAttribute = SledFindResultsType.Type.GetAttributeInfo("file"); SledFindResultsType.lineAttribute = SledFindResultsType.Type.GetAttributeInfo("line"); SledFindResultsType.start_offsetAttribute = SledFindResultsType.Type.GetAttributeInfo("start_offset"); SledFindResultsType.end_offsetAttribute = SledFindResultsType.Type.GetAttributeInfo("end_offset"); SledFindResultsType.line_textAttribute = SledFindResultsType.Type.GetAttributeInfo("line_text"); SledProfileInfoType.Type = typeCollection.GetNodeType("SledProfileInfoType"); SledProfileInfoType.functionAttribute = SledProfileInfoType.Type.GetAttributeInfo("function"); SledProfileInfoType.time_totalAttribute = SledProfileInfoType.Type.GetAttributeInfo("time_total"); SledProfileInfoType.time_avgAttribute = SledProfileInfoType.Type.GetAttributeInfo("time_avg"); SledProfileInfoType.time_minAttribute = SledProfileInfoType.Type.GetAttributeInfo("time_min"); SledProfileInfoType.time_maxAttribute = SledProfileInfoType.Type.GetAttributeInfo("time_max"); SledProfileInfoType.time_total_innerAttribute = SledProfileInfoType.Type.GetAttributeInfo("time_total_inner"); SledProfileInfoType.time_avg_innerAttribute = SledProfileInfoType.Type.GetAttributeInfo("time_avg_inner"); SledProfileInfoType.time_min_innerAttribute = SledProfileInfoType.Type.GetAttributeInfo("time_min_inner"); SledProfileInfoType.time_max_innerAttribute = SledProfileInfoType.Type.GetAttributeInfo("time_max_inner"); SledProfileInfoType.num_callsAttribute = SledProfileInfoType.Type.GetAttributeInfo("num_calls"); SledProfileInfoType.lineAttribute = SledProfileInfoType.Type.GetAttributeInfo("line"); SledProfileInfoType.fileAttribute = SledProfileInfoType.Type.GetAttributeInfo("file"); SledProfileInfoType.num_funcs_calledAttribute = SledProfileInfoType.Type.GetAttributeInfo("num_funcs_called"); SledProfileInfoType.ProfileInfoChild = SledProfileInfoType.Type.GetChildInfo("ProfileInfo"); SledProfileInfoListType.Type = typeCollection.GetNodeType("SledProfileInfoListType"); SledProfileInfoListType.nameAttribute = SledProfileInfoListType.Type.GetAttributeInfo("name"); SledProfileInfoListType.ProfileInfoChild = SledProfileInfoListType.Type.GetChildInfo("ProfileInfo"); SledMemoryTraceType.Type = typeCollection.GetNodeType("SledMemoryTraceType"); SledMemoryTraceType.orderAttribute = SledMemoryTraceType.Type.GetAttributeInfo("order"); SledMemoryTraceType.whatAttribute = SledMemoryTraceType.Type.GetAttributeInfo("what"); SledMemoryTraceType.oldaddressAttribute = SledMemoryTraceType.Type.GetAttributeInfo("oldaddress"); SledMemoryTraceType.newaddressAttribute = SledMemoryTraceType.Type.GetAttributeInfo("newaddress"); SledMemoryTraceType.oldsizeAttribute = SledMemoryTraceType.Type.GetAttributeInfo("oldsize"); SledMemoryTraceType.newsizeAttribute = SledMemoryTraceType.Type.GetAttributeInfo("newsize"); SledMemoryTraceListType.Type = typeCollection.GetNodeType("SledMemoryTraceListType"); SledMemoryTraceListType.nameAttribute = SledMemoryTraceListType.Type.GetAttributeInfo("name"); SledMemoryTraceListType.MemoryTraceChild = SledMemoryTraceListType.Type.GetChildInfo("MemoryTrace"); SledCallStackType.Type = typeCollection.GetNodeType("SledCallStackType"); SledCallStackType.functionAttribute = SledCallStackType.Type.GetAttributeInfo("function"); SledCallStackType.fileAttribute = SledCallStackType.Type.GetAttributeInfo("file"); SledCallStackType.currentlineAttribute = SledCallStackType.Type.GetAttributeInfo("currentline"); SledCallStackType.linedefinedAttribute = SledCallStackType.Type.GetAttributeInfo("linedefined"); SledCallStackType.lineendAttribute = SledCallStackType.Type.GetAttributeInfo("lineend"); SledCallStackType.levelAttribute = SledCallStackType.Type.GetAttributeInfo("level"); SledCallStackListType.Type = typeCollection.GetNodeType("SledCallStackListType"); SledCallStackListType.nameAttribute = SledCallStackListType.Type.GetAttributeInfo("name"); SledCallStackListType.CallStackChild = SledCallStackListType.Type.GetChildInfo("CallStack"); SledVarLocationType.Type = typeCollection.GetNodeType("SledVarLocationType"); SledVarLocationType.fileAttribute = SledVarLocationType.Type.GetAttributeInfo("file"); SledVarLocationType.lineAttribute = SledVarLocationType.Type.GetAttributeInfo("line"); SledVarLocationType.occurenceAttribute = SledVarLocationType.Type.GetAttributeInfo("occurence"); SledVarBaseWatchListType.Type = typeCollection.GetNodeType("SledVarBaseWatchListType"); SledVarBaseWatchListType.nameAttribute = SledVarBaseWatchListType.Type.GetAttributeInfo("name"); SledVarBaseType.Type = typeCollection.GetNodeType("SledVarBaseType"); SledVarBaseType.nameAttribute = SledVarBaseType.Type.GetAttributeInfo("name"); SledVarBaseType.unique_nameAttribute = SledVarBaseType.Type.GetAttributeInfo("unique_name"); SledVarBaseType.LocationsChild = SledVarBaseType.Type.GetChildInfo("Locations"); SledProjectFilesRootElement = typeCollection.GetRootElement("SledProjectFiles"); SledProjectFilesEmptyRootElement = typeCollection.GetRootElement("SledProjectEmpty"); SledSyntaxErrorsRootElement = typeCollection.GetRootElement("SledSyntaxErrors"); SledFindResults1RootElement = typeCollection.GetRootElement("SledFindResults1"); SledFindResults2RootElement = typeCollection.GetRootElement("SledFindResults2"); } #pragma warning disable 1591 public static class SledProjectFilesType { public static DomNodeType Type; public static AttributeInfo nameAttribute; public static AttributeInfo expandedAttribute; public static AttributeInfo assetdirectoryAttribute; public static AttributeInfo guidAttribute; public static ChildInfo FilesChild; public static ChildInfo FoldersChild; public static ChildInfo LanguagesChild; public static ChildInfo WatchesChild; public static ChildInfo RootsChild; public static ChildInfo UserSettingsChild; } public static class SledProjectFilesEmptyType { public static DomNodeType Type; public static AttributeInfo nameAttribute; } public static class SledProjectFilesFolderType { public static DomNodeType Type; public static AttributeInfo nameAttribute; public static AttributeInfo expandedAttribute; public static ChildInfo FilesChild; public static ChildInfo FoldersChild; } public static class SledProjectFilesBaseType { public static DomNodeType Type; public static AttributeInfo nameAttribute; public static AttributeInfo expandedAttribute; } public static class SledProjectFilesFileType { public static DomNodeType Type; public static AttributeInfo nameAttribute; public static AttributeInfo expandedAttribute; public static AttributeInfo pathAttribute; public static AttributeInfo guidAttribute; public static ChildInfo BreakpointsChild; public static ChildInfo FunctionsChild; public static ChildInfo AttributesChild; } public static class SledProjectFilesBreakpointType { public static DomNodeType Type; public static AttributeInfo lineAttribute; public static AttributeInfo enabledAttribute; public static AttributeInfo conditionAttribute; public static AttributeInfo conditionenabledAttribute; public static AttributeInfo conditionresultAttribute; public static AttributeInfo usefunctionenvironmentAttribute; } public static class SledFunctionBaseType { public static DomNodeType Type; public static AttributeInfo nameAttribute; public static AttributeInfo line_definedAttribute; } public static class SledAttributeBaseType { public static DomNodeType Type; public static AttributeInfo nameAttribute; } public static class SledProjectFilesLanguageType { public static DomNodeType Type; public static AttributeInfo languageAttribute; public static AttributeInfo versionAttribute; } public static class SledProjectFilesWatchType { public static DomNodeType Type; public static AttributeInfo nameAttribute; public static AttributeInfo expandedAttribute; public static AttributeInfo language_pluginAttribute; } public static class SledProjectFilesRootType { public static DomNodeType Type; public static AttributeInfo directoryAttribute; } public static class SledProjectFilesUserSettingsType { public static DomNodeType Type; public static AttributeInfo nameAttribute; public static AttributeInfo expandedAttribute; } public static class SledSyntaxErrorListType { public static DomNodeType Type; public static AttributeInfo nameAttribute; public static ChildInfo ErrorsChild; } public static class SledSyntaxErrorType { public static DomNodeType Type; public static AttributeInfo lineAttribute; public static AttributeInfo errorAttribute; } public static class SledFindResultsListType { public static DomNodeType Type; public static AttributeInfo nameAttribute; public static ChildInfo FindResultsChild; } public static class SledFindResultsType { public static DomNodeType Type; public static AttributeInfo nameAttribute; public static AttributeInfo fileAttribute; public static AttributeInfo lineAttribute; public static AttributeInfo start_offsetAttribute; public static AttributeInfo end_offsetAttribute; public static AttributeInfo line_textAttribute; } public static class SledProfileInfoType { public static DomNodeType Type; public static AttributeInfo functionAttribute; public static AttributeInfo time_totalAttribute; public static AttributeInfo time_avgAttribute; public static AttributeInfo time_minAttribute; public static AttributeInfo time_maxAttribute; public static AttributeInfo time_total_innerAttribute; public static AttributeInfo time_avg_innerAttribute; public static AttributeInfo time_min_innerAttribute; public static AttributeInfo time_max_innerAttribute; public static AttributeInfo num_callsAttribute; public static AttributeInfo lineAttribute; public static AttributeInfo fileAttribute; public static AttributeInfo num_funcs_calledAttribute; public static ChildInfo ProfileInfoChild; } public static class SledProfileInfoListType { public static DomNodeType Type; public static AttributeInfo nameAttribute; public static ChildInfo ProfileInfoChild; } public static class SledMemoryTraceType { public static DomNodeType Type; public static AttributeInfo orderAttribute; public static AttributeInfo whatAttribute; public static AttributeInfo oldaddressAttribute; public static AttributeInfo newaddressAttribute; public static AttributeInfo oldsizeAttribute; public static AttributeInfo newsizeAttribute; } public static class SledMemoryTraceListType { public static DomNodeType Type; public static AttributeInfo nameAttribute; public static ChildInfo MemoryTraceChild; } public static class SledCallStackType { public static DomNodeType Type; public static AttributeInfo functionAttribute; public static AttributeInfo fileAttribute; public static AttributeInfo currentlineAttribute; public static AttributeInfo linedefinedAttribute; public static AttributeInfo lineendAttribute; public static AttributeInfo levelAttribute; } public static class SledCallStackListType { public static DomNodeType Type; public static AttributeInfo nameAttribute; public static ChildInfo CallStackChild; } public static class SledVarLocationType { public static DomNodeType Type; public static AttributeInfo fileAttribute; public static AttributeInfo lineAttribute; public static AttributeInfo occurenceAttribute; } public static class SledVarBaseWatchListType { public static DomNodeType Type; public static AttributeInfo nameAttribute; } public static class SledVarBaseType { public static DomNodeType Type; public static AttributeInfo nameAttribute; public static AttributeInfo unique_nameAttribute; public static ChildInfo LocationsChild; } public static ChildInfo SledProjectFilesRootElement; public static ChildInfo SledProjectFilesEmptyRootElement; public static ChildInfo SledSyntaxErrorsRootElement; public static ChildInfo SledFindResults1RootElement; public static ChildInfo SledFindResults2RootElement; #pragma warning restore 1591 } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ // this file contains the data structures for the in memory database // containing display and formatting information using System.Collections.Generic; using Microsoft.PowerShell.Commands; using Microsoft.PowerShell.Commands.Internal.Format; namespace Microsoft.PowerShell.Commands.Internal.Format { #region Wide View Definitions /// <summary> /// in line definition of a wide control /// </summary> internal sealed class WideControlBody : ControlBody { /// <summary> /// number of columns to use for wide display /// </summary> internal int columns = 0; /// <summary> /// default wide entry definition /// It's mandatory /// </summary> internal WideControlEntryDefinition defaultEntryDefinition = null; /// <summary> /// optional list of list entry definition overrides. It can be empty if there are no overrides /// </summary> internal List<WideControlEntryDefinition> optionalEntryList = new List<WideControlEntryDefinition>(); } /// <summary> /// definition of the data to be displayed in a list entry /// </summary> internal sealed class WideControlEntryDefinition { /// <summary> /// applicability clause /// Only valid if not the default definition /// </summary> internal AppliesTo appliesTo = null; /// <summary> /// format directive body telling how to format the cell /// RULE: the body can only contain /// * TextToken /// * PropertyToken /// * NOTHING (provide an empty cell) /// </summary> internal List<FormatToken> formatTokenList = new List<FormatToken>(); } #endregion } namespace System.Management.Automation { /// <summary> /// Defines a list control /// </summary> public sealed class WideControl : PSControl { /// <summary>Entries in this wide control</summary> public List<WideControlEntryItem> Entries { get; internal set; } /// <summary>When true, widths are calculated based on more than the first object.</summary> public bool AutoSize { get; set; } /// <summary>Number of columns in the control</summary> public uint Columns { get; internal set; } /// <summary>Create a default WideControl</summary> public static WideControlBuilder Create(bool outOfBand = false, bool autoSize = false, uint columns = 0) { var control = new WideControl { OutOfBand = false, AutoSize = autoSize, Columns = columns }; return new WideControlBuilder(control); } internal override void WriteToXml(FormatXmlWriter writer) { writer.WriteWideControl(this); } /// <summary> /// Indicates if this control does not have /// any script blocks and is safe to export /// </summary> /// <returns>true if exportable, false otherwise</returns> internal override bool SafeForExport() { if (!base.SafeForExport()) return false; foreach (var entry in Entries) { if (!entry.SafeForExport()) return false; } return true; } internal override bool CompatibleWithOldPowerShell() { if (!base.CompatibleWithOldPowerShell()) return false; foreach (var entry in Entries) { if (!entry.CompatibleWithOldPowerShell()) return false; } return true; } /// <summary>Default constructor for WideControl</summary> public WideControl() { Entries = new List<WideControlEntryItem>(); } internal WideControl(WideControlBody widecontrolbody, ViewDefinition viewDefinition) : this() { OutOfBand = viewDefinition.outOfBand; GroupBy = PSControlGroupBy.Get(viewDefinition.groupBy); AutoSize = widecontrolbody.autosize.HasValue && widecontrolbody.autosize.Value; Columns = (uint)widecontrolbody.columns; Entries.Add(new WideControlEntryItem(widecontrolbody.defaultEntryDefinition)); foreach (WideControlEntryDefinition definition in widecontrolbody.optionalEntryList) { Entries.Add(new WideControlEntryItem(definition)); } } /// <summary>Public constructor for WideControl</summary> public WideControl(IEnumerable<WideControlEntryItem> wideEntries) : this() { if (wideEntries == null) throw PSTraceSource.NewArgumentNullException("wideEntries"); foreach (WideControlEntryItem entryItem in wideEntries) { this.Entries.Add(entryItem); } } /// <summary>Public constructor for WideControl</summary> public WideControl(IEnumerable<WideControlEntryItem> wideEntries, uint columns) : this() { if (wideEntries == null) throw PSTraceSource.NewArgumentNullException("wideEntries"); foreach (WideControlEntryItem entryItem in wideEntries) { this.Entries.Add(entryItem); } this.Columns = columns; } /// <summary>Construct an instance with columns</summary> public WideControl(uint columns) : this() { this.Columns = columns; } } /// <summary> /// Defines one item in a wide control entry /// </summary> public sealed class WideControlEntryItem { /// <summary>Display entry</summary> public DisplayEntry DisplayEntry { get; internal set; } /// <summary>List of typenames which select this entry, deprecated, use EntrySelectedBy</summary> public List<string> SelectedBy { get { if (EntrySelectedBy == null) EntrySelectedBy = new EntrySelectedBy { TypeNames = new List<string>() }; return EntrySelectedBy.TypeNames; } } /// <summary>List of typenames and/or a script block which select this entry.</summary> public EntrySelectedBy EntrySelectedBy { get; internal set; } /// <summary>Format string to apply</summary> public string FormatString { get; internal set; } internal WideControlEntryItem() { } internal WideControlEntryItem(WideControlEntryDefinition definition) : this() { FieldPropertyToken fpt = definition.formatTokenList[0] as FieldPropertyToken; if (fpt != null) { DisplayEntry = new DisplayEntry(fpt.expression); FormatString = fpt.fieldFormattingDirective.formatString; } if (definition.appliesTo != null) { EntrySelectedBy = EntrySelectedBy.Get(definition.appliesTo.referenceList); } } /// <summary> /// Public constructor for WideControlEntryItem. /// </summary> public WideControlEntryItem(DisplayEntry entry) : this() { if (entry == null) throw PSTraceSource.NewArgumentNullException("entry"); this.DisplayEntry = entry; } /// <summary> /// Public constructor for WideControlEntryItem. /// </summary> public WideControlEntryItem(DisplayEntry entry, IEnumerable<string> selectedBy) : this() { if (entry == null) throw PSTraceSource.NewArgumentNullException("entry"); if (selectedBy == null) throw PSTraceSource.NewArgumentNullException("selectedBy"); this.DisplayEntry = entry; this.EntrySelectedBy = EntrySelectedBy.Get(selectedBy, null); } internal bool SafeForExport() { return DisplayEntry.SafeForExport() && EntrySelectedBy == null || EntrySelectedBy.SafeForExport(); } internal bool CompatibleWithOldPowerShell() { // Old versions of PowerShell don't know anything about FormatString or conditions in EntrySelectedBy. return FormatString == null && (EntrySelectedBy == null || EntrySelectedBy.CompatibleWithOldPowerShell()); } } /// <summary/> public sealed class WideControlBuilder { private readonly WideControl _control; internal WideControlBuilder(WideControl control) { _control = control; } /// <summary>Group instances by the property name with an optional label.</summary> public WideControlBuilder GroupByProperty(string property, CustomControl customControl = null, string label = null) { _control.GroupBy = new PSControlGroupBy { Expression = new DisplayEntry(property, DisplayEntryValueType.Property), CustomControl = customControl, Label = label }; return this; } /// <summary>Group instances by the script block expression with an optional label.</summary> public WideControlBuilder GroupByScriptBlock(string scriptBlock, CustomControl customControl = null, string label = null) { _control.GroupBy = new PSControlGroupBy { Expression = new DisplayEntry(scriptBlock, DisplayEntryValueType.ScriptBlock), CustomControl = customControl, Label = label }; return this; } /// <summary/> public WideControlBuilder AddScriptBlockEntry(string scriptBlock, string format = null, IEnumerable<string> entrySelectedByType = null, IEnumerable<DisplayEntry> entrySelectedByCondition = null) { var entry = new WideControlEntryItem(new DisplayEntry(scriptBlock, DisplayEntryValueType.ScriptBlock)) { EntrySelectedBy = EntrySelectedBy.Get(entrySelectedByType, entrySelectedByCondition) }; _control.Entries.Add(entry); return this; } /// <summary/> public WideControlBuilder AddPropertyEntry(string propertyName, string format = null, IEnumerable<string> entrySelectedByType = null, IEnumerable<DisplayEntry> entrySelectedByCondition = null) { var entry = new WideControlEntryItem(new DisplayEntry(propertyName, DisplayEntryValueType.Property)) { EntrySelectedBy = EntrySelectedBy.Get(entrySelectedByType, entrySelectedByCondition) }; _control.Entries.Add(entry); return this; } /// <summary/> public WideControl EndWideControl() { return _control; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Selector.cs" company="Slash Games"> // Copyright (c) Slash Games. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Slash.AI.BehaviorTrees.Implementations.Composites { using System; using System.Collections.Generic; using Slash.AI.BehaviorTrees.Attributes; using Slash.AI.BehaviorTrees.Enums; using Slash.AI.BehaviorTrees.Interfaces; using Slash.AI.BehaviorTrees.Tree; using Slash.Math.Utils; /// <summary> /// Task which selects one of its children to be executed. If the chosen child finished execution, the task finishes. /// </summary> [Serializable] [Task(Name = "Selector", Description = "Task which selects one of its children to be executed. If the chosen child finished execution, the task finishes." )] public class Selector : Composite<Selector.Data> { #region Constructors and Destructors /// <summary> /// Constructor. /// </summary> public Selector() { } /// <summary> /// Constructor. /// </summary> /// <param name="children"> Child tasks. </param> public Selector(List<ITask> children) : base(children) { } #endregion #region Public Methods and Operators /// <summary> /// Activation. This method is called when the task was chosen to be executed. It's called right before the first update of the task. The task can setup its specific task data in here and do initial actions. /// </summary> /// <param name="agentData"> Agent data. </param> /// <param name="decisionData"> Decision data to use in activate method. </param> /// <returns> The SlashGames.AI.BehaviorTrees.Enums.ExecutionStatus. </returns> public override ExecutionStatus Activate(IAgentData agentData, IDecisionData decisionData) { DecisionData selectorDecisionData = decisionData as DecisionData; if (selectorDecisionData == null) { throw new InvalidCastException(string.Format("Decision data was null or not of correct type.")); } Data data = new Data { ActiveChildIdx = selectorDecisionData.SelectedChildIdx }; agentData.CurrentTaskData = data; // Activate selected child. IDecisionData childDecisionData = selectorDecisionData.ChildDecisionData; ExecutionStatus executionStatus = ExecutionStatus.None; while (executionStatus == ExecutionStatus.None) { // Update child. ExecutionStatus childExecutionStatus = this.ActivateChild( data.ActiveChildIdx, agentData, childDecisionData); switch (childExecutionStatus) { case ExecutionStatus.Success: { // Invoke callback. this.InvokeOnSuccess(); executionStatus = ExecutionStatus.Success; } break; case ExecutionStatus.Failed: case ExecutionStatus.None: { // Try next child. float decideValue = 0.0f; int selectedChildIdx = -1; if (this.CheckForTakeOverDecider( agentData, data, ref selectedChildIdx, ref decideValue, ref childDecisionData)) { data.ActiveChildIdx = selectedChildIdx; } else { executionStatus = ExecutionStatus.Failed; } } break; default: { executionStatus = childExecutionStatus; } break; } } return executionStatus; } /// <summary> /// Deactivation. /// </summary> /// <param name="agentData"> Agent data. </param> public override void Deactivate(IAgentData agentData) { // Deactivate current active child. Data data = agentData.GetTaskData<Data>(); if (data.ActiveChildIdx >= 0) { this.DeactivateChild(data.ActiveChildIdx, agentData); } base.Deactivate(agentData); } /// <summary> /// Depending on the group policy of its parent, the floating point return value indicates whether the task will be activated. /// </summary> /// <param name="agentData"> Agent data. </param> /// <param name="decisionData"> Decision data to use in activate method. </param> /// <returns> Floating point value used to decide if the task will be activated. </returns> public override float Decide(IAgentData agentData, ref IDecisionData decisionData) { float decideValue = 0.0f; int selectedChildIdx = -1; IDecisionData childDecisionData = null; if (this.DecideForFirstPossible(agentData, ref selectedChildIdx, ref decideValue, ref childDecisionData)) { // Create decision data to pass to use in Activate() method. decisionData = new DecisionData { SelectedChildIdx = selectedChildIdx, ChildDecisionData = childDecisionData }; return decideValue; } return 0.0f; } /// <summary> /// Generates a collection of active task nodes under this task. Used for debugging only. /// </summary> /// <param name="agentData"> Agent data. </param> /// <param name="taskNode"> Task node this task is located in. </param> /// <param name="activeTasks"> Collection of active task nodes. </param> public override void GetActiveTasks( IAgentData agentData, TaskNode taskNode, ref ICollection<TaskNode> activeTasks) { Data data = agentData.CurrentTaskData as Data; if (data == null) { throw new ArgumentException(string.Format("Expected selector data for task '{0}'.", this.Name)); } // Check if selector has an active child. if (!MathUtils.IsWithinBounds(data.ActiveChildIdx, 0, this.Children.Count)) { return; } // Add task to active tasks and collect active tasks of active child. TaskNode childTaskNode = taskNode.CreateChildNode(this.Children[data.ActiveChildIdx], data.ActiveChildIdx); activeTasks.Add(childTaskNode); this.GetActiveChildTasks(data.ActiveChildIdx, agentData, childTaskNode, ref activeTasks); } /// <summary> /// Per frame update. /// </summary> /// <param name="agentData"> Agent data. </param> /// <returns> Execution status after this update. </returns> public override ExecutionStatus Update(IAgentData agentData) { Data data = agentData.CurrentTaskData as Data; if (data == null) { throw new InvalidCastException(string.Format("task data was null or not of correct type.")); } // Check for higher prioritized task which interrupts current executing task. float decideValue = 0.0f; int selectedChildIdx = -1; IDecisionData childDecisionData = null; ExecutionStatus childExecutionStatus = ExecutionStatus.Running; if (this.CheckForInterruptingDecider( agentData, data, ref selectedChildIdx, ref decideValue, ref childDecisionData)) { // Deactivate current task. this.DeactivateChild(data.ActiveChildIdx, agentData); data.ActiveChildIdx = selectedChildIdx; // Activate new task. childExecutionStatus = this.ActivateChild(data.ActiveChildIdx, agentData, childDecisionData); } // Loop while an execution status was determined. ExecutionStatus executionStatus = ExecutionStatus.None; while (executionStatus == ExecutionStatus.None) { // Activate child if necessary. if (childExecutionStatus == ExecutionStatus.None) { // Activate new task. childExecutionStatus = this.ActivateChild(data.ActiveChildIdx, agentData, childDecisionData); } if (childExecutionStatus == ExecutionStatus.Running) { // Update child. childExecutionStatus = this.UpdateChild(data.ActiveChildIdx, agentData); } switch (childExecutionStatus) { case ExecutionStatus.Success: { // Invoke callback. this.InvokeOnSuccess(); executionStatus = ExecutionStatus.Success; } break; case ExecutionStatus.Failed: case ExecutionStatus.None: { // Try next child. if (this.CheckForTakeOverDecider( agentData, data, ref selectedChildIdx, ref decideValue, ref childDecisionData)) { data.ActiveChildIdx = selectedChildIdx; childExecutionStatus = ExecutionStatus.None; } else { executionStatus = ExecutionStatus.Failed; } } break; default: { executionStatus = childExecutionStatus; } break; } } return executionStatus; } #endregion #region Methods /// <summary> /// Checks for an interrupting task. Only checks higher prioritized deciders as they are the only ones which can interrupt the running task. /// </summary> /// <param name="agentData"> Agent data. </param> /// <param name="data"> task data. </param> /// <param name="childIdx"> Index of child which will be activated. </param> /// <param name="childDecideValue"> Decide value of child which will be activated. </param> /// <param name="childDecisionData"> Decision data of child to be used in activate method. </param> /// <returns> True if there's a child which wants to be activated, else false. </returns> private bool CheckForInterruptingDecider( IAgentData agentData, Data data, ref int childIdx, ref float childDecideValue, ref IDecisionData childDecisionData) { return this.DecideForFirstPossible( agentData, 0, data.ActiveChildIdx, ref childIdx, ref childDecideValue, ref childDecisionData); } /// <summary> /// Checks for a task which will take over the control when the current active child task failed. /// </summary> /// <param name="agentData"> Agent data. </param> /// <param name="data"> task data. </param> /// <param name="childIdx"> Index of child which will be activated. </param> /// <param name="childDecideValue"> Decide value of child which will be activated. </param> /// <param name="childDecisionData"> Decision data of child to be used in activate method. </param> /// <returns> True if there's a child which wants to be activated, else false. </returns> private bool CheckForTakeOverDecider( IAgentData agentData, Data data, ref int childIdx, ref float childDecideValue, ref IDecisionData childDecisionData) { return this.DecideForFirstPossible( agentData, data.ActiveChildIdx + 1, this.Children.Count, ref childIdx, ref childDecideValue, ref childDecisionData); } /// <summary> /// Takes first task which wants to be active. /// </summary> /// <param name="agentData"> Agent data. </param> /// <param name="childIdx"> Index of child which will be activated. </param> /// <param name="childDecideValue"> Decide value of child which will be activated. </param> /// <param name="childDecisionData"> Decision data of child to be used in activate method. </param> /// <returns> True if there's a child which wants to be activated, else false. </returns> private bool DecideForFirstPossible( IAgentData agentData, ref int childIdx, ref float childDecideValue, ref IDecisionData childDecisionData) { return this.DecideForFirstPossible( agentData, 0, this.Children.Count, ref childIdx, ref childDecideValue, ref childDecisionData); } #endregion /// <summary> /// Task data. /// </summary> public class Data : ITaskData { #region Public Properties /// <summary> /// Index of active child. /// </summary> public int ActiveChildIdx { get; set; } #endregion } /// <summary> /// The decision data. /// </summary> public class DecisionData : IDecisionData { #region Public Properties /// <summary> /// Decision data of selected child. /// </summary> public IDecisionData ChildDecisionData { get; set; } /// <summary> /// Index of selected child. /// </summary> public int SelectedChildIdx { get; set; } #endregion } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //----------------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Reflection; using System.Runtime; using System.Runtime.Serialization; using System.Security; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Dispatcher; using System.Xml; using System.Xml.Serialization; namespace System.ServiceModel.Description { public class XmlSerializerOperationBehavior : IOperationBehavior { private readonly Reflector.OperationReflector _reflector; private readonly bool _builtInOperationBehavior; public XmlSerializerOperationBehavior(OperationDescription operation) : this(operation, null) { } public XmlSerializerOperationBehavior(OperationDescription operation, XmlSerializerFormatAttribute attribute) { if (operation == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("operation"); #pragma warning suppress 56506 // Declaring contract cannot be null Reflector parentReflector = new Reflector(operation.DeclaringContract.Namespace, operation.DeclaringContract.ContractType); #pragma warning suppress 56506 // parentReflector cannot be null _reflector = parentReflector.ReflectOperation(operation, attribute ?? new XmlSerializerFormatAttribute()); } internal XmlSerializerOperationBehavior(OperationDescription operation, XmlSerializerFormatAttribute attribute, Reflector parentReflector) : this(operation, attribute) { // used by System.ServiceModel.Web _reflector = parentReflector.ReflectOperation(operation, attribute ?? new XmlSerializerFormatAttribute()); } private XmlSerializerOperationBehavior(Reflector.OperationReflector reflector, bool builtInOperationBehavior) { Fx.Assert(reflector != null, ""); _reflector = reflector; _builtInOperationBehavior = builtInOperationBehavior; } internal Reflector.OperationReflector OperationReflector { get { return _reflector; } } internal bool IsBuiltInOperationBehavior { get { return _builtInOperationBehavior; } } public XmlSerializerFormatAttribute XmlSerializerFormatAttribute { get { return _reflector.Attribute; } } internal static XmlSerializerOperationFormatter CreateOperationFormatter(OperationDescription operation) { return new XmlSerializerOperationBehavior(operation).CreateFormatter(); } internal static XmlSerializerOperationFormatter CreateOperationFormatter(OperationDescription operation, XmlSerializerFormatAttribute attr) { return new XmlSerializerOperationBehavior(operation, attr).CreateFormatter(); } internal static void AddBehaviors(ContractDescription contract) { AddBehaviors(contract, false); } internal static void AddBuiltInBehaviors(ContractDescription contract) { AddBehaviors(contract, true); } private static void AddBehaviors(ContractDescription contract, bool builtInOperationBehavior) { Reflector reflector = new Reflector(contract.Namespace, contract.ContractType); foreach (OperationDescription operation in contract.Operations) { Reflector.OperationReflector operationReflector = reflector.ReflectOperation(operation); if (operationReflector != null) { bool isInherited = operation.DeclaringContract != contract; if (!isInherited) { operation.Behaviors.Add(new XmlSerializerOperationBehavior(operationReflector, builtInOperationBehavior)); } } } } internal XmlSerializerOperationFormatter CreateFormatter() { return new XmlSerializerOperationFormatter(_reflector.Operation, _reflector.Attribute, _reflector.Request, _reflector.Reply); } private XmlSerializerFaultFormatter CreateFaultFormatter(SynchronizedCollection<FaultContractInfo> faultContractInfos) { return new XmlSerializerFaultFormatter(faultContractInfos, _reflector.XmlSerializerFaultContractInfos); } void IOperationBehavior.Validate(OperationDescription description) { } void IOperationBehavior.AddBindingParameters(OperationDescription description, BindingParameterCollection parameters) { } void IOperationBehavior.ApplyDispatchBehavior(OperationDescription description, DispatchOperation dispatch) { } void IOperationBehavior.ApplyClientBehavior(OperationDescription description, ClientOperation proxy) { if (description == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("description"); if (proxy == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("proxy"); if (proxy.Formatter == null) { proxy.Formatter = (IClientMessageFormatter)CreateFormatter(); proxy.SerializeRequest = _reflector.RequestRequiresSerialization; proxy.DeserializeReply = _reflector.ReplyRequiresSerialization; } if (_reflector.Attribute.SupportFaults && !proxy.IsFaultFormatterSetExplicit) proxy.FaultFormatter = (IClientFaultFormatter)CreateFaultFormatter(proxy.FaultContractInfos); } // helper for reflecting operations internal class Reflector { private readonly XmlSerializerImporter _importer; private readonly SerializerGenerationContext _generation; private Collection<OperationReflector> _operationReflectors = new Collection<OperationReflector>(); private object _thisLock = new object(); internal Reflector(string defaultNs, Type type) { _importer = new XmlSerializerImporter(defaultNs); _generation = new SerializerGenerationContext(type); } internal void EnsureMessageInfos() { lock (_thisLock) { foreach (OperationReflector operationReflector in _operationReflectors) { operationReflector.EnsureMessageInfos(); } } } private static XmlSerializerFormatAttribute FindAttribute(OperationDescription operation) { Type contractType = operation.DeclaringContract != null ? operation.DeclaringContract.ContractType : null; XmlSerializerFormatAttribute contractFormatAttribute = contractType != null ? TypeLoader.GetFormattingAttribute(contractType, null) as XmlSerializerFormatAttribute : null; return TypeLoader.GetFormattingAttribute(operation.OperationMethod, contractFormatAttribute) as XmlSerializerFormatAttribute; } // auto-reflects the operation, returning null if no attribute was found or inherited internal OperationReflector ReflectOperation(OperationDescription operation) { XmlSerializerFormatAttribute attr = FindAttribute(operation); if (attr == null) return null; return ReflectOperation(operation, attr); } // overrides the auto-reflection with an attribute internal OperationReflector ReflectOperation(OperationDescription operation, XmlSerializerFormatAttribute attrOverride) { OperationReflector operationReflector = new OperationReflector(this, operation, attrOverride, true/*reflectOnDemand*/); _operationReflectors.Add(operationReflector); return operationReflector; } internal class OperationReflector { private readonly Reflector _parent; internal readonly OperationDescription Operation; internal readonly XmlSerializerFormatAttribute Attribute; internal readonly bool IsRpc; internal readonly bool IsOneWay; internal readonly bool RequestRequiresSerialization; internal readonly bool ReplyRequiresSerialization; private readonly string _keyBase; private MessageInfo _request; private MessageInfo _reply; private SynchronizedCollection<XmlSerializerFaultContractInfo> _xmlSerializerFaultContractInfos; internal OperationReflector(Reflector parent, OperationDescription operation, XmlSerializerFormatAttribute attr, bool reflectOnDemand) { Fx.Assert(parent != null, ""); Fx.Assert(operation != null, ""); Fx.Assert(attr != null, ""); OperationFormatter.Validate(operation, attr.Style == OperationFormatStyle.Rpc, false/*IsEncoded*/); _parent = parent; this.Operation = operation; this.Attribute = attr; this.IsRpc = (attr.Style == OperationFormatStyle.Rpc); this.IsOneWay = operation.Messages.Count == 1; this.RequestRequiresSerialization = !operation.Messages[0].IsUntypedMessage; this.ReplyRequiresSerialization = !this.IsOneWay && !operation.Messages[1].IsUntypedMessage; MethodInfo methodInfo = operation.OperationMethod; if (methodInfo == null) { // keyBase needs to be unique within the scope of the parent reflector _keyBase = string.Empty; if (operation.DeclaringContract != null) { _keyBase = operation.DeclaringContract.Name + "," + operation.DeclaringContract.Namespace + ":"; } _keyBase = _keyBase + operation.Name; } else _keyBase = methodInfo.DeclaringType.FullName + ":" + methodInfo.ToString(); foreach (MessageDescription message in operation.Messages) foreach (MessageHeaderDescription header in message.Headers) SetUnknownHeaderInDescription(header); if (!reflectOnDemand) { this.EnsureMessageInfos(); } } private void SetUnknownHeaderInDescription(MessageHeaderDescription header) { if (header.AdditionalAttributesProvider != null) { object[] attrs = header.AdditionalAttributesProvider.GetCustomAttributes(false); foreach (var attr in attrs) { if (attr is XmlAnyElementAttribute) { if (String.IsNullOrEmpty(((XmlAnyElementAttribute)attr).Name)) { header.IsUnknownHeaderCollection = true; } } } } } private string ContractName { get { return this.Operation.DeclaringContract.Name; } } private string ContractNamespace { get { return this.Operation.DeclaringContract.Namespace; } } internal MessageInfo Request { get { _parent.EnsureMessageInfos(); return _request; } } internal MessageInfo Reply { get { _parent.EnsureMessageInfos(); return _reply; } } internal SynchronizedCollection<XmlSerializerFaultContractInfo> XmlSerializerFaultContractInfos { get { _parent.EnsureMessageInfos(); return _xmlSerializerFaultContractInfos; } } internal void EnsureMessageInfos() { if (_request == null) { foreach (Type knownType in Operation.KnownTypes) { if (knownType == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxKnownTypeNull, Operation.Name))); _parent._importer.IncludeType(knownType); } _request = CreateMessageInfo(this.Operation.Messages[0], ":Request"); // We don't do the following check at Net Native runtime because XmlMapping.XsdElementName // is not available at that time. bool skipVerifyXsdElementName = false; #if FEATURE_NETNATIVE skipVerifyXsdElementName = GeneratedXmlSerializers.IsInitialized; #endif if (_request != null && this.IsRpc && this.Operation.IsValidateRpcWrapperName && !skipVerifyXsdElementName && _request.BodyMapping.XsdElementName != this.Operation.Name) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxRpcMessageBodyPartNameInvalid, Operation.Name, this.Operation.Messages[0].MessageName, _request.BodyMapping.XsdElementName, this.Operation.Name))); if (!this.IsOneWay) { _reply = CreateMessageInfo(this.Operation.Messages[1], ":Response"); XmlName responseName = TypeLoader.GetBodyWrapperResponseName(this.Operation.Name); if (_reply != null && this.IsRpc && this.Operation.IsValidateRpcWrapperName && !skipVerifyXsdElementName && _reply.BodyMapping.XsdElementName != responseName.EncodedName) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxRpcMessageBodyPartNameInvalid, Operation.Name, this.Operation.Messages[1].MessageName, _reply.BodyMapping.XsdElementName, responseName.EncodedName))); } if (this.Attribute.SupportFaults) { GenerateXmlSerializerFaultContractInfos(); } } } private void GenerateXmlSerializerFaultContractInfos() { SynchronizedCollection<XmlSerializerFaultContractInfo> faultInfos = new SynchronizedCollection<XmlSerializerFaultContractInfo>(); for (int i = 0; i < this.Operation.Faults.Count; i++) { FaultDescription fault = this.Operation.Faults[i]; FaultContractInfo faultContractInfo = new FaultContractInfo(fault.Action, fault.DetailType, fault.ElementName, fault.Namespace, this.Operation.KnownTypes); XmlQualifiedName elementName; XmlMembersMapping xmlMembersMapping = this.ImportFaultElement(fault, out elementName); SerializerStub serializerStub = _parent._generation.AddSerializer(xmlMembersMapping); faultInfos.Add(new XmlSerializerFaultContractInfo(faultContractInfo, serializerStub, elementName)); } _xmlSerializerFaultContractInfos = faultInfos; } private MessageInfo CreateMessageInfo(MessageDescription message, string key) { if (message.IsUntypedMessage) return null; MessageInfo info = new MessageInfo(); bool isEncoded = false; if (message.IsTypedMessage) key = message.MessageType.FullName + ":" + isEncoded + ":" + IsRpc; XmlMembersMapping headersMapping = LoadHeadersMapping(message, key + ":Headers"); info.SetHeaders(_parent._generation.AddSerializer(headersMapping)); MessagePartDescriptionCollection rpcEncodedTypedMessgeBodyParts; info.SetBody(_parent._generation.AddSerializer(LoadBodyMapping(message, key, out rpcEncodedTypedMessgeBodyParts)), rpcEncodedTypedMessgeBodyParts); CreateHeaderDescriptionTable(message, info, headersMapping); return info; } private void CreateHeaderDescriptionTable(MessageDescription message, MessageInfo info, XmlMembersMapping headersMapping) { int headerNameIndex = 0; OperationFormatter.MessageHeaderDescriptionTable headerDescriptionTable = new OperationFormatter.MessageHeaderDescriptionTable(); info.SetHeaderDescriptionTable(headerDescriptionTable); foreach (MessageHeaderDescription header in message.Headers) { if (header.IsUnknownHeaderCollection) info.SetUnknownHeaderDescription(header); else if (headersMapping != null) { XmlMemberMapping memberMapping = headersMapping[headerNameIndex++]; string headerName, headerNs; headerName = memberMapping.XsdElementName; headerNs = memberMapping.Namespace; if (headerName != header.Name) { if (message.MessageType != null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxHeaderNameMismatchInMessageContract, message.MessageType, header.MemberInfo.Name, header.Name, headerName))); else throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxHeaderNameMismatchInOperation, this.Operation.Name, this.Operation.DeclaringContract.Name, this.Operation.DeclaringContract.Namespace, header.Name, headerName))); } if (headerNs != header.Namespace) { if (message.MessageType != null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxHeaderNamespaceMismatchInMessageContract, message.MessageType, header.MemberInfo.Name, header.Namespace, headerNs))); else throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxHeaderNamespaceMismatchInOperation, this.Operation.Name, this.Operation.DeclaringContract.Name, this.Operation.DeclaringContract.Namespace, header.Namespace, headerNs))); } headerDescriptionTable.Add(headerName, headerNs, header); } } } private XmlMembersMapping LoadBodyMapping(MessageDescription message, string mappingKey, out MessagePartDescriptionCollection rpcEncodedTypedMessageBodyParts) { MessagePartDescription returnPart; string wrapperName, wrapperNs; MessagePartDescriptionCollection bodyParts; rpcEncodedTypedMessageBodyParts = null; returnPart = OperationFormatter.IsValidReturnValue(message.Body.ReturnValue) ? message.Body.ReturnValue : null; bodyParts = message.Body.Parts; wrapperName = message.Body.WrapperName; wrapperNs = message.Body.WrapperNamespace; bool isWrapped = (wrapperName != null); bool hasReturnValue = returnPart != null; int paramCount = bodyParts.Count + (hasReturnValue ? 1 : 0); if (paramCount == 0 && !isWrapped) // no need to create serializer { return null; } XmlReflectionMember[] members = new XmlReflectionMember[paramCount]; int paramIndex = 0; if (hasReturnValue) members[paramIndex++] = XmlSerializerHelper.GetXmlReflectionMember(returnPart, IsRpc, isWrapped); for (int i = 0; i < bodyParts.Count; i++) members[paramIndex++] = XmlSerializerHelper.GetXmlReflectionMember(bodyParts[i], IsRpc, isWrapped); if (!isWrapped) wrapperNs = ContractNamespace; return ImportMembersMapping(wrapperName, wrapperNs, members, isWrapped, IsRpc, mappingKey); } private XmlMembersMapping LoadHeadersMapping(MessageDescription message, string mappingKey) { int headerCount = message.Headers.Count; if (headerCount == 0) return null; int unknownHeaderCount = 0, headerIndex = 0; XmlReflectionMember[] members = new XmlReflectionMember[headerCount]; for (int i = 0; i < headerCount; i++) { MessageHeaderDescription header = message.Headers[i]; if (!header.IsUnknownHeaderCollection) { members[headerIndex++] = XmlSerializerHelper.GetXmlReflectionMember(header, false/*isRpc*/, false/*isWrapped*/); } else { unknownHeaderCount++; } } if (unknownHeaderCount == headerCount) { return null; } if (unknownHeaderCount > 0) { XmlReflectionMember[] newMembers = new XmlReflectionMember[headerCount - unknownHeaderCount]; Array.Copy(members, newMembers, newMembers.Length); members = newMembers; } return ImportMembersMapping(ContractName, ContractNamespace, members, false /*isWrapped*/, false /*isRpc*/, mappingKey); } internal XmlMembersMapping ImportMembersMapping(string elementName, string ns, XmlReflectionMember[] members, bool hasWrapperElement, bool rpc, string mappingKey) { string key = mappingKey.StartsWith(":", StringComparison.Ordinal) ? _keyBase + mappingKey : mappingKey; return _parent._importer.ImportMembersMapping(new XmlName(elementName, true /*isEncoded*/), ns, members, hasWrapperElement, rpc, key); } internal XmlMembersMapping ImportFaultElement(FaultDescription fault, out XmlQualifiedName elementName) { // the number of reflection members is always 1 because there is only one fault detail type XmlReflectionMember[] members = new XmlReflectionMember[1]; XmlName faultElementName = fault.ElementName; string faultNamespace = fault.Namespace; if (faultElementName == null) { XmlTypeMapping mapping = _parent._importer.ImportTypeMapping(fault.DetailType); faultElementName = new XmlName(mapping.ElementName, false /*isEncoded*/); faultNamespace = mapping.Namespace; if (faultElementName == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxFaultTypeAnonymous, this.Operation.Name, fault.DetailType.FullName))); } elementName = new XmlQualifiedName(faultElementName.DecodedName, faultNamespace); members[0] = XmlSerializerHelper.GetXmlReflectionMember(null /*memberName*/, faultElementName, faultNamespace, fault.DetailType, null /*additionalAttributesProvider*/, false /*isMultiple*/, false /*isWrapped*/); string mappingKey = "fault:" + faultElementName.DecodedName + ":" + faultNamespace; return ImportMembersMapping(faultElementName.EncodedName, faultNamespace, members, false /*hasWrapperElement*/, this.IsRpc, mappingKey); } } private class XmlSerializerImporter { private readonly string _defaultNs; private XmlReflectionImporter _xmlImporter; private Dictionary<string, XmlMembersMapping> _xmlMappings; internal XmlSerializerImporter(string defaultNs) { _defaultNs = defaultNs; _xmlImporter = null; } private XmlReflectionImporter XmlImporter { get { if (_xmlImporter == null) { _xmlImporter = new XmlReflectionImporter(_defaultNs); } return _xmlImporter; } } private Dictionary<string, XmlMembersMapping> XmlMappings { get { if (_xmlMappings == null) { _xmlMappings = new Dictionary<string, XmlMembersMapping>(); } return _xmlMappings; } } internal XmlMembersMapping ImportMembersMapping(XmlName elementName, string ns, XmlReflectionMember[] members, bool hasWrapperElement, bool rpc, string mappingKey) { XmlMembersMapping mapping; string mappingName = elementName.DecodedName; if (XmlMappings.TryGetValue(mappingKey, out mapping)) { return mapping; } mapping = this.XmlImporter.ImportMembersMapping(mappingName, ns, members, hasWrapperElement, rpc); mapping.SetKey(mappingKey); XmlMappings.Add(mappingKey, mapping); return mapping; } internal XmlTypeMapping ImportTypeMapping(Type type) { return this.XmlImporter.ImportTypeMapping(type); } internal void IncludeType(Type knownType) { this.XmlImporter.IncludeType(knownType); } } internal class SerializerGenerationContext { private List<XmlMembersMapping> _mappings = new List<XmlMembersMapping>(); private XmlSerializer[] _serializers = null; private Type _type; private object _thisLock = new object(); internal SerializerGenerationContext(Type type) { _type = type; } // returns a stub to a serializer internal SerializerStub AddSerializer(XmlMembersMapping mapping) { int handle = -1; if (mapping != null) { handle = ((IList)_mappings).Add(mapping); } return new SerializerStub(this, mapping, handle); } internal XmlSerializer GetSerializer(int handle) { if (handle < 0) { return null; } if (_serializers == null) { lock (_thisLock) { if (_serializers == null) { _serializers = GenerateSerializers(); } } } return _serializers[handle]; } private XmlSerializer[] GenerateSerializers() { //this.Mappings may have duplicate mappings (for e.g. same message contract is used by more than one operation) //XmlSerializer.FromMappings require unique mappings. The following code uniquifies, calls FromMappings and deuniquifies List<XmlMembersMapping> uniqueMappings = new List<XmlMembersMapping>(); int[] uniqueIndexes = new int[_mappings.Count]; for (int srcIndex = 0; srcIndex < _mappings.Count; srcIndex++) { XmlMembersMapping mapping = _mappings[srcIndex]; int uniqueIndex = uniqueMappings.IndexOf(mapping); if (uniqueIndex < 0) { uniqueMappings.Add(mapping); uniqueIndex = uniqueMappings.Count - 1; } uniqueIndexes[srcIndex] = uniqueIndex; } XmlSerializer[] uniqueSerializers = CreateSerializersFromMappings(uniqueMappings.ToArray(), _type); if (uniqueMappings.Count == _mappings.Count) return uniqueSerializers; XmlSerializer[] serializers = new XmlSerializer[_mappings.Count]; for (int i = 0; i < _mappings.Count; i++) { serializers[i] = uniqueSerializers[uniqueIndexes[i]]; } return serializers; } [Fx.Tag.SecurityNote(Critical = "XmlSerializer.FromMappings has a LinkDemand.", Safe = "LinkDemand is spurious, not protecting anything in particular.")] [SecuritySafeCritical] private XmlSerializer[] CreateSerializersFromMappings(XmlMapping[] mappings, Type type) { return XmlSerializerHelper.FromMappings(mappings, type); } } internal struct SerializerStub { private readonly SerializerGenerationContext _context; internal readonly XmlMembersMapping Mapping; internal readonly int Handle; internal SerializerStub(SerializerGenerationContext context, XmlMembersMapping mapping, int handle) { _context = context; this.Mapping = mapping; this.Handle = handle; } internal XmlSerializer GetSerializer() { return _context.GetSerializer(Handle); } } internal class XmlSerializerFaultContractInfo { private FaultContractInfo _faultContractInfo; private SerializerStub _serializerStub; private XmlQualifiedName _faultContractElementName; private XmlSerializerObjectSerializer _serializer; internal XmlSerializerFaultContractInfo(FaultContractInfo faultContractInfo, SerializerStub serializerStub, XmlQualifiedName faultContractElementName) { if (faultContractInfo == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("faultContractInfo"); } if (faultContractElementName == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("faultContractElementName"); } _faultContractInfo = faultContractInfo; _serializerStub = serializerStub; _faultContractElementName = faultContractElementName; } internal FaultContractInfo FaultContractInfo { get { return _faultContractInfo; } } internal XmlQualifiedName FaultContractElementName { get { return _faultContractElementName; } } internal XmlSerializerObjectSerializer Serializer { get { if (_serializer == null) _serializer = new XmlSerializerObjectSerializer(_faultContractInfo.Detail, _faultContractElementName, _serializerStub.GetSerializer()); return _serializer; } } } internal class MessageInfo : XmlSerializerOperationFormatter.MessageInfo { private SerializerStub _headers; private SerializerStub _body; private OperationFormatter.MessageHeaderDescriptionTable _headerDescriptionTable; private MessageHeaderDescription _unknownHeaderDescription; private MessagePartDescriptionCollection _rpcEncodedTypedMessageBodyParts; internal XmlMembersMapping BodyMapping { get { return _body.Mapping; } } internal override XmlSerializer BodySerializer { get { return _body.GetSerializer(); } } internal XmlMembersMapping HeadersMapping { get { return _headers.Mapping; } } internal override XmlSerializer HeaderSerializer { get { return _headers.GetSerializer(); } } internal override OperationFormatter.MessageHeaderDescriptionTable HeaderDescriptionTable { get { return _headerDescriptionTable; } } internal override MessageHeaderDescription UnknownHeaderDescription { get { return _unknownHeaderDescription; } } internal override MessagePartDescriptionCollection RpcEncodedTypedMessageBodyParts { get { return _rpcEncodedTypedMessageBodyParts; } } internal void SetBody(SerializerStub body, MessagePartDescriptionCollection rpcEncodedTypedMessageBodyParts) { _body = body; _rpcEncodedTypedMessageBodyParts = rpcEncodedTypedMessageBodyParts; } internal void SetHeaders(SerializerStub headers) { _headers = headers; } internal void SetHeaderDescriptionTable(OperationFormatter.MessageHeaderDescriptionTable headerDescriptionTable) { _headerDescriptionTable = headerDescriptionTable; } internal void SetUnknownHeaderDescription(MessageHeaderDescription unknownHeaderDescription) { _unknownHeaderDescription = unknownHeaderDescription; } } } } internal static class XmlSerializerHelper { static internal XmlReflectionMember GetXmlReflectionMember(MessagePartDescription part, bool isRpc, bool isWrapped) { string ns = isRpc ? null : part.Namespace; MemberInfo additionalAttributesProvider = null; if (part.AdditionalAttributesProvider.MemberInfo != null) additionalAttributesProvider = part.AdditionalAttributesProvider.MemberInfo; XmlName memberName = string.IsNullOrEmpty(part.UniquePartName) ? null : new XmlName(part.UniquePartName, true /*isEncoded*/); XmlName elementName = part.XmlName; return GetXmlReflectionMember(memberName, elementName, ns, part.Type, additionalAttributesProvider, part.Multiple, isWrapped); } static internal XmlReflectionMember GetXmlReflectionMember(XmlName memberName, XmlName elementName, string ns, Type type, MemberInfo additionalAttributesProvider, bool isMultiple, bool isWrapped) { XmlReflectionMember member = new XmlReflectionMember(); member.MemberName = (memberName ?? elementName).DecodedName; member.MemberType = type; if (member.MemberType.IsByRef) member.MemberType = member.MemberType.GetElementType(); if (isMultiple) member.MemberType = member.MemberType.MakeArrayType(); if (additionalAttributesProvider != null) { member.XmlAttributes = XmlAttributesHelper.CreateXmlAttributes(additionalAttributesProvider); } if (member.XmlAttributes == null) member.XmlAttributes = new XmlAttributes(); else { Type invalidAttributeType = null; if (member.XmlAttributes.XmlAttribute != null) invalidAttributeType = typeof(XmlAttributeAttribute); else if (member.XmlAttributes.XmlAnyAttribute != null && !isWrapped) invalidAttributeType = typeof(XmlAnyAttributeAttribute); else if (member.XmlAttributes.XmlChoiceIdentifier != null) invalidAttributeType = typeof(XmlChoiceIdentifierAttribute); else if (member.XmlAttributes.XmlIgnore) invalidAttributeType = typeof(XmlIgnoreAttribute); else if (member.XmlAttributes.Xmlns) invalidAttributeType = typeof(XmlNamespaceDeclarationsAttribute); else if (member.XmlAttributes.XmlText != null) invalidAttributeType = typeof(XmlTextAttribute); else if (member.XmlAttributes.XmlEnum != null) invalidAttributeType = typeof(XmlEnumAttribute); if (invalidAttributeType != null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(isWrapped ? SR.SFxInvalidXmlAttributeInWrapped : SR.SFxInvalidXmlAttributeInBare, invalidAttributeType, elementName.DecodedName))); if (member.XmlAttributes.XmlArray != null && isMultiple) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxXmlArrayNotAllowedForMultiple, elementName.DecodedName, ns))); } bool isArray = member.MemberType.IsArray; if ((isArray && !isMultiple && member.MemberType != typeof(byte[])) || (!isArray && typeof(IEnumerable).IsAssignableFrom(member.MemberType) && member.MemberType != typeof(string) && !typeof(XmlNode).IsAssignableFrom(member.MemberType) && !typeof(IXmlSerializable).IsAssignableFrom(member.MemberType))) { if (member.XmlAttributes.XmlArray != null) { if (member.XmlAttributes.XmlArray.ElementName == String.Empty) member.XmlAttributes.XmlArray.ElementName = elementName.DecodedName; if (member.XmlAttributes.XmlArray.Namespace == null) member.XmlAttributes.XmlArray.Namespace = ns; } else if (HasNoXmlParameterAttributes(member.XmlAttributes)) { member.XmlAttributes.XmlArray = new XmlArrayAttribute(); member.XmlAttributes.XmlArray.ElementName = elementName.DecodedName; member.XmlAttributes.XmlArray.Namespace = ns; } } else { if (member.XmlAttributes.XmlElements == null || member.XmlAttributes.XmlElements.Count == 0) { if (HasNoXmlParameterAttributes(member.XmlAttributes)) { XmlElementAttribute elementAttribute = new XmlElementAttribute(); elementAttribute.ElementName = elementName.DecodedName; elementAttribute.Namespace = ns; member.XmlAttributes.XmlElements.Add(elementAttribute); } } else { foreach (XmlElementAttribute elementAttribute in member.XmlAttributes.XmlElements) { if (elementAttribute.ElementName == String.Empty) elementAttribute.ElementName = elementName.DecodedName; if (elementAttribute.Namespace == null) elementAttribute.Namespace = ns; } } } return member; } private static bool HasNoXmlParameterAttributes(XmlAttributes xmlAttributes) { return xmlAttributes.XmlAnyAttribute == null && (xmlAttributes.XmlAnyElements == null || xmlAttributes.XmlAnyElements.Count == 0) && xmlAttributes.XmlArray == null && xmlAttributes.XmlAttribute == null && !xmlAttributes.XmlIgnore && xmlAttributes.XmlText == null && xmlAttributes.XmlChoiceIdentifier == null && (xmlAttributes.XmlElements == null || xmlAttributes.XmlElements.Count == 0) && !xmlAttributes.Xmlns; } public static XmlSerializer[] FromMappings(XmlMapping[] mappings, Type type) { #if FEATURE_NETNATIVE if (GeneratedXmlSerializers.IsInitialized) { return FromMappingsViaInjection(mappings, type); } #endif return FromMappingsViaReflection(mappings, type); } private static XmlSerializer[] FromMappingsViaReflection(XmlMapping[] mappings, Type type) { if (mappings == null || mappings.Length == 0) { return new XmlSerializer[0]; } Array mappingArray = XmlMappingTypesHelper.InitializeArray(XmlMappingTypesHelper.XmlMappingType, mappings); MethodInfo method = typeof(XmlSerializer).GetMethod("FromMappings", new Type[] { XmlMappingTypesHelper.XmlMappingType.MakeArrayType(), typeof(Type) }); object result = method.Invoke(null, new object[] { mappingArray, type }); return (XmlSerializer[])result; } #if FEATURE_NETNATIVE private static XmlSerializer[] FromMappingsViaInjection(XmlMapping[] mappings, Type type) { XmlSerializer[] serializers = new XmlSerializer[mappings.Length]; for (int i = 0; i < serializers.Length; i++) { Type t; GeneratedXmlSerializers.GetGeneratedSerializers().TryGetValue(mappings[i].Key, out t); if (t == null) { throw new InvalidOperationException(SR.Format(SR.SFxXmlSerializerIsNotFound, type)); } serializers[i] = new XmlSerializer(t); } return serializers; } #endif } }
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using ZXing.Common; namespace ZXing.OneD { /// <summary> /// Encapsulates functionality and implementation that is common to all families /// of one-dimensional barcodes. /// <author>[email protected] (Daniel Switkin)</author> /// <author>Sean Owen</author> /// </summary> internal abstract class OneDReader : Reader { /// <summary> /// /// </summary> protected static int INTEGER_MATH_SHIFT = 8; /// <summary> /// /// </summary> protected static int PATTERN_MATCH_RESULT_SCALE_FACTOR = 1 << INTEGER_MATH_SHIFT; /// <summary> /// Locates and decodes a barcode in some format within an image. /// </summary> /// <param name="image">image of barcode to decode</param> /// <returns> /// String which the barcode encodes /// </returns> public Result decode(BinaryBitmap image) { return decode(image, null); } /// <summary> /// Locates and decodes a barcode in some format within an image. This method also accepts /// hints, each possibly associated to some data, which may help the implementation decode. /// Note that we don't try rotation without the try harder flag, even if rotation was supported. /// </summary> /// <param name="image">image of barcode to decode</param> /// <param name="hints">passed as a <see cref="IDictionary{TKey, TValue}"/> from <see cref="DecodeHintType"/> /// to arbitrary data. The /// meaning of the data depends upon the hint type. The implementation may or may not do /// anything with these hints.</param> /// <returns> /// String which the barcode encodes /// </returns> virtual public Result decode(BinaryBitmap image, IDictionary<DecodeHintType, object> hints) { var result = doDecode(image, hints); if (result == null) { bool tryHarder = hints != null && hints.ContainsKey(DecodeHintType.TRY_HARDER); bool tryHarderWithoutRotation = hints != null && hints.ContainsKey(DecodeHintType.TRY_HARDER_WITHOUT_ROTATION); if (tryHarder && !tryHarderWithoutRotation && image.RotateSupported) { BinaryBitmap rotatedImage = image.rotateCounterClockwise(); result = doDecode(rotatedImage, hints); if (result == null) return null; // Record that we found it rotated 90 degrees CCW / 270 degrees CW IDictionary<ResultMetadataType, object> metadata = result.ResultMetadata; int orientation = 270; if (metadata != null && metadata.ContainsKey(ResultMetadataType.ORIENTATION)) { // But if we found it reversed in doDecode(), add in that result here: orientation = (orientation + (int) metadata[ResultMetadataType.ORIENTATION])%360; } result.putMetadata(ResultMetadataType.ORIENTATION, orientation); // Update result points ResultPoint[] points = result.ResultPoints; if (points != null) { int height = rotatedImage.Height; for (int i = 0; i < points.Length; i++) { points[i] = new ResultPoint(height - points[i].Y - 1, points[i].X); } } } } return result; } /// <summary> /// Resets any internal state the implementation has after a decode, to prepare it /// for reuse. /// </summary> virtual public void reset() { // do nothing } /// <summary> /// We're going to examine rows from the middle outward, searching alternately above and below the /// middle, and farther out each time. rowStep is the number of rows between each successive /// attempt above and below the middle. So we'd scan row middle, then middle - rowStep, then /// middle + rowStep, then middle - (2 * rowStep), etc. /// rowStep is bigger as the image is taller, but is always at least 1. We've somewhat arbitrarily /// decided that moving up and down by about 1/16 of the image is pretty good; we try more of the /// image if "trying harder". /// </summary> /// <param name="image">The image to decode</param> /// <param name="hints">Any hints that were requested</param> /// <returns>The contents of the decoded barcode</returns> private Result doDecode(BinaryBitmap image, IDictionary<DecodeHintType, object> hints) { int width = image.Width; int height = image.Height; BitArray row = new BitArray(width); int middle = height >> 1; bool tryHarder = hints != null && hints.ContainsKey(DecodeHintType.TRY_HARDER); int rowStep = Math.Max(1, height >> (tryHarder ? 8 : 5)); int maxLines; if (tryHarder) { maxLines = height; // Look at the whole image, not just the center } else { maxLines = 15; // 15 rows spaced 1/32 apart is roughly the middle half of the image } for (int x = 0; x < maxLines; x++) { // Scanning from the middle out. Determine which row we're looking at next: int rowStepsAboveOrBelow = (x + 1) >> 1; bool isAbove = (x & 0x01) == 0; // i.e. is x even? int rowNumber = middle + rowStep * (isAbove ? rowStepsAboveOrBelow : -rowStepsAboveOrBelow); if (rowNumber < 0 || rowNumber >= height) { // Oops, if we run off the top or bottom, stop break; } // Estimate black point for this row and load it: row = image.getBlackRow(rowNumber, row); if (row == null) continue; // While we have the image data in a BitArray, it's fairly cheap to reverse it in place to // handle decoding upside down barcodes. for (int attempt = 0; attempt < 2; attempt++) { if (attempt == 1) { // trying again? row.reverse(); // reverse the row and continue // This means we will only ever draw result points *once* in the life of this method // since we want to avoid drawing the wrong points after flipping the row, and, // don't want to clutter with noise from every single row scan -- just the scans // that start on the center line. if (hints != null && hints.ContainsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK)) { IDictionary<DecodeHintType, Object> newHints = new Dictionary<DecodeHintType, Object>(); foreach (var hint in hints) { if (hint.Key != DecodeHintType.NEED_RESULT_POINT_CALLBACK) newHints.Add(hint.Key, hint.Value); } hints = newHints; } } // Look for a barcode Result result = decodeRow(rowNumber, row, hints); if (result == null) continue; // We found our barcode if (attempt == 1) { // But it was upside down, so note that result.putMetadata(ResultMetadataType.ORIENTATION, 180); // And remember to flip the result points horizontally. ResultPoint[] points = result.ResultPoints; if (points != null) { points[0] = new ResultPoint(width - points[0].X - 1, points[0].Y); points[1] = new ResultPoint(width - points[1].X - 1, points[1].Y); } } return result; } } return null; } /// <summary> /// Records the size of successive runs of white and black pixels in a row, starting at a given point. /// The values are recorded in the given array, and the number of runs recorded is equal to the size /// of the array. If the row starts on a white pixel at the given start point, then the first count /// recorded is the run of white pixels starting from that point; likewise it is the count of a run /// of black pixels if the row begin on a black pixels at that point. /// </summary> /// <param name="row">row to count from</param> /// <param name="start">offset into row to start at</param> /// <param name="counters">array into which to record counts</param> protected static bool recordPattern(BitArray row, int start, int[] counters) { return recordPattern(row, start, counters, counters.Length); } /// <summary> /// Records the size of successive runs of white and black pixels in a row, starting at a given point. /// The values are recorded in the given array, and the number of runs recorded is equal to the size /// of the array. If the row starts on a white pixel at the given start point, then the first count /// recorded is the run of white pixels starting from that point; likewise it is the count of a run /// of black pixels if the row begin on a black pixels at that point. /// </summary> /// <param name="row">row to count from</param> /// <param name="start">offset into row to start at</param> /// <param name="counters">array into which to record counts</param> protected static bool recordPattern(BitArray row, int start, int[] counters, int numCounters) { for (int idx = 0; idx < numCounters; idx++) { counters[idx] = 0; } int end = row.Size; if (start >= end) { return false; } bool isWhite = !row[start]; int counterPosition = 0; int i = start; while (i < end) { if (row[i] ^ isWhite) { // that is, exactly one is true counters[counterPosition]++; } else { counterPosition++; if (counterPosition == numCounters) { break; } else { counters[counterPosition] = 1; isWhite = !isWhite; } } i++; } // If we read fully the last section of pixels and filled up our counters -- or filled // the last counter but ran off the side of the image, OK. Otherwise, a problem. return (counterPosition == numCounters || (counterPosition == numCounters - 1 && i == end)); } /// <summary> /// Records the pattern in reverse. /// </summary> /// <param name="row">The row.</param> /// <param name="start">The start.</param> /// <param name="counters">The counters.</param> /// <returns></returns> protected static bool recordPatternInReverse(BitArray row, int start, int[] counters) { // This could be more efficient I guess int numTransitionsLeft = counters.Length; bool last = row[start]; while (start > 0 && numTransitionsLeft >= 0) { if (row[--start] != last) { numTransitionsLeft--; last = !last; } } if (numTransitionsLeft >= 0) { return false; } return recordPattern(row, start + 1, counters); } /// <summary> /// Determines how closely a set of observed counts of runs of black/white values matches a given /// target pattern. This is reported as the ratio of the total variance from the expected pattern /// proportions across all pattern elements, to the length of the pattern. /// </summary> /// <param name="counters">observed counters</param> /// <param name="pattern">expected pattern</param> /// <param name="maxIndividualVariance">The most any counter can differ before we give up</param> /// <returns>ratio of total variance between counters and pattern compared to total pattern size, /// where the ratio has been multiplied by 256. So, 0 means no variance (perfect match); 256 means /// the total variance between counters and patterns equals the pattern length, higher values mean /// even more variance</returns> protected static int patternMatchVariance(int[] counters, int[] pattern, int maxIndividualVariance) { int numCounters = counters.Length; int total = 0; int patternLength = 0; for (int i = 0; i < numCounters; i++) { total += counters[i]; patternLength += pattern[i]; } if (total < patternLength) { // If we don't even have one pixel per unit of bar width, assume this is too small // to reliably match, so fail: return Int32.MaxValue; } // We're going to fake floating-point math in integers. We just need to use more bits. // Scale up patternLength so that intermediate values below like scaledCounter will have // more "significant digits" int unitBarWidth = (total << INTEGER_MATH_SHIFT) / patternLength; maxIndividualVariance = (maxIndividualVariance * unitBarWidth) >> INTEGER_MATH_SHIFT; int totalVariance = 0; for (int x = 0; x < numCounters; x++) { int counter = counters[x] << INTEGER_MATH_SHIFT; int scaledPattern = pattern[x] * unitBarWidth; int variance = counter > scaledPattern ? counter - scaledPattern : scaledPattern - counter; if (variance > maxIndividualVariance) { return Int32.MaxValue; } totalVariance += variance; } return totalVariance / total; } /// <summary> /// Attempts to decode a one-dimensional barcode format given a single row of /// an image. /// </summary> /// <param name="rowNumber">row number from top of the row</param> /// <param name="row">the black/white pixel data of the row</param> /// <param name="hints">decode hints</param> /// <returns> /// <see cref="Result"/>containing encoded string and start/end of barcode /// </returns> public abstract Result decodeRow(int rowNumber, BitArray row, IDictionary<DecodeHintType, object> hints); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Globalization; using Xunit; namespace System.Tests { public partial class StringTests { [Theory] [InlineData("Hello", 'o', true)] [InlineData("Hello", 'O', false)] [InlineData("o", 'o', true)] [InlineData("o", 'O', false)] [InlineData("Hello", 'e', false)] [InlineData("Hello", '\0', false)] [InlineData("", '\0', false)] [InlineData("\0", '\0', true)] [InlineData("", 'a', false)] [InlineData("abcdefghijklmnopqrstuvwxyz", 'z', true)] public static void EndsWith(string s, char value, bool expected) { Assert.Equal(expected, s.EndsWith(value)); } [Theory] [InlineData("Hello", 'H', true)] [InlineData("Hello", 'h', false)] [InlineData("H", 'H', true)] [InlineData("H", 'h', false)] [InlineData("Hello", 'e', false)] [InlineData("Hello", '\0', false)] [InlineData("", '\0', false)] [InlineData("\0", '\0', true)] [InlineData("", 'a', false)] [InlineData("abcdefghijklmnopqrstuvwxyz", 'a', true)] public static void StartsWith(string s, char value, bool expected) { Assert.Equal(expected, s.StartsWith(value)); } public static IEnumerable<object[]> Join_Char_StringArray_TestData() { yield return new object[] { '|', new string[0], 0, 0, "" }; yield return new object[] { '|', new string[] { "a" }, 0, 1, "a" }; yield return new object[] { '|', new string[] { "a", "b", "c" }, 0, 3, "a|b|c" }; yield return new object[] { '|', new string[] { "a", "b", "c" }, 0, 2, "a|b" }; yield return new object[] { '|', new string[] { "a", "b", "c" }, 1, 1, "b" }; yield return new object[] { '|', new string[] { "a", "b", "c" }, 1, 2, "b|c" }; yield return new object[] { '|', new string[] { "a", "b", "c" }, 3, 0, "" }; yield return new object[] { '|', new string[] { "a", "b", "c" }, 0, 0, "" }; yield return new object[] { '|', new string[] { "", "", "" }, 0, 3, "||" }; yield return new object[] { '|', new string[] { null, null, null }, 0, 3, "||" }; } [Theory] [MemberData(nameof(Join_Char_StringArray_TestData))] public static void Join_Char_StringArray(char separator, string[] values, int startIndex, int count, string expected) { if (startIndex == 0 && count == values.Length) { Assert.Equal(expected, string.Join(separator, values)); Assert.Equal(expected, string.Join(separator, (IEnumerable<string>)values)); Assert.Equal(expected, string.Join(separator, (object[])values)); Assert.Equal(expected, string.Join(separator, (IEnumerable<object>)values)); } Assert.Equal(expected, string.Join(separator, values, startIndex, count)); Assert.Equal(expected, string.Join(separator.ToString(), values, startIndex, count)); } public static IEnumerable<object[]> Join_Char_ObjectArray_TestData() { yield return new object[] { '|', new object[0], "" }; yield return new object[] { '|', new object[] { 1 }, "1" }; yield return new object[] { '|', new object[] { 1, 2, 3 }, "1|2|3" }; yield return new object[] { '|', new object[] { new ObjectWithNullToString(), 2, new ObjectWithNullToString() }, "|2|" }; yield return new object[] { '|', new object[] { "1", null, "3" }, "1||3" }; yield return new object[] { '|', new object[] { "", "", "" }, "||" }; yield return new object[] { '|', new object[] { "", null, "" }, "||" }; yield return new object[] { '|', new object[] { null, null, null }, "||" }; } [Theory] [MemberData(nameof(Join_Char_ObjectArray_TestData))] public static void Join_Char_ObjectArray(char separator, object[] values, string expected) { Assert.Equal(expected, string.Join(separator, values)); Assert.Equal(expected, string.Join(separator, (IEnumerable<object>)values)); } [Fact] public static void Join_Char_NullValues_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("value", () => string.Join('|', (string[])null)); AssertExtensions.Throws<ArgumentNullException>("value", () => string.Join('|', (string[])null, 0, 0)); AssertExtensions.Throws<ArgumentNullException>("values", () => string.Join('|', (object[])null)); AssertExtensions.Throws<ArgumentNullException>("values", () => string.Join('|', (IEnumerable<object>)null)); } [Fact] public static void Join_Char_NegativeStartIndex_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => string.Join('|', new string[] { "Foo" }, -1, 0)); } [Fact] public static void Join_Char_NegativeCount_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => string.Join('|', new string[] { "Foo" }, 0, -1)); } [Theory] [InlineData(2, 1)] [InlineData(2, 0)] [InlineData(1, 2)] [InlineData(1, 1)] [InlineData(0, 2)] [InlineData(-1, 0)] public static void Join_Char_InvalidStartIndexCount_ThrowsArgumentOutOfRangeException(int startIndex, int count) { AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => string.Join('|', new string[] { "Foo" }, startIndex, count)); } public static IEnumerable<object[]> Replace_StringComparison_TestData() { yield return new object[] { "abc", "abc", "def", StringComparison.CurrentCulture, "def" }; yield return new object[] { "abc", "ABC", "def", StringComparison.CurrentCulture, "abc" }; yield return new object[] { "abc", "abc", "", StringComparison.CurrentCulture, "" }; yield return new object[] { "abc", "b", "LONG", StringComparison.CurrentCulture, "aLONGc" }; yield return new object[] { "abc", "b", "d", StringComparison.CurrentCulture, "adc" }; yield return new object[] { "abc", "b", null, StringComparison.CurrentCulture, "ac" }; yield return new object[] { "abc", "abc" + SoftHyphen, "def", StringComparison.CurrentCulture, "def" }; yield return new object[] { "abc", "abc", "def", StringComparison.CurrentCultureIgnoreCase, "def" }; yield return new object[] { "abc", "ABC", "def", StringComparison.CurrentCultureIgnoreCase, "def" }; yield return new object[] { "abc", "abc", "", StringComparison.CurrentCultureIgnoreCase, "" }; yield return new object[] { "abc", "b", "LONG", StringComparison.CurrentCultureIgnoreCase, "aLONGc" }; yield return new object[] { "abc", "b", "d", StringComparison.CurrentCultureIgnoreCase, "adc" }; yield return new object[] { "abc", "b", null, StringComparison.CurrentCultureIgnoreCase, "ac" }; yield return new object[] { "abc", "abc" + SoftHyphen, "def", StringComparison.CurrentCultureIgnoreCase, "def" }; yield return new object[] { "abc", "abc", "def", StringComparison.Ordinal, "def" }; yield return new object[] { "abc", "ABC", "def", StringComparison.Ordinal, "abc" }; yield return new object[] { "abc", "abc", "", StringComparison.Ordinal, "" }; yield return new object[] { "abc", "b", "LONG", StringComparison.Ordinal, "aLONGc" }; yield return new object[] { "abc", "b", "d", StringComparison.Ordinal, "adc" }; yield return new object[] { "abc", "b", null, StringComparison.Ordinal, "ac" }; yield return new object[] { "abc", "abc" + SoftHyphen, "def", StringComparison.Ordinal, "abc" }; yield return new object[] { "abc", "abc", "def", StringComparison.OrdinalIgnoreCase, "def" }; yield return new object[] { "abc", "ABC", "def", StringComparison.OrdinalIgnoreCase, "def" }; yield return new object[] { "abc", "abc", "", StringComparison.OrdinalIgnoreCase, "" }; yield return new object[] { "abc", "b", "LONG", StringComparison.OrdinalIgnoreCase, "aLONGc" }; yield return new object[] { "abc", "b", "d", StringComparison.OrdinalIgnoreCase, "adc" }; yield return new object[] { "abc", "b", null, StringComparison.OrdinalIgnoreCase, "ac" }; yield return new object[] { "abc", "abc" + SoftHyphen, "def", StringComparison.OrdinalIgnoreCase, "abc" }; yield return new object[] { "abc", "abc", "def", StringComparison.InvariantCulture, "def" }; yield return new object[] { "abc", "ABC", "def", StringComparison.InvariantCulture, "abc" }; yield return new object[] { "abc", "abc", "", StringComparison.InvariantCulture, "" }; yield return new object[] { "abc", "b", "LONG", StringComparison.InvariantCulture, "aLONGc" }; yield return new object[] { "abc", "b", "d", StringComparison.InvariantCulture, "adc" }; yield return new object[] { "abc", "b", null, StringComparison.InvariantCulture, "ac" }; yield return new object[] { "abc", "abc" + SoftHyphen, "def", StringComparison.InvariantCulture, "def" }; yield return new object[] { "abc", "abc", "def", StringComparison.InvariantCultureIgnoreCase, "def" }; yield return new object[] { "abc", "ABC", "def", StringComparison.InvariantCultureIgnoreCase, "def" }; yield return new object[] { "abc", "abc", "", StringComparison.InvariantCultureIgnoreCase, "" }; yield return new object[] { "abc", "b", "LONG", StringComparison.InvariantCultureIgnoreCase, "aLONGc" }; yield return new object[] { "abc", "b", "d", StringComparison.InvariantCultureIgnoreCase, "adc" }; yield return new object[] { "abc", "b", null, StringComparison.InvariantCultureIgnoreCase, "ac" }; yield return new object[] { "abc", "abc" + SoftHyphen, "def", StringComparison.InvariantCultureIgnoreCase, "def" }; string turkishSource = "\u0069\u0130"; yield return new object[] { turkishSource, "\u0069", "a", StringComparison.Ordinal, "a\u0130" }; yield return new object[] { turkishSource, "\u0069", "a", StringComparison.OrdinalIgnoreCase, "a\u0130" }; yield return new object[] { turkishSource, "\u0130", "a", StringComparison.Ordinal, "\u0069a" }; yield return new object[] { turkishSource, "\u0130", "a", StringComparison.OrdinalIgnoreCase, "\u0069a" }; yield return new object[] { turkishSource, "\u0069", "a", StringComparison.InvariantCulture, "a\u0130" }; yield return new object[] { turkishSource, "\u0069", "a", StringComparison.InvariantCultureIgnoreCase, "a\u0130" }; yield return new object[] { turkishSource, "\u0130", "a", StringComparison.InvariantCulture, "\u0069a" }; yield return new object[] { turkishSource, "\u0130", "a", StringComparison.InvariantCultureIgnoreCase, "\u0069a" }; } [Theory] [MemberData(nameof(Replace_StringComparison_TestData))] public void Replace_StringComparison_ReturnsExpected(string original, string oldValue, string newValue, StringComparison comparisonType, string expected) { Assert.Equal(expected, original.Replace(oldValue, newValue, comparisonType)); } [Fact] public void Replace_StringComparison_TurkishI() { string source = "\u0069\u0130"; Helpers.PerformActionWithCulture(new CultureInfo("tr-TR"), () => { Assert.True("\u0069".Equals("\u0130", StringComparison.CurrentCultureIgnoreCase)); Assert.Equal("a\u0130", source.Replace("\u0069", "a", StringComparison.CurrentCulture)); Assert.Equal("aa", source.Replace("\u0069", "a", StringComparison.CurrentCultureIgnoreCase)); Assert.Equal("\u0069a", source.Replace("\u0130", "a", StringComparison.CurrentCulture)); Assert.Equal("aa", source.Replace("\u0130", "a", StringComparison.CurrentCultureIgnoreCase)); }); Helpers.PerformActionWithCulture(new CultureInfo("en-US"), () => { Assert.False("\u0069".Equals("\u0130", StringComparison.CurrentCultureIgnoreCase)); Assert.Equal("a\u0130", source.Replace("\u0069", "a", StringComparison.CurrentCulture)); Assert.Equal("a\u0130", source.Replace("\u0069", "a", StringComparison.CurrentCultureIgnoreCase)); Assert.Equal("\u0069a", source.Replace("\u0130", "a", StringComparison.CurrentCulture)); Assert.Equal("\u0069a", source.Replace("\u0130", "a", StringComparison.CurrentCultureIgnoreCase)); }); } public static IEnumerable<object[]> Replace_StringComparisonCulture_TestData() { yield return new object[] { "abc", "abc", "def", false, null, "def" }; yield return new object[] { "abc", "ABC", "def", false, null, "abc" }; yield return new object[] { "abc", "abc", "def", false, CultureInfo.InvariantCulture, "def" }; yield return new object[] { "abc", "ABC", "def", false, CultureInfo.InvariantCulture, "abc" }; yield return new object[] { "abc", "abc", "def", true, null, "def" }; yield return new object[] { "abc", "ABC", "def", true, null, "def" }; yield return new object[] { "abc", "abc", "def", true, CultureInfo.InvariantCulture, "def" }; yield return new object[] { "abc", "ABC", "def", true, CultureInfo.InvariantCulture, "def" }; yield return new object[] { "abc", "abc" + SoftHyphen, "def", false, null, "def" }; yield return new object[] { "abc", "abc" + SoftHyphen, "def", true, null, "def" }; yield return new object[] { "abc", "abc" + SoftHyphen, "def", false, CultureInfo.InvariantCulture, "def" }; yield return new object[] { "abc", "abc" + SoftHyphen, "def", true, CultureInfo.InvariantCulture, "def" }; yield return new object[] { "\u0069\u0130", "\u0069", "a", false, new CultureInfo("tr-TR"), "a\u0130" }; yield return new object[] { "\u0069\u0130", "\u0069", "a", true, new CultureInfo("tr-TR"), "aa" }; yield return new object[] { "\u0069\u0130", "\u0069", "a", false, CultureInfo.InvariantCulture, "a\u0130" }; yield return new object[] { "\u0069\u0130", "\u0069", "a", true, CultureInfo.InvariantCulture, "a\u0130" }; } [Theory] [MemberData(nameof(Replace_StringComparisonCulture_TestData))] public void Replace_StringComparisonCulture_ReturnsExpected(string original, string oldValue, string newValue, bool ignoreCase, CultureInfo culture, string expected) { Assert.Equal(expected, original.Replace(oldValue, newValue, ignoreCase, culture)); if (culture == null) { Assert.Equal(expected, original.Replace(oldValue, newValue, ignoreCase, CultureInfo.CurrentCulture)); } } [Fact] public void Replace_StringComparison_NullOldValue_ThrowsArgumentException() { Assert.Throws<ArgumentNullException>("oldValue", () => "abc".Replace(null, "def", StringComparison.CurrentCulture)); Assert.Throws<ArgumentNullException>("oldValue", () => "abc".Replace(null, "def", true, CultureInfo.CurrentCulture)); } [Fact] public void Replace_StringComparison_EmptyOldValue_ThrowsArgumentException() { Assert.Throws<ArgumentException>("oldValue", () => "abc".Replace("", "def", StringComparison.CurrentCulture)); Assert.Throws<ArgumentException>("oldValue", () => "abc".Replace("", "def", true, CultureInfo.CurrentCulture)); } [Theory] [InlineData(StringComparison.CurrentCulture - 1)] [InlineData(StringComparison.OrdinalIgnoreCase + 1)] public void Replace_NoSuchStringComparison_ThrowsArgumentException(StringComparison comparisonType) { Assert.Throws<ArgumentException>("comparisonType", () => "abc".Replace("abc", "def", comparisonType)); } } }
#region LGPL License /* Axiom Game Engine Library Copyright (C) 2003 Axiom Project Team The overall design, and a majority of the core engine and rendering code contained within this library is a derivative of the open source Object Oriented Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net. Many thanks to the OGRE team for maintaining such a high quality project. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #endregion using System; using System.Diagnostics; using Axiom.Core; using Axiom.Fonts; using Axiom.Scripting; using Axiom.Graphics; using Font = Axiom.Fonts.Font; namespace Axiom.Overlays.Elements { /// <summary> /// Label type control that can be used to display text using a specified font. /// </summary> public class TextArea : OverlayElement { #region Member variables protected Font font; protected HorizontalAlignment alignment; protected float charHeight; protected int pixelCharHeight; protected float spaceWidth; protected int pixelSpaceWidth; protected int allocSize; protected bool isTransparent; protected RenderOperation renderOp = new RenderOperation(); /// Colors to use for the vertices protected ColorEx colorBottom; protected ColorEx colorTop; protected bool haveColorsChanged; const int DEFAULT_INITIAL_CHARS = 12; const int POSITION_TEXCOORD = 0; const int COLORS = 1; #endregion #region Constructors /// <summary> /// Basic constructor, internal since it should only be created by factories. /// </summary> /// <param name="name"></param> internal TextArea(string name) : base(name) { isTransparent = false; alignment = HorizontalAlignment.Left; colorTop = ColorEx.White; colorBottom = ColorEx.White; haveColorsChanged = true; charHeight = 0.02f; pixelCharHeight = 12; } #endregion #region Methods /// <summary> /// /// </summary> /// <param name="size"></param> protected void CheckMemoryAllocation(int numChars) { if(allocSize < numChars) { // Create and bind new buffers // Note that old buffers will be deleted automatically through reference counting // 6 verts per char since we're doing tri lists without indexes // Allocate space for positions & texture coords VertexDeclaration decl = renderOp.vertexData.vertexDeclaration; VertexBufferBinding binding = renderOp.vertexData.vertexBufferBinding; renderOp.vertexData.vertexCount = numChars * 6; // Create dynamic since text tends to change alot // positions & texcoords HardwareVertexBuffer buffer = HardwareBufferManager.Instance.CreateVertexBuffer( decl.GetVertexSize(POSITION_TEXCOORD), renderOp.vertexData.vertexCount, BufferUsage.Dynamic); // bind the pos/tex buffer binding.SetBinding(POSITION_TEXCOORD, buffer); // colors buffer = HardwareBufferManager.Instance.CreateVertexBuffer( decl.GetVertexSize(COLORS), renderOp.vertexData.vertexCount, BufferUsage.Dynamic); // bind the color buffer binding.SetBinding(COLORS, buffer); allocSize = numChars; // force color buffer regeneration haveColorsChanged = true; } } /// <summary> /// /// </summary> /// <param name="op"></param> public override void GetRenderOperation(RenderOperation op) { op.vertexData = renderOp.vertexData; op.useIndices = false; op.operationType = renderOp.operationType; } /// <summary> /// /// </summary> public override void Initialize() { // Set up the render operation // Combine positions and texture coords since they tend to change together // since character sizes are different renderOp.vertexData = new VertexData(); VertexDeclaration decl = renderOp.vertexData.vertexDeclaration; int offset = 0; // positions decl.AddElement(POSITION_TEXCOORD, offset, VertexElementType.Float3, VertexElementSemantic.Position); offset += VertexElement.GetTypeSize(VertexElementType.Float3); // texcoords decl.AddElement(POSITION_TEXCOORD, offset, VertexElementType.Float2, VertexElementSemantic.TexCoords, 0); // colors, stored in seperate buffer since they change less often decl.AddElement(COLORS, 0, VertexElementType.Color, VertexElementSemantic.Diffuse); renderOp.operationType = OperationType.TriangleList; renderOp.useIndices = false; renderOp.vertexData.vertexStart = 0; // buffers are created in CheckMemoryAllocation CheckMemoryAllocation(DEFAULT_INITIAL_CHARS); } /// <summary> /// Override to update char sizing based on current viewport settings. /// </summary> public override void Update() { if(metricsMode == MetricsMode.Pixels && (OverlayManager.Instance.HasViewportChanged || geomPositionsOutOfDate)) { float vpHeight = OverlayManager.Instance.ViewportHeight; charHeight = (float)pixelCharHeight / vpHeight; spaceWidth = (float)pixelSpaceWidth / vpHeight; geomPositionsOutOfDate = true; } base.Update (); } /// <summary> /// /// </summary> protected unsafe void UpdateColors() { if(!haveColorsChanged) { // nothing to see here folks return; } // convert to API specific color values uint topColor = Root.Instance.ConvertColor(colorTop); uint bottomColor = Root.Instance.ConvertColor(colorBottom); // get the seperate color buffer HardwareVertexBuffer buffer = renderOp.vertexData.vertexBufferBinding.GetBuffer(COLORS); IntPtr data = buffer.Lock(BufferLocking.Discard); uint* colPtr = (uint*)data.ToPointer(); int index = 0; for(int i = 0; i < allocSize; i++) { // first tri (top, bottom, top); colPtr[index++] = topColor; colPtr[index++] = bottomColor; colPtr[index++] = topColor; // second tri (top, bottom, bottom); colPtr[index++] = topColor; colPtr[index++] = bottomColor; colPtr[index++] = bottomColor; } // unlock this bad boy buffer.Unlock(); haveColorsChanged = false; } /// <summary> /// /// </summary> protected unsafe void UpdateGeometry() { if(font == null || text == null || !geomPositionsOutOfDate) { // must not be initialized yet, probably due to order of creation in a template return; } int charLength = text.Length; // make sure the buffers are big enough CheckMemoryAllocation(charLength); renderOp.vertexData.vertexCount = charLength * 6; float largestWidth = 0.0f; float left = this.DerivedLeft * 2.0f - 1.0f; float top = -((this.DerivedTop * 2.0f) - 1.0f); // derive space width from the size of a capital A if(spaceWidth == 0) { spaceWidth = font.GetGlyphAspectRatio('A') * charHeight * 2.0f; } // get pos/tex buffer HardwareVertexBuffer buffer = renderOp.vertexData.vertexBufferBinding.GetBuffer(POSITION_TEXCOORD); IntPtr data = buffer.Lock(BufferLocking.Discard); float* vertPtr = (float*)data.ToPointer(); int index = 0; bool newLine = true; // go through each character and process for(int i = 0; i < text.Length; i++) { char c = text[i]; if(newLine) { float length = 0.0f; // precalc the length of this line for(int j = i; j < text.Length && text[j] != '\n'; j++) { if(text[j] == ' ') { length += spaceWidth; } else { length += font.GetGlyphAspectRatio(text[j]) * charHeight * 2; } } // for j if(alignment == HorizontalAlignment.Right) { left -= length; } else if(alignment == HorizontalAlignment.Center) { left -= length * 0.5f; } newLine = false; } // if newLine if(c == '\n') { left = this.DerivedLeft * 2.0f - 1.0f; top -= charHeight * 2.0f; newLine = true; // reduce tri count renderOp.vertexData.vertexCount -= 6; continue; } if(c == ' ') { // leave a gap, no tris required left += spaceWidth; // reduce tri count renderOp.vertexData.vertexCount -= 6; continue; } float horizHeight = font.GetGlyphAspectRatio(c); float u1, u2, v1, v2; // get the texcoords for the specified character font.GetGlyphTexCoords(c, out u1, out v1, out u2, out v2); // each vert is (x, y, z, u, v) // first tri // upper left vertPtr[index++] = left; vertPtr[index++] = top; vertPtr[index++] = -1.0f; vertPtr[index++] = u1; vertPtr[index++] = v1; top -= charHeight * 2.0f; // bottom left vertPtr[index++] = left; vertPtr[index++] = top; vertPtr[index++] = -1.0f; vertPtr[index++] = u1; vertPtr[index++] = v2; top += charHeight * 2.0f; left += horizHeight * charHeight * 2.0f; // top right vertPtr[index++] = left; vertPtr[index++] = top; vertPtr[index++] = -1.0f; vertPtr[index++] = u2; vertPtr[index++] = v1; // second tri // top right (again) vertPtr[index++] = left; vertPtr[index++] = top; vertPtr[index++] = -1.0f; vertPtr[index++] = u2; vertPtr[index++] = v1; top -= charHeight * 2.0f; left -= horizHeight * charHeight * 2.0f; // bottom left (again) vertPtr[index++] = left; vertPtr[index++] = top; vertPtr[index++] = -1.0f; vertPtr[index++] = u1; vertPtr[index++] = v2; left += horizHeight * charHeight * 2.0f; // bottom right vertPtr[index++] = left; vertPtr[index++] = top; vertPtr[index++] = -1.0f; vertPtr[index++] = u2; vertPtr[index++] = v2; // go back up with top top += charHeight * 2.0f; float currentWidth = (left + 1) / 2 - this.DerivedLeft; if(currentWidth > largestWidth) { largestWidth = currentWidth; } } // for i // unlock vertex buffer buffer.Unlock(); if(metricsMode == MetricsMode.Pixels) { // Derive parametric version of dimensions float vpWidth = OverlayManager.Instance.ViewportWidth; largestWidth *= vpWidth; } // record the width as the longest width calculated for any of the lines if(this.Width < largestWidth) { this.Width = largestWidth; } // update colors UpdateColors(); } /// <summary> /// /// </summary> protected override void UpdatePositionGeometry() { UpdateGeometry(); } #endregion #region Properties /// <summary> /// /// </summary> public float CharHeight { get { return charHeight; } set { if(metricsMode == MetricsMode.Pixels) { pixelCharHeight = (int)value; } else { charHeight = value; } UpdateGeometry(); } } /// <summary> /// Gets/Sets the color value of the text when it is all the same color. /// </summary> public override ColorEx Color { get { // doesnt matter if they are both the same return colorTop; } set { colorTop = value; colorBottom = value; haveColorsChanged = true; UpdateColors(); } } /// <summary> /// /// </summary> public ColorEx ColorTop { get { return colorTop; } set { colorTop = value; haveColorsChanged = true; UpdateColors(); } } /// <summary> /// /// </summary> public ColorEx ColorBottom { get { return colorBottom; } set { colorBottom = value; haveColorsChanged = true; UpdateColors(); } } /// <summary> /// Gets/Sets the name of the font currently being used when rendering the text. /// </summary> public string FontName { get { return font.Name; } set { font = (Font)FontManager.Instance.GetByName(value); font.Load(); // note: font materials are created with lighting and depthcheck disabled by default material = font.Material; // TODO: See if this can be eliminated material.Lighting = false; material.DepthCheck = false; geomPositionsOutOfDate = true; } } /// <summary> /// Override to update geometry when new material is assigned. /// </summary> public override string MaterialName { get { return base.MaterialName; } set { base.MaterialName = value; UpdateGeometry(); } } /// <summary> /// Override to handle character spacing /// </summary> public override MetricsMode MetricsMode { get { return base.MetricsMode; } set { base.MetricsMode = value; // configure pixel variables based on current viewport if(metricsMode == MetricsMode.Pixels) { float vpHeight = OverlayManager.Instance.ViewportHeight; pixelCharHeight = (int)(charHeight * vpHeight); pixelSpaceWidth = (int)(spaceWidth * vpHeight); } } } /// <summary> /// /// </summary> public float SpaceWidth { get { return spaceWidth; } set { if(metricsMode == MetricsMode.Pixels) { pixelSpaceWidth = (int)value; } else { spaceWidth = value; } geomPositionsOutOfDate = true; } } /// <summary> /// Alignment of text specifically. /// </summary> public HorizontalAlignment TextAlign { get { return alignment; } set { alignment = value; UpdateGeometry(); } } /// <summary> /// Override to update string geometry. /// </summary> public override string Text { get { return base.Text; } set { base.Text = value; UpdateGeometry(); } } /// <summary> /// Overridden to return this elements type. /// </summary> public override string Type { get { return "TextArea"; } } #endregion #region Script parser methods [AttributeParser("char_height", "TextArea")] public static void ParseCharHeight(string[] parms, params object[] objects) { TextArea textArea = (TextArea)objects[0]; textArea.CharHeight = StringConverter.ParseFloat(parms[0]); } [AttributeParser("space_width", "TextArea")] public static void ParseSpaceWidth(string[] parms, params object[] objects) { TextArea textArea = (TextArea)objects[0]; textArea.SpaceWidth = StringConverter.ParseFloat(parms[0]); } [AttributeParser("font_name", "TextArea")] public static void ParseFontName(string[] parms, params object[] objects) { TextArea textArea = (TextArea)objects[0]; textArea.FontName = parms[0]; } [AttributeParser("color", "TextArea")] [AttributeParser("colour", "TextArea")] public static void ParseColor(string[] parms, params object[] objects) { TextArea textArea = (TextArea)objects[0]; textArea.Color = StringConverter.ParseColor(parms); } [AttributeParser("color_top", "TextArea")] [AttributeParser("colour_top", "TextArea")] public static void ParseColorTop(string[] parms, params object[] objects) { TextArea textArea = (TextArea)objects[0]; textArea.ColorTop = StringConverter.ParseColor(parms); } [AttributeParser("color_bottom", "TextArea")] [AttributeParser("colour_bottom", "TextArea")] public static void ParseColorBottom(string[] parms, params object[] objects) { TextArea textArea = (TextArea)objects[0]; textArea.ColorBottom = StringConverter.ParseColor(parms); } #endregion } }
using System; using System.Collections.Generic; using System.Text; using TestLibrary; public class StringConcat4 { private int c_MAX_STRING_LENGTH = 256; private int c_MINI_STRING_LENGTH = 8; public static int Main() { StringConcat4 sc4 = new StringConcat4(); TestLibrary.TestFramework.BeginTestCase("StringConcat4"); if (sc4.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; retVal = PosTest7() && retVal; retVal = PosTest8() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; return retVal; } #region PositiveTesting public bool PosTest1() { bool retVal = true; Random rand = new Random(-55); string ActualResult; object[] ObjA = new object[rand.Next(c_MINI_STRING_LENGTH,c_MAX_STRING_LENGTH)]; TestLibrary.TestFramework.BeginScenario("PostTest1:Concat object Array with all null member"); try { for (int i = 0; i < ObjA.Length; i++) { ObjA[i] = null; } ActualResult = string.Concat(ObjA); if (ActualResult != MergeStrings(ObjA)) { TestLibrary.TestFramework.LogError("001", "Concat object Array with all null member ExpectResult is" + MergeStrings(ObjA) + "ActualResult is (" + ActualResult + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; Random rand = new Random(-55); string ActualResult; object[] ObjA = new object[rand.Next(c_MINI_STRING_LENGTH,c_MAX_STRING_LENGTH)]; TestLibrary.TestFramework.BeginScenario("PostTest2:Concat object Array with empty member"); try { for (int i = 0; i < ObjA.Length; i++) { ObjA[i] = ""; } ActualResult = string.Concat(ObjA); if (ActualResult != MergeStrings(ObjA)) { TestLibrary.TestFramework.LogError("003", "Concat object Array with empty member ExpectResult is" + MergeStrings(ObjA) + " ActualResult is (" + ActualResult + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; string ActualResult; object[] ObjA; TestLibrary.TestFramework.BeginScenario("PosTest3:Concat object Array with null and empty member"); try { ObjA = new object[]{ null, "", null, "", null, "" }; ActualResult = string.Concat(ObjA); if (ActualResult != MergeStrings(ObjA)) { TestLibrary.TestFramework.LogError("005", "Concat object Array with null and empty member ExpectResult is equel" + MergeStrings(ObjA) + ",ActualResult is (" + ActualResult + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception" + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; string ActualResult; object[] ObjA; TestLibrary.TestFramework.BeginScenario("PosTest4: Concat object Array with null,empty and space member"); try { ObjA = new object[] {" ",null,""," "}; ActualResult = string.Concat(ObjA); if (ActualResult != MergeStrings(ObjA)) { TestLibrary.TestFramework.LogError("007", "Concat object Array with null,empty and space member ExpectResult is" + MergeStrings(ObjA) + " ,ActualResult is (" + ActualResult + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception" + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; string ActualResult; object[] ObjA; TestLibrary.TestFramework.BeginScenario("PosTest5:Concat object Array with int,datetime,bool and class instance member"); try { object obj1 = -123; object obj2 = new DateTime(); object obj3 = new bool(); object obj4 = new StringConcat4(); ObjA = new object[] { obj1, obj2, obj3, obj4 }; ActualResult = string.Concat(ObjA); if (ActualResult != MergeStrings(ObjA)) { TestLibrary.TestFramework.LogError("009", "Concat an object of int ExpectResult is equel" + MergeStrings(ObjA) + " ,ActualResult is (" + ActualResult + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception" + e); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; string ActualResult; object[] ObjA; TestLibrary.TestFramework.BeginScenario("PosTest6: Concat object Array with guid and some special symbols member"); try { object obj1 = new Guid(); object obj2 = "\n"; object obj3 = "\t"; object obj4 = "\u0041"; ObjA = new object[] { obj1, obj2, obj3, obj4}; ActualResult = string.Concat(ObjA); if (ActualResult != MergeStrings(ObjA)) { TestLibrary.TestFramework.LogError("011", "Concat object Array with guid and some special symbols member ExpectResult is equel" + MergeStrings(ObjA) + ",ActualResult is (" + ActualResult + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("012", "Unexpected exception" + e); retVal = false; } return retVal; } public bool PosTest7() { bool retVal = true; string ActualResult; object[] ObjA; TestLibrary.TestFramework.BeginScenario("PosTest7: Concat object Array with some strings and symbols member"); try { object obj1 = "hello"; object obj2 = "\0"; object obj3 = "World"; object obj4 = "\u0020"; object obj5 = "!"; ObjA = new object[] { obj1, obj2, obj3, obj4, obj5 }; ActualResult = string.Concat(ObjA); if (ActualResult != MergeStrings(ObjA)) { TestLibrary.TestFramework.LogError("013", "Concat object Array with some strings and symbols member ExpectResult is equel" + MergeStrings(ObjA) + ",ActualResult is (" + ActualResult + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("014", "Unexpected exception" + e); retVal = false; } return retVal; } public bool PosTest8() { bool retVal = true; string ActualResult; object[] ObjA; TestLibrary.TestFramework.BeginScenario("PosTest8:Concat object Array with bool and some strings member"); try { object obj1 = true; object obj2 = "hello\0world"; object obj3 = 12; object obj4 = "uff21"; ObjA = new object[] { obj1, obj2, obj3, obj4 }; ActualResult = string.Concat(ObjA); if (ActualResult != MergeStrings(ObjA)) { TestLibrary.TestFramework.LogError("015", "Concat object Array with bool and some strings member ExpectResult is equel" + MergeStrings(ObjA) + " ,ActualResult is (" + ActualResult + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("016", "Unexpected exception" + e); retVal = false; } return retVal; } #endregion #region NegativeTesting public bool NegTest1() { bool retVal = true; Random rand = new Random(-55); TestLibrary.TestFramework.BeginScenario("NegTest1: Concat object Array is null"); object[] ObjA = new object[rand.Next(c_MINI_STRING_LENGTH,c_MAX_STRING_LENGTH)]; string ActualResult; try { ObjA = null; ActualResult = string.Concat(ObjA); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("001", "Unexpected exception" + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; Random rand = new Random(-55); object[] ObjA = new object[50 * 1024 * 1024]; string ActualResult; TestLibrary.TestFramework.BeginScenario("NegTest2: Concat object Array with many strings"); int TotalLength = 0; try { for (int i = 0; i < ObjA.Length; i++) { ObjA[i] = "HelloworldHelloworldHelloworldHelloworld!"; TotalLength += ObjA[i].ToString().Length; } ActualResult = string.Concat(ObjA); retVal = false; } catch (OutOfMemoryException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception:" + e); retVal = false; } return retVal; } #region Help method private string MergeStrings(object[] ObjS) { string ResultString =""; foreach (object obj in ObjS) { if (obj == null) ResultString += string.Empty; else ResultString += obj.ToString(); } return ResultString; } #endregion #endregion }
#region Copyright notice and license // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Grpc.Core.Internal; using Grpc.Core.Utils; namespace Grpc.Core.Internal { /// <summary> /// Manages server side native call lifecycle. /// </summary> internal class AsyncCallServer<TRequest, TResponse> : AsyncCallBase<TResponse, TRequest> { readonly TaskCompletionSource<object> finishedServersideTcs = new TaskCompletionSource<object>(); readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); readonly Server server; public AsyncCallServer(Func<TResponse, byte[]> serializer, Func<byte[], TRequest> deserializer, GrpcEnvironment environment, Server server) : base(serializer, deserializer, environment) { this.server = GrpcPreconditions.CheckNotNull(server); } public void Initialize(CallSafeHandle call) { call.Initialize(environment.CompletionRegistry, environment.CompletionQueue); server.AddCallReference(this); InitializeInternal(call); } /// <summary> /// Starts a server side call. /// </summary> public Task ServerSideCallAsync() { lock (myLock) { GrpcPreconditions.CheckNotNull(call); started = true; call.StartServerSide(HandleFinishedServerside); return finishedServersideTcs.Task; } } /// <summary> /// Sends a streaming response. Only one pending send action is allowed at any given time. /// completionDelegate is called when the operation finishes. /// </summary> public void StartSendMessage(TResponse msg, WriteFlags writeFlags, AsyncCompletionDelegate<object> completionDelegate) { StartSendMessageInternal(msg, writeFlags, completionDelegate); } /// <summary> /// Receives a streaming request. Only one pending read action is allowed at any given time. /// completionDelegate is called when the operation finishes. /// </summary> public void StartReadMessage(AsyncCompletionDelegate<TRequest> completionDelegate) { StartReadMessageInternal(completionDelegate); } /// <summary> /// Initiates sending a initial metadata. /// Even though C-core allows sending metadata in parallel to sending messages, we will treat sending metadata as a send message operation /// to make things simpler. /// completionDelegate is invoked upon completion. /// </summary> public void StartSendInitialMetadata(Metadata headers, AsyncCompletionDelegate<object> completionDelegate) { lock (myLock) { GrpcPreconditions.CheckNotNull(headers, "metadata"); GrpcPreconditions.CheckNotNull(completionDelegate, "Completion delegate cannot be null"); GrpcPreconditions.CheckState(!initialMetadataSent, "Response headers can only be sent once per call."); GrpcPreconditions.CheckState(streamingWritesCounter == 0, "Response headers can only be sent before the first write starts."); CheckSendingAllowed(allowFinished: false); GrpcPreconditions.CheckNotNull(completionDelegate, "Completion delegate cannot be null"); using (var metadataArray = MetadataArraySafeHandle.Create(headers)) { call.StartSendInitialMetadata(HandleSendFinished, metadataArray); } this.initialMetadataSent = true; sendCompletionDelegate = completionDelegate; } } /// <summary> /// Sends call result status, also indicating server is done with streaming responses. /// Only one pending send action is allowed at any given time. /// completionDelegate is called when the operation finishes. /// </summary> public void StartSendStatusFromServer(Status status, Metadata trailers, AsyncCompletionDelegate<object> completionDelegate) { lock (myLock) { GrpcPreconditions.CheckNotNull(completionDelegate, "Completion delegate cannot be null"); CheckSendingAllowed(allowFinished: false); using (var metadataArray = MetadataArraySafeHandle.Create(trailers)) { call.StartSendStatusFromServer(HandleSendStatusFromServerFinished, status, metadataArray, !initialMetadataSent); } halfcloseRequested = true; readingDone = true; sendCompletionDelegate = completionDelegate; } } /// <summary> /// Gets cancellation token that gets cancelled once close completion /// is received and the cancelled flag is set. /// </summary> public CancellationToken CancellationToken { get { return cancellationTokenSource.Token; } } public string Peer { get { return call.GetPeer(); } } protected override bool IsClient { get { return false; } } protected override void CheckReadingAllowed() { base.CheckReadingAllowed(); GrpcPreconditions.CheckArgument(!cancelRequested); } protected override void OnAfterReleaseResources() { server.RemoveCallReference(this); } /// <summary> /// Handles the server side close completion. /// </summary> private void HandleFinishedServerside(bool success, bool cancelled) { lock (myLock) { finished = true; ReleaseResourcesIfPossible(); } // TODO(jtattermusch): handle error if (cancelled) { cancellationTokenSource.Cancel(); } finishedServersideTcs.SetResult(null); } } }
// Copyright (c) 2015 semdiffdotnet. Distributed under the MIT License. // See LICENSE file or opensource.org/licenses/MIT. using Microsoft.VisualStudio.TestTools.UnitTesting; using SemDiff.Core; using System.Linq; namespace SemDiff.Test { [TestClass] public class DiffTests : TestBase { [TestMethod] public void GetChangesNotChangedTest() { var original = @" var total = 0; var n = 100; for (var i = n - 1; i >= 0; i--) { total = i + total; } ".WrapWithMethod().Parse(); var changed = @" var total = 0; var n = 100; for (var i = n - 1; i >= 0; i--) { total = i + total; } ".WrapWithMethod().Parse(); var changes = Diff.Compare(original, changed); Assert.AreEqual(0, changes.Count()); } [TestMethod] public void GetChangesChangedOnceTest() { var original = @" var total = 0; var n = 100; for (var i = n - 1; i >= 0; i--) { total = i + total; } ".WrapWithMethod().Parse(); var changed = @" var total = 0; var n = 100; for (var i = n - 1; i >= 0; i--) { total += i; } ".WrapWithMethod().Parse(); var changes = Diff.Compare(original, changed); Assert.AreEqual("= i + total", changes.Single().Ancestor.Text); Assert.AreEqual("+= i", changes.Single().Changed.Text); } [TestMethod] public void GetChangesChangedTwiceTest() { var original = @" var total = 0; var n = 100; for (var i = n - 1; i >= 0; i--) { total = i + total; } ".WrapWithMethod().Parse(); var changed = @" var total = 0; var n = 100; for (var i = 0; i < n; i++) { total += i; } ".WrapWithMethod().Parse(); var changes = Diff.Compare(original, changed).ToList(); Assert.AreEqual(4, changes.Count()); //Even though two changes are made it is interpreted as 4! Assert.AreEqual("n - 1", changes[0].Ancestor.Text); Assert.AreEqual("0", changes[0].Changed.Text); Assert.AreEqual(">= 0", changes[1].Ancestor.Text); Assert.AreEqual("< n", changes[1].Changed.Text); Assert.AreEqual("--", changes[2].Ancestor.Text); Assert.AreEqual("++", changes[2].Changed.Text); Assert.AreEqual("= i + total", changes[3].Ancestor.Text); Assert.AreEqual("+= i", changes[3].Changed.Text); } [TestMethod] public void IntersectFalseTest() { var original = @" var total = 0; var n = 100; for (var i = n - 1; i >= 0; i--) { total = i + total; } ".WrapWithMethod().Parse(); var changed1 = @" var total = 0; var n = 100; for (var i = 0; i < n; i++) { total = i + total; } ".WrapWithMethod().Parse(); var changed2 = @" var total = 0; var n = 100; for (var i = n - 1; i >= 0; i--) { total += i; } ".WrapWithMethod().Parse(); var c1s = Diff.Compare(original, changed1).ToList(); var c2 = Diff.Compare(original, changed2).Single(); foreach (var x in Enumerable.Range(0, 3)) { Assert.IsFalse(Diff.Intersects(c1s[x], c2)); Assert.IsFalse(Diff.Intersects(c2, c1s[x])); } } [TestMethod] public void IntersectTrueInsertsTest() { var original = @" var total = 0; var n = 100; for (var i = 0; i < n; i++) { } ".WrapWithMethod().Parse(); var changed1 = @" var total = 0; var n = 100; for (var i = 0; i < n; i++) { total = i + total; } ".WrapWithMethod().Parse(); var changed2 = @" var total = 0; var n = 100; for (var i = 0; i < n; i++) { total += i; } ".WrapWithMethod().Parse(); var c1 = Diff.Compare(original, changed1).Single(); var c2 = Diff.Compare(original, changed2).Single(); Assert.IsTrue(Diff.Intersects(c1, c2)); Assert.IsTrue(Diff.Intersects(c2, c1)); } //TODO: Test to see if this subtle conflict could result in a merge conflict //[TestMethod] //public void IntersectTrueReplacePartTest() //{ // var original = @" // var total = 0; // var n = 100; // for (var i = 0; i < n; i++) // { // total = i; // } // ".WrapWithMethod().Parse(); // var changed1 = @" // var total = 0; // var n = 100; // for (var i = 0; i < n; i++) // { // total = i + total; // } // ".WrapWithMethod().Parse(); // var changed2 = @" // var total = 0; // var n = 100; // for (var i = 0; i < n; i++) // { // total += i; // } // ".WrapWithMethod().Parse(); // var c1 = Diff.Compare(original, changed1).Single(); // var c2 = Diff.Compare(original, changed2).Single(); // Assert.IsTrue(Diff.Intersects(c1, c2)); //} [TestMethod] public void IntersectTrueOverlapingTest() { var original = @" var total = 0; var n = 100; for (var i = 0; i < n; i++) { total = i + total; } ".WrapWithMethod().Parse(); var changed1 = @" var total = 0; ".WrapWithMethod().Parse(); var changed2 = @" var total = 0; var n = 100; for (var i = 0; i < n; i++) { total += i; } ".WrapWithMethod().Parse(); var c1 = Diff.Compare(original, changed1).Single(); var c2 = Diff.Compare(original, changed2).Single(); Assert.IsTrue(Diff.Intersects(c1, c2)); Assert.IsTrue(Diff.Intersects(c2, c1)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.AspNetCore.Cryptography; using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption; using Microsoft.AspNetCore.DataProtection.KeyManagement.Internal; using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.DataProtection.KeyManagement { internal sealed unsafe class KeyRingBasedDataProtector : IDataProtector, IPersistedDataProtector { // This magic header identifies a v0 protected data blob. It's the high 28 bits of the SHA1 hash of // "Microsoft.AspNet.DataProtection.KeyManagement.KeyRingBasedDataProtector" [US-ASCII], big-endian. // The last nibble reserved for version information. There's also the nice property that "F0 C9" // can never appear in a well-formed UTF8 sequence, so attempts to treat a protected payload as a // UTF8-encoded string will fail, and devs can catch the mistake early. private const uint MAGIC_HEADER_V0 = 0x09F0C9F0; private AdditionalAuthenticatedDataTemplate _aadTemplate; private readonly IKeyRingProvider _keyRingProvider; private readonly ILogger? _logger; public KeyRingBasedDataProtector(IKeyRingProvider keyRingProvider, ILogger? logger, string[]? originalPurposes, string newPurpose) { Debug.Assert(keyRingProvider != null); Purposes = ConcatPurposes(originalPurposes, newPurpose); _logger = logger; // can be null _keyRingProvider = keyRingProvider; _aadTemplate = new AdditionalAuthenticatedDataTemplate(Purposes); } internal string[] Purposes { get; } private static string[] ConcatPurposes(string[]? originalPurposes, string newPurpose) { if (originalPurposes != null && originalPurposes.Length > 0) { var newPurposes = new string[originalPurposes.Length + 1]; Array.Copy(originalPurposes, 0, newPurposes, 0, originalPurposes.Length); newPurposes[originalPurposes.Length] = newPurpose; return newPurposes; } else { return new string[] { newPurpose }; } } public IDataProtector CreateProtector(string purpose) { if (purpose == null) { throw new ArgumentNullException(nameof(purpose)); } return new KeyRingBasedDataProtector( logger: _logger, keyRingProvider: _keyRingProvider, originalPurposes: Purposes, newPurpose: purpose); } private static string JoinPurposesForLog(IEnumerable<string> purposes) { return "(" + String.Join(", ", purposes.Select(p => "'" + p + "'")) + ")"; } // allows decrypting payloads whose keys have been revoked public byte[] DangerousUnprotect(byte[] protectedData, bool ignoreRevocationErrors, out bool requiresMigration, out bool wasRevoked) { // argument & state checking if (protectedData == null) { throw new ArgumentNullException(nameof(protectedData)); } UnprotectStatus status; var retVal = UnprotectCore(protectedData, ignoreRevocationErrors, status: out status); requiresMigration = (status != UnprotectStatus.Ok); wasRevoked = (status == UnprotectStatus.DecryptionKeyWasRevoked); return retVal; } public byte[] Protect(byte[] plaintext) { if (plaintext == null) { throw new ArgumentNullException(nameof(plaintext)); } try { // Perform the encryption operation using the current default encryptor. var currentKeyRing = _keyRingProvider.GetCurrentKeyRing(); var defaultKeyId = currentKeyRing.DefaultKeyId; var defaultEncryptorInstance = currentKeyRing.DefaultAuthenticatedEncryptor; CryptoUtil.Assert(defaultEncryptorInstance != null, "defaultEncryptorInstance != null"); if (_logger.IsDebugLevelEnabled()) { _logger.PerformingProtectOperationToKeyWithPurposes(defaultKeyId, JoinPurposesForLog(Purposes)); } // We'll need to apply the default key id to the template if it hasn't already been applied. // If the default key id has been updated since the last call to Protect, also write back the updated template. var aad = _aadTemplate.GetAadForKey(defaultKeyId, isProtecting: true); // We allocate a 20-byte pre-buffer so that we can inject the magic header and key id into the return value. var retVal = defaultEncryptorInstance.Encrypt( plaintext: new ArraySegment<byte>(plaintext), additionalAuthenticatedData: new ArraySegment<byte>(aad), preBufferSize: (uint)(sizeof(uint) + sizeof(Guid)), postBufferSize: 0); CryptoUtil.Assert(retVal != null && retVal.Length >= sizeof(uint) + sizeof(Guid), "retVal != null && retVal.Length >= sizeof(uint) + sizeof(Guid)"); // At this point: retVal := { 000..000 || encryptorSpecificProtectedPayload }, // where 000..000 is a placeholder for our magic header and key id. // Write out the magic header and key id fixed (byte* pbRetVal = retVal) { WriteBigEndianInteger(pbRetVal, MAGIC_HEADER_V0); WriteGuid(&pbRetVal[sizeof(uint)], defaultKeyId); } // At this point, retVal := { magicHeader || keyId || encryptorSpecificProtectedPayload } // And we're done! return retVal; } catch (Exception ex) when (ex.RequiresHomogenization()) { // homogenize all errors to CryptographicException throw Error.Common_EncryptionFailed(ex); } } private static Guid ReadGuid(void* ptr) { #if NETCOREAPP // Performs appropriate endianness fixups return new Guid(new ReadOnlySpan<byte>(ptr, sizeof(Guid))); #elif NETSTANDARD2_0 || NETFRAMEWORK Debug.Assert(BitConverter.IsLittleEndian); return Unsafe.ReadUnaligned<Guid>(ptr); #else #error Update target frameworks #endif } private static uint ReadBigEndian32BitInteger(byte* ptr) { return ((uint)ptr[0] << 24) | ((uint)ptr[1] << 16) | ((uint)ptr[2] << 8) | ((uint)ptr[3]); } private static bool TryGetVersionFromMagicHeader(uint magicHeader, out int version) { const uint MAGIC_HEADER_VERSION_MASK = 0xFU; if ((magicHeader & ~MAGIC_HEADER_VERSION_MASK) == MAGIC_HEADER_V0) { version = (int)(magicHeader & MAGIC_HEADER_VERSION_MASK); return true; } else { version = default(int); return false; } } public byte[] Unprotect(byte[] protectedData) { if (protectedData == null) { throw new ArgumentNullException(nameof(protectedData)); } // Argument checking will be done by the callee bool requiresMigration, wasRevoked; // unused return DangerousUnprotect(protectedData, ignoreRevocationErrors: false, requiresMigration: out requiresMigration, wasRevoked: out wasRevoked); } private byte[] UnprotectCore(byte[] protectedData, bool allowOperationsOnRevokedKeys, out UnprotectStatus status) { Debug.Assert(protectedData != null); try { // argument & state checking if (protectedData.Length < sizeof(uint) /* magic header */ + sizeof(Guid) /* key id */) { // payload must contain at least the magic header and key id throw Error.ProtectionProvider_BadMagicHeader(); } // Need to check that protectedData := { magicHeader || keyId || encryptorSpecificProtectedPayload } // Parse the payload version number and key id. uint magicHeaderFromPayload; Guid keyIdFromPayload; fixed (byte* pbInput = protectedData) { magicHeaderFromPayload = ReadBigEndian32BitInteger(pbInput); keyIdFromPayload = ReadGuid(&pbInput[sizeof(uint)]); } // Are the magic header and version information correct? int payloadVersion; if (!TryGetVersionFromMagicHeader(magicHeaderFromPayload, out payloadVersion)) { throw Error.ProtectionProvider_BadMagicHeader(); } else if (payloadVersion != 0) { throw Error.ProtectionProvider_BadVersion(); } if (_logger.IsDebugLevelEnabled()) { _logger.PerformingUnprotectOperationToKeyWithPurposes(keyIdFromPayload, JoinPurposesForLog(Purposes)); } // Find the correct encryptor in the keyring. bool keyWasRevoked; var currentKeyRing = _keyRingProvider.GetCurrentKeyRing(); var requestedEncryptor = currentKeyRing.GetAuthenticatedEncryptorByKeyId(keyIdFromPayload, out keyWasRevoked); if (requestedEncryptor == null) { if (_keyRingProvider is KeyRingProvider provider && provider.InAutoRefreshWindow()) { currentKeyRing = provider.RefreshCurrentKeyRing(); requestedEncryptor = currentKeyRing.GetAuthenticatedEncryptorByKeyId(keyIdFromPayload, out keyWasRevoked); } if (requestedEncryptor == null) { if (_logger.IsTraceLevelEnabled()) { _logger.KeyWasNotFoundInTheKeyRingUnprotectOperationCannotProceed(keyIdFromPayload); } throw Error.Common_KeyNotFound(keyIdFromPayload); } } // Do we need to notify the caller that they should reprotect the data? status = UnprotectStatus.Ok; if (keyIdFromPayload != currentKeyRing.DefaultKeyId) { status = UnprotectStatus.DefaultEncryptionKeyChanged; } // Do we need to notify the caller that this key was revoked? if (keyWasRevoked) { if (allowOperationsOnRevokedKeys) { if (_logger.IsDebugLevelEnabled()) { _logger.KeyWasRevokedCallerRequestedUnprotectOperationProceedRegardless(keyIdFromPayload); } status = UnprotectStatus.DecryptionKeyWasRevoked; } else { if (_logger.IsDebugLevelEnabled()) { _logger.KeyWasRevokedUnprotectOperationCannotProceed(keyIdFromPayload); } throw Error.Common_KeyRevoked(keyIdFromPayload); } } // Perform the decryption operation. ArraySegment<byte> ciphertext = new ArraySegment<byte>(protectedData, sizeof(uint) + sizeof(Guid), protectedData.Length - (sizeof(uint) + sizeof(Guid))); // chop off magic header + encryptor id ArraySegment<byte> additionalAuthenticatedData = new ArraySegment<byte>(_aadTemplate.GetAadForKey(keyIdFromPayload, isProtecting: false)); // At this point, cipherText := { encryptorSpecificPayload }, // so all that's left is to invoke the decryption routine directly. return requestedEncryptor.Decrypt(ciphertext, additionalAuthenticatedData) ?? CryptoUtil.Fail<byte[]>("IAuthenticatedEncryptor.Decrypt returned null."); } catch (Exception ex) when (ex.RequiresHomogenization()) { // homogenize all failures to CryptographicException throw Error.DecryptionFailed(ex); } } private static void WriteGuid(void* ptr, Guid value) { #if NETCOREAPP var span = new Span<byte>(ptr, sizeof(Guid)); // Performs appropriate endianness fixups var success = value.TryWriteBytes(span); Debug.Assert(success, "Failed to write Guid."); #elif NETSTANDARD2_0 || NETFRAMEWORK Debug.Assert(BitConverter.IsLittleEndian); Unsafe.WriteUnaligned<Guid>(ptr, value); #else #error Update target frameworks #endif } private static void WriteBigEndianInteger(byte* ptr, uint value) { ptr[0] = (byte)(value >> 24); ptr[1] = (byte)(value >> 16); ptr[2] = (byte)(value >> 8); ptr[3] = (byte)(value); } private struct AdditionalAuthenticatedDataTemplate { private byte[] _aadTemplate; public AdditionalAuthenticatedDataTemplate(IEnumerable<string> purposes) { const int MEMORYSTREAM_DEFAULT_CAPACITY = 0x100; // matches MemoryStream.EnsureCapacity var ms = new MemoryStream(MEMORYSTREAM_DEFAULT_CAPACITY); // additionalAuthenticatedData := { magicHeader (32-bit) || keyId || purposeCount (32-bit) || (purpose)* } // purpose := { utf8ByteCount (7-bit encoded) || utf8Text } using (var writer = new PurposeBinaryWriter(ms)) { writer.WriteBigEndian(MAGIC_HEADER_V0); Debug.Assert(ms.Position == sizeof(uint)); var posPurposeCount = writer.Seek(sizeof(Guid), SeekOrigin.Current); // skip over where the key id will be stored; we'll fill it in later writer.Seek(sizeof(uint), SeekOrigin.Current); // skip over where the purposeCount will be stored; we'll fill it in later uint purposeCount = 0; foreach (string purpose in purposes) { Debug.Assert(purpose != null); writer.Write(purpose); // prepends length as a 7-bit encoded integer purposeCount++; } // Once we have written all the purposes, go back and fill in 'purposeCount' writer.Seek(checked((int)posPurposeCount), SeekOrigin.Begin); writer.WriteBigEndian(purposeCount); } _aadTemplate = ms.ToArray(); } public byte[] GetAadForKey(Guid keyId, bool isProtecting) { // Multiple threads might be trying to read and write the _aadTemplate field // simultaneously. We need to make sure all accesses to it are thread-safe. var existingTemplate = Volatile.Read(ref _aadTemplate); Debug.Assert(existingTemplate.Length >= sizeof(uint) /* MAGIC_HEADER */ + sizeof(Guid) /* keyId */); // If the template is already initialized to this key id, return it. // The caller will not mutate it. fixed (byte* pExistingTemplate = existingTemplate) { if (ReadGuid(&pExistingTemplate[sizeof(uint)]) == keyId) { return existingTemplate; } } // Clone since we're about to make modifications. // If this is an encryption operation, we only ever encrypt to the default key, // so we should replace the existing template. This could occur after the protector // has already been created, such as when the underlying key ring has been modified. byte[] newTemplate = (byte[])existingTemplate.Clone(); fixed (byte* pNewTemplate = newTemplate) { WriteGuid(&pNewTemplate[sizeof(uint)], keyId); if (isProtecting) { Volatile.Write(ref _aadTemplate, newTemplate); } return newTemplate; } } private sealed class PurposeBinaryWriter : BinaryWriter { public PurposeBinaryWriter(MemoryStream stream) : base(stream, EncodingUtil.SecureUtf8Encoding, leaveOpen: true) { } // Writes a big-endian 32-bit integer to the underlying stream. public void WriteBigEndian(uint value) { var outStream = BaseStream; // property accessor also performs a flush outStream.WriteByte((byte)(value >> 24)); outStream.WriteByte((byte)(value >> 16)); outStream.WriteByte((byte)(value >> 8)); outStream.WriteByte((byte)(value)); } } } private enum UnprotectStatus { Ok, DefaultEncryptionKeyChanged, DecryptionKeyWasRevoked } } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Web.Hosting; using System.Web.Mvc; using System.Xml.Linq; using NuGet; using Orchard.Environment; using Orchard.Environment.Configuration; using Orchard.Environment.Extensions.Models; using Orchard.FileSystems.AppData; using Orchard.Localization; using Orchard.Modules.Services; using Orchard.Mvc.Extensions; using Orchard.Packaging.Extensions; using Orchard.Packaging.Services; using Orchard.Packaging.ViewModels; using Orchard.Recipes.Models; using Orchard.Recipes.Services; using Orchard.Security; using Orchard.Themes; using Orchard.UI.Admin; using Orchard.UI.Notify; using IPackageManager = Orchard.Packaging.Services.IPackageManager; using PackageBuilder = Orchard.Packaging.Services.PackageBuilder; namespace Orchard.Packaging.Controllers { [Themed, Admin] public class PackagingServicesController : Controller { private readonly ShellSettings _shellSettings; private readonly IPackageManager _packageManager; private readonly IPackagingSourceManager _packagingSourceManager; private readonly IAppDataFolderRoot _appDataFolderRoot; private readonly IModuleService _moduleService; private readonly IHostEnvironment _hostEnvironment; private readonly IRecipeHarvester _recipeHarvester; private readonly IRecipeManager _recipeManager; public PackagingServicesController( ShellSettings shellSettings, IPackageManager packageManager, IPackagingSourceManager packagingSourceManager, IAppDataFolderRoot appDataFolderRoot, IOrchardServices services, IModuleService moduleService, IHostEnvironment hostEnvironment) : this(shellSettings, packageManager, packagingSourceManager, appDataFolderRoot, services, moduleService, hostEnvironment, null, null) { } public PackagingServicesController( ShellSettings shellSettings, IPackageManager packageManager, IPackagingSourceManager packagingSourceManager, IAppDataFolderRoot appDataFolderRoot, IOrchardServices services, IModuleService moduleService, IHostEnvironment hostEnvironment, IRecipeHarvester recipeHarvester, IRecipeManager recipeManager) { _shellSettings = shellSettings; _packageManager = packageManager; _appDataFolderRoot = appDataFolderRoot; _moduleService = moduleService; _hostEnvironment = hostEnvironment; _recipeHarvester = recipeHarvester; _recipeManager = recipeManager; _packagingSourceManager = packagingSourceManager; Services = services; T = NullLocalizer.Instance; Logger = Logging.NullLogger.Instance; } public Localizer T { get; set; } public IOrchardServices Services { get; set; } public Logging.ILogger Logger { get; set; } public ActionResult AddTheme(string returnUrl) { if (_shellSettings.Name != ShellSettings.DefaultName || !Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to add themes"))) return new HttpUnauthorizedResult(); return View(); } [HttpPost, ActionName("UninstallTheme")] public ActionResult UninstallThemePost(string themeId, string returnUrl, string retryUrl) { if (String.IsNullOrEmpty(themeId)) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } if (_shellSettings.Name != ShellSettings.DefaultName || !Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to remove themes"))) return new HttpUnauthorizedResult(); return UninstallPackage(PackageBuilder.BuildPackageId(themeId, DefaultExtensionTypes.Theme), returnUrl, retryUrl); } [HttpPost, ActionName("UninstallModule")] public ActionResult UninstallModulePost(string moduleId, string returnUrl, string retryUrl) { if (String.IsNullOrEmpty(moduleId)) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } if (_shellSettings.Name != ShellSettings.DefaultName || !Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to remove modules"))) return new HttpUnauthorizedResult(); return UninstallPackage(PackageBuilder.BuildPackageId(moduleId, DefaultExtensionTypes.Module), returnUrl, retryUrl); } public ActionResult AddModule(string returnUrl) { if (_shellSettings.Name != ShellSettings.DefaultName || !Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to add modules"))) return new HttpUnauthorizedResult(); return View(); } public ActionResult InstallGallery(string packageId, string version, int sourceId, string redirectUrl) { if (_shellSettings.Name != ShellSettings.DefaultName || !Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to add sources"))) return new HttpUnauthorizedResult(); var source = _packagingSourceManager.GetSources().FirstOrDefault(s => s.Id == sourceId); if (source == null) { return HttpNotFound(); } try { PackageInfo packageInfo = _packageManager.Install(packageId, version, source.FeedUrl, MapAppRoot()); if (DefaultExtensionTypes.IsTheme(packageInfo.ExtensionType)) { Services.Notifier.Information(T("The theme has been successfully installed. It can be enabled in the \"Themes\" page accessible from the menu.")); } else if (DefaultExtensionTypes.IsModule(packageInfo.ExtensionType)) { Services.Notifier.Information(T("The module has been successfully installed.")); IPackageRepository packageRepository = PackageRepositoryFactory.Default.CreateRepository(new PackageSource(source.FeedUrl, "Default")); IPackage package = packageRepository.FindPackage(packageId); ExtensionDescriptor extensionDescriptor = package.GetExtensionDescriptor(packageInfo.ExtensionType); return InstallPackageDetails(extensionDescriptor, redirectUrl); } } catch (OrchardException e) { Services.Notifier.Error(T("Package installation failed: {0}", e.Message)); return View("InstallPackageFailed"); } catch (Exception) { Services.Notifier.Error(T("Package installation failed.")); return View("InstallPackageFailed"); } return Redirect(redirectUrl); } public ActionResult InstallLocally(string redirectUrl) { if (_shellSettings.Name != ShellSettings.DefaultName || !Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to install packages"))) return new HttpUnauthorizedResult(); var httpPostedFileBase = Request.Files.Get(0); if (httpPostedFileBase == null || Request.Files.Count == 0 || string.IsNullOrWhiteSpace(httpPostedFileBase.FileName)) { throw new OrchardException(T("Select a file to upload.")); } try { string fullFileName = Path.Combine(_appDataFolderRoot.RootFolder, Path.GetFileName(httpPostedFileBase.FileName)).Replace(Path.DirectorySeparatorChar, '/'); httpPostedFileBase.SaveAs(fullFileName); var package = new ZipPackage(fullFileName); PackageInfo packageInfo = _packageManager.Install(package, _appDataFolderRoot.RootFolder, MapAppRoot()); ExtensionDescriptor extensionDescriptor = package.GetExtensionDescriptor(packageInfo.ExtensionType); System.IO.File.Delete(fullFileName); if (DefaultExtensionTypes.IsTheme(extensionDescriptor.ExtensionType)) { Services.Notifier.Information(T("The theme has been successfully installed. It can be enabled in the \"Themes\" page accessible from the menu.")); } else if (DefaultExtensionTypes.IsModule(extensionDescriptor.ExtensionType)) { Services.Notifier.Information(T("The module has been successfully installed.")); return InstallPackageDetails(extensionDescriptor, redirectUrl); } } catch (OrchardException e) { Services.Notifier.Error(T("Package uploading and installation failed: {0}", e.Message)); return View("InstallPackageFailed"); } catch (Exception) { Services.Notifier.Error(T("Package uploading and installation failed.")); return View("InstallPackageFailed"); } return Redirect(redirectUrl); } private ActionResult InstallPackageDetails(ExtensionDescriptor extensionDescriptor, string redirectUrl) { if (DefaultExtensionTypes.IsModule(extensionDescriptor.ExtensionType)) { List<PackagingInstallFeatureViewModel> features = extensionDescriptor.Features .Where(featureDescriptor => !DefaultExtensionTypes.IsTheme(featureDescriptor.Extension.ExtensionType)) .Select(featureDescriptor => new PackagingInstallFeatureViewModel { Enable = true, // by default all features are enabled FeatureDescriptor = featureDescriptor }).ToList(); List<PackagingInstallRecipeViewModel> recipes = null; if (_recipeHarvester != null) { recipes = _recipeHarvester.HarvestRecipes(extensionDescriptor.Id) .Select(recipe => new PackagingInstallRecipeViewModel { Execute = false, // by default no recipes are executed Recipe = recipe }).ToList(); } if (features.Count > 0) { return View("InstallModuleDetails", new PackagingInstallViewModel { Features = features, Recipes = recipes, ExtensionDescriptor = extensionDescriptor }); } } return Redirect(redirectUrl); } [HttpPost, ActionName("InstallPackageDetails")] public ActionResult InstallPackageDetailsPOST(PackagingInstallViewModel packagingInstallViewModel, string redirectUrl) { if (_shellSettings.Name != ShellSettings.DefaultName || !Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to add sources"))) return new HttpUnauthorizedResult(); try { if (_recipeHarvester != null && _recipeManager != null) { IEnumerable<Recipe> recipes = _recipeHarvester.HarvestRecipes(packagingInstallViewModel.ExtensionDescriptor.Id) .Where(loadedRecipe => packagingInstallViewModel.Recipes.FirstOrDefault(recipeViewModel => recipeViewModel.Execute && recipeViewModel.Recipe.Name.Equals(loadedRecipe.Name)) != null); foreach (Recipe recipe in recipes) { try { _recipeManager.Execute(recipe); } catch { Services.Notifier.Error(T("Recipes contains {0} unsupported module installation steps.", recipe.Name)); } } } // Enable selected features if (packagingInstallViewModel.Features.Count > 0) { IEnumerable<string> featureIds = packagingInstallViewModel.Features .Where(feature => feature.Enable) .Select(feature => feature.FeatureDescriptor.Id); // Enable the features and its dependencies using recipes, so that they are run after the module's recipes var recipe = new Recipe { Name = "Test", RecipeSteps = featureIds.Select( (i,x) => new RecipeStep( id: i.ToString(CultureInfo.InvariantCulture), recipeName: "Test", name: "Feature", step: new XElement("Feature", new XAttribute("enable", x)))) }; _recipeManager.Execute(recipe); } } catch (Exception exception) { Services.Notifier.Error(T("Post installation steps failed with error: {0}", exception.Message)); } return Redirect(redirectUrl); } private ActionResult UninstallPackage(string id, string returnUrl, string retryUrl) { try { _packageManager.Uninstall(id, MapAppRoot()); } catch (Exception exception) { Services.Notifier.Error(T("Uninstall failed: {0}", exception.Message)); return Redirect(!String.IsNullOrEmpty(retryUrl) ? retryUrl : returnUrl); } Services.Notifier.Information(T("Uninstalled package \"{0}\"", id)); return this.RedirectLocal(returnUrl, "~/"); } private string MapAppRoot() { return _hostEnvironment.MapPath("~/"); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Security; using Microsoft.Build.Framework; using Microsoft.Build.BuildEngine.Shared; namespace Microsoft.Build.BuildEngine { /// <summary> /// This class wraps a project item, and provides a "view" on the item's BuildItem class that is suitable to expose to tasks. /// </summary> /// <owner>SumedhK</owner> internal sealed class TaskItem : MarshalByRefObject, ITaskItem { /// <summary> /// Private default constructor disallows parameterless instantiation. /// </summary> /// <owner>SumedhK</owner> private TaskItem() { // do nothing } /// <summary> /// Creates an instance of this class given the item-spec. /// </summary> /// <owner>SumedhK</owner> /// <param name="itemSpec"></param> internal TaskItem(string itemSpec) { ErrorUtilities.VerifyThrow(itemSpec != null, "Need to specify item-spec."); item = new BuildItem(null, itemSpec); } /// <summary> /// Creates an instance of this class given the backing item. /// </summary> /// <owner>SumedhK</owner> /// <param name="item"></param> internal TaskItem(BuildItem item) { ErrorUtilities.VerifyThrow(item != null, "Need to specify backing item."); this.item = item.VirtualClone(); } /// <summary> /// Gets or sets the item-spec for the item. /// </summary> /// <owner>SumedhK</owner> /// <value>Item-spec string.</value> public string ItemSpec { get { return item.FinalItemSpec; } set { ErrorUtilities.VerifyThrowArgumentNull(value, "ItemSpec"); item.SetFinalItemSpecEscaped(EscapingUtilities.Escape(value)); } } /// <summary> /// Gets the names of metadata on the item -- also includes the pre-defined/reserved item-spec modifiers. /// </summary> /// <owner>SumedhK, JomoF</owner> /// <value>Collection of name strings.</value> public ICollection MetadataNames { get { // Add all the custom metadata. return item.MetadataNames; } } /// <summary> /// Gets the number of metadata set on the item. /// </summary> /// <owner>SumedhK</owner> /// <value>Count of metadata.</value> public int MetadataCount { get { return item.MetadataCount; } } /// <summary> /// Gets the names of custom metadata on the item /// </summary> /// <value>Collection of name strings.</value> public ICollection CustomMetadataNames { get { // All the custom metadata. return item.CustomMetadataNames; } } /// <summary> /// Gets the number of custom metadata set on the item. /// </summary> /// <value>Count of metadata.</value> public int CustomMetadataCount { get { return item.CustomMetadataCount; } } /// <summary> /// Looks up the value of the given custom metadata. /// </summary> /// <owner>SumedhK</owner> /// <param name="metadataName"></param> /// <returns>value of metadata</returns> public string GetMetadata(string metadataName) { ErrorUtilities.VerifyThrowArgumentNull(metadataName, nameof(metadataName)); // Return the unescaped data to the task. return item.GetEvaluatedMetadata(metadataName); } /// <summary> /// Sets the value of the specified custom metadata. /// </summary> /// <owner>SumedhK</owner> /// <param name="metadataName"></param> /// <param name="metadataValue"></param> public void SetMetadata(string metadataName, string metadataValue) { ErrorUtilities.VerifyThrowArgumentLength(metadataName, nameof(metadataName)); ErrorUtilities.VerifyThrowArgumentNull(metadataValue, nameof(metadataValue)); item.SetMetadata(metadataName, EscapingUtilities.Escape(metadataValue)); } /// <summary> /// Removes the specified custom metadata. /// </summary> /// <owner>SumedhK</owner> /// <param name="metadataName"></param> public void RemoveMetadata(string metadataName) { ErrorUtilities.VerifyThrowArgumentNull(metadataName, nameof(metadataName)); item.RemoveMetadata(metadataName); } /// <summary> /// Copy the metadata (but not the ItemSpec or other built-in metadata) to destinationItem. If a particular metadata /// already exists on the destination item, then it is not overwritten -- the original value wins. /// </summary> /// <owner>JomoF</owner> /// <param name="destinationItem"></param> public void CopyMetadataTo ( ITaskItem destinationItem ) { ErrorUtilities.VerifyThrowArgumentNull(destinationItem, nameof(destinationItem)); // Intentionally not _computed_ properties. These are slow and don't really // apply anyway. foreach (DictionaryEntry entry in item.GetAllCustomEvaluatedMetadata()) { string key = (string)entry.Key; string destinationValue = destinationItem.GetMetadata(key); if (string.IsNullOrEmpty(destinationValue)) { destinationItem.SetMetadata(key, EscapingUtilities.UnescapeAll((string)entry.Value)); } } // also copy the original item-spec under a "magic" metadata -- this is useful for tasks that forward metadata // between items, and need to know the source item where the metadata came from string originalItemSpec = destinationItem.GetMetadata("OriginalItemSpec"); if (string.IsNullOrEmpty(originalItemSpec)) { destinationItem.SetMetadata("OriginalItemSpec", ItemSpec); } } /// <summary> /// Get the collection of metadata. This does not include built-in metadata. /// </summary> /// <remarks> /// RECOMMENDED GUIDELINES FOR METHOD IMPLEMENTATIONS: /// 1) this method should return a clone of the metadata /// 2) writing to this dictionary should not be reflected in the underlying item. /// </remarks> /// <owner>JomoF</owner> public IDictionary CloneCustomMetadata() { IDictionary backingItemMetadata = item.CloneCustomMetadata(); // Go through and escape the metadata as necessary. string[] keys = new string[backingItemMetadata.Count]; backingItemMetadata.Keys.CopyTo(keys, 0); foreach (string singleMetadataName in keys) { string singleMetadataValue = (string) backingItemMetadata[singleMetadataName]; bool unescapingWasNecessary; string singleMetadataValueUnescaped = EscapingUtilities.UnescapeAll(singleMetadataValue, out unescapingWasNecessary); // It's very important for perf not to touch this IDictionary unless we really need to. Touching // it in any way causes it to get cloned (in the implementation of CopyOnWriteHashtable). if (unescapingWasNecessary) { backingItemMetadata[singleMetadataName] = singleMetadataValueUnescaped; } } return backingItemMetadata; } /// <summary> /// Produce a string representation. /// </summary> /// <owner>JomoF</owner> public override string ToString() { return ItemSpec; } /// <summary> /// Overriden to give this class infinite lease time. Otherwise we end up with a limited /// lease (5 minutes I think) and instances can expire if they take long time processing. /// </summary> [SecurityCritical] public override object InitializeLifetimeService() { // null means infinite lease time return null; } // the backing item internal BuildItem item; #region Operators /// <summary> /// This allows an explicit typecast from a "TaskItem" to a "string", returning the ItemSpec for this item. /// </summary> /// <owner>RGoel</owner> /// <param name="taskItemToCast">The item to operate on.</param> /// <returns>The item-spec of the item.</returns> public static explicit operator string ( TaskItem taskItemToCast ) { return taskItemToCast.ItemSpec; } #endregion } }
#region License /* Copyright (c) 2005 Leslie Sanford * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Contact /* * Leslie Sanford * Email: [email protected] */ #endregion using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; using Sanford.Multimedia; namespace Sanford.Multimedia.Midi { public partial class InputDevice : MidiDevice { private void HandleMessage(IntPtr hnd, int msg, int instance, int param1, int param2) { //first send RawMessage delegateQueue.Post(HandleRawMessage, param1); if (msg == MIM_OPEN) { } else if (msg == MIM_CLOSE) { } else if(msg == MIM_DATA) { delegateQueue.Post(HandleShortMessage, param1); } else if(msg == MIM_MOREDATA) { delegateQueue.Post(HandleShortMessage, param1); } else if(msg == MIM_LONGDATA) { delegateQueue.Post(HandleSysExMessage, new IntPtr(param1)); } else if(msg == MIM_ERROR) { delegateQueue.Post(HandleInvalidShortMessage, param1); } else if(msg == MIM_LONGERROR) { delegateQueue.Post(HandleInvalidSysExMessage, new IntPtr(param1)); } } private void HandleRawMessage(object state) { OnRawMessage(new RawMessageEventArgs((int)state)); } private void HandleShortMessage(object state) { int message = (int)state; int status = ShortMessage.UnpackStatus(message); if(status >= (int)ChannelCommand.NoteOff && status <= (int)ChannelCommand.PitchWheel + ChannelMessage.MidiChannelMaxValue) { cmBuilder.Message = message; cmBuilder.Build(); OnChannelMessageReceived(new ChannelMessageEventArgs(cmBuilder.Result)); } else if(status == (int)SysCommonType.MidiTimeCode || status == (int)SysCommonType.SongPositionPointer || status == (int)SysCommonType.SongSelect || status == (int)SysCommonType.TuneRequest) { scBuilder.Message = message; scBuilder.Build(); OnSysCommonMessageReceived(new SysCommonMessageEventArgs(scBuilder.Result)); } else { SysRealtimeMessageEventArgs e = null; switch((SysRealtimeType)status) { case SysRealtimeType.ActiveSense: e = SysRealtimeMessageEventArgs.ActiveSense; break; case SysRealtimeType.Clock: e = SysRealtimeMessageEventArgs.Clock; break; case SysRealtimeType.Continue: e = SysRealtimeMessageEventArgs.Continue; break; case SysRealtimeType.Reset: e = SysRealtimeMessageEventArgs.Reset; break; case SysRealtimeType.Start: e = SysRealtimeMessageEventArgs.Start; break; case SysRealtimeType.Stop: e = SysRealtimeMessageEventArgs.Stop; break; case SysRealtimeType.Tick: e = SysRealtimeMessageEventArgs.Tick; break; } OnSysRealtimeMessageReceived(e); } } private void HandleSysExMessage(object state) { lock(lockObject) { IntPtr headerPtr = (IntPtr)state; MidiHeader header = (MidiHeader)Marshal.PtrToStructure(headerPtr, typeof(MidiHeader)); if(!resetting) { for(int i = 0; i < header.bytesRecorded; i++) { sysExData.Add(Marshal.ReadByte(header.data, i)); } if(sysExData[0] == 0xF0 && sysExData[sysExData.Count - 1] == 0xF7) { SysExMessage message = new SysExMessage(sysExData.ToArray()); sysExData.Clear(); OnSysExMessageReceived(new SysExMessageEventArgs(message)); } int result = AddSysExBuffer(); if(result != DeviceException.MMSYSERR_NOERROR) { Exception ex = new InputDeviceException(result); OnError(new ErrorEventArgs(ex)); } } ReleaseBuffer(headerPtr); } } private void HandleInvalidShortMessage(object state) { OnInvalidShortMessageReceived(new InvalidShortMessageEventArgs((int)state)); } private void HandleInvalidSysExMessage(object state) { lock(lockObject) { IntPtr headerPtr = (IntPtr)state; MidiHeader header = (MidiHeader)Marshal.PtrToStructure(headerPtr, typeof(MidiHeader)); if(!resetting) { byte[] data = new byte[header.bytesRecorded]; Marshal.Copy(header.data, data, 0, data.Length); OnInvalidSysExMessageReceived(new InvalidSysExMessageEventArgs(data)); int result = AddSysExBuffer(); if(result != DeviceException.MMSYSERR_NOERROR) { Exception ex = new InputDeviceException(result); OnError(new ErrorEventArgs(ex)); } } ReleaseBuffer(headerPtr); } } private void ReleaseBuffer(IntPtr headerPtr) { int result = midiInUnprepareHeader(Handle, headerPtr, SizeOfMidiHeader); if(result != DeviceException.MMSYSERR_NOERROR) { Exception ex = new InputDeviceException(result); OnError(new ErrorEventArgs(ex)); } headerBuilder.Destroy(headerPtr); bufferCount--; Debug.Assert(bufferCount >= 0); Monitor.Pulse(lockObject); } public int AddSysExBuffer() { int result; // Initialize the MidiHeader builder. headerBuilder.BufferLength = sysExBufferSize; headerBuilder.Build(); // Get the pointer to the built MidiHeader. IntPtr headerPtr = headerBuilder.Result; // Prepare the header to be used. result = midiInPrepareHeader(Handle, headerPtr, SizeOfMidiHeader); // If the header was perpared successfully. if(result == DeviceException.MMSYSERR_NOERROR) { bufferCount++; // Add the buffer to the InputDevice. result = midiInAddBuffer(Handle, headerPtr, SizeOfMidiHeader); // If the buffer could not be added. if(result != MidiDeviceException.MMSYSERR_NOERROR) { // Unprepare header - there's a chance that this will fail // for whatever reason, but there's not a lot that can be // done at this point. midiInUnprepareHeader(Handle, headerPtr, SizeOfMidiHeader); bufferCount--; // Destroy header. headerBuilder.Destroy(); } } // Else the header could not be prepared. else { // Destroy header. headerBuilder.Destroy(); } return result; } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. extern alias analysis; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Microsoft.PythonTools; using Microsoft.PythonTools.Intellisense; using Microsoft.PythonTools.Interpreter; using Microsoft.PythonTools.Interpreter.Default; using Microsoft.PythonTools.Parsing; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.VisualStudioTools.Project; using TestUtilities; using TestUtilities.Python; using Assert = Microsoft.VisualStudio.TestTools.UnitTesting.Assert; namespace PythonToolsTests { [TestClass] public class CompletionDBTest { [ClassInitialize] public static void DoDeployment(TestContext context) { AssertListener.Initialize(); PythonTestData.Deploy(); } private void TestOpen(PythonVersion path) { path.AssertInstalled(); Console.WriteLine(path.InterpreterPath); Guid testId = Guid.NewGuid(); var testDir = TestData.GetTempPath(testId.ToString()); // run the scraper using (var proc = ProcessOutput.RunHiddenAndCapture( path.InterpreterPath, TestData.GetPath("PythonScraper.py"), testDir, TestData.GetPath("CompletionDB") )) { Console.WriteLine("Command: " + proc.Arguments); proc.Wait(); // it should succeed Console.WriteLine("**Stdout**"); foreach (var line in proc.StandardOutputLines) { Console.WriteLine(line); } Console.WriteLine(""); Console.WriteLine("**Stdout**"); foreach (var line in proc.StandardErrorLines) { Console.WriteLine(line); } Assert.AreEqual(0, proc.ExitCode, "Bad exit code: " + proc.ExitCode); } // perform some basic validation dynamic builtinDb = Unpickle.Load(new FileStream(Path.Combine(testDir, path.Version.Is3x() ? "builtins.idb" : "__builtin__.idb"), FileMode.Open, FileAccess.Read)); if (path.Version.Is2x()) { // no open in 3.x foreach (var overload in builtinDb["members"]["open"]["value"]["overloads"]) { Assert.AreEqual("__builtin__", overload["ret_type"][0][0]); Assert.AreEqual("file", overload["ret_type"][0][1]); } if (!path.InterpreterPath.Contains("Iron")) { // http://pytools.codeplex.com/workitem/799 var arr = (IList<object>)builtinDb["members"]["list"]["value"]["members"]["__init__"]["value"]["overloads"]; Assert.AreEqual( "args", ((dynamic)(arr[0]))["args"][1]["name"] ); } } if (!path.InterpreterPath.Contains("Iron")) { dynamic itertoolsDb = Unpickle.Load(new FileStream(Path.Combine(testDir, "itertools.idb"), FileMode.Open, FileAccess.Read)); var tee = itertoolsDb["members"]["tee"]["value"]; var overloads = tee["overloads"]; var nArg = overloads[0]["args"][1]; Assert.AreEqual("n", nArg["name"]); Assert.AreEqual("2", nArg["default_value"]); dynamic sreDb = Unpickle.Load(new FileStream(Path.Combine(testDir, "_sre.idb"), FileMode.Open, FileAccess.Read)); var members = sreDb["members"]; Assert.IsTrue(members.ContainsKey("SRE_Pattern")); Assert.IsTrue(members.ContainsKey("SRE_Match")); } Console.WriteLine("Passed: {0}", path.InterpreterPath); } [TestMethod, Priority(1)] public void TestOpen25() { TestOpen(PythonPaths.Python25 ?? PythonPaths.Python25_x64); } [TestMethod, Priority(1)] public void TestOpen26() { TestOpen(PythonPaths.Python26 ?? PythonPaths.Python26_x64); } [TestMethod, Priority(1)] public void TestOpen27() { TestOpen(PythonPaths.Python27 ?? PythonPaths.Python27_x64); } [TestMethod, Priority(1)] public void TestOpen30() { TestOpen(PythonPaths.Python30 ?? PythonPaths.Python30_x64); } [TestMethod, Priority(1)] public void TestOpen31() { TestOpen(PythonPaths.Python31 ?? PythonPaths.Python31_x64); } [TestMethod, Priority(1)] public void TestOpen32() { TestOpen(PythonPaths.Python32 ?? PythonPaths.Python32_x64); } [TestMethod, Priority(1)] public void TestOpen33() { TestOpen(PythonPaths.Python33 ?? PythonPaths.Python33_x64); } [TestMethod, Priority(1)] public void TestOpen34() { TestOpen(PythonPaths.Python34 ?? PythonPaths.Python34_x64); } [TestMethod, Priority(1)] public void TestOpen35() { TestOpen(PythonPaths.Python35 ?? PythonPaths.Python35_x64); } [TestMethod, Priority(1)] public void TestPthFiles() { var outputPath = TestData.GetTempPath(randomSubPath: true); Console.WriteLine("Writing to: " + outputPath); // run the analyzer using (var output = ProcessOutput.RunHiddenAndCapture("Microsoft.PythonTools.Analyzer.exe", "/lib", TestData.GetPath(@"TestData\PathStdLib"), "/version", "2.7", "/outdir", outputPath, "/indir", TestData.GetPath("CompletionDB"), "/log", "AnalysisLog.txt")) { output.Wait(); Console.WriteLine("* Stdout *"); foreach (var line in output.StandardOutputLines) { Console.WriteLine(line); } Console.WriteLine("* Stderr *"); foreach (var line in output.StandardErrorLines) { Console.WriteLine(line); } Assert.AreEqual(0, output.ExitCode); } File.Copy(TestData.GetPath(@"CompletionDB\__builtin__.idb"), Path.Combine(outputPath, "__builtin__.idb")); var fact = InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(new Version(2, 7)); var paths = new List<string> { outputPath }; paths.AddRange(Directory.EnumerateDirectories(outputPath)); var typeDb = new PythonTypeDatabase(fact, paths); var module = typeDb.GetModule("SomeLib"); Assert.IsNotNull(module, "Could not import SomeLib"); var fobMod = typeDb.GetModule("SomeLib.fob"); Assert.IsNotNull(fobMod, "Could not import SomeLib.fob"); var cClass = ((IPythonModule)fobMod).GetMember(null, "C"); Assert.IsNotNull(cClass, "Could not get SomeLib.fob.C"); Assert.AreEqual(PythonMemberType.Class, cClass.MemberType); } [TestMethod, Priority(1)] public void PydInPackage() { PythonPaths.Python27.AssertInstalled(); var outputPath = TestData.GetTempPath(randomSubPath: true); Console.WriteLine("Writing to: " + outputPath); // run the analyzer using (var output = ProcessOutput.RunHiddenAndCapture("Microsoft.PythonTools.Analyzer.exe", "/python", PythonPaths.Python27.InterpreterPath, "/lib", TestData.GetPath(@"TestData\PydStdLib"), "/version", "2.7", "/outdir", outputPath, "/indir", TestData.GetPath("CompletionDB"), "/log", "AnalysisLog.txt")) { output.Wait(); Console.WriteLine("* Stdout *"); foreach (var line in output.StandardOutputLines) { Console.WriteLine(line); } Console.WriteLine("* Stderr *"); foreach (var line in output.StandardErrorLines) { Console.WriteLine(line); } Assert.AreEqual(0, output.ExitCode); } var fact = InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(new Version(2, 7)); var paths = new List<string> { outputPath }; paths.AddRange(Directory.EnumerateDirectories(outputPath)); var typeDb = new PythonTypeDatabase(fact, paths); var module = typeDb.GetModule("Package.winsound"); Assert.IsNotNull(module, "Package.winsound was not analyzed"); var package = typeDb.GetModule("Package"); Assert.IsNotNull(package, "Could not import Package"); var member = package.GetMember(null, "winsound"); Assert.IsNotNull(member, "Could not get member Package.winsound"); Assert.AreSame(module, member); module = typeDb.GetModule("Package._testcapi"); Assert.IsNotNull(module, "Package._testcapi was not analyzed"); package = typeDb.GetModule("Package"); Assert.IsNotNull(package, "Could not import Package"); member = package.GetMember(null, "_testcapi"); Assert.IsNotNull(member, "Could not get member Package._testcapi"); Assert.IsNotInstanceOfType(member, typeof(CPythonMultipleMembers)); Assert.AreSame(module, member); module = typeDb.GetModule("Package.select"); Assert.IsNotNull(module, "Package.select was not analyzed"); package = typeDb.GetModule("Package"); Assert.IsNotNull(package, "Could not import Package"); member = package.GetMember(null, "select"); Assert.IsNotNull(member, "Could not get member Package.select"); Assert.IsInstanceOfType(member, typeof(CPythonMultipleMembers)); var mm = (CPythonMultipleMembers)member; AssertUtil.ContainsExactly(mm.Members.Select(m => m.MemberType), PythonMemberType.Module, PythonMemberType.Constant, PythonMemberType.Class ); Assert.IsNotNull(mm.Members.Contains(module)); try { // Only clean up if the test passed Directory.Delete(outputPath, true); } catch { } } /// <summary> /// Checks that members removed or introduced in later versions show up or don't in /// earlier versions as appropriate. /// </summary> [TestMethod, Priority(1)] public void VersionedSharedDatabase() { var twoFive = PythonTypeDatabase.CreateDefaultTypeDatabase(new Version(2, 5)); var twoSix = PythonTypeDatabase.CreateDefaultTypeDatabase(new Version(2, 6)); var twoSeven = PythonTypeDatabase.CreateDefaultTypeDatabase(new Version(2, 7)); var threeOh = PythonTypeDatabase.CreateDefaultTypeDatabase(new Version(3, 0)); var threeOne = PythonTypeDatabase.CreateDefaultTypeDatabase(new Version(3, 1)); var threeTwo = PythonTypeDatabase.CreateDefaultTypeDatabase(new Version(3, 2)); // new in 2.6 Assert.AreEqual(null, twoFive.BuiltinModule.GetAnyMember("bytearray")); foreach (var version in new[] { twoSix, twoSeven, threeOh, threeOne, threeTwo }) { Assert.AreNotEqual(version, version.BuiltinModule.GetAnyMember("bytearray")); } // new in 2.7 Assert.AreEqual(null, twoSix.BuiltinModule.GetAnyMember("memoryview")); foreach (var version in new[] { twoSeven, threeOh, threeOne, threeTwo }) { Assert.AreNotEqual(version, version.BuiltinModule.GetAnyMember("memoryview")); } // not in 3.0 foreach (var version in new[] { twoFive, twoSix, twoSeven }) { Assert.AreNotEqual(null, version.BuiltinModule.GetAnyMember("StandardError")); } foreach (var version in new[] { threeOh, threeOne, threeTwo }) { Assert.AreEqual(null, version.BuiltinModule.GetAnyMember("StandardError")); } // new in 3.0 foreach (var version in new[] { twoFive, twoSix, twoSeven }) { Assert.AreEqual(null, version.BuiltinModule.GetAnyMember("exec")); Assert.AreEqual(null, version.BuiltinModule.GetAnyMember("print")); } foreach (var version in new[] { threeOh, threeOne, threeTwo }) { Assert.AreNotEqual(null, version.BuiltinModule.GetAnyMember("exec")); Assert.AreNotEqual(null, version.BuiltinModule.GetAnyMember("print")); } // new in 3.1 foreach (var version in new[] { twoFive, twoSix, twoSeven, threeOh }) { Assert.AreEqual(null, version.GetModule("sys").GetMember(null, "int_info")); } foreach (var version in new[] { threeOne, threeTwo }) { Assert.AreNotEqual(null, version.GetModule("sys").GetMember(null, "int_info")); } // new in 3.2 foreach (var version in new[] { twoFive, twoSix, twoSeven, threeOh, threeOne }) { Assert.AreEqual(null, version.GetModule("sys").GetMember(null, "setswitchinterval")); } foreach (var version in new[] { threeTwo }) { Assert.AreNotEqual(null, version.GetModule("sys").GetMember(null, "setswitchinterval")); } } [TestMethod, Priority(2)] public void CheckObsoleteGenerateFunction() { var path = PythonPaths.Versions.LastOrDefault(p => p != null && p.IsCPython); path.AssertInstalled(); var factory = InterpreterFactoryCreator.CreateInterpreterFactory(new InterpreterFactoryCreationOptions { Id = path.Id, LanguageVersion = path.Version.ToVersion(), Description = "Test Interpreter", Architecture = path.Isx64 ? ProcessorArchitecture.Amd64 : ProcessorArchitecture.X86, LibraryPath = path.LibPath, PrefixPath = path.PrefixPath, InterpreterPath = path.InterpreterPath, WatchLibraryForNewModules = false }); var tcs = new TaskCompletionSource<int>(); var beforeProc = Process.GetProcessesByName("Microsoft.PythonTools.Analyzer"); var request = new PythonTypeDatabaseCreationRequest { Factory = factory, OutputPath = TestData.GetTempPath(randomSubPath: true), SkipUnchanged = true, OnExit = tcs.SetResult }; Console.WriteLine("OutputPath: {0}", request.OutputPath); #pragma warning disable 618 PythonTypeDatabase.Generate(request); #pragma warning restore 618 int expected = 0; if (!tcs.Task.Wait(TimeSpan.FromMinutes(1.0))) { var proc = Process.GetProcessesByName("Microsoft.PythonTools.Analyzer") .Except(beforeProc) .ToArray(); // Ensure we actually started running Assert.AreNotEqual(0, proc.Length, "Process is not running"); expected = -1; // Kill the process foreach (var p in proc) { Console.WriteLine("Killing process {0}", p.Id); p.Kill(); } Assert.IsTrue(tcs.Task.Wait(TimeSpan.FromMinutes(1.0)), "Process did not die"); } Assert.AreEqual(expected, tcs.Task.Result, "Incorrect exit code"); } } }
using System; using System.IO; using NUnit.Framework; using ToolBelt; using System.Collections.Generic; namespace ToolBelt.Tests { [TestFixture] public class ParsedPathTests { [Test] public void TestOperators() { ParsedPath pp = new ParsedPath("file.txt", PathType.Unknown); Assert.IsFalse(pp == null); Assert.IsFalse(null == pp); Assert.IsTrue(pp != null); Assert.IsTrue(null != pp); Assert.IsFalse(pp.Equals(null)); Assert.IsFalse(ParsedPath.Equals(pp, null)); Assert.IsFalse(ParsedPath.Equals(null, pp)); Assert.AreNotEqual(0, pp.GetHashCode()); Assert.IsFalse(pp == ParsedPath.Empty); } [Test] public void TestCompareTo() { ParsedPath ppA = new ParsedPath(@"c:\blah\a.txt", PathType.File); ParsedPath ppB = new ParsedPath(@"c:\blah\a.txt", PathType.File); ParsedPath ppB2 = new ParsedPath(@"c:\blah\b.txt", PathType.File); ParsedPath ppC = new ParsedPath(@"c:\blah\a.txt", PathType.File); ParsedPath ppC2 = new ParsedPath(@"c:\blah\b.txt", PathType.File); #if MACOS string p = @"c:/blah/a.txt"; #else string p = @"c:\blah\a.txt"; #endif // MSDN gives the following axioms for CompareTo() Assert.AreEqual(0, ppA.CompareTo(ppB)); Assert.AreEqual(0, ppB.CompareTo(ppA)); Assert.AreEqual(0, ppB.CompareTo(ppC)); Assert.AreEqual(0, ppA.CompareTo(ppC)); int x = ppA.CompareTo(ppB2); Assert.IsTrue(x != 0); Assert.IsTrue(Math.Sign(x) == -Math.Sign(ppB2.CompareTo(ppA))); int y = ppB.CompareTo(ppC2); Assert.IsTrue(Math.Sign(x) == Math.Sign(y)); Assert.AreEqual(Math.Sign(x), ppA.CompareTo(ppC2)); // Need to be able to compare ParsePath to String Assert.AreEqual(0, ppA.CompareTo(p)); } [Test] public void ConstructParsedPath() { // Test some good paths AssertPathParts(@"\", PathType.Unknown, "", "", "", @"\", "", ""); AssertPathParts(@".txt", PathType.Unknown, "", "", "", "", "", ".txt"); AssertPathParts(@"*.txt", PathType.File, "", "", "", "", @"*", @".txt"); AssertPathParts(@"..\*.txt", PathType.Unknown, "", "", "", @"..\", @"*", @".txt"); AssertPathParts(@".", PathType.Unknown, "", "", "", "", "", ""); AssertPathParts(@".", PathType.Directory, "", "", "", @".\", "", ""); AssertPathParts(@"..", PathType.Unknown, "", "", "", "", "", ""); AssertPathParts(@"..", PathType.Directory, "", "", "", @"..\", "", ""); AssertPathParts(@"c:", PathType.Unknown, "", "", @"c:", "", "", ""); AssertPathParts(@"c:", PathType.Volume, "", "", @"c:", "", "", ""); AssertPathParts(@"c:\", PathType.Directory, "", "", @"c:", @"\", "", ""); AssertPathParts(@"c:foo.txt", PathType.Unknown, "", "", @"c:", "", "foo", ".txt"); AssertPathParts(@"c:.txt", PathType.Unknown, "", "", @"c:", "", "", ".txt"); AssertPathParts(@"c:....txt", PathType.Unknown, "", "", @"c:", "", "...", ".txt"); AssertPathParts(@"c:foo.txt", PathType.Directory, "", "", @"c:", @"foo.txt\", "", ""); AssertPathParts(@"c:blah\blah\", PathType.Unknown, "", "", @"c:", @"blah\blah\", "", ""); AssertPathParts(@"c:blah\blah", PathType.Directory, "", "", @"c:", @"blah\blah\", "", ""); AssertPathParts(@"c:blah\blah", PathType.Unknown, "", "", @"c:", @"blah\", "blah", ""); AssertPathParts(@"c:\test", PathType.Directory, "", "", @"c:", @"\test\", @"", ""); AssertPathParts(@"c:\test", PathType.File, "", "", @"c:", @"\", @"test", ""); AssertPathParts(@"c:\test.txt", PathType.File, "", "", @"c:", @"\", @"test", @".txt"); AssertPathParts(@"c:\whatever\test.txt", PathType.File, "", "", @"c:", @"\whatever\", @"test", @".txt"); AssertPathParts(@"c:\test\..\temp\??.txt", PathType.File, "", "", @"c:", @"\test\..\temp\", @"??", @".txt"); AssertPathParts(@"C:/test\the/use of\forward/slashes\a.txt", PathType.Unknown, "", "", @"C:", @"\test\the\use of\forward\slashes\", "a", @".txt"); AssertPathParts(@" C:\ remove \ trailing \ spaces \ file.txt ", PathType.Unknown, "", "", @"C:", @"\ remove\ trailing\ spaces\", " file", @".txt"); AssertPathParts(@"C:\remove.\trailing....\dots . .\and\spaces. . \file.txt. . .", PathType.Unknown, "", "", @"C:", @"\remove\trailing\dots\and\spaces\", "file", @".txt"); AssertPathParts(@" . . a . really . strange . name .. . . \a\b\c\...", PathType.Directory, "", "", "", @". . a . really . strange . name\a\b\c\...\", "", ""); AssertPathParts(@" "" C:\this path is quoted\file.txt "" ", PathType.Unknown, "", "", @"C:", @"\this path is quoted\", "file", @".txt"); AssertPathParts(@"c:\assembly\Company.Product.Subcomponent.dll", PathType.Unknown, "", "", @"c:", @"\assembly\", "Company.Product.Subcomponent", @".dll"); AssertPathParts(@"\\machine\share", PathType.Unknown, @"\\machine", @"\share", "", "", "", ""); AssertPathParts(@"\\machine\share\", PathType.Unknown, @"\\machine", @"\share", "", @"\", @"", @""); AssertPathParts(@"\\computer\share\test\subtest\abc.txt", PathType.Unknown, @"\\computer", @"\share", "", @"\test\subtest\", @"abc", @".txt"); // Test special last folder property Assert.AreEqual("c", new ParsedPath(@"c:\a\b\c\", PathType.Unknown).LastDirectoryNoSeparator); #if MACOS Assert.AreEqual(@"/", new ParsedPath(@"c:\", PathType.Unknown).LastDirectoryNoSeparator); #else Assert.AreEqual(@"\", new ParsedPath(@"c:\", PathType.Unknown).LastDirectoryNoSeparator); #endif // Test some bad paths AssertBadPath(@"", PathType.File); AssertBadPath(@":", PathType.File); AssertBadPath(@"::::a", PathType.File); AssertBadPath(@"\", PathType.File); AssertBadPath(@"\ \", PathType.Directory); AssertBadPath(@" "" "" ", PathType.Unknown); AssertBadPath(@"c:\*&#()_@\~{}|<>", PathType.Unknown); AssertBadPath(@"c:", PathType.Directory); AssertBadPath(@"c: \file.txt", PathType.File); AssertBadPath(@"c:\a\b\*\c\", PathType.Unknown); AssertBadPath(@"c:\dir\file.txt", PathType.Volume); AssertBadPath(@"\\", PathType.Volume); AssertBadPath(@"\\computer", PathType.Volume); AssertBadPath(@"\\computer\", PathType.Volume); AssertBadPath(@"\\computer\\", PathType.Volume); } [Test] public void MakeFullPath() { // Test some good paths #if MACOS AssertPathPartsFull(@".txt", @"/temp/", "", "", "", @"\temp\", "", ".txt"); AssertPathPartsFull(@"/test/../temp/??.txt", null, "", "", "", @"\temp\", @"??", @".txt"); AssertPathPartsFull(@"\test\..\temp\abc.txt", @"\a\b\", "", "", "", @"\temp\", @"abc", @".txt"); AssertPathPartsFull(@"test\..\temp\abc.txt", @"\a\b\", "", "", "", @"\a\b\temp\", @"abc", @".txt"); AssertPathPartsFull(@".\test\....\temp\abc.txt", @"\a\b\c\", "", "", "", @"\a\temp\", @"abc", @".txt"); AssertPathPartsFull(@"...\test\abc.txt", @"\a\b\c\", "", "", "", @"\a\test\", @"abc", @".txt"); AssertPathPartsFull(@"C:\temp\..yes...this...is.a..legal.file.name....\and...\so...\...is\.this.\blah.txt", null, "", "", @"C:", @"\temp\..yes...this...is.a..legal.file.name\and\so\...is\.this\", @"blah", @".txt"); #else AssertPathPartsFull(@".txt", @"c:\temp\", "", "", @"c:", @"\temp\", "", ".txt"); AssertPathPartsFull(@"c:\test\..\temp\??.txt", null, "", "", @"c:", @"\temp\", @"??", @".txt"); AssertPathPartsFull(@"\test\..\temp\abc.txt", @"c:\a\b\", "", "", "c:", @"\temp\", @"abc", @".txt"); AssertPathPartsFull(@"test\..\temp\abc.txt", @"c:\a\b\", "", "", @"c:", @"\a\b\temp\", @"abc", @".txt"); AssertPathPartsFull(@".\test\....\temp\abc.txt", @"c:\a\b\c\", "", "", "c:", @"\a\temp\", @"abc", @".txt"); AssertPathPartsFull(@"...\test\abc.txt", @"c:\a\b\c\", "", "", "c:", @"\a\test\", @"abc", @".txt"); AssertPathPartsFull(@"C:\temp\..yes...this...is.a..legal.file.name....\and...\so...\...is\.this.\blah.txt", null, "", "", @"C:", @"\temp\..yes...this...is.a..legal.file.name\and\so\...is\.this\", @"blah", @".txt"); #endif // Test that using the current directory works ParsedPath pp = new ParsedPath(Environment.CurrentDirectory, PathType.Directory); AssertPathPartsFull(@"test.txt", null, pp.Machine, pp.Share, pp.Drive, pp.Directory, "test", ".txt"); // Test some bad paths AssertBadPathFull(@"c:\test\..\..\temp\abc.txt", null); // Too many '..'s AssertBadPathFull(@"test\......\temp\.\abc.txt", @"c:\"); // Too many '....'s } [Test] public void MakeRelativePath() { AssertPathPartsRelative(@"c:\a\p.q", @"c:\a\", @"./"); AssertPathPartsRelative(@"c:\a\", @"c:\a\b\c\p.q", @"../../"); AssertPathPartsRelative(@"c:\a\b\c\p.q", @"c:\a\", @"./b/c/"); AssertPathPartsRelative(@"c:\a\b\c\p.q", @"c:\a\x\y\", @"../../b/c/"); AssertPathPartsRelative(@"/a/b/c.e", @"/a/b/x/y/z.1", @"../../"); AssertBadPathPartsRelative(@"..\a.txt", @"c:/a/b"); AssertBadPathPartsRelative(@"a.txt", @"b"); } [Test] public void MakeParentPath() { // Test going up one parent AssertParentPath(@"c:\a\b\c\p.q", -1, "", "", "c:", @"\a\b\", "p", ".q"); AssertParentPath(@"c:\a\b\c\", -1, "", "", "c:", @"\a\b\", "", ""); AssertParentPath(@"\\machine\share\a\b\c\d\foo.bar", -1, @"\\machine", @"\share", "", @"\a\b\c\", "foo", ".bar"); // Test going up multiple parents AssertParentPath(@"c:\a\b\c\d\e\", -3, "", "", "c:", @"\a\b\", "", ""); AssertParentPath(@"c:\a\b\c\d\e\", -5, "", "", "c:", @"\", "", ""); // Test bad stuff AssertBadParentPath(@"c:\", -1); // Already root AssertBadParentPath(@"c:\a\", 2); // Positive index not allowed AssertBadParentPath(@"c:\a\b\c\", -4); // Too many parent levels AssertBadParentPath(@"c:\a\b\..\c\", -1); // Path cannot be relative } #region Assert paths parts public static void AssertPathParts( string path, PathType type, string machine, string share, string drive, string directory, string file, string extension) { ParsedPath pp = new ParsedPath(path, type); #if MACOS // We have to compare to OS specific paths machine = machine.Replace(@"\", "/"); share = share.Replace(@"\", "/"); directory = directory.Replace(@"\", "/"); #endif Assert.AreEqual(machine, pp.Machine.ToString()); Assert.AreEqual(share, pp.Share.ToString()); Assert.AreEqual(drive, pp.Drive.ToString()); Assert.AreEqual(directory, pp.Directory.ToString()); Assert.AreEqual(file, pp.File.ToString()); Assert.AreEqual(extension, pp.Extension.ToString()); } public static void AssertBadPath( string path, PathType type) { try { ParsedPath pp = new ParsedPath(path, type); Assert.IsNotNull(pp); Assert.Fail("Badly formed path not caught"); } catch (Exception e) { Assert.IsTrue(e is ArgumentException); } } #endregion #region Assert path parts with MakeFullPath() public static void AssertPathPartsFull( string path, string baseDir, string machine, string share, string drive, string directory, string file, string extension) { ParsedPath pp; if (baseDir != null) pp = new ParsedPath(path, PathType.Unknown).MakeFullPath(new ParsedPath(baseDir, PathType.Directory)); else pp = new ParsedPath(path, PathType.Unknown).MakeFullPath(); #if MACOS // We have to compare to OS specific paths machine = machine.Replace(@"\", "/"); share = share.Replace(@"\", "/"); directory = directory.Replace(@"\", "/"); #endif Assert.AreEqual(machine, pp.Machine.ToString()); Assert.AreEqual(share, pp.Share.ToString()); Assert.AreEqual(drive, pp.Drive.ToString()); Assert.AreEqual(directory, pp.Directory.ToString()); Assert.AreEqual(file, pp.File.ToString()); Assert.AreEqual(extension, pp.Extension.ToString()); } public static void AssertBadPathFull( string path, string baseDir) { try { ParsedPath pp = new ParsedPath(path, PathType.Unknown).MakeFullPath( baseDir == null ? null : new ParsedPath(baseDir, PathType.Directory)); Assert.IsNotNull(pp); Assert.Fail("Badly formed path not caught"); } catch (Exception e) { Assert.IsTrue(e is ArgumentException); } } #endregion #region Assert path directory with MakeRelativePath() public static void AssertPathPartsRelative( string path, string basePath, string directory) { ParsedPath pp = new ParsedPath(path, PathType.Unknown).MakeRelativePath(new ParsedPath(basePath, PathType.Unknown)); Assert.AreEqual(directory, pp.Directory.ToString()); } private void AssertBadPathPartsRelative( string path, string basePath) { try { ParsedPath pp = new ParsedPath(path, PathType.Unknown).MakeRelativePath(new ParsedPath(basePath, PathType.Unknown)); Assert.IsNotNull(pp); Assert.Fail("MakeRelativePath succeeded and should have failed"); } catch (Exception e) { Assert.IsTrue(e is ArgumentException); } } #endregion #region Assert path directory with MakeParentPath() public static void AssertParentPath( string path, int level, string machine, string share, string drive, string directory, string file, string extension) { ParsedPath pp; // Test out specific entry points based on the values passed in if (level < -1) { pp = new ParsedPath(path, PathType.Unknown).MakeParentPath(level); if (pp == null) { Assert.IsNull(directory, "Expected result was not null"); return; } } else { pp = new ParsedPath(path, PathType.Unknown).MakeParentPath(); if (pp == null) { Assert.IsNull(directory, "Expected result was not null"); return; } } #if MACOS // We have to compare to OS specific paths machine = machine.Replace(@"\", "/"); share = share.Replace(@"\", "/"); directory = directory.Replace(@"\", "/"); #endif Assert.AreEqual(machine, pp.Machine.ToString()); Assert.AreEqual(share, pp.Share.ToString()); Assert.AreEqual(drive, pp.Drive.ToString()); Assert.AreEqual(directory, pp.Directory.ToString()); Assert.AreEqual(file, pp.File.ToString()); Assert.AreEqual(extension, pp.Extension.ToString()); } public static void AssertBadParentPath( string path, int level) { try { ParsedPath pp; if (level <= -1 || level > 0) pp = new ParsedPath(path, PathType.Unknown).MakeParentPath(level); else pp = new ParsedPath(path, PathType.Unknown).MakeParentPath(); Assert.IsNotNull(pp); Assert.Fail("Get parent succeeded and should have failed"); } catch (Exception e) { Assert.IsTrue(e is ArgumentException || e is InvalidOperationException); } } #endregion [Test] public void TestPathTypes() { Assert.IsTrue(new ParsedPath(@"c:\temp\", PathType.Unknown).IsDirectory); Assert.IsFalse(new ParsedPath(@"c:\temp", PathType.Unknown).IsDirectory); Assert.IsTrue(new ParsedPath(@"\\machine\share\foo", PathType.Unknown).HasUnc); Assert.IsFalse(new ParsedPath(@"c:\foo", PathType.Unknown).HasUnc); Assert.IsTrue(new ParsedPath(@"\\machine\share\foo\*.t?t", PathType.Unknown).HasWildcards); Assert.IsFalse(new ParsedPath(@"\\machine\share\foo\foo.txt", PathType.Unknown).HasWildcards); Assert.IsTrue(new ParsedPath(@"\\machine\share\foo\test.txt", PathType.Unknown).HasVolume); Assert.IsFalse(new ParsedPath(@"foo\test.txt", PathType.Unknown).HasVolume); Assert.IsTrue(new ParsedPath(@"C:\share\foo\", PathType.Unknown).HasDrive); Assert.IsFalse(new ParsedPath(@"\\machine\share\foo\", PathType.Unknown).HasDrive); Assert.IsTrue(new ParsedPath(@"C:\share\foo\..\..\thing.txt", PathType.Unknown).IsRelativePath); Assert.IsTrue(new ParsedPath(@"C:\share\foo\...\thing.txt", PathType.Unknown).IsRelativePath); Assert.IsTrue(new ParsedPath(@"...\thing.txt", PathType.Unknown).IsRelativePath); Assert.IsFalse(new ParsedPath(@"\\machine\share\foo\thing.txt", PathType.Unknown).IsRelativePath); Assert.IsFalse(new ParsedPath(@"C:\share\foo\thing.txt", PathType.Unknown).IsRelativePath); Assert.IsFalse(new ParsedPath(@"/home/thing.txt", PathType.Unknown).IsRelativePath); } [Test] public void TestSubDirectories() { Assert.AreEqual(4, new ParsedPath(@"c:\a\b\c\", PathType.Unknown).SubDirectories.Count); Assert.AreEqual(4, new ParsedPath(@"\\machine\share\a\b\c\", PathType.Unknown).SubDirectories.Count); IList<ParsedPath> subDirs; subDirs = new ParsedPath(@"c:\a\b\c\", PathType.Directory).SubDirectories; Assert.AreEqual(4, subDirs.Count); Assert.AreEqual(Path.DirectorySeparatorChar.ToString(), subDirs[0].ToString()); Assert.AreEqual("c" + PathUtility.DirectorySeparator, subDirs[3].ToString()); subDirs = new ParsedPath(@"c:\", PathType.Directory).SubDirectories; Assert.AreEqual(1, subDirs.Count); Assert.AreEqual(PathUtility.DirectorySeparator, subDirs[0].ToString()); } [Test] public void TestAppend() { ParsedPath pp1 = new ParsedPath(@"c:\blah\blah", PathType.Directory); ParsedPath ppCombine = pp1.Append("file.txt", PathType.File); #if MACOS Assert.AreEqual(@"c:/blah/blah/file.txt", ppCombine.ToString()); #else Assert.AreEqual(@"c:\blah\blah\file.txt", ppCombine.ToString()); #endif pp1 = new ParsedPath(@"c:\blah\blah", PathType.Directory); Assert.Throws(typeof(ArgumentException), delegate { ppCombine = pp1.Append(@"\blah\file.txt", PathType.File); }); pp1 = new ParsedPath(@"c:\blah\blah", PathType.Directory); ppCombine = pp1.Append(@"blah\file.txt", PathType.File); #if MACOS Assert.AreEqual(@"c:/blah/blah/blah/file.txt", ppCombine.ToString()); #else Assert.AreEqual(@"c:\blah\blah\blah\file.txt", ppCombine.ToString()); #endif } } }
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Infoplus.Model { /// <summary> /// /// </summary> [DataContract] public partial class ItemAccountCode : IEquatable<ItemAccountCode> { /// <summary> /// Initializes a new instance of the <see cref="ItemAccountCode" /> class. /// Initializes a new instance of the <see cref="ItemAccountCode" />class. /// </summary> /// <param name="LobId">LobId (required).</param> /// <param name="Id">Id (required).</param> /// <param name="Name">Name (required).</param> /// <param name="CustomFields">CustomFields.</param> public ItemAccountCode(int? LobId = null, string Id = null, string Name = null, Dictionary<string, Object> CustomFields = null) { // to ensure "LobId" is required (not null) if (LobId == null) { throw new InvalidDataException("LobId is a required property for ItemAccountCode and cannot be null"); } else { this.LobId = LobId; } // to ensure "Id" is required (not null) if (Id == null) { throw new InvalidDataException("Id is a required property for ItemAccountCode and cannot be null"); } else { this.Id = Id; } // to ensure "Name" is required (not null) if (Name == null) { throw new InvalidDataException("Name is a required property for ItemAccountCode and cannot be null"); } else { this.Name = Name; } this.CustomFields = CustomFields; } /// <summary> /// Gets or Sets LobId /// </summary> [DataMember(Name="lobId", EmitDefaultValue=false)] public int? LobId { get; set; } /// <summary> /// Gets or Sets InternalId /// </summary> [DataMember(Name="internalId", EmitDefaultValue=false)] public int? InternalId { get; private set; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=false)] public string Id { get; set; } /// <summary> /// Gets or Sets Name /// </summary> [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } /// <summary> /// Gets or Sets CustomFields /// </summary> [DataMember(Name="customFields", EmitDefaultValue=false)] public Dictionary<string, Object> CustomFields { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class ItemAccountCode {\n"); sb.Append(" LobId: ").Append(LobId).Append("\n"); sb.Append(" InternalId: ").Append(InternalId).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" CustomFields: ").Append(CustomFields).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as ItemAccountCode); } /// <summary> /// Returns true if ItemAccountCode instances are equal /// </summary> /// <param name="other">Instance of ItemAccountCode to be compared</param> /// <returns>Boolean</returns> public bool Equals(ItemAccountCode other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.LobId == other.LobId || this.LobId != null && this.LobId.Equals(other.LobId) ) && ( this.InternalId == other.InternalId || this.InternalId != null && this.InternalId.Equals(other.InternalId) ) && ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.Name == other.Name || this.Name != null && this.Name.Equals(other.Name) ) && ( this.CustomFields == other.CustomFields || this.CustomFields != null && this.CustomFields.SequenceEqual(other.CustomFields) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.LobId != null) hash = hash * 59 + this.LobId.GetHashCode(); if (this.InternalId != null) hash = hash * 59 + this.InternalId.GetHashCode(); if (this.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.Name != null) hash = hash * 59 + this.Name.GetHashCode(); if (this.CustomFields != null) hash = hash * 59 + this.CustomFields.GetHashCode(); return hash; } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Windows.Forms; using Tao.OpenGl; using Tao.Platform.Windows; using ICSharpCode.SharpZipLib.Zip; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenMetaverse.Imaging; using OpenMetaverse.Rendering; // NOTE: Batches are divided by texture, fullbright, shiny, transparent, and glow namespace PrimWorkshop { public struct FaceData { public float[] Vertices; public ushort[] Indices; public float[] TexCoords; public int TexturePointer; public System.Drawing.Image Texture; // TODO: Normals / binormals? } public static class Render { public static IRendering Plugin; } public partial class frmPrimWorkshop : Form { #region Form Globals List<FacetedMesh> Prims = null; FacetedMesh CurrentPrim = null; ProfileFace? CurrentFace = null; bool DraggingTexture = false; bool Wireframe = true; int[] TexturePointers = new int[1]; Dictionary<UUID, Image> Textures = new Dictionary<UUID, Image>(); #endregion Form Globals public frmPrimWorkshop() { InitializeComponent(); glControl.InitializeContexts(); Gl.glShadeModel(Gl.GL_SMOOTH); Gl.glClearColor(0f, 0f, 0f, 0f); Gl.glClearDepth(1.0f); Gl.glEnable(Gl.GL_DEPTH_TEST); Gl.glDepthMask(Gl.GL_TRUE); Gl.glDepthFunc(Gl.GL_LEQUAL); Gl.glHint(Gl.GL_PERSPECTIVE_CORRECTION_HINT, Gl.GL_NICEST); TexturePointers[0] = 0; // Call the resizing function which sets up the GL drawing window // and will also invalidate the GL control glControl_Resize(null, null); } private void frmPrimWorkshop_Shown(object sender, EventArgs e) { // Get a list of rendering plugins List<string> renderers = RenderingLoader.ListRenderers("."); foreach (string r in renderers) { DialogResult result = MessageBox.Show( String.Format("Use renderer {0}?", r), "Select Rendering Plugin", MessageBoxButtons.YesNo); if (result == DialogResult.Yes) { Render.Plugin = RenderingLoader.LoadRenderer(r); break; } } if (Render.Plugin == null) { MessageBox.Show("No valid rendering plugin loaded, exiting..."); Application.Exit(); } } #region GLControl Callbacks private void glControl_Paint(object sender, PaintEventArgs e) { Gl.glClear(Gl.GL_COLOR_BUFFER_BIT | Gl.GL_DEPTH_BUFFER_BIT); Gl.glLoadIdentity(); // Setup wireframe or solid fill drawing mode if (Wireframe) Gl.glPolygonMode(Gl.GL_FRONT_AND_BACK, Gl.GL_LINE); else Gl.glPolygonMode(Gl.GL_FRONT, Gl.GL_FILL); Vector3 center = Vector3.Zero; Glu.gluLookAt( center.X, (double)scrollZoom.Value * 0.1d + center.Y, center.Z, center.X, center.Y, center.Z, 0d, 0d, 1d); // Push the world matrix Gl.glPushMatrix(); Gl.glEnableClientState(Gl.GL_VERTEX_ARRAY); Gl.glEnableClientState(Gl.GL_TEXTURE_COORD_ARRAY); // World rotations Gl.glRotatef((float)scrollRoll.Value, 1f, 0f, 0f); Gl.glRotatef((float)scrollPitch.Value, 0f, 1f, 0f); Gl.glRotatef((float)scrollYaw.Value, 0f, 0f, 1f); if (Prims != null) { for (int i = 0; i < Prims.Count; i++) { Primitive prim = Prims[i].Prim; if (i == cboPrim.SelectedIndex) Gl.glColor3f(1f, 0f, 0f); else Gl.glColor3f(1f, 1f, 1f); // Individual prim matrix Gl.glPushMatrix(); // The root prim position is sim-relative, while child prim positions are // parent-relative. We want to apply parent-relative translations but not // sim-relative ones if (Prims[i].Prim.ParentID != 0) { // Apply prim translation and rotation Gl.glMultMatrixf(Math3D.CreateTranslationMatrix(prim.Position)); Gl.glMultMatrixf(Math3D.CreateRotationMatrix(prim.Rotation)); } // Prim scaling Gl.glScalef(prim.Scale.X, prim.Scale.Y, prim.Scale.Z); // Draw the prim faces for (int j = 0; j < Prims[i].Faces.Count; j++) { if (i == cboPrim.SelectedIndex) { // This prim is currently selected in the dropdown //Gl.glColor3f(0f, 1f, 0f); Gl.glColor3f(1f, 1f, 1f); if (j == cboFace.SelectedIndex) { // This face is currently selected in the dropdown } else { // This face is not currently selected in the dropdown } } else { // This prim is not currently selected in the dropdown Gl.glColor3f(1f, 1f, 1f); } #region Texturing Face face = Prims[i].Faces[j]; FaceData data = (FaceData)face.UserData; if (data.TexturePointer != 0) { // Set the color to solid white so the texture is not altered //Gl.glColor3f(1f, 1f, 1f); // Enable texturing for this face Gl.glEnable(Gl.GL_TEXTURE_2D); } else { Gl.glDisable(Gl.GL_TEXTURE_2D); } // Bind the texture Gl.glBindTexture(Gl.GL_TEXTURE_2D, data.TexturePointer); #endregion Texturing Gl.glTexCoordPointer(2, Gl.GL_FLOAT, 0, data.TexCoords); Gl.glVertexPointer(3, Gl.GL_FLOAT, 0, data.Vertices); Gl.glDrawElements(Gl.GL_TRIANGLES, data.Indices.Length, Gl.GL_UNSIGNED_SHORT, data.Indices); } // Pop the prim matrix Gl.glPopMatrix(); } } // Pop the world matrix Gl.glPopMatrix(); Gl.glDisableClientState(Gl.GL_TEXTURE_COORD_ARRAY); Gl.glDisableClientState(Gl.GL_VERTEX_ARRAY); Gl.glFlush(); } private void glControl_Resize(object sender, EventArgs e) { Gl.glClearColor(0.39f, 0.58f, 0.93f, 1.0f); Gl.glViewport(0, 0, glControl.Width, glControl.Height); Gl.glPushMatrix(); Gl.glMatrixMode(Gl.GL_PROJECTION); Gl.glLoadIdentity(); Glu.gluPerspective(50.0d, 1.0d, 0.1d, 50d); Gl.glMatrixMode(Gl.GL_MODELVIEW); Gl.glPopMatrix(); } #endregion GLControl Callbacks #region Menu Callbacks private void openPrimXMLToolStripMenuItem1_Click(object sender, EventArgs e) { Prims = null; OpenFileDialog dialog = new OpenFileDialog(); dialog.Filter = "Prim Package (*.zip)|*.zip"; if (dialog.ShowDialog() == DialogResult.OK) { string tempPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), System.IO.Path.GetRandomFileName()); try { // Create a temporary directory Directory.CreateDirectory(tempPath); FastZip fastzip = new FastZip(); fastzip.ExtractZip(dialog.FileName, tempPath, String.Empty); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } // Check for the prims.xml file string primsFile = System.IO.Path.Combine(tempPath, "prims.xml"); if (!File.Exists(primsFile)) { MessageBox.Show("prims.xml not found in the archive"); return; } LLSD llsd = null; try { llsd = LLSDParser.DeserializeXml(File.ReadAllText(primsFile)); } catch (Exception ex) { MessageBox.Show(ex.Message); } if (llsd != null && llsd.Type == LLSDType.Map) { List<Primitive> primList = Helpers.LLSDToPrimList(llsd); Prims = new List<FacetedMesh>(primList.Count); for (int i = 0; i < primList.Count; i++) { // TODO: Can't render sculpted prims without the textures if (primList[i].Sculpt.SculptTexture != UUID.Zero) continue; Primitive prim = primList[i]; FacetedMesh mesh = Render.Plugin.GenerateFacetedMesh(prim, DetailLevel.Highest); // Create a FaceData struct for each face that stores the 3D data // in a Tao.OpenGL friendly format for (int j = 0; j < mesh.Faces.Count; j++) { Face face = mesh.Faces[j]; FaceData data = new FaceData(); // Vertices for this face data.Vertices = new float[face.Vertices.Count * 3]; for (int k = 0; k < face.Vertices.Count; k++) { data.Vertices[k * 3 + 0] = face.Vertices[k].Position.X; data.Vertices[k * 3 + 1] = face.Vertices[k].Position.Y; data.Vertices[k * 3 + 2] = face.Vertices[k].Position.Z; } // Indices for this face data.Indices = face.Indices.ToArray(); // Texture transform for this face Primitive.TextureEntryFace teFace = prim.Textures.GetFace((uint)j); Render.Plugin.TransformTexCoords(face.Vertices, face.Center, teFace); // Texcoords for this face data.TexCoords = new float[face.Vertices.Count * 2]; for (int k = 0; k < face.Vertices.Count; k++) { data.TexCoords[k * 2 + 0] = face.Vertices[k].TexCoord.X; data.TexCoords[k * 2 + 1] = face.Vertices[k].TexCoord.Y; } // Texture for this face if (LoadTexture(tempPath, teFace.TextureID, ref data.Texture)) { Bitmap bitmap = new Bitmap(data.Texture); bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY); Rectangle rectangle = new Rectangle(0, 0, bitmap.Width, bitmap.Height); BitmapData bitmapData = bitmap.LockBits(rectangle, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); Gl.glGenTextures(1, out data.TexturePointer); Gl.glBindTexture(Gl.GL_TEXTURE_2D, data.TexturePointer); Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MIN_FILTER, Gl.GL_LINEAR_MIPMAP_LINEAR); Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MAG_FILTER, Gl.GL_LINEAR); Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_WRAP_S, Gl.GL_REPEAT); Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_WRAP_T, Gl.GL_REPEAT); Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_GENERATE_MIPMAP, Gl.GL_TRUE); Glu.gluBuild2DMipmaps(Gl.GL_TEXTURE_2D, Gl.GL_RGB8, bitmap.Width, bitmap.Height, Gl.GL_BGR, Gl.GL_UNSIGNED_BYTE, bitmapData.Scan0); bitmap.UnlockBits(bitmapData); bitmap.Dispose(); } // Set the UserData for this face to our FaceData struct face.UserData = data; mesh.Faces[j] = face; } Prims.Add(mesh); } // Setup the dropdown list of prims PopulatePrimCombobox(); glControl.Invalidate(); } else { MessageBox.Show("Failed to load LLSD formatted primitive data from " + dialog.FileName); } Directory.Delete(tempPath); } } private bool LoadTexture(string basePath, UUID textureID, ref System.Drawing.Image texture) { if (Textures.ContainsKey(textureID)) { texture = Textures[textureID]; return true; } string texturePath = System.IO.Path.Combine(basePath, textureID.ToString()); if (File.Exists(texturePath + ".tga")) { try { texture = (Image)LoadTGAClass.LoadTGA(texturePath + ".tga"); Textures[textureID] = texture; return true; } catch (Exception) { } } else if (File.Exists(texturePath + ".jp2")) { try { ManagedImage managedImage; if (OpenJPEG.DecodeToImage(File.ReadAllBytes(texturePath + ".jp2"), out managedImage, out texture)) { Textures[textureID] = texture; return true; } } catch (Exception) { } } return false; } private void textureToolStripMenuItem_Click(object sender, EventArgs e) { picTexture.Image = null; TexturePointers[0] = 0; OpenFileDialog dialog = new OpenFileDialog(); if (dialog.ShowDialog() == DialogResult.OK) { try { picTexture.Image = System.Drawing.Image.FromFile(dialog.FileName); Bitmap bitmap = new Bitmap(picTexture.Image); bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY); // Create the GL texture space Gl.glGenTextures(1, TexturePointers); Rectangle rectangle = new Rectangle(0, 0, bitmap.Width, bitmap.Height); BitmapData bitmapData = bitmap.LockBits(rectangle, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); Gl.glBindTexture(Gl.GL_TEXTURE_2D, TexturePointers[0]); Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MIN_FILTER, Gl.GL_LINEAR_MIPMAP_LINEAR); Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MAG_FILTER, Gl.GL_LINEAR); Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_WRAP_S, Gl.GL_CLAMP_TO_EDGE); Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_WRAP_T, Gl.GL_CLAMP_TO_EDGE); Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_GENERATE_MIPMAP, Gl.GL_TRUE); Glu.gluBuild2DMipmaps(Gl.GL_TEXTURE_2D, Gl.GL_RGB8, bitmap.Width, bitmap.Height, Gl.GL_BGR, Gl.GL_UNSIGNED_BYTE, bitmapData.Scan0); bitmap.UnlockBits(bitmapData); bitmap.Dispose(); } catch (Exception ex) { MessageBox.Show("Failed to load image from file " + dialog.FileName + ": " + ex.Message); } } } private void savePrimXMLToolStripMenuItem_Click(object sender, EventArgs e) { } private void saveTextureToolStripMenuItem_Click(object sender, EventArgs e) { } private void oBJToolStripMenuItem_Click(object sender, EventArgs e) { SaveFileDialog dialog = new SaveFileDialog(); dialog.Filter = "OBJ files (*.obj)|*.obj"; if (dialog.ShowDialog() == DialogResult.OK) { if (!MeshToOBJ.MeshesToOBJ(Prims, dialog.FileName)) { MessageBox.Show("Failed to save file " + dialog.FileName + ". Ensure that you have permission to write to that file and it is currently not in use"); } } } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { Close(); } private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { MessageBox.Show( "Written by John Hurliman <[email protected]> (http://www.jhurliman.org/)"); } #endregion Menu Callbacks #region Scrollbar Callbacks private void scroll_ValueChanged(object sender, EventArgs e) { glControl.Invalidate(); } private void scrollZoom_ValueChanged(object sender, EventArgs e) { glControl_Resize(null, null); glControl.Invalidate(); } #endregion Scrollbar Callbacks #region PictureBox Callbacks private void picTexture_MouseDown(object sender, MouseEventArgs e) { DraggingTexture = true; } private void picTexture_MouseUp(object sender, MouseEventArgs e) { DraggingTexture = false; } private void picTexture_MouseLeave(object sender, EventArgs e) { DraggingTexture = false; } private void picTexture_MouseMove(object sender, MouseEventArgs e) { if (DraggingTexture) { // What is the current action? // None, DraggingEdge, DraggingCorner, DraggingWhole } else { // Check if the mouse is close to the edge or corner of a selection // rectangle // If so, change the cursor accordingly } } private void picTexture_Paint(object sender, PaintEventArgs e) { // Draw the current selection rectangles } #endregion PictureBox Callbacks private void cboPrim_SelectedIndexChanged(object sender, EventArgs e) { CurrentPrim = (FacetedMesh)cboPrim.Items[cboPrim.SelectedIndex]; PopulateFaceCombobox(); glControl.Invalidate(); } private void cboFace_SelectedIndexChanged(object sender, EventArgs e) { CurrentFace = (ProfileFace)cboFace.Items[cboFace.SelectedIndex]; glControl.Invalidate(); } private void PopulatePrimCombobox() { cboPrim.Items.Clear(); if (Prims != null) { for (int i = 0; i < Prims.Count; i++) cboPrim.Items.Add(Prims[i]); } if (cboPrim.Items.Count > 0) cboPrim.SelectedIndex = 0; } private void PopulateFaceCombobox() { cboFace.Items.Clear(); if (CurrentPrim != null) { for (int i = 0; i < CurrentPrim.Profile.Faces.Count; i++) cboFace.Items.Add(CurrentPrim.Profile.Faces[i]); } if (cboFace.Items.Count > 0) cboFace.SelectedIndex = 0; } private void wireframeToolStripMenuItem_Click(object sender, EventArgs e) { wireframeToolStripMenuItem.Checked = !wireframeToolStripMenuItem.Checked; Wireframe = wireframeToolStripMenuItem.Checked; glControl.Invalidate(); } private void worldBrowserToolStripMenuItem_Click(object sender, EventArgs e) { frmBrowser browser = new frmBrowser(); browser.ShowDialog(); } } }
using osu_StreamCompanion.Code.Core; using osu_StreamCompanion.Code.Helpers; using osu_StreamCompanion.Code.Windows; using System; using System.Collections.Generic; using System.Reflection; using System.Runtime.InteropServices; using System.Security.AccessControl; using System.Security.Principal; using System.Threading; using System.Windows.Forms; using osu_StreamCompanion.Code.Core.Loggers; using System.IO; using System.Net.Sockets; using System.Threading.Tasks; using StreamCompanionTypes.Enums; using TaskExtensions = StreamCompanion.Common.TaskExtensions; #if DEBUG using System.Diagnostics; #endif namespace osu_StreamCompanion { static class Program { public static string ScVersion ="v210310.19"; private static Initializer _initializer; private static bool AllowMultiInstance = false; /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { #if False AllowMultiInstance = true; #endif string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString(); string mutexId = string.Format("Global\\{{{0}}}", appGuid); string settingsProfileName = GetSettingsProfileNameFromArgs(args)?.Trim(); if (!string.IsNullOrEmpty(settingsProfileName) && settingsProfileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) { // settingsProfileName contains chars not valid for a filename MessageBox.Show(settingsProfileName + " is an invalid settings profile name", "Error"); return; } if (!OperatingSystem.IsWindows() || AllowMultiInstance) Run(settingsProfileName); else using (var mutex = new Mutex(false, mutexId)) { var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); var securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); mutex.SetAccessControl(securitySettings); var hasHandle = false; try { try { hasHandle = mutex.WaitOne(2000, false); if (hasHandle == false) { MessageBox.Show("osu!StreamCompanion is already running.", "Error"); return; } } catch (AbandonedMutexException) { hasHandle = true; } Run(settingsProfileName); } finally { if (hasHandle) mutex.ReleaseMutex(); } } } private static string GetSettingsProfileNameFromArgs(string[] args) { const string argPrefix = "--settings-profile="; int argIndex = args.AnyStartsWith(argPrefix); return argIndex == -1 ? null : args[argIndex].Substring(argPrefix.Length); } private static void Run(string settingsProfileName) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); Application.ThreadException += Application_ThreadException; TaskScheduler.UnobservedTaskException += TaskSchedulerOnUnobservedTaskException; TaskExtensions.GlobalExceptionHandler = HandleException; _initializer = new Initializer(settingsProfileName); _initializer.Start(); Application.Run(_initializer); } private static void TaskSchedulerOnUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e) { HandleException(e.Exception); } private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e) { HandleException(e.Exception); } /// <summary> /// Is user currently performing an action that should not be interuppted no matter what (aka. Do not ever steal focus from osu! when user is playing) /// </summary> /// <returns></returns> public static bool UserCanBeNotified() { if (!StreamCompanionTypes.DataTypes.Tokens.AllTokens.TryGetValue("status", out var statusToken)) return false; return ((OsuStatus)statusToken.Value & OsuStatus.Playing) == 0; } static void HandleNonLoggableException(NonLoggableException ex) { if (UserCanBeNotified()) MessageBox.Show(ex.CustomMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); } public static void SafeQuit() { try { _initializer?.Exit(); } catch (Exception ex) { MainLogger.Instance.Log(ex, LogLevel.Error); if (UserCanBeNotified()) MessageBox.Show( $"There was a problem while shutting down Stream Companion. Some of the settings might have not been saved.{Environment.NewLine}{Environment.NewLine}{ex}", "Stream Companion Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } Quit(); } private static void Quit() { if (System.Windows.Forms.Application.MessageLoop) { System.Windows.Forms.Application.Exit(); } else { System.Environment.Exit(0); } } static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { if (e.ExceptionObject is NonLoggableException) { var ex = (NonLoggableException)e.ExceptionObject; HandleNonLoggableException(ex); } else { #if DEBUG WaitForDebugger((Exception)e.ExceptionObject); //throw (Exception)e.ExceptionObject; #endif Exception ex = null; try { ex = (Exception)e.ExceptionObject; } finally { } HandleException(ex); } } #if DEBUG private static void WaitForDebugger(Exception ex) { var result = MessageBox.Show($"Unhandled error: attach debugger?{Environment.NewLine}" + $"press Yes to attach local debugger{Environment.NewLine}" + $"press No to wait for debugger (Application will freeze){Environment.NewLine}" + $"press cancel to ignore and continue error handling as usual{Environment.NewLine}" + $"{ex}", "Error - attach debugger?", MessageBoxButtons.YesNoCancel); switch (result) { case DialogResult.Cancel: return; case DialogResult.Yes: Debugger.Launch(); break; case DialogResult.No: break; } while (!Debugger.IsAttached) { Thread.Sleep(100); } Debugger.Break(); } #endif private static (bool SendReport, string Message) GetErrorData() { // ReSharper disable ConditionIsAlwaysTrueOrFalse bool sendReport = false; #if WITHSENTRY sendReport = true; #endif if (sendReport) return (true, $"{errorNotificationFormat} {needToExit} {messageWasSent}"); return (false, $"{errorNotificationFormat} {needToExit} {privateBuildMessageNotSent}"); // ReSharper restore ConditionIsAlwaysTrueOrFalse } private static string errorNotificationFormat = @"There was unhandled problem with a program"; private static string needToExit = @"and it needs to exit."; private static string messageWasSent = "Error report was sent to Piotrekol."; private static string privateBuildMessageNotSent = "This is private build, so error report WAS NOT SENT."; public static void HandleException(Exception ex) { try { ex.Data.Add("netFramework", GetDotNetVersion.Get45PlusFromRegistry()); var errorConsensus = GetErrorData(); #if DEBUG WaitForDebugger(ex); #endif var errorResult = GetExceptionText(ex); foreach (var d in errorResult.Data) { ex.Data[d.Key] = d.Value; } //also reports to sentry if enabled MainLogger.Instance.Log(ex, LogLevel.Critical); if (UserCanBeNotified()) { MessageBox.Show(errorConsensus.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); var form = new Error(errorResult.Text, null); form.ShowDialog(); } } finally { try { SafeQuit(); } catch { _initializer.ExitThread(); } } } private static (string Text, IDictionary<string, object> Data) GetExceptionText(Exception ex) { var exceptionMessage = string.Empty; var dict = new Dictionary<string, object>(); exceptionMessage += $"{ex.GetType().Name}: {ex.Message}"; if (ex is SocketException socketEx) { ex.Data["SocketErrorCode"] = socketEx.SocketErrorCode.ToString(); ex.Data["ErrorCode"] = socketEx.ErrorCode.ToString(); exceptionMessage += $"{Environment.NewLine}SocketErrorCode: {socketEx.SocketErrorCode}, ErrorCode: {socketEx.ErrorCode}"; } exceptionMessage += $"{Environment.NewLine}{ex.StackTrace}{Environment.NewLine}{Environment.NewLine}"; if (ex is AggregateException aggEx) { foreach (var innerException in aggEx.InnerExceptions) { var exResult = GetExceptionText(innerException); exceptionMessage += exResult.Text; foreach (var d in exResult.Data) { dict[d.Key] = d.Value; } } } return (exceptionMessage, dict); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Net; using System.IO; using System.Timers; using System.Drawing; using System.Drawing.Imaging; using log4net; using Mono.Addins; using Nini.Config; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using OpenSim.Server.Base; using OpenMetaverse; using OpenMetaverse.StructuredData; namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.MapImage { /// <summary> /// </summary> /// <remarks> /// </remarks> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "MapImageServiceModule")] public class MapImageServiceModule : IMapImageUploadModule, ISharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static string LogHeader = "[MAP IMAGE SERVICE MODULE]"; private bool m_enabled = false; private IMapImageService m_MapService; private Dictionary<UUID, Scene> m_scenes = new Dictionary<UUID, Scene>(); private int m_refreshtime = 0; private int m_lastrefresh = 0; private System.Timers.Timer m_refreshTimer; #region ISharedRegionModule public Type ReplaceableInterface { get { return null; } } public string Name { get { return "MapImageServiceModule"; } } public void RegionLoaded(Scene scene) { } public void Close() { } public void PostInitialise() { } ///<summary> /// ///</summary> public void Initialise(IConfigSource source) { IConfig moduleConfig = source.Configs["Modules"]; if (moduleConfig != null) { string name = moduleConfig.GetString("MapImageService", ""); if (name != Name) return; } IConfig config = source.Configs["MapImageService"]; if (config == null) return; int refreshminutes = Convert.ToInt32(config.GetString("RefreshTime")); // if refresh is less than zero, disable the module if (refreshminutes < 0) { m_log.WarnFormat("[MAP IMAGE SERVICE MODULE]: Negative refresh time given in config. Module disabled."); return; } string service = config.GetString("LocalServiceModule", string.Empty); if (service == string.Empty) { m_log.WarnFormat("[MAP IMAGE SERVICE MODULE]: No service dll given in config. Unable to proceed."); return; } Object[] args = new Object[] { source }; m_MapService = ServerUtils.LoadPlugin<IMapImageService>(service, args); if (m_MapService == null) { m_log.WarnFormat("[MAP IMAGE SERVICE MODULE]: Unable to load LocalServiceModule from {0}. MapService module disabled. Please fix the configuration.", service); return; } // we don't want the timer if the interval is zero, but we still want this module enables if(refreshminutes > 0) { m_refreshtime = refreshminutes * 60 * 1000; // convert from minutes to ms m_refreshTimer = new System.Timers.Timer(); m_refreshTimer.Enabled = true; m_refreshTimer.AutoReset = true; m_refreshTimer.Interval = m_refreshtime; m_refreshTimer.Elapsed += new ElapsedEventHandler(HandleMaptileRefresh); m_log.InfoFormat("[MAP IMAGE SERVICE MODULE]: enabled with refresh time {0} min and service object {1}", refreshminutes, service); } else { m_log.InfoFormat("[MAP IMAGE SERVICE MODULE]: enabled with no refresh and service object {0}", service); } m_enabled = true; } ///<summary> /// ///</summary> public void AddRegion(Scene scene) { if (!m_enabled) return; // Every shared region module has to maintain an indepedent list of // currently running regions lock (m_scenes) m_scenes[scene.RegionInfo.RegionID] = scene; scene.EventManager.OnRegionReadyStatusChange += s => { if (s.Ready) UploadMapTile(s); }; scene.RegisterModuleInterface<IMapImageUploadModule>(this); } ///<summary> /// ///</summary> public void RemoveRegion(Scene scene) { if (! m_enabled) return; lock (m_scenes) m_scenes.Remove(scene.RegionInfo.RegionID); } #endregion ISharedRegionModule ///<summary> /// ///</summary> private void HandleMaptileRefresh(object sender, EventArgs ea) { // this approach is a bit convoluted becase we want to wait for the // first upload to happen on startup but after all the objects are // loaded and initialized if (m_lastrefresh > 0 && Util.EnvironmentTickCountSubtract(m_lastrefresh) < m_refreshtime) return; m_log.DebugFormat("[MAP IMAGE SERVICE MODULE]: map refresh!"); lock (m_scenes) { foreach (IScene scene in m_scenes.Values) { try { UploadMapTile(scene); } catch (Exception ex) { m_log.WarnFormat("[MAP IMAGE SERVICE MODULE]: something bad happened {0}", ex.Message); } } } m_lastrefresh = Util.EnvironmentTickCount(); } public void UploadMapTile(IScene scene, Bitmap mapTile) { m_log.DebugFormat("{0} Upload maptile for {1}", LogHeader, scene.Name); // mapTile.Save( // DEBUG DEBUG // String.Format("maptiles/raw-{0}-{1}-{2}.jpg", regionName, scene.RegionInfo.RegionLocX, scene.RegionInfo.RegionLocY), // ImageFormat.Jpeg); // If the region/maptile is legacy sized, just upload the one tile like it has always been done if (mapTile.Width == Constants.RegionSize && mapTile.Height == Constants.RegionSize) { ConvertAndUploadMaptile(mapTile, scene.RegionInfo.RegionLocX, scene.RegionInfo.RegionLocY, scene.RegionInfo.RegionName); } else { // For larger regions (varregion) we must cut the region image into legacy sized // pieces since that is how the maptile system works. // Note the assumption that varregions are always a multiple of legacy size. for (uint xx = 0; xx < mapTile.Width; xx += Constants.RegionSize) { for (uint yy = 0; yy < mapTile.Height; yy += Constants.RegionSize) { // Images are addressed from the upper left corner so have to do funny // math to pick out the sub-tile since regions are numbered from // the lower left. Rectangle rect = new Rectangle( (int)xx, mapTile.Height - (int)yy - (int)Constants.RegionSize, (int)Constants.RegionSize, (int)Constants.RegionSize); using (Bitmap subMapTile = mapTile.Clone(rect, mapTile.PixelFormat)) { ConvertAndUploadMaptile(subMapTile, scene.RegionInfo.RegionLocX + (xx / Constants.RegionSize), scene.RegionInfo.RegionLocY + (yy / Constants.RegionSize), scene.Name); } } } } } ///<summary> /// ///</summary> private void UploadMapTile(IScene scene) { // Create a JPG map tile and upload it to the AddMapTile API IMapImageGenerator tileGenerator = scene.RequestModuleInterface<IMapImageGenerator>(); if (tileGenerator == null) { m_log.WarnFormat("{0} Cannot upload map tile without an ImageGenerator", LogHeader); return; } using (Bitmap mapTile = tileGenerator.CreateMapTile()) { if (mapTile != null) { UploadMapTile(scene, mapTile); } else { m_log.WarnFormat("{0} Tile image generation failed", LogHeader); } } } private void ConvertAndUploadMaptile(Image tileImage, uint locX, uint locY, string regionName) { byte[] jpgData = Utils.EmptyBytes; using (MemoryStream stream = new MemoryStream()) { tileImage.Save(stream, ImageFormat.Jpeg); jpgData = stream.ToArray(); } if (jpgData != Utils.EmptyBytes) { string reason = string.Empty; if (!m_MapService.AddMapTile((int)locX, (int)locY, jpgData, out reason)) { m_log.DebugFormat("{0} Unable to upload tile image for {1} at {2}-{3}: {4}", LogHeader, regionName, locX, locY, reason); } } else { m_log.WarnFormat("{0} Tile image generation failed for region {1}", LogHeader, regionName); } } } }
using System; using Raksha.Crypto.Modes; using Raksha.Crypto.Paddings; using Raksha.Crypto.Parameters; namespace Raksha.Crypto.Macs { /** * implements a Cipher-FeedBack (CFB) mode on top of a simple cipher. */ class MacCFBBlockCipher : IBlockCipher { private byte[] IV; private byte[] cfbV; private byte[] cfbOutV; private readonly int blockSize; private readonly IBlockCipher cipher; /** * Basic constructor. * * @param cipher the block cipher to be used as the basis of the * feedback mode. * @param blockSize the block size in bits (note: a multiple of 8) */ public MacCFBBlockCipher( IBlockCipher cipher, int bitBlockSize) { this.cipher = cipher; this.blockSize = bitBlockSize / 8; this.IV = new byte[cipher.GetBlockSize()]; this.cfbV = new byte[cipher.GetBlockSize()]; this.cfbOutV = new byte[cipher.GetBlockSize()]; } /** * Initialise the cipher and, possibly, the initialisation vector (IV). * If an IV isn't passed as part of the parameter, the IV will be all zeros. * An IV which is too short is handled in FIPS compliant fashion. * * @param param the key and other data required by the cipher. * @exception ArgumentException if the parameters argument is * inappropriate. */ public void Init( bool forEncryption, ICipherParameters parameters) { if (parameters is ParametersWithIV) { ParametersWithIV ivParam = (ParametersWithIV)parameters; byte[] iv = ivParam.GetIV(); if (iv.Length < IV.Length) { Array.Copy(iv, 0, IV, IV.Length - iv.Length, iv.Length); } else { Array.Copy(iv, 0, IV, 0, IV.Length); } parameters = ivParam.Parameters; } Reset(); cipher.Init(true, parameters); } /** * return the algorithm name and mode. * * @return the name of the underlying algorithm followed by "/CFB" * and the block size in bits. */ public string AlgorithmName { get { return cipher.AlgorithmName + "/CFB" + (blockSize * 8); } } public bool IsPartialBlockOkay { get { return true; } } /** * return the block size we are operating at. * * @return the block size we are operating at (in bytes). */ public int GetBlockSize() { return blockSize; } /** * Process one block of input from the array in and write it to * the out array. * * @param in the array containing the input data. * @param inOff offset into the in array the data starts at. * @param out the array the output data will be copied into. * @param outOff the offset into the out array the output will start at. * @exception DataLengthException if there isn't enough data in in, or * space in out. * @exception InvalidOperationException if the cipher isn't initialised. * @return the number of bytes processed and produced. */ public int ProcessBlock( byte[] input, int inOff, byte[] outBytes, int outOff) { if ((inOff + blockSize) > input.Length) throw new DataLengthException("input buffer too short"); if ((outOff + blockSize) > outBytes.Length) throw new DataLengthException("output buffer too short"); cipher.ProcessBlock(cfbV, 0, cfbOutV, 0); // // XOR the cfbV with the plaintext producing the cipher text // for (int i = 0; i < blockSize; i++) { outBytes[outOff + i] = (byte)(cfbOutV[i] ^ input[inOff + i]); } // // change over the input block. // Array.Copy(cfbV, blockSize, cfbV, 0, cfbV.Length - blockSize); Array.Copy(outBytes, outOff, cfbV, cfbV.Length - blockSize, blockSize); return blockSize; } /** * reset the chaining vector back to the IV and reset the underlying * cipher. */ public void Reset() { IV.CopyTo(cfbV, 0); cipher.Reset(); } public void GetMacBlock( byte[] mac) { cipher.ProcessBlock(cfbV, 0, mac, 0); } } public class CfbBlockCipherMac : IMac { private byte[] mac; private byte[] Buffer; private int bufOff; private MacCFBBlockCipher cipher; private IBlockCipherPadding padding; private int macSize; /** * create a standard MAC based on a CFB block cipher. This will produce an * authentication code half the length of the block size of the cipher, with * the CFB mode set to 8 bits. * * @param cipher the cipher to be used as the basis of the MAC generation. */ public CfbBlockCipherMac( IBlockCipher cipher) : this(cipher, 8, (cipher.GetBlockSize() * 8) / 2, null) { } /** * create a standard MAC based on a CFB block cipher. This will produce an * authentication code half the length of the block size of the cipher, with * the CFB mode set to 8 bits. * * @param cipher the cipher to be used as the basis of the MAC generation. * @param padding the padding to be used. */ public CfbBlockCipherMac( IBlockCipher cipher, IBlockCipherPadding padding) : this(cipher, 8, (cipher.GetBlockSize() * 8) / 2, padding) { } /** * create a standard MAC based on a block cipher with the size of the * MAC been given in bits. This class uses CFB mode as the basis for the * MAC generation. * <p> * Note: the size of the MAC must be at least 24 bits (FIPS Publication 81), * or 16 bits if being used as a data authenticator (FIPS Publication 113), * and in general should be less than the size of the block cipher as it reduces * the chance of an exhaustive attack (see Handbook of Applied Cryptography). * </p> * @param cipher the cipher to be used as the basis of the MAC generation. * @param cfbBitSize the size of an output block produced by the CFB mode. * @param macSizeInBits the size of the MAC in bits, must be a multiple of 8. */ public CfbBlockCipherMac( IBlockCipher cipher, int cfbBitSize, int macSizeInBits) : this(cipher, cfbBitSize, macSizeInBits, null) { } /** * create a standard MAC based on a block cipher with the size of the * MAC been given in bits. This class uses CFB mode as the basis for the * MAC generation. * <p> * Note: the size of the MAC must be at least 24 bits (FIPS Publication 81), * or 16 bits if being used as a data authenticator (FIPS Publication 113), * and in general should be less than the size of the block cipher as it reduces * the chance of an exhaustive attack (see Handbook of Applied Cryptography). * </p> * @param cipher the cipher to be used as the basis of the MAC generation. * @param cfbBitSize the size of an output block produced by the CFB mode. * @param macSizeInBits the size of the MAC in bits, must be a multiple of 8. * @param padding a padding to be used. */ public CfbBlockCipherMac( IBlockCipher cipher, int cfbBitSize, int macSizeInBits, IBlockCipherPadding padding) { if ((macSizeInBits % 8) != 0) throw new ArgumentException("MAC size must be multiple of 8"); mac = new byte[cipher.GetBlockSize()]; this.cipher = new MacCFBBlockCipher(cipher, cfbBitSize); this.padding = padding; this.macSize = macSizeInBits / 8; Buffer = new byte[this.cipher.GetBlockSize()]; bufOff = 0; } public string AlgorithmName { get { return cipher.AlgorithmName; } } public void Init( ICipherParameters parameters) { Reset(); cipher.Init(true, parameters); } public int GetMacSize() { return macSize; } public void Update( byte input) { if (bufOff == Buffer.Length) { cipher.ProcessBlock(Buffer, 0, mac, 0); bufOff = 0; } Buffer[bufOff++] = input; } public void BlockUpdate( byte[] input, int inOff, int len) { if (len < 0) throw new ArgumentException("Can't have a negative input length!"); int blockSize = cipher.GetBlockSize(); int resultLen = 0; int gapLen = blockSize - bufOff; if (len > gapLen) { Array.Copy(input, inOff, Buffer, bufOff, gapLen); resultLen += cipher.ProcessBlock(Buffer, 0, mac, 0); bufOff = 0; len -= gapLen; inOff += gapLen; while (len > blockSize) { resultLen += cipher.ProcessBlock(input, inOff, mac, 0); len -= blockSize; inOff += blockSize; } } Array.Copy(input, inOff, Buffer, bufOff, len); bufOff += len; } public int DoFinal( byte[] output, int outOff) { int blockSize = cipher.GetBlockSize(); // pad with zeroes if (this.padding == null) { while (bufOff < blockSize) { Buffer[bufOff++] = 0; } } else { padding.AddPadding(Buffer, bufOff); } cipher.ProcessBlock(Buffer, 0, mac, 0); cipher.GetMacBlock(mac); Array.Copy(mac, 0, output, outOff, macSize); Reset(); return macSize; } /** * Reset the mac generator. */ public void Reset() { // Clear the buffer. Array.Clear(Buffer, 0, Buffer.Length); bufOff = 0; // Reset the underlying cipher. cipher.Reset(); } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the machinelearning-2014-12-12.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.MachineLearning.Model { /// <summary> /// Represents the output of a <a>GetEvaluation</a> operation and describes an <code>Evaluation</code>. /// </summary> public partial class GetEvaluationResponse : AmazonWebServiceResponse { private DateTime? _createdAt; private string _createdByIamUser; private string _evaluationDataSourceId; private string _evaluationId; private string _inputDataLocationS3; private DateTime? _lastUpdatedAt; private string _logUri; private string _message; private string _mlModelId; private string _name; private PerformanceMetrics _performanceMetrics; private EntityStatus _status; /// <summary> /// Gets and sets the property CreatedAt. /// <para> /// The time that the <code>Evaluation</code> was created. The time is expressed in epoch /// time. /// </para> /// </summary> public DateTime CreatedAt { get { return this._createdAt.GetValueOrDefault(); } set { this._createdAt = value; } } // Check to see if CreatedAt property is set internal bool IsSetCreatedAt() { return this._createdAt.HasValue; } /// <summary> /// Gets and sets the property CreatedByIamUser. /// <para> /// The AWS user account that invoked the evaluation. The account type can be either an /// AWS root account or an AWS Identity and Access Management (IAM) user account. /// </para> /// </summary> public string CreatedByIamUser { get { return this._createdByIamUser; } set { this._createdByIamUser = value; } } // Check to see if CreatedByIamUser property is set internal bool IsSetCreatedByIamUser() { return this._createdByIamUser != null; } /// <summary> /// Gets and sets the property EvaluationDataSourceId. /// <para> /// The <code>DataSource</code> used for this evaluation. /// </para> /// </summary> public string EvaluationDataSourceId { get { return this._evaluationDataSourceId; } set { this._evaluationDataSourceId = value; } } // Check to see if EvaluationDataSourceId property is set internal bool IsSetEvaluationDataSourceId() { return this._evaluationDataSourceId != null; } /// <summary> /// Gets and sets the property EvaluationId. /// <para> /// The evaluation ID which is same as the <code>EvaluationId</code> in the request. /// </para> /// </summary> public string EvaluationId { get { return this._evaluationId; } set { this._evaluationId = value; } } // Check to see if EvaluationId property is set internal bool IsSetEvaluationId() { return this._evaluationId != null; } /// <summary> /// Gets and sets the property InputDataLocationS3. /// <para> /// The location of the data file or directory in Amazon Simple Storage Service (Amazon /// S3). /// </para> /// </summary> public string InputDataLocationS3 { get { return this._inputDataLocationS3; } set { this._inputDataLocationS3 = value; } } // Check to see if InputDataLocationS3 property is set internal bool IsSetInputDataLocationS3() { return this._inputDataLocationS3 != null; } /// <summary> /// Gets and sets the property LastUpdatedAt. /// <para> /// The time of the most recent edit to the <code>BatchPrediction</code>. The time is /// expressed in epoch time. /// </para> /// </summary> public DateTime LastUpdatedAt { get { return this._lastUpdatedAt.GetValueOrDefault(); } set { this._lastUpdatedAt = value; } } // Check to see if LastUpdatedAt property is set internal bool IsSetLastUpdatedAt() { return this._lastUpdatedAt.HasValue; } /// <summary> /// Gets and sets the property LogUri. /// <para> /// A link to the file that contains logs of the <a>CreateEvaluation</a> operation. /// </para> /// </summary> public string LogUri { get { return this._logUri; } set { this._logUri = value; } } // Check to see if LogUri property is set internal bool IsSetLogUri() { return this._logUri != null; } /// <summary> /// Gets and sets the property Message. /// <para> /// A description of the most recent details about evaluating the <code>MLModel</code>. /// </para> /// </summary> public string Message { get { return this._message; } set { this._message = value; } } // Check to see if Message property is set internal bool IsSetMessage() { return this._message != null; } /// <summary> /// Gets and sets the property MLModelId. /// <para> /// The ID of the <code>MLModel</code> that was the focus of the evaluation. /// </para> /// </summary> public string MLModelId { get { return this._mlModelId; } set { this._mlModelId = value; } } // Check to see if MLModelId property is set internal bool IsSetMLModelId() { return this._mlModelId != null; } /// <summary> /// Gets and sets the property Name. /// <para> /// A user-supplied name or description of the <code>Evaluation</code>. /// </para> /// </summary> public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } /// <summary> /// Gets and sets the property PerformanceMetrics. /// <para> /// Measurements of how well the <code>MLModel</code> performed using observations referenced /// by the <code>DataSource</code>. One of the following metric is returned based on the /// type of the <code>MLModel</code>: /// </para> /// <ul> <li> /// <para> /// BinaryAUC: A binary <code>MLModel</code> uses the Area Under the Curve (AUC) technique /// to measure performance. /// </para> /// </li> <li> /// <para> /// RegressionRMSE: A regression <code>MLModel</code> uses the Root Mean Square Error /// (RMSE) technique to measure performance. RMSE measures the difference between predicted /// and actual values for a single variable. /// </para> /// </li> <li> /// <para> /// MulticlassAvgFScore: A multiclass <code>MLModel</code> uses the F1 score technique /// to measure performance. /// </para> /// </li> </ul> /// <para> /// For more information about performance metrics, please see the <a href="http://docs.aws.amazon.com/machine-learning/latest/dg">Amazon /// Machine Learning Developer Guide</a>. /// </para> /// </summary> public PerformanceMetrics PerformanceMetrics { get { return this._performanceMetrics; } set { this._performanceMetrics = value; } } // Check to see if PerformanceMetrics property is set internal bool IsSetPerformanceMetrics() { return this._performanceMetrics != null; } /// <summary> /// Gets and sets the property Status. /// <para> /// The status of the evaluation. This element can have one of the following values: /// </para> /// <ul> <li> <code>PENDING</code> - Amazon Machine Language (Amazon ML) submitted a /// request to evaluate an <code>MLModel</code>.</li> <li> <code>INPROGRESS</code> - The /// evaluation is underway.</li> <li> <code>FAILED</code> - The request to evaluate an /// <code>MLModel</code> did not run to completion. It is not usable.</li> <li> <code>COMPLETED</code> /// - The evaluation process completed successfully.</li> <li> <code>DELETED</code> - /// The <code>Evaluation</code> is marked as deleted. It is not usable.</li> </ul> /// </summary> public EntityStatus Status { get { return this._status; } set { this._status = value; } } // Check to see if Status property is set internal bool IsSetStatus() { return this._status != null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection.Tests; using System.Runtime.CompilerServices; using Xunit; [assembly: Attr(77, name = "AttrSimple"), Int32Attr(77, name = "Int32AttrSimple"), Int64Attr(77, name = "Int64AttrSimple"), StringAttr("hello", name = "StringAttrSimple"), EnumAttr(PublicEnum.Case1, name = "EnumAttrSimple"), TypeAttr(typeof(object), name = "TypeAttrSimple")] [assembly: CompilationRelaxations(8)] [assembly: Debuggable((DebuggableAttribute.DebuggingModes)263)] [assembly: CLSCompliant(false)] namespace System.Reflection.Tests { public class AssemblyTests { [Theory] [InlineData(typeof(Int32Attr))] [InlineData(typeof(Int64Attr))] [InlineData(typeof(StringAttr))] [InlineData(typeof(EnumAttr))] [InlineData(typeof(TypeAttr))] [InlineData(typeof(CompilationRelaxationsAttribute))] [InlineData(typeof(AssemblyTitleAttribute))] [InlineData(typeof(AssemblyDescriptionAttribute))] [InlineData(typeof(AssemblyCompanyAttribute))] [InlineData(typeof(CLSCompliantAttribute))] [InlineData(typeof(DebuggableAttribute))] [InlineData(typeof(Attr))] public void CustomAttributes(Type type) { Assembly assembly = Helpers.ExecutingAssembly; IEnumerable<Type> attributesData = assembly.CustomAttributes.Select(customAttribute => customAttribute.AttributeType); Assert.Contains(type, attributesData); ICustomAttributeProvider attributeProvider = assembly; Assert.Single(attributeProvider.GetCustomAttributes(type, false)); Assert.True(attributeProvider.IsDefined(type, false)); IEnumerable<Type> customAttributes = attributeProvider.GetCustomAttributes(false).Select(attribute => attribute.GetType()); Assert.Contains(type, customAttributes); } [Theory] [InlineData(typeof(int), false)] [InlineData(typeof(Attr), true)] [InlineData(typeof(Int32Attr), true)] [InlineData(typeof(Int64Attr), true)] [InlineData(typeof(StringAttr), true)] [InlineData(typeof(EnumAttr), true)] [InlineData(typeof(TypeAttr), true)] [InlineData(typeof(ObjectAttr), true)] [InlineData(typeof(NullAttr), true)] public void DefinedTypes(Type type, bool expected) { IEnumerable<Type> customAttrs = Helpers.ExecutingAssembly.DefinedTypes.Select(typeInfo => typeInfo.AsType()); Assert.Equal(expected, customAttrs.Contains(type)); } [Theory] [InlineData("EmbeddedImage.png", true)] [InlineData("NoSuchFile", false)] public void EmbeddedFiles(string resource, bool exists) { string[] resources = Helpers.ExecutingAssembly.GetManifestResourceNames(); Stream resourceStream = Helpers.ExecutingAssembly.GetManifestResourceStream(resource); Assert.Equal(exists, resources.Contains(resource)); Assert.Equal(exists, resourceStream != null); } public static IEnumerable<object[]> Equals_TestData() { yield return new object[] { Assembly.Load(new AssemblyName(typeof(int).GetTypeInfo().Assembly.FullName)), Assembly.Load(new AssemblyName(typeof(int).GetTypeInfo().Assembly.FullName)), true }; yield return new object[] { Assembly.Load(new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName)), Assembly.Load(new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName)), true }; yield return new object[] { Assembly.Load(new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName)), Helpers.ExecutingAssembly, false }; } [Theory] [MemberData(nameof(Equals_TestData))] public void Equals(Assembly assembly1, Assembly assembly2, bool expected) { Assert.Equal(expected, assembly1.Equals(assembly2)); } [Theory] [InlineData(typeof(AssemblyPublicClass), true)] [InlineData(typeof(AssemblyTests), true)] [InlineData(typeof(AssemblyPublicClass.PublicNestedClass), true)] [InlineData(typeof(PublicEnum), true)] [InlineData(typeof(AssemblyGenericPublicClass<>), true)] [InlineData(typeof(AssemblyInternalClass), false)] public void ExportedTypes(Type type, bool expected) { Assembly assembly = Helpers.ExecutingAssembly; Assert.Equal(assembly.GetExportedTypes(), assembly.ExportedTypes); Assert.Equal(expected, assembly.ExportedTypes.Contains(type)); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "On desktop, XUnit hosts in an appdomain in such a way that GetEntryAssembly() returns null")] public void GetEntryAssembly() { Assert.NotNull(Assembly.GetEntryAssembly()); string assembly = Assembly.GetEntryAssembly().ToString(); bool correct = assembly.IndexOf("xunit.console", StringComparison.OrdinalIgnoreCase) != -1 || assembly.IndexOf("Microsoft.DotNet.XUnitRunnerUap", StringComparison.OrdinalIgnoreCase) != -1; Assert.True(correct, $"Unexpected assembly name {assembly}"); } public static IEnumerable<object[]> GetHashCode_TestData() { yield return new object[] { LoadSystemRuntimeAssembly() }; yield return new object[] { LoadSystemCollectionsAssembly() }; yield return new object[] { LoadSystemReflectionAssembly() }; yield return new object[] { typeof(AssemblyTests).GetTypeInfo().Assembly }; } [Theory] [MemberData(nameof(GetHashCode_TestData))] public void GetHashCode(Assembly assembly) { int hashCode = assembly.GetHashCode(); Assert.NotEqual(-1, hashCode); Assert.NotEqual(0, hashCode); } [Theory] [InlineData("System.Reflection.Tests.AssemblyPublicClass", true)] [InlineData("System.Reflection.Tests.AssemblyInternalClass", true)] [InlineData("System.Reflection.Tests.PublicEnum", true)] [InlineData("System.Reflection.Tests.PublicStruct", true)] [InlineData("AssemblyPublicClass", false)] [InlineData("NoSuchType", false)] public void GetType(string name, bool exists) { Type type = Helpers.ExecutingAssembly.GetType(name); if (exists) { Assert.Equal(name, type.FullName); } else { Assert.Null(type); } } public static IEnumerable<object[]> IsDynamic_TestData() { yield return new object[] { Helpers.ExecutingAssembly, false }; yield return new object[] { LoadSystemCollectionsAssembly(), false }; } [Theory] [MemberData(nameof(IsDynamic_TestData))] public void IsDynamic(Assembly assembly, bool expected) { Assert.Equal(expected, assembly.IsDynamic); } public static IEnumerable<object[]> Load_TestData() { yield return new object[] { new AssemblyName(typeof(int).GetTypeInfo().Assembly.FullName) }; yield return new object[] { new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName) }; yield return new object[] { new AssemblyName(typeof(AssemblyName).GetTypeInfo().Assembly.FullName) }; } [Theory] [MemberData(nameof(Load_TestData))] public void Load(AssemblyName assemblyRef) { Assert.NotNull(Assembly.Load(assemblyRef)); } [Fact] public void Load_Invalid() { Assert.Throws<ArgumentNullException>(() => Assembly.Load((AssemblyName)null)); // AssemblyRef is null Assert.Throws<FileNotFoundException>(() => Assembly.Load(new AssemblyName("no such assembly"))); // No such assembly } [Fact] public void Location_ExecutingAssembly_IsNotNull() { // This test applies on all platforms including .NET Native. Location must at least be non-null (it can be empty). // System.Reflection.CoreCLR.Tests adds tests that expect more than that. Assert.NotNull(Helpers.ExecutingAssembly.Location); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "CodeBase is not supported on UapAot")] public void CodeBase() { Assert.NotEmpty(Helpers.ExecutingAssembly.CodeBase); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "ImageRuntimeVersion is not supported on UapAot.")] public void ImageRuntimeVersion() { Assert.NotEmpty(Helpers.ExecutingAssembly.ImageRuntimeVersion); } public static IEnumerable<object[]> CreateInstance_TestData() { yield return new object[] { Helpers.ExecutingAssembly, typeof(AssemblyPublicClass).FullName, typeof(AssemblyPublicClass) }; yield return new object[] { typeof(int).GetTypeInfo().Assembly, typeof(int).FullName, typeof(int) }; yield return new object[] { typeof(int).GetTypeInfo().Assembly, typeof(Dictionary<int, string>).FullName, typeof(Dictionary<int, string>) }; } [Theory] [MemberData(nameof(CreateInstance_TestData))] public void CreateInstance(Assembly assembly, string typeName, Type expectedType) { Assert.IsType(expectedType, assembly.CreateInstance(typeName)); Assert.IsType(expectedType, assembly.CreateInstance(typeName, false)); Assert.IsType(expectedType, assembly.CreateInstance(typeName, true)); Assert.IsType(expectedType, assembly.CreateInstance(typeName.ToUpper(), true)); Assert.IsType(expectedType, assembly.CreateInstance(typeName.ToLower(), true)); } public static IEnumerable<object[]> CreateInstance_Invalid_TestData() { yield return new object[] { "", typeof(ArgumentException) }; yield return new object[] { null, typeof(ArgumentNullException) }; yield return new object[] { typeof(AssemblyClassWithPrivateCtor).FullName, typeof(MissingMethodException) }; yield return new object[] { typeof(AssemblyClassWithNoDefaultCtor).FullName, typeof(MissingMethodException) }; } [Theory] [MemberData(nameof(CreateInstance_Invalid_TestData))] public void CreateInstance_Invalid(string typeName, Type exceptionType) { Assembly assembly = Helpers.ExecutingAssembly; Assert.Throws(exceptionType, () => Helpers.ExecutingAssembly.CreateInstance(typeName)); Assert.Throws(exceptionType, () => Helpers.ExecutingAssembly.CreateInstance(typeName, true)); Assert.Throws(exceptionType, () => Helpers.ExecutingAssembly.CreateInstance(typeName, false)); } [Fact] public void CreateQualifiedName() { string assemblyName = Helpers.ExecutingAssembly.ToString(); Assert.Equal(typeof(AssemblyTests).FullName + ", " + assemblyName, Assembly.CreateQualifiedName(assemblyName, typeof(AssemblyTests).FullName)); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "GetReferencedAssemblies is not supported on UapAot.")] public void GetReferencedAssemblies() { // It is too brittle to depend on the assembly references so we just call the method and check that it does not throw. AssemblyName[] assemblies = Helpers.ExecutingAssembly.GetReferencedAssemblies(); Assert.NotEmpty(assemblies); } public static IEnumerable<object[]> Modules_TestData() { yield return new object[] { LoadSystemCollectionsAssembly() }; yield return new object[] { LoadSystemReflectionAssembly() }; } [Theory] [MemberData(nameof(Modules_TestData))] public void Modules(Assembly assembly) { Assert.NotEmpty(assembly.Modules); foreach (Module module in assembly.Modules) { Assert.NotNull(module); } } public IEnumerable<object[]> ToString_TestData() { yield return new object[] { Helpers.ExecutingAssembly, "System.Reflection.Tests" }; yield return new object[] { Assembly.Load(new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName)), "PublicKeyToken=" }; } [Theory] public void ToString(Assembly assembly, string expected) { Assert.Contains(expected, assembly.ToString()); Assert.Equal(assembly.ToString(), assembly.FullName); } private static Assembly LoadSystemCollectionsAssembly() { // Force System.collections to be linked statically List<int> li = new List<int>(); li.Add(1); return Assembly.Load(new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName)); } private static Assembly LoadSystemReflectionAssembly() { // Force System.Reflection to be linked statically return Assembly.Load(new AssemblyName(typeof(AssemblyName).GetTypeInfo().Assembly.FullName)); } private static Assembly LoadSystemRuntimeAssembly() { // Load System.Runtime return Assembly.Load(new AssemblyName(typeof(int).GetTypeInfo().Assembly.FullName)); ; } } public struct PublicStruct { } public class AssemblyPublicClass { public class PublicNestedClass { } } public class AssemblyGenericPublicClass<T> { } internal class AssemblyInternalClass { } public class AssemblyClassWithPrivateCtor { private AssemblyClassWithPrivateCtor() { } } public class AssemblyClassWithNoDefaultCtor { public AssemblyClassWithNoDefaultCtor(int x) { } } }
using System; using System.Collections.Generic; using System.Dynamic; using Microsoft.Data.SqlClient; using System.Linq; using System.Linq.Expressions; using System.Reflection; namespace Artisan.Orm { public static partial class SqlDataReaderExtensions { #region [ CreateObject ] public static T CreateObject<T>(this SqlDataReader dr) { var key = GetAutoCreateObjectFuncKey<T>(dr); var autoMappingFunc = MappingManager.GetAutoCreateObjectFunc<T>(key); return CreateObject(dr, autoMappingFunc, key); } internal static T CreateObject<T>(this SqlDataReader dr, Func<SqlDataReader, T> autoMappingFunc, string key) { if (autoMappingFunc == null) { autoMappingFunc = CreateAutoMappingFunc<T>(dr); MappingManager.AddAutoCreateObjectFunc(key, autoMappingFunc); } return autoMappingFunc(dr); } public static dynamic CreateDynamic(this SqlDataReader dr) { dynamic expando = new ExpandoObject(); var dict = expando as IDictionary<string, object>; for (var i = 0; i < dr.FieldCount; i++) { var columnName = dr.GetName(i); var value = dr.GetValue(i); dict.Add(columnName, value == DBNull.Value ? null : value); } return expando; } #endregion #region [ private members ] private static readonly PropertyInfo CommandProperty = typeof(SqlDataReader).GetProperties(BindingFlags.NonPublic | BindingFlags.Instance).First(p => p.Name == "Command"); internal static string GetCommandText(this SqlDataReader dr) { var command = (SqlCommand)CommandProperty.GetValue(dr); return command.CommandText; } internal static string GetAutoCreateObjectFuncKey<T>(SqlDataReader dr) { return GetAutoCreateObjectFuncKey<T>(dr.GetCommandText()); } internal static string GetAutoCreateObjectFuncKey<T>(string commandText) { return $"{commandText}+{typeof(T).FullName}"; } private static readonly Dictionary<Type, string> ReaderGetMethodNames = new Dictionary<Type, string> { { typeof(Boolean) , "GetBoolean" }, { typeof(Byte) , "GetByte" }, { typeof(Int16) , "GetInt16" }, { typeof(Int32) , "GetInt32" }, { typeof(Int64) , "GetInt64" }, { typeof(Single) , "GetFloat" }, { typeof(Double) , "GetDouble" }, { typeof(Decimal) , "GetDecimal" }, { typeof(String) , "GetString" }, { typeof(DateTime) , "GetDateTime" }, { typeof(DateTimeOffset) , "GetDateTimeOffset" }, { typeof(TimeSpan) , "GetTimeSpan" }, { typeof(Guid) , "GetGuid" } }; private static MethodCallExpression GetTypedValueMethodCallExpression(Type propertyType, Type fieldType, ParameterExpression sqlDataReaderParam, ConstantExpression indexConst, out bool isDefaultGetValueMethod) { var underlyingType = propertyType.GetUnderlyingType(); isDefaultGetValueMethod = false; if (propertyType == fieldType) { string methodName; if(ReaderGetMethodNames.TryGetValue(underlyingType, out methodName)) return Expression.Call( sqlDataReaderParam, typeof(SqlDataReader).GetMethod(methodName, new[] { typeof(int) }), indexConst ); if (underlyingType == typeof(Char)) return Expression.Call( null, typeof(SqlDataReaderExtensions).GetMethod("GetCharacter", new[] { typeof(SqlDataReader), typeof(int) }), sqlDataReaderParam, indexConst ); } isDefaultGetValueMethod = true; return Expression.Call( null, typeof(Convert).GetMethod("ChangeType", new[] { typeof(object), typeof(Type) }), Expression.Call( sqlDataReaderParam, typeof(SqlDataReader).GetMethod("GetValue", new[] { typeof(int) }), indexConst ), Expression.Constant(underlyingType, typeof(Type)) ); } internal static Func<SqlDataReader, T> CreateAutoMappingFunc<T>(SqlDataReader dr) { var properties = typeof(T) .GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(p => p.CanWrite && p.PropertyType.IsSimpleType()).ToList(); var memberBindings = new List<MemberBinding>(); var readerParam = Expression.Parameter(typeof(SqlDataReader), "reader"); for (var i = 0; i < dr.FieldCount; i++) { var columnName = dr.GetName(i); var prop = properties.FirstOrDefault(p => p.Name == columnName); if (prop != null) { var indexConst = Expression.Constant(i, typeof(int)); var fieldType = dr.GetFieldType(i); bool isDefaultGetValueMethod; MethodCallExpression getTypedValueExp = GetTypedValueMethodCallExpression(prop.PropertyType, fieldType, readerParam, indexConst, out isDefaultGetValueMethod); Expression getValueExp = null; if (prop.PropertyType.IsNullableValueType()) { getValueExp = Expression.Condition ( Expression.Call( readerParam, typeof(SqlDataReader).GetMethod("IsDBNull", new[] { typeof(int) }), indexConst ), Expression.Default(prop.PropertyType), Expression.Convert(getTypedValueExp, prop.PropertyType) ); } else if (isDefaultGetValueMethod) { getValueExp = Expression.Convert(getTypedValueExp, prop.PropertyType); } else { getValueExp = getTypedValueExp; } var binding = Expression.Bind(prop, getValueExp); memberBindings.Add(binding); } } if (memberBindings.Count == 0) throw new ApplicationException($"Creation of AutoMapping Func failed. No property-field name matching found for class = '{typeof(T).FullName}' and CommandText = '{dr.GetCommandText()}'"); var ctor = Expression.New(typeof(T)); var memberInit = Expression.MemberInit(ctor, memberBindings); var func = Expression.Lambda<Func<SqlDataReader, T>>(memberInit, readerParam).Compile(); return func; } #endregion } } /* Old implementations with reflection: internal static T CreateObject<T>(SqlDataReader dr) { var obj = Activator.CreateInstance<T>(); for (var i = 0; i < dr.FieldCount; i++) { var columnName = dr.GetName(i); var prop = obj.GetType().GetProperty(columnName, BindingFlags.Public | BindingFlags.Instance); if (prop != null && prop.CanWrite) { var t = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType; var value = dr.IsDBNull(i) ? null : Convert.ChangeType(dr.GetValue(i), t); prop.SetValue(obj, value, null); } } return obj; } public static IList<T> ReadAsList<T>(this SqlDataReader dr, IList<T> list, bool getNextResult = true) { if (list == null) list = new List<T>(); if (typeof(T).IsSimpleType()) return dr.ReadToListOfValues<T>(list, getNextResult); var dict = new Dictionary<string, Tuple<PropertyInfo, Type>>(); var properties = typeof(T) .GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(p => p.CanWrite && p.PropertyType.IsSimpleType()).ToList(); foreach (var property in properties) { var type = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType; dict.Add(property.Name, new Tuple<PropertyInfo, Type>(property, type)); } while (dr.Read()) { var item = Activator.CreateInstance<T>(); for (var i = 0; i < dr.FieldCount; i++) { var columnName = dr.GetName(i); Tuple<PropertyInfo, Type> propTuple; if (dict.TryGetValue(columnName, out propTuple)) { var value = dr.IsDBNull(i) ? null : Convert.ChangeType(dr.GetValue(i), propTuple.Item2); propTuple.Item1.SetValue(item, value, null); } } list.Add(item); } if (getNextResult) dr.NextResult(); return list; } */
////////////////////////////////////////////////////////////////////////// // Code Named: VG-Ripper // Function : Extracts Images posted on RiP forums and attempts to fetch // them to disk. // // This software is licensed under the MIT license. See license.txt for // details. // // Copyright (c) The Watcher // Partial Rights Reserved. // ////////////////////////////////////////////////////////////////////////// // This file is part of the RiP Ripper project base. namespace Ripper.Services.ImageHosts { using System; using System.Collections; using System.IO; using System.Net; using System.Threading; using Ripper.Core.Components; using Ripper.Core.Objects; /// <summary> /// Worker class to get images from ImageGiga.com /// </summary> public class ImageGiga : ServiceTemplate { /// <summary> /// Initializes a new instance of the <see cref="ImageGiga"/> class. /// </summary> /// <param name="sSavePath"> /// The s save path. /// </param> /// <param name="strURL"> /// The str url. /// </param> /// <param name="hTbl"> /// The h tbl. /// </param> public ImageGiga(ref string sSavePath, ref string strURL, ref string thumbURL, ref string imageName, ref int imageNumber, ref Hashtable hashtable) : base(sSavePath, strURL, thumbURL, imageName, imageNumber, ref hashtable) { } /// <summary> /// Do the Download /// </summary> /// <returns> /// Return if Downloaded or not /// </returns> protected override bool DoDownload() { string strImgURL = ImageLinkURL; if (EventTable.ContainsKey(strImgURL)) { return true; } string strFilePath = string.Empty; try { if (!Directory.Exists(SavePath)) { Directory.CreateDirectory(SavePath); } } catch (IOException ex) { //MainForm.DeleteMessage = ex.Message; //MainForm.Delete = true; return false; } CacheObject ccObj = new CacheObject { IsDownloaded = false, FilePath = strFilePath, Url = strImgURL }; try { EventTable.Add(strImgURL, ccObj); } catch (ThreadAbortException) { return true; } catch (Exception) { if (EventTable.ContainsKey(strImgURL)) { return false; } EventTable.Add(strImgURL, ccObj); } const string StartSrc = "<script type=\"text/javascript\" src=\"imgiga/showimg"; string sPage = GetImageHostPage(ref strImgURL); if (sPage.Length < 10) { return false; } int iStartSrc = sPage.IndexOf(StartSrc); if (iStartSrc < 0) { return false; } iStartSrc += StartSrc.Length; int iEndSrc = sPage.IndexOf("\"", iStartSrc); if (iEndSrc < 0) { return false; } string sScriptUrl = strImgURL; sScriptUrl = sScriptUrl.Remove(sScriptUrl.IndexOf(@"img.php")); sScriptUrl += string.Format("imgiga/showimg{0}", sPage.Substring(iStartSrc, iEndSrc - iStartSrc)); string sPage2 = GetImageHostPage(ref sScriptUrl); const string StartSrc2 = "href=\""; int iStartSrc2 = sPage2.IndexOf(StartSrc2); if (iStartSrc2 < 0) { return false; } iStartSrc2 += StartSrc2.Length; int iEndSrc2 = sPage2.IndexOf("\"", iStartSrc2); string strNewURL = sPage2.Substring(iStartSrc2, iEndSrc2 - iStartSrc2); strFilePath = strNewURL; if (strFilePath.Contains(".jpg")) { strFilePath = strFilePath.Remove(strFilePath.IndexOf(".jpg") + 4); } else if (strFilePath.Contains(".jpeg")) { strFilePath = strFilePath.Remove(strFilePath.IndexOf(".jpeg") + 5); } strFilePath = strFilePath.Substring(strFilePath.LastIndexOf("/") + 1); strFilePath = Path.Combine(SavePath, Utility.RemoveIllegalCharecters(strFilePath)); ////////////////////////////////////////////////////////////////////////// string newAlteredPath = Utility.GetSuitableName(strFilePath); if (strFilePath != newAlteredPath) { strFilePath = newAlteredPath; ((CacheObject)EventTable[ImageLinkURL]).FilePath = strFilePath; } strFilePath = Utility.CheckPathLength(strFilePath); ((CacheObject)EventTable[ImageLinkURL]).FilePath = strFilePath; try { WebClient client = new WebClient(); client.Headers.Add("Referer: " + strImgURL); client.Headers.Add("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6"); client.DownloadFile(strNewURL, strFilePath); client.Dispose(); } catch (ThreadAbortException) { ((CacheObject)EventTable[strImgURL]).IsDownloaded = false; ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL); return true; } catch (IOException ex) { //MainForm.DeleteMessage = ex.Message; //MainForm.Delete = true; ((CacheObject)EventTable[strImgURL]).IsDownloaded = false; ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL); return true; } catch (WebException) { ((CacheObject)EventTable[strImgURL]).IsDownloaded = false; ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL); return false; } ((CacheObject)EventTable[ImageLinkURL]).IsDownloaded = true; CacheController.Instance().LastPic = ((CacheObject)EventTable[ImageLinkURL]).FilePath = strFilePath; return true; } ////////////////////////////////////////////////////////////////////////// } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Collections.ObjectModel { public abstract partial class KeyedCollection<TKey, TItem> : System.Collections.ObjectModel.Collection<TItem> { protected KeyedCollection() { } protected KeyedCollection(System.Collections.Generic.IEqualityComparer<TKey> comparer) { } protected KeyedCollection(System.Collections.Generic.IEqualityComparer<TKey> comparer, int dictionaryCreationThreshold) { } public System.Collections.Generic.IEqualityComparer<TKey> Comparer { get { return default(System.Collections.Generic.IEqualityComparer<TKey>); } } protected System.Collections.Generic.IDictionary<TKey, TItem> Dictionary { get { return default(System.Collections.Generic.IDictionary<TKey, TItem>); } } public TItem this[TKey key] { get { return default(TItem); } } protected void ChangeItemKey(TItem item, TKey newKey) { } protected override void ClearItems() { } public bool Contains(TKey key) { return default(bool); } protected abstract TKey GetKeyForItem(TItem item); protected override void InsertItem(int index, TItem item) { } public bool Remove(TKey key) { return default(bool); } protected override void RemoveItem(int index) { } protected override void SetItem(int index, TItem item) { } } public partial class ObservableCollection<T> : System.Collections.ObjectModel.Collection<T>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged { public ObservableCollection() { } public ObservableCollection(System.Collections.Generic.IEnumerable<T> collection) { } public virtual event System.Collections.Specialized.NotifyCollectionChangedEventHandler CollectionChanged { add { } remove { } } protected virtual event System.ComponentModel.PropertyChangedEventHandler PropertyChanged { add { } remove { } } event System.ComponentModel.PropertyChangedEventHandler System.ComponentModel.INotifyPropertyChanged.PropertyChanged { add { } remove { } } protected System.IDisposable BlockReentrancy() { return default(System.IDisposable); } protected void CheckReentrancy() { } protected override void ClearItems() { } protected override void InsertItem(int index, T item) { } public void Move(int oldIndex, int newIndex) { } protected virtual void MoveItem(int oldIndex, int newIndex) { } protected virtual void OnCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { } protected virtual void OnPropertyChanged(System.ComponentModel.PropertyChangedEventArgs e) { } protected override void RemoveItem(int index) { } protected override void SetItem(int index, T item) { } } public partial class ReadOnlyDictionary<TKey, TValue> : System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IDictionary<TKey, TValue>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyCollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>, System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable { public ReadOnlyDictionary(System.Collections.Generic.IDictionary<TKey, TValue> dictionary) { } public int Count { get { return default(int); } } protected System.Collections.Generic.IDictionary<TKey, TValue> Dictionary { get { return default(System.Collections.Generic.IDictionary<TKey, TValue>); } } public TValue this[TKey key] { get { return default(TValue); } } public System.Collections.ObjectModel.ReadOnlyDictionary<TKey, TValue>.KeyCollection Keys { get { return default(System.Collections.ObjectModel.ReadOnlyDictionary<TKey, TValue>.KeyCollection); } } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.IsReadOnly { get { return default(bool); } } TValue System.Collections.Generic.IDictionary<TKey, TValue>.this[TKey key] { get { return default(TValue); } set { } } System.Collections.Generic.ICollection<TKey> System.Collections.Generic.IDictionary<TKey, TValue>.Keys { get { return default(System.Collections.Generic.ICollection<TKey>); } } System.Collections.Generic.ICollection<TValue> System.Collections.Generic.IDictionary<TKey, TValue>.Values { get { return default(System.Collections.Generic.ICollection<TValue>); } } System.Collections.Generic.IEnumerable<TKey> System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>.Keys { get { return default(System.Collections.Generic.IEnumerable<TKey>); } } System.Collections.Generic.IEnumerable<TValue> System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>.Values { get { return default(System.Collections.Generic.IEnumerable<TValue>); } } bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } } object System.Collections.ICollection.SyncRoot { get { return default(object); } } bool System.Collections.IDictionary.IsFixedSize { get { return default(bool); } } bool System.Collections.IDictionary.IsReadOnly { get { return default(bool); } } object System.Collections.IDictionary.this[object key] { get { return default(object); } set { } } System.Collections.ICollection System.Collections.IDictionary.Keys { get { return default(System.Collections.ICollection); } } System.Collections.ICollection System.Collections.IDictionary.Values { get { return default(System.Collections.ICollection); } } public System.Collections.ObjectModel.ReadOnlyDictionary<TKey, TValue>.ValueCollection Values { get { return default(System.Collections.ObjectModel.ReadOnlyDictionary<TKey, TValue>.ValueCollection); } } public bool ContainsKey(TKey key) { return default(bool); } public System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>> GetEnumerator() { return default(System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>>); } void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Add(System.Collections.Generic.KeyValuePair<TKey, TValue> item) { } void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Clear() { } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Contains(System.Collections.Generic.KeyValuePair<TKey, TValue> item) { return default(bool); } void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.CopyTo(System.Collections.Generic.KeyValuePair<TKey, TValue>[] array, int arrayIndex) { } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Remove(System.Collections.Generic.KeyValuePair<TKey, TValue> item) { return default(bool); } void System.Collections.Generic.IDictionary<TKey, TValue>.Add(TKey key, TValue value) { } bool System.Collections.Generic.IDictionary<TKey, TValue>.Remove(TKey key) { return default(bool); } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } void System.Collections.IDictionary.Add(object key, object value) { } void System.Collections.IDictionary.Clear() { } bool System.Collections.IDictionary.Contains(object key) { return default(bool); } System.Collections.IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator() { return default(System.Collections.IDictionaryEnumerator); } void System.Collections.IDictionary.Remove(object key) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } public bool TryGetValue(TKey key, out TValue value) { value = default(TValue); return default(bool); } public sealed partial class KeyCollection : System.Collections.Generic.ICollection<TKey>, System.Collections.Generic.IEnumerable<TKey>, System.Collections.Generic.IReadOnlyCollection<TKey>, System.Collections.ICollection, System.Collections.IEnumerable { internal KeyCollection() { } public int Count { get { return default(int); } } bool System.Collections.Generic.ICollection<TKey>.IsReadOnly { get { return default(bool); } } bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } } object System.Collections.ICollection.SyncRoot { get { return default(object); } } public void CopyTo(TKey[] array, int arrayIndex) { } public System.Collections.Generic.IEnumerator<TKey> GetEnumerator() { return default(System.Collections.Generic.IEnumerator<TKey>); } void System.Collections.Generic.ICollection<TKey>.Add(TKey item) { } void System.Collections.Generic.ICollection<TKey>.Clear() { } bool System.Collections.Generic.ICollection<TKey>.Contains(TKey item) { return default(bool); } bool System.Collections.Generic.ICollection<TKey>.Remove(TKey item) { return default(bool); } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } } public sealed partial class ValueCollection : System.Collections.Generic.ICollection<TValue>, System.Collections.Generic.IEnumerable<TValue>, System.Collections.Generic.IReadOnlyCollection<TValue>, System.Collections.ICollection, System.Collections.IEnumerable { internal ValueCollection() { } public int Count { get { return default(int); } } bool System.Collections.Generic.ICollection<TValue>.IsReadOnly { get { return default(bool); } } bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } } object System.Collections.ICollection.SyncRoot { get { return default(object); } } public void CopyTo(TValue[] array, int arrayIndex) { } public System.Collections.Generic.IEnumerator<TValue> GetEnumerator() { return default(System.Collections.Generic.IEnumerator<TValue>); } void System.Collections.Generic.ICollection<TValue>.Add(TValue item) { } void System.Collections.Generic.ICollection<TValue>.Clear() { } bool System.Collections.Generic.ICollection<TValue>.Contains(TValue item) { return default(bool); } bool System.Collections.Generic.ICollection<TValue>.Remove(TValue item) { return default(bool); } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } } } public partial class ReadOnlyObservableCollection<T> : System.Collections.ObjectModel.ReadOnlyCollection<T>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged { public ReadOnlyObservableCollection(System.Collections.ObjectModel.ObservableCollection<T> list) : base(default(System.Collections.Generic.IList<T>)) { } protected virtual event System.Collections.Specialized.NotifyCollectionChangedEventHandler CollectionChanged { add { } remove { } } protected virtual event System.ComponentModel.PropertyChangedEventHandler PropertyChanged { add { } remove { } } event System.Collections.Specialized.NotifyCollectionChangedEventHandler System.Collections.Specialized.INotifyCollectionChanged.CollectionChanged { add { } remove { } } event System.ComponentModel.PropertyChangedEventHandler System.ComponentModel.INotifyPropertyChanged.PropertyChanged { add { } remove { } } protected virtual void OnCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs args) { } protected virtual void OnPropertyChanged(System.ComponentModel.PropertyChangedEventArgs args) { } } } namespace System.Collections.Specialized { public partial interface INotifyCollectionChanged { event System.Collections.Specialized.NotifyCollectionChangedEventHandler CollectionChanged; } public enum NotifyCollectionChangedAction { Add = 0, Move = 3, Remove = 1, Replace = 2, Reset = 4, } public partial class NotifyCollectionChangedEventArgs : System.EventArgs { public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, System.Collections.IList changedItems) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, System.Collections.IList newItems, System.Collections.IList oldItems) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, System.Collections.IList newItems, System.Collections.IList oldItems, int startingIndex) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, System.Collections.IList changedItems, int startingIndex) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, System.Collections.IList changedItems, int index, int oldIndex) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, object changedItem) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, object changedItem, int index) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, object changedItem, int index, int oldIndex) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, object newItem, object oldItem) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, object newItem, object oldItem, int index) { } public System.Collections.Specialized.NotifyCollectionChangedAction Action { get { return default(System.Collections.Specialized.NotifyCollectionChangedAction); } } public System.Collections.IList NewItems { get { return default(System.Collections.IList); } } public int NewStartingIndex { get { return default(int); } } public System.Collections.IList OldItems { get { return default(System.Collections.IList); } } public int OldStartingIndex { get { return default(int); } } } public delegate void NotifyCollectionChangedEventHandler(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e); } namespace System.ComponentModel { public partial class DataErrorsChangedEventArgs : System.EventArgs { public DataErrorsChangedEventArgs(string propertyName) { } public virtual string PropertyName { get { return default(string); } } } public partial interface INotifyDataErrorInfo { bool HasErrors { get; } event System.EventHandler<System.ComponentModel.DataErrorsChangedEventArgs> ErrorsChanged; System.Collections.IEnumerable GetErrors(string propertyName); } public partial interface INotifyPropertyChanged { event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; } public partial interface INotifyPropertyChanging { event System.ComponentModel.PropertyChangingEventHandler PropertyChanging; } public partial class PropertyChangedEventArgs : System.EventArgs { public PropertyChangedEventArgs(string propertyName) { } public virtual string PropertyName { get { return default(string); } } } public delegate void PropertyChangedEventHandler(object sender, System.ComponentModel.PropertyChangedEventArgs e); public partial class PropertyChangingEventArgs : System.EventArgs { public PropertyChangingEventArgs(string propertyName) { } public virtual string PropertyName { get { return default(string); } } } public delegate void PropertyChangingEventHandler(object sender, System.ComponentModel.PropertyChangingEventArgs e); } namespace System.Windows.Input { public partial interface ICommand { event System.EventHandler CanExecuteChanged; bool CanExecute(object parameter); void Execute(object parameter); } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Utilities { public class BloomFilterTests { private IEnumerable<string> GenerateStrings(int count) { for (var i = 1; i <= count; i++) { yield return GenerateString(i); } } private string GenerateString(int value) { const string Alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; var builder = new StringBuilder(); while (value > 0) { var v = value % Alphabet.Length; var c = Alphabet[v]; builder.Append(c); value /= Alphabet.Length; } return builder.ToString(); } private void Test(bool isCaseSensitive) { var comparer = isCaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase; var strings = GenerateStrings(2000).Skip(500).Take(1000).ToSet(comparer); var testStrings = GenerateStrings(100000); for (var d = 0.1; d >= 0.0001; d /= 10) { var filter = new BloomFilter(strings.Count, d, isCaseSensitive); filter.AddRange(strings); var correctCount = 0.0; var incorrectCount = 0.0; foreach (var test in testStrings) { var actualContains = strings.Contains(test); var filterContains = filter.ProbablyContains(test); if (!filterContains) { // if the filter says no, then it can't be in the real set. Assert.False(actualContains); } if (actualContains == filterContains) { correctCount++; } else { incorrectCount++; } } var falsePositivePercentage = incorrectCount / (correctCount + incorrectCount); Assert.True(falsePositivePercentage < (d * 1.5), string.Format("falsePositivePercentage={0}, d={1}", falsePositivePercentage, d)); } } [Fact] public void Test1() { Test(isCaseSensitive: true); } [Fact] public void TestInsensitive() { Test(isCaseSensitive: false); } [Fact] public void TestEmpty() { for (var d = 0.1; d >= 0.0001; d /= 10) { var filter = new BloomFilter(0, d, isCaseSensitive: true); Assert.False(filter.ProbablyContains(string.Empty)); Assert.False(filter.ProbablyContains("a")); Assert.False(filter.ProbablyContains("b")); Assert.False(filter.ProbablyContains("c")); var testStrings = GenerateStrings(100000); foreach (var test in testStrings) { Assert.False(filter.ProbablyContains(test)); } } } [Fact] public void TestSerialization() { var stream = new MemoryStream(); var bloomFilter = new BloomFilter(0.001, false, new[] { "Hello, World" }); using (var writer = new ObjectWriter(stream)) { bloomFilter.WriteTo(writer); } stream.Position = 0; using (var reader = ObjectReader.TryGetReader(stream)) { var rehydratedFilter = BloomFilter.ReadFrom(reader); Assert.True(bloomFilter.IsEquivalent(rehydratedFilter)); } } [Fact] public void TestSerialization2() { var stream = new MemoryStream(); var bloomFilter = new BloomFilter(0.001, new[] { "Hello, World" }, new long[] { long.MaxValue, -1, 0, 1, long.MinValue }); using (var writer = new ObjectWriter(stream)) { bloomFilter.WriteTo(writer); } stream.Position = 0; using (var reader = ObjectReader.TryGetReader(stream)) { var rehydratedFilter = BloomFilter.ReadFrom(reader); Assert.True(bloomFilter.IsEquivalent(rehydratedFilter)); } } [Fact] public void TestInt64() { var longs = CreateLongs(GenerateStrings(2000).Skip(500).Take(1000).Select(s => s.GetHashCode()).ToList()); var testLongs = CreateLongs(GenerateStrings(100000).Select(s => s.GetHashCode()).ToList()); for (var d = 0.1; d >= 0.0001; d /= 10) { var filter = new BloomFilter(d, new string[] { }, longs); var correctCount = 0.0; var incorrectCount = 0.0; foreach (var test in testLongs) { var actualContains = longs.Contains(test); var filterContains = filter.ProbablyContains(test); if (!filterContains) { // if the filter says no, then it can't be in the real set. Assert.False(actualContains); } if (actualContains == filterContains) { correctCount++; } else { incorrectCount++; } } var falsePositivePercentage = incorrectCount / (correctCount + incorrectCount); Assert.True(falsePositivePercentage < (d * 1.5), string.Format("falsePositivePercentage={0}, d={1}", falsePositivePercentage, d)); } } private HashSet<long> CreateLongs(List<int> ints) { var result = new HashSet<long>(); for (var i = 0; i < ints.Count; i += 2) { var long1 = ((long)ints[i]) << 32; var long2 = (long)ints[i + 1]; result.Add(long1 | long2); } return result; } } }
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using sc = System.Collections; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Showcase.V1Beta1 { /// <summary>Settings for <see cref="TestingClient"/> instances.</summary> public sealed partial class TestingSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="TestingSettings"/>.</summary> /// <returns>A new instance of the default <see cref="TestingSettings"/>.</returns> public static TestingSettings GetDefault() => new TestingSettings(); /// <summary>Constructs a new <see cref="TestingSettings"/> object with default settings.</summary> public TestingSettings() { } private TestingSettings(TestingSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); CreateSessionSettings = existing.CreateSessionSettings; GetSessionSettings = existing.GetSessionSettings; ListSessionsSettings = existing.ListSessionsSettings; DeleteSessionSettings = existing.DeleteSessionSettings; ReportSessionSettings = existing.ReportSessionSettings; ListTestsSettings = existing.ListTestsSettings; DeleteTestSettings = existing.DeleteTestSettings; VerifyTestSettings = existing.VerifyTestSettings; OnCopy(existing); } partial void OnCopy(TestingSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to <c>TestingClient.CreateSession</c> /// and <c>TestingClient.CreateSessionAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>No timeout is applied.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings CreateSessionSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to <c>TestingClient.GetSession</c> /// and <c>TestingClient.GetSessionAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>No timeout is applied.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetSessionSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to <c>TestingClient.ListSessions</c> /// and <c>TestingClient.ListSessionsAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>No timeout is applied.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings ListSessionsSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to <c>TestingClient.DeleteSession</c> /// and <c>TestingClient.DeleteSessionAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>No timeout is applied.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings DeleteSessionSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to <c>TestingClient.ReportSession</c> /// and <c>TestingClient.ReportSessionAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>No timeout is applied.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings ReportSessionSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to <c>TestingClient.ListTests</c> /// and <c>TestingClient.ListTestsAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>No timeout is applied.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings ListTestsSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to <c>TestingClient.DeleteTest</c> /// and <c>TestingClient.DeleteTestAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>No timeout is applied.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings DeleteTestSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to <c>TestingClient.VerifyTest</c> /// and <c>TestingClient.VerifyTestAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>No timeout is applied.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings VerifyTestSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="TestingSettings"/> object.</returns> public TestingSettings Clone() => new TestingSettings(this); } /// <summary> /// Builder class for <see cref="TestingClient"/> to provide simple configuration of credentials, endpoint etc. /// </summary> public sealed partial class TestingClientBuilder : gaxgrpc::ClientBuilderBase<TestingClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public TestingSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public TestingClientBuilder() { UseJwtAccessWithScopes = TestingClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref TestingClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<TestingClient> task); /// <summary>Builds the resulting client.</summary> public override TestingClient Build() { TestingClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<TestingClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<TestingClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private TestingClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return TestingClient.Create(callInvoker, Settings); } private async stt::Task<TestingClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return TestingClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => TestingClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => TestingClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => TestingClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>Testing client wrapper, for convenient use.</summary> /// <remarks> /// A service to facilitate running discrete sets of tests /// against Showcase. /// </remarks> public abstract partial class TestingClient { /// <summary> /// The default endpoint for the Testing service, which is a host of "localhost:7469" and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "localhost:7469:443"; /// <summary>The default Testing scopes.</summary> /// <remarks>The default Testing scopes are:<list type="bullet"></list></remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="TestingClient"/> using the default credentials, endpoint and settings. /// To specify custom credentials or other settings, use <see cref="TestingClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="TestingClient"/>.</returns> public static stt::Task<TestingClient> CreateAsync(st::CancellationToken cancellationToken = default) => new TestingClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="TestingClient"/> using the default credentials, endpoint and settings. To /// specify custom credentials or other settings, use <see cref="TestingClientBuilder"/>. /// </summary> /// <returns>The created <see cref="TestingClient"/>.</returns> public static TestingClient Create() => new TestingClientBuilder().Build(); /// <summary> /// Creates a <see cref="TestingClient"/> which uses the specified call invoker for remote operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="TestingSettings"/>.</param> /// <returns>The created <see cref="TestingClient"/>.</returns> internal static TestingClient Create(grpccore::CallInvoker callInvoker, TestingSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } Testing.TestingClient grpcClient = new Testing.TestingClient(callInvoker); return new TestingClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC Testing client</summary> public virtual Testing.TestingClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Creates a new testing session. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual Session CreateSession(CreateSessionRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates a new testing session. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<Session> CreateSessionAsync(CreateSessionRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates a new testing session. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<Session> CreateSessionAsync(CreateSessionRequest request, st::CancellationToken cancellationToken) => CreateSessionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Gets a testing session. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual Session GetSession(GetSessionRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Gets a testing session. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<Session> GetSessionAsync(GetSessionRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Gets a testing session. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<Session> GetSessionAsync(GetSessionRequest request, st::CancellationToken cancellationToken) => GetSessionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Lists the current test sessions. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="Session"/> resources.</returns> public virtual gax::PagedEnumerable<ListSessionsResponse, Session> ListSessions(ListSessionsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Lists the current test sessions. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="Session"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<ListSessionsResponse, Session> ListSessionsAsync(ListSessionsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Delete a test session. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual void DeleteSession(DeleteSessionRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Delete a test session. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task DeleteSessionAsync(DeleteSessionRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Delete a test session. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task DeleteSessionAsync(DeleteSessionRequest request, st::CancellationToken cancellationToken) => DeleteSessionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Report on the status of a session. /// This generates a report detailing which tests have been completed, /// and an overall rollup. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual ReportSessionResponse ReportSession(ReportSessionRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Report on the status of a session. /// This generates a report detailing which tests have been completed, /// and an overall rollup. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<ReportSessionResponse> ReportSessionAsync(ReportSessionRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Report on the status of a session. /// This generates a report detailing which tests have been completed, /// and an overall rollup. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<ReportSessionResponse> ReportSessionAsync(ReportSessionRequest request, st::CancellationToken cancellationToken) => ReportSessionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// List the tests of a sessesion. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="Test"/> resources.</returns> public virtual gax::PagedEnumerable<ListTestsResponse, Test> ListTests(ListTestsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// List the tests of a sessesion. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="Test"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<ListTestsResponse, Test> ListTestsAsync(ListTestsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Explicitly decline to implement a test. /// /// This removes the test from subsequent `ListTests` calls, and /// attempting to do the test will error. /// /// This method will error if attempting to delete a required test. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual void DeleteTest(DeleteTestRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Explicitly decline to implement a test. /// /// This removes the test from subsequent `ListTests` calls, and /// attempting to do the test will error. /// /// This method will error if attempting to delete a required test. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task DeleteTestAsync(DeleteTestRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Explicitly decline to implement a test. /// /// This removes the test from subsequent `ListTests` calls, and /// attempting to do the test will error. /// /// This method will error if attempting to delete a required test. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task DeleteTestAsync(DeleteTestRequest request, st::CancellationToken cancellationToken) => DeleteTestAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Register a response to a test. /// /// In cases where a test involves registering a final answer at the /// end of the test, this method provides the means to do so. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual VerifyTestResponse VerifyTest(VerifyTestRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Register a response to a test. /// /// In cases where a test involves registering a final answer at the /// end of the test, this method provides the means to do so. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<VerifyTestResponse> VerifyTestAsync(VerifyTestRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Register a response to a test. /// /// In cases where a test involves registering a final answer at the /// end of the test, this method provides the means to do so. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<VerifyTestResponse> VerifyTestAsync(VerifyTestRequest request, st::CancellationToken cancellationToken) => VerifyTestAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>Testing client wrapper implementation, for convenient use.</summary> /// <remarks> /// A service to facilitate running discrete sets of tests /// against Showcase. /// </remarks> public sealed partial class TestingClientImpl : TestingClient { private readonly gaxgrpc::ApiCall<CreateSessionRequest, Session> _callCreateSession; private readonly gaxgrpc::ApiCall<GetSessionRequest, Session> _callGetSession; private readonly gaxgrpc::ApiCall<ListSessionsRequest, ListSessionsResponse> _callListSessions; private readonly gaxgrpc::ApiCall<DeleteSessionRequest, wkt::Empty> _callDeleteSession; private readonly gaxgrpc::ApiCall<ReportSessionRequest, ReportSessionResponse> _callReportSession; private readonly gaxgrpc::ApiCall<ListTestsRequest, ListTestsResponse> _callListTests; private readonly gaxgrpc::ApiCall<DeleteTestRequest, wkt::Empty> _callDeleteTest; private readonly gaxgrpc::ApiCall<VerifyTestRequest, VerifyTestResponse> _callVerifyTest; /// <summary> /// Constructs a client wrapper for the Testing service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="TestingSettings"/> used within this client.</param> public TestingClientImpl(Testing.TestingClient grpcClient, TestingSettings settings) { GrpcClient = grpcClient; TestingSettings effectiveSettings = settings ?? TestingSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callCreateSession = clientHelper.BuildApiCall<CreateSessionRequest, Session>(grpcClient.CreateSessionAsync, grpcClient.CreateSession, effectiveSettings.CreateSessionSettings); Modify_ApiCall(ref _callCreateSession); Modify_CreateSessionApiCall(ref _callCreateSession); _callGetSession = clientHelper.BuildApiCall<GetSessionRequest, Session>(grpcClient.GetSessionAsync, grpcClient.GetSession, effectiveSettings.GetSessionSettings).WithGoogleRequestParam("name", request => request.Name); Modify_ApiCall(ref _callGetSession); Modify_GetSessionApiCall(ref _callGetSession); _callListSessions = clientHelper.BuildApiCall<ListSessionsRequest, ListSessionsResponse>(grpcClient.ListSessionsAsync, grpcClient.ListSessions, effectiveSettings.ListSessionsSettings); Modify_ApiCall(ref _callListSessions); Modify_ListSessionsApiCall(ref _callListSessions); _callDeleteSession = clientHelper.BuildApiCall<DeleteSessionRequest, wkt::Empty>(grpcClient.DeleteSessionAsync, grpcClient.DeleteSession, effectiveSettings.DeleteSessionSettings).WithGoogleRequestParam("name", request => request.Name); Modify_ApiCall(ref _callDeleteSession); Modify_DeleteSessionApiCall(ref _callDeleteSession); _callReportSession = clientHelper.BuildApiCall<ReportSessionRequest, ReportSessionResponse>(grpcClient.ReportSessionAsync, grpcClient.ReportSession, effectiveSettings.ReportSessionSettings).WithGoogleRequestParam("name", request => request.Name); Modify_ApiCall(ref _callReportSession); Modify_ReportSessionApiCall(ref _callReportSession); _callListTests = clientHelper.BuildApiCall<ListTestsRequest, ListTestsResponse>(grpcClient.ListTestsAsync, grpcClient.ListTests, effectiveSettings.ListTestsSettings).WithGoogleRequestParam("parent", request => request.Parent); Modify_ApiCall(ref _callListTests); Modify_ListTestsApiCall(ref _callListTests); _callDeleteTest = clientHelper.BuildApiCall<DeleteTestRequest, wkt::Empty>(grpcClient.DeleteTestAsync, grpcClient.DeleteTest, effectiveSettings.DeleteTestSettings).WithGoogleRequestParam("name", request => request.Name); Modify_ApiCall(ref _callDeleteTest); Modify_DeleteTestApiCall(ref _callDeleteTest); _callVerifyTest = clientHelper.BuildApiCall<VerifyTestRequest, VerifyTestResponse>(grpcClient.VerifyTestAsync, grpcClient.VerifyTest, effectiveSettings.VerifyTestSettings).WithGoogleRequestParam("name", request => request.Name); Modify_ApiCall(ref _callVerifyTest); Modify_VerifyTestApiCall(ref _callVerifyTest); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_CreateSessionApiCall(ref gaxgrpc::ApiCall<CreateSessionRequest, Session> call); partial void Modify_GetSessionApiCall(ref gaxgrpc::ApiCall<GetSessionRequest, Session> call); partial void Modify_ListSessionsApiCall(ref gaxgrpc::ApiCall<ListSessionsRequest, ListSessionsResponse> call); partial void Modify_DeleteSessionApiCall(ref gaxgrpc::ApiCall<DeleteSessionRequest, wkt::Empty> call); partial void Modify_ReportSessionApiCall(ref gaxgrpc::ApiCall<ReportSessionRequest, ReportSessionResponse> call); partial void Modify_ListTestsApiCall(ref gaxgrpc::ApiCall<ListTestsRequest, ListTestsResponse> call); partial void Modify_DeleteTestApiCall(ref gaxgrpc::ApiCall<DeleteTestRequest, wkt::Empty> call); partial void Modify_VerifyTestApiCall(ref gaxgrpc::ApiCall<VerifyTestRequest, VerifyTestResponse> call); partial void OnConstruction(Testing.TestingClient grpcClient, TestingSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC Testing client</summary> public override Testing.TestingClient GrpcClient { get; } partial void Modify_CreateSessionRequest(ref CreateSessionRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_GetSessionRequest(ref GetSessionRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_ListSessionsRequest(ref ListSessionsRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_DeleteSessionRequest(ref DeleteSessionRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_ReportSessionRequest(ref ReportSessionRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_ListTestsRequest(ref ListTestsRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_DeleteTestRequest(ref DeleteTestRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_VerifyTestRequest(ref VerifyTestRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Creates a new testing session. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override Session CreateSession(CreateSessionRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_CreateSessionRequest(ref request, ref callSettings); return _callCreateSession.Sync(request, callSettings); } /// <summary> /// Creates a new testing session. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<Session> CreateSessionAsync(CreateSessionRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_CreateSessionRequest(ref request, ref callSettings); return _callCreateSession.Async(request, callSettings); } /// <summary> /// Gets a testing session. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override Session GetSession(GetSessionRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetSessionRequest(ref request, ref callSettings); return _callGetSession.Sync(request, callSettings); } /// <summary> /// Gets a testing session. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<Session> GetSessionAsync(GetSessionRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetSessionRequest(ref request, ref callSettings); return _callGetSession.Async(request, callSettings); } /// <summary> /// Lists the current test sessions. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="Session"/> resources.</returns> public override gax::PagedEnumerable<ListSessionsResponse, Session> ListSessions(ListSessionsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListSessionsRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedEnumerable<ListSessionsRequest, ListSessionsResponse, Session>(_callListSessions, request, callSettings); } /// <summary> /// Lists the current test sessions. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="Session"/> resources.</returns> public override gax::PagedAsyncEnumerable<ListSessionsResponse, Session> ListSessionsAsync(ListSessionsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListSessionsRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedAsyncEnumerable<ListSessionsRequest, ListSessionsResponse, Session>(_callListSessions, request, callSettings); } /// <summary> /// Delete a test session. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override void DeleteSession(DeleteSessionRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_DeleteSessionRequest(ref request, ref callSettings); _callDeleteSession.Sync(request, callSettings); } /// <summary> /// Delete a test session. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task DeleteSessionAsync(DeleteSessionRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_DeleteSessionRequest(ref request, ref callSettings); return _callDeleteSession.Async(request, callSettings); } /// <summary> /// Report on the status of a session. /// This generates a report detailing which tests have been completed, /// and an overall rollup. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override ReportSessionResponse ReportSession(ReportSessionRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ReportSessionRequest(ref request, ref callSettings); return _callReportSession.Sync(request, callSettings); } /// <summary> /// Report on the status of a session. /// This generates a report detailing which tests have been completed, /// and an overall rollup. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<ReportSessionResponse> ReportSessionAsync(ReportSessionRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ReportSessionRequest(ref request, ref callSettings); return _callReportSession.Async(request, callSettings); } /// <summary> /// List the tests of a sessesion. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="Test"/> resources.</returns> public override gax::PagedEnumerable<ListTestsResponse, Test> ListTests(ListTestsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListTestsRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedEnumerable<ListTestsRequest, ListTestsResponse, Test>(_callListTests, request, callSettings); } /// <summary> /// List the tests of a sessesion. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="Test"/> resources.</returns> public override gax::PagedAsyncEnumerable<ListTestsResponse, Test> ListTestsAsync(ListTestsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListTestsRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedAsyncEnumerable<ListTestsRequest, ListTestsResponse, Test>(_callListTests, request, callSettings); } /// <summary> /// Explicitly decline to implement a test. /// /// This removes the test from subsequent `ListTests` calls, and /// attempting to do the test will error. /// /// This method will error if attempting to delete a required test. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override void DeleteTest(DeleteTestRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_DeleteTestRequest(ref request, ref callSettings); _callDeleteTest.Sync(request, callSettings); } /// <summary> /// Explicitly decline to implement a test. /// /// This removes the test from subsequent `ListTests` calls, and /// attempting to do the test will error. /// /// This method will error if attempting to delete a required test. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task DeleteTestAsync(DeleteTestRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_DeleteTestRequest(ref request, ref callSettings); return _callDeleteTest.Async(request, callSettings); } /// <summary> /// Register a response to a test. /// /// In cases where a test involves registering a final answer at the /// end of the test, this method provides the means to do so. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override VerifyTestResponse VerifyTest(VerifyTestRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_VerifyTestRequest(ref request, ref callSettings); return _callVerifyTest.Sync(request, callSettings); } /// <summary> /// Register a response to a test. /// /// In cases where a test involves registering a final answer at the /// end of the test, this method provides the means to do so. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<VerifyTestResponse> VerifyTestAsync(VerifyTestRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_VerifyTestRequest(ref request, ref callSettings); return _callVerifyTest.Async(request, callSettings); } } public partial class ListSessionsRequest : gaxgrpc::IPageRequest { } public partial class ListTestsRequest : gaxgrpc::IPageRequest { } public partial class ListSessionsResponse : gaxgrpc::IPageResponse<Session> { /// <summary>Returns an enumerator that iterates through the resources in this response.</summary> public scg::IEnumerator<Session> GetEnumerator() => Sessions.GetEnumerator(); sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator(); } public partial class ListTestsResponse : gaxgrpc::IPageResponse<Test> { /// <summary>Returns an enumerator that iterates through the resources in this response.</summary> public scg::IEnumerator<Test> GetEnumerator() => Tests.GetEnumerator(); sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator(); } }
namespace Nancy.ViewEngines.SuperSimpleViewEngine { using Microsoft.CSharp.RuntimeBinder; using System; using System.Collections; using System.Collections.Generic; using System.Dynamic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using System.Text; /// <summary> /// A super-simple view engine /// </summary> public class SuperSimpleViewEngine { /// <summary> /// Compiled Regex for viewbag substitutions /// </summary> private static readonly Regex ViewBagSubstitutionsRegEx = new Regex(@"@(?<Encode>!)?ViewBag(?:\.(?<ParameterName>[a-zA-Z0-9-_]+))*;?", RegexOptions.Compiled); /// <summary> /// Compiled Regex for single substitutions /// </summary> private static readonly Regex SingleSubstitutionsRegEx = new Regex(@"@(?<Encode>!)?Model(?:\.(?<ParameterName>[a-zA-Z0-9-_]+))*;?", RegexOptions.Compiled); /// <summary> /// Compiled Regex for context subsituations /// </summary> private static readonly Regex ContextSubstitutionsRegEx = new Regex(@"@(?<Encode>!)?Context(?:\.(?<ParameterName>[a-zA-Z0-9-_]+))*;?", RegexOptions.Compiled); /// <summary> /// Compiled Regex for each blocks /// </summary> private static readonly Regex EachSubstitutionRegEx = new Regex(@"@Each(?:\.(?<ModelSource>(Model|Context)+))?(?:\.(?<ParameterName>[a-zA-Z0-9-_]+))*;?(?<Contents>.*?)@EndEach;?", RegexOptions.Compiled | RegexOptions.Singleline); /// <summary> /// Compiled Regex for each block current substitutions /// </summary> private static readonly Regex EachItemSubstitutionRegEx = new Regex(@"@(?<Encode>!)?Current(?:\.(?<ParameterName>[a-zA-Z0-9-_]+))*;?", RegexOptions.Compiled); /// <summary> /// Compiled Regex for if blocks /// </summary> private const string ConditionalOpenSyntaxPattern = @"@If(?<Not>Not)?(?<Null>Null)?(?:\.(?<ModelSource>(Model|Context)+))?(?:\.(?<ParameterName>[a-zA-Z0-9-_]+))+;?"; private const string ConditionalOpenInnerSyntaxPattern = @"@If(?:Not)?(?:Null)?(?:\.(?:(Model|Context)+))?(?:\.(?:[a-zA-Z0-9-_]+))+;?"; private const string ConditionalCloseStynaxPattern = @"@EndIf;?"; private static readonly string ConditionalSubstituionPattern = string.Format(@"{0}(?<Contents>:[.*]|(?>{2}(?<DEPTH>)|{1}(?<-DEPTH>)|.)*(?(DEPTH)(?!))){1}", ConditionalOpenSyntaxPattern, ConditionalCloseStynaxPattern, ConditionalOpenInnerSyntaxPattern); private static readonly Regex ConditionalSubstitutionRegEx = new Regex(ConditionalSubstituionPattern, RegexOptions.Compiled | RegexOptions.Singleline); /// <summary> /// Compiled regex for partial blocks /// </summary> private static readonly Regex PartialSubstitutionRegEx = new Regex(@"@Partial\['(?<ViewName>[^\]]+)'(?:.[ ]?@?(?<Model>(Model|Current)(?:\.(?<ParameterName>[a-zA-Z0-9-_]+))*))?\];?", RegexOptions.Compiled); /// <summary> /// Compiled RegEx for section block declarations /// </summary> private static readonly Regex SectionDeclarationRegEx = new Regex(@"@Section\[\'(?<SectionName>.+?)\'\];?", RegexOptions.Compiled); /// <summary> /// Compiled RegEx for section block contents /// </summary> private static readonly Regex SectionContentsRegEx = new Regex(@"(?:@Section\[\'(?<SectionName>.+?)\'\];?(?<SectionContents>.*?)@EndSection;?)", RegexOptions.Compiled | RegexOptions.Singleline); /// <summary> /// Compiled RegEx for master page declaration /// </summary> private static readonly Regex MasterPageHeaderRegEx = new Regex(@"^(?:@Master\[\'(?<MasterPage>.+?)\'\]);?", RegexOptions.Compiled); /// <summary> /// Compiled RegEx for path expansion /// </summary> private static readonly Regex PathExpansionRegEx = new Regex(@"(?:@Path\[\'(?<Path>.+?)\'\]);?", RegexOptions.Compiled); /// <summary> /// Compiled RegEx for path expansion in attribute values /// </summary> private static readonly Regex AttributeValuePathExpansionRegEx = new Regex(@"(?<Attribute>[a-zA-Z]+)=(?<Quote>[""'])(?<Path>~.+?)\k<Quote>", RegexOptions.Compiled); /// <summary> /// Compiled RegEx for the CSRF anti forgery token /// </summary> private static readonly Regex AntiForgeryTokenRegEx = new Regex(@"@AntiForgeryToken;?", RegexOptions.Compiled); /// <summary> /// View engine transform processors /// </summary> private readonly List<Func<string, object, IViewEngineHost, string>> processors; /// <summary> /// View engine extensions /// </summary> private readonly IEnumerable<ISuperSimpleViewEngineMatcher> matchers; /// <summary> /// Initializes a new instance of the <see cref="SuperSimpleViewEngine"/> class. /// </summary> public SuperSimpleViewEngine() : this(Enumerable.Empty<ISuperSimpleViewEngineMatcher>()) { } /// <summary> /// Initializes a new instance of the <see cref="SuperSimpleViewEngine"/> class, using /// the provided <see cref="ISuperSimpleViewEngineMatcher"/> extensions. /// </summary> /// <param name="matchers">The matchers to use with the engine.</param> public SuperSimpleViewEngine(IEnumerable<ISuperSimpleViewEngineMatcher> matchers) { this.matchers = matchers ?? Enumerable.Empty<ISuperSimpleViewEngineMatcher>(); this.processors = new List<Func<string, object, IViewEngineHost, string>> { PerformViewBagSubstitutions, PerformSingleSubstitutions, PerformContextSubstitutions, PerformEachSubstitutions, PerformConditionalSubstitutions, PerformPathSubstitutions, PerformAntiForgeryTokenSubstitutions, this.PerformPartialSubstitutions, this.PerformMasterPageSubstitutions, }; } /// <summary> /// Renders a template /// </summary> /// <param name="template">The template to render.</param> /// <param name="model">The model to user for rendering.</param> /// <param name="host">The view engine host</param> /// <returns>A string containing the expanded template.</returns> public string Render(string template, dynamic model, IViewEngineHost host) { var output = this.processors.Aggregate(template, (current, processor) => processor(current, model ?? new object(), host)); return this.matchers.Aggregate(output, (current, extension) => extension.Invoke(current, model, host)); } /// <summary> /// <para> /// Gets a property value from the given model. /// </para> /// <para> /// Anonymous types, standard types and ExpandoObject are supported. /// Arbitrary dynamics (implementing IDynamicMetaObjectProvider) are not, unless /// they also implement IDictionary string, object for accessing properties. /// </para> /// </summary> /// <param name="model">The model.</param> /// <param name="propertyName">The property name to evaluate.</param> /// <returns>Tuple - Item1 being a bool for whether the evaluation was successful, Item2 being the value.</returns> /// <exception cref="ArgumentException">Model type is not supported.</exception> private static Tuple<bool, object> GetPropertyValue(object model, string propertyName) { if (model == null || string.IsNullOrEmpty(propertyName)) { return new Tuple<bool, object>(false, null); } if (model is IDictionary<string, object>) { return DynamicDictionaryPropertyEvaluator(model, propertyName); } if (!(model is IDynamicMetaObjectProvider)) { return StandardTypePropertyEvaluator(model, propertyName); } if (model is DynamicDictionaryValue) { var dynamicModel = model as DynamicDictionaryValue; return GetPropertyValue(dynamicModel.Value, propertyName); } if (model is DynamicObject) { return GetDynamicMember(model, propertyName); } throw new ArgumentException("model must be a standard type or implement IDictionary<string, object>", "model"); } private static Tuple<bool, object> GetDynamicMember(object obj, string memberName) { var binder = Microsoft.CSharp.RuntimeBinder.Binder.GetMember(CSharpBinderFlags.None, memberName, obj.GetType(), new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }); var callsite = CallSite<Func<CallSite, object, object>>.Create(binder); var result = callsite.Target(callsite, obj); return result == null ? new Tuple<bool, object>(false, null) : new Tuple<bool, object>(true, result); } /// <summary> /// A property extractor for standard types. /// </summary> /// <param name="model">The model.</param> /// <param name="propertyName">The property name.</param> /// <returns>Tuple - Item1 being a bool for whether the evaluation was successful, Item2 being the value.</returns> private static Tuple<bool, object> StandardTypePropertyEvaluator(object model, string propertyName) { var type = model.GetType(); var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); var property = properties.Where(p => string.Equals(p.Name, propertyName, StringComparison.Ordinal)). FirstOrDefault(); if (property != null) { return new Tuple<bool, object>(true, property.GetValue(model, null)); } var fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); var field = fields.Where(p => string.Equals(p.Name, propertyName, StringComparison.Ordinal)). FirstOrDefault(); return field == null ? new Tuple<bool, object>(false, null) : new Tuple<bool, object>(true, field.GetValue(model)); } /// <summary> /// A property extractor designed for ExpandoObject, but also for any /// type that implements IDictionary string object for accessing its /// properties. /// </summary> /// <param name="model">The model.</param> /// <param name="propertyName">The property name.</param> /// <returns>Tuple - Item1 being a bool for whether the evaluation was successful, Item2 being the value.</returns> private static Tuple<bool, object> DynamicDictionaryPropertyEvaluator(object model, string propertyName) { var dictionaryModel = (IDictionary<string, object>)model; object output; return !dictionaryModel.TryGetValue(propertyName, out output) ? new Tuple<bool, object>(false, null) : new Tuple<bool, object>(true, output); } /// <summary> /// Gets an IEnumerable of capture group values /// </summary> /// <param name="m">The match to use.</param> /// <param name="groupName">Group name containing the capture group.</param> /// <returns>IEnumerable of capture group values as strings.</returns> private static IEnumerable<string> GetCaptureGroupValues(Match m, string groupName) { return m.Groups[groupName].Captures.Cast<Capture>().Select(c => c.Value); } /// <summary> /// Gets a property value from a collection of nested parameter names /// </summary> /// <param name="model">The model containing properties.</param> /// <param name="parameters">A collection of nested parameters (e.g. User, Name</param> /// <returns>Tuple - Item1 being a bool for whether the evaluation was successful, Item2 being the value.</returns> private static Tuple<bool, object> GetPropertyValueFromParameterCollection(object model, IEnumerable<string> parameters) { if (parameters == null) { return new Tuple<bool, object>(true, model); } var currentObject = model; foreach (var parameter in parameters) { var currentResult = GetPropertyValue(currentObject, parameter); if (currentResult.Item1 == false) { return new Tuple<bool, object>(false, null); } currentObject = currentResult.Item2; } return new Tuple<bool, object>(true, currentObject); } /// <summary> /// Gets the predicate result for an If or IfNot block /// </summary> /// <param name="item">The item to evaluate</param> /// <param name="properties">Property list to evaluate</param> /// <param name="nullCheck">Whether to check for null, rather than straight boolean</param> /// <returns>Bool representing the predicate result</returns> private static bool GetPredicateResult(object item, IEnumerable<string> properties, bool nullCheck) { var substitutionObject = GetPropertyValueFromParameterCollection(item, properties); if (substitutionObject.Item1 == false && properties.Last().StartsWith("Has")) { var newProperties = properties.Take(properties.Count() - 1).Concat(new[] { properties.Last().Substring(3) }); substitutionObject = GetPropertyValueFromParameterCollection(item, newProperties); return GetHasPredicateResultFromSubstitutionObject(substitutionObject.Item2); } return GetPredicateResultFromSubstitutionObject(substitutionObject.Item2, nullCheck); } /// <summary> /// Returns the predicate result if the substitionObject is a valid bool /// </summary> /// <param name="substitutionObject">The substitution object.</param> /// <param name="nullCheck"></param> /// <returns>Bool value of the substitutionObject, or false if unable to cast.</returns> private static bool GetPredicateResultFromSubstitutionObject(object substitutionObject, bool nullCheck) { if (nullCheck) { return substitutionObject == null; } if (substitutionObject != null && substitutionObject.GetType().GetProperty("Value") != null) { object value = ((dynamic)substitutionObject).Value; if (value is bool?) { substitutionObject = value; } } var predicateResult = false; var substitutionBool = substitutionObject as bool?; if (substitutionBool != null) { predicateResult = substitutionBool.Value; } return predicateResult; } /// <summary> /// Returns the predicate result if the substitionObject is a valid ICollection /// </summary> /// <param name="substitutionObject">The substitution object.</param> /// <returns>Bool value of the whether the ICollection has items, or false if unable to cast.</returns> private static bool GetHasPredicateResultFromSubstitutionObject(object substitutionObject) { var predicateResult = false; var substitutionCollection = substitutionObject as ICollection; if (substitutionCollection != null) { predicateResult = substitutionCollection.Count != 0; } return predicateResult; } /// <summary> /// Performs single @ViewBag.PropertyName substitutions. /// </summary> /// <param name="template">The template.</param> /// <param name="model">This parameter is not used, the model is based on the "host.Context.ViewBag".</param> /// <param name="host">View engine host</param> /// <returns>Template with @ViewBag.PropertyName blocks expanded.</returns> private static string PerformViewBagSubstitutions(string template, object model, IViewEngineHost host) { return ViewBagSubstitutionsRegEx.Replace( template, m => { var properties = GetCaptureGroupValues(m, "ParameterName"); var substitution = GetPropertyValueFromParameterCollection(((dynamic)host.Context).ViewBag, properties); if (!substitution.Item1) { return "[ERR!]"; } if (substitution.Item2 == null) { return string.Empty; } return m.Groups["Encode"].Success ? host.HtmlEncode(substitution.Item2.ToString()) : substitution.Item2.ToString(); }); } /// <summary> /// Performs single @Model.PropertyName substitutions. /// </summary> /// <param name="template">The template.</param> /// <param name="model">The model.</param> /// <param name="host">View engine host</param> /// <returns>Template with @Model.PropertyName blocks expanded.</returns> private static string PerformSingleSubstitutions(string template, object model, IViewEngineHost host) { return SingleSubstitutionsRegEx.Replace( template, m => { var properties = GetCaptureGroupValues(m, "ParameterName"); var substitution = GetPropertyValueFromParameterCollection(model, properties); if (!substitution.Item1) { return "[ERR!]"; } if (substitution.Item2 == null) { return string.Empty; } return m.Groups["Encode"].Success ? host.HtmlEncode(substitution.Item2.ToString()) : substitution.Item2.ToString(); }); } /// <summary> /// Performs single @Context.PropertyName substitutions. /// </summary> /// <param name="template">The template.</param> /// <param name="model">The model.</param> /// <param name="host">View engine host</param> /// <returns>Template with @Context.PropertyName blocks expanded.</returns> private static string PerformContextSubstitutions(string template, object model, IViewEngineHost host) { return ContextSubstitutionsRegEx.Replace( template, m => { var properties = GetCaptureGroupValues(m, "ParameterName"); var substitution = GetPropertyValueFromParameterCollection(host.Context, properties); if (!substitution.Item1) { return "[ERR!]"; } if (substitution.Item2 == null) { return string.Empty; } return m.Groups["Encode"].Success ? host.HtmlEncode(substitution.Item2.ToString()) : substitution.Item2.ToString(); }); } /// <summary> /// Performs @Each.PropertyName substitutions /// </summary> /// <param name="template">The template.</param> /// <param name="model">The model.</param> /// <param name="host">View engine host</param> /// <returns>Template with @Each.PropertyName blocks expanded.</returns> private string PerformEachSubstitutions(string template, object model, IViewEngineHost host) { return EachSubstitutionRegEx.Replace( template, m => { var properties = GetCaptureGroupValues(m, "ParameterName"); var modelSource = GetCaptureGroupValues(m, "ModelSource").SingleOrDefault(); if (modelSource != null && modelSource.Equals("Context", StringComparison.OrdinalIgnoreCase)) { model = host.Context; } var substitutionObject = GetPropertyValueFromParameterCollection(model, properties); if (substitutionObject.Item1 == false) { return "[ERR!]"; } if (substitutionObject.Item2 == null) { return string.Empty; } var substitutionEnumerable = substitutionObject.Item2 as IEnumerable; if (substitutionEnumerable == null) { return "[ERR!]"; } var contents = m.Groups["Contents"].Value; var result = new StringBuilder(); foreach (var item in substitutionEnumerable) { var modifiedContent = PerformPartialSubstitutions(contents, item, host); modifiedContent = PerformConditionalSubstitutions(modifiedContent, item, host); result.Append(ReplaceCurrentMatch(modifiedContent, item, host)); } return result.ToString(); }); } /// <summary> /// Expand a @Current match inside an @Each iterator /// </summary> /// <param name="contents">Contents of the @Each block</param> /// <param name="item">Current item from the @Each enumerable</param> /// <param name="host">View engine host</param> /// <returns>String result of the expansion of the @Each.</returns> private static string ReplaceCurrentMatch(string contents, object item, IViewEngineHost host) { return EachItemSubstitutionRegEx.Replace( contents, eachMatch => { if (string.IsNullOrEmpty(eachMatch.Groups["ParameterName"].Value)) { return eachMatch.Groups["Encode"].Success ? host.HtmlEncode(item.ToString()) : item.ToString(); } var properties = GetCaptureGroupValues(eachMatch, "ParameterName"); var substitution = GetPropertyValueFromParameterCollection(item, properties); if (!substitution.Item1) { return "[ERR!]"; } if (substitution.Item2 == null) { return string.Empty; } return eachMatch.Groups["Encode"].Success ? host.HtmlEncode(substitution.Item2.ToString()) : substitution.Item2.ToString(); }); } /// <summary> /// Performs @If.PropertyName and @IfNot.PropertyName substitutions /// </summary> /// <param name="template">The template.</param> /// <param name="model">The model.</param> /// <param name="host">View engine host</param> /// <returns>Template with @If.PropertyName @IfNot.PropertyName blocks removed/expanded.</returns> private static string PerformConditionalSubstitutions(string template, object model, IViewEngineHost host) { var result = template; result = ConditionalSubstitutionRegEx.Replace( result, m => { var properties = GetCaptureGroupValues(m, "ParameterName"); var modelSource = GetCaptureGroupValues(m, "ModelSource").SingleOrDefault(); if (modelSource != null && modelSource.Equals("Context", StringComparison.OrdinalIgnoreCase)) { model = host.Context; } var predicateResult = GetPredicateResult(model, properties, m.Groups["Null"].Value == "Null"); if (m.Groups["Not"].Value == "Not") { predicateResult = !predicateResult; } return predicateResult ? PerformConditionalSubstitutions(m.Groups["Contents"].Value, model, host) : string.Empty; }); return result; } /// <summary> /// Perform path expansion substitutions /// </summary> /// <param name="template">The template.</param> /// <param name="model">The model.</param> /// <param name="host">View engine host</param> /// <returns>Template with paths expanded</returns> private static string PerformPathSubstitutions(string template, object model, IViewEngineHost host) { var result = template; result = PathExpansionRegEx.Replace( result, m => { var path = m.Groups["Path"].Value; return host.ExpandPath(path); }); result = AttributeValuePathExpansionRegEx.Replace( result, m => { var attribute = m.Groups["Attribute"]; var quote = m.Groups["Quote"].Value; var path = m.Groups["Path"].Value; var expandedPath = host.ExpandPath(path); return string.Format("{0}={1}{2}{1}", attribute, quote, expandedPath); }); return result; } /// <summary> /// Perform CSRF anti forgery token expansions /// </summary> /// <param name="template">The template.</param> /// <param name="model">The model.</param> /// <param name="host">View engine host</param> /// <returns>Template with anti forgery tokens expanded</returns> private static string PerformAntiForgeryTokenSubstitutions(string template, object model, IViewEngineHost host) { return AntiForgeryTokenRegEx.Replace(template, x => host.AntiForgeryToken()); } /// <summary> /// Perform @Partial partial view expansion /// </summary> /// <param name="template">The template.</param> /// <param name="model">The model.</param> /// <param name="host">View engine host</param> /// <returns>Template with partials expanded</returns> private string PerformPartialSubstitutions(string template, dynamic model, IViewEngineHost host) { var result = template; result = PartialSubstitutionRegEx.Replace( result, m => { var partialViewName = m.Groups["ViewName"].Value; var partialModel = model; var properties = GetCaptureGroupValues(m, "ParameterName"); if (m.Groups["Model"].Length > 0) { var modelValue = GetPropertyValueFromParameterCollection(partialModel, properties); if (modelValue.Item1 != true) { return "[ERR!]"; } partialModel = modelValue.Item2; } var partialTemplate = host.GetTemplate(partialViewName, partialModel); return this.Render(partialTemplate, partialModel, host); }); return result; } /// <summary> /// Invokes the master page rendering with current sections if necessary /// </summary> /// <param name="template">The template.</param> /// <param name="model">The model.</param> /// <param name="host">View engine host</param> /// <returns>Template with master page applied and sections substituted</returns> private string PerformMasterPageSubstitutions(string template, object model, IViewEngineHost host) { var masterPageName = GetMasterPageName(template); if (string.IsNullOrWhiteSpace(masterPageName)) { return template; } var masterTemplate = host.GetTemplate(masterPageName, model); var sectionMatches = SectionContentsRegEx.Matches(template); var sections = sectionMatches.Cast<Match>().ToDictionary(sectionMatch => sectionMatch.Groups["SectionName"].Value, sectionMatch => sectionMatch.Groups["SectionContents"].Value); return this.RenderMasterPage(masterTemplate, sections, model, host); } /// <summary> /// Renders a master page - does a normal render then replaces any section tags with sections passed in /// </summary> /// <param name="masterTemplate">The master page template</param> /// <param name="sections">Dictionary of section contents</param> /// <param name="model">The model.</param> /// <param name="host">View engine host</param> /// <returns>Template with the master page applied and sections substituted</returns> private string RenderMasterPage(string masterTemplate, IDictionary<string, string> sections, object model, IViewEngineHost host) { var result = this.Render(masterTemplate, model, host); result = SectionDeclarationRegEx.Replace( result, m => { var sectionName = m.Groups["SectionName"].Value; return sections.ContainsKey(sectionName) ? sections[sectionName] : string.Empty; }); return result; } /// <summary> /// Gets the master page name, if one is specified /// </summary> /// <param name="template">The template</param> /// <returns>Master page name or String.Empty</returns> private static string GetMasterPageName(string template) { using (var stringReader = new StringReader(template)) { var firstLine = stringReader.ReadLine(); if (firstLine == null) { return string.Empty; } var masterPageMatch = MasterPageHeaderRegEx.Match(firstLine); return masterPageMatch.Success ? masterPageMatch.Groups["MasterPage"].Value : string.Empty; } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Timers; using OpenMetaverse.Packets; using OpenSim.Framework; using OpenSim.Framework.Monitoring; using OpenSim.Region.Framework.Interfaces; namespace OpenSim.Region.Framework.Scenes { /// <summary> /// Collect statistics from the scene to send to the client and for access by other monitoring tools. /// </summary> /// <remarks> /// FIXME: This should be a monitoring region module /// </remarks> public class SimStatsReporter { private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); public const string LastReportedObjectUpdateStatName = "LastReportedObjectUpdates"; public const string SlowFramesStatName = "SlowFrames"; public delegate void SendStatResult(SimStats stats); public delegate void YourStatsAreWrong(); public event SendStatResult OnSendStatsResult; public event YourStatsAreWrong OnStatsIncorrect; private SendStatResult handlerSendStatResult; private YourStatsAreWrong handlerStatsIncorrect; /// <summary> /// These are the IDs of stats sent in the StatsPacket to the viewer. /// </summary> /// <remarks> /// Some of these are not relevant to OpenSimulator since it is architected differently to other simulators /// (e.g. script instructions aren't executed as part of the frame loop so 'script time' is tricky). /// </remarks> public enum Stats : uint { TimeDilation = 0, SimFPS = 1, PhysicsFPS = 2, AgentUpdates = 3, FrameMS = 4, NetMS = 5, OtherMS = 6, PhysicsMS = 7, AgentMS = 8, ImageMS = 9, ScriptMS = 10, TotalPrim = 11, ActivePrim = 12, Agents = 13, ChildAgents = 14, ActiveScripts = 15, ScriptLinesPerSecond = 16, InPacketsPerSecond = 17, OutPacketsPerSecond = 18, PendingDownloads = 19, PendingUploads = 20, VirtualSizeKb = 21, ResidentSizeKb = 22, PendingLocalUploads = 23, UnAckedBytes = 24, PhysicsPinnedTasks = 25, PhysicsLodTasks = 26, SimPhysicsStepMs = 27, SimPhysicsShapeMs = 28, SimPhysicsOtherMs = 29, SimPhysicsMemory = 30, ScriptEps = 31, SimSpareMs = 32, SimSleepMs = 33, SimIoPumpTime = 34 } /// <summary> /// This is for llGetRegionFPS /// </summary> public float LastReportedSimFPS { get { return lastReportedSimFPS; } } /// <summary> /// Number of object updates performed in the last stats cycle /// </summary> /// <remarks> /// This isn't sent out to the client but it is very useful data to detect whether viewers are being sent a /// large number of object updates. /// </remarks> public float LastReportedObjectUpdates { get; private set; } public float[] LastReportedSimStats { get { return lastReportedSimStats; } } /// <summary> /// Number of frames that have taken longer to process than Scene.MIN_FRAME_TIME /// </summary> public Stat SlowFramesStat { get; private set; } /// <summary> /// The threshold at which we log a slow frame. /// </summary> public int SlowFramesStatReportThreshold { get; private set; } /// <summary> /// Extra sim statistics that are used by monitors but not sent to the client. /// </summary> /// <value> /// The keys are the stat names. /// </value> private Dictionary<string, float> m_lastReportedExtraSimStats = new Dictionary<string, float>(); // Sending a stats update every 3 seconds- private int m_statsUpdatesEveryMS = 3000; private float m_statsUpdateFactor; private float m_timeDilation; private int m_fps; /// <summary> /// Number of the last frame on which we processed a stats udpate. /// </summary> private uint m_lastUpdateFrame; /// <summary> /// Our nominal fps target, as expected in fps stats when a sim is running normally. /// </summary> private float m_nominalReportedFps = 55; /// <summary> /// Parameter to adjust reported scene fps /// </summary> /// <remarks> /// Our scene loop runs slower than other server implementations, apparantly because we work somewhat differently. /// However, we will still report an FPS that's closer to what people are used to seeing. A lower FPS might /// affect clients and monitoring scripts/software. /// </remarks> private float m_reportedFpsCorrectionFactor = 5; // saved last reported value so there is something available for llGetRegionFPS private float lastReportedSimFPS; private float[] lastReportedSimStats = new float[22]; private float m_pfps; /// <summary> /// Number of agent updates requested in this stats cycle /// </summary> private int m_agentUpdates; /// <summary> /// Number of object updates requested in this stats cycle /// </summary> private int m_objectUpdates; private int m_frameMS; private int m_spareMS; private int m_netMS; private int m_agentMS; private int m_physicsMS; private int m_imageMS; private int m_otherMS; //Ckrinke: (3-21-08) Comment out to remove a compiler warning. Bring back into play when needed. //Ckrinke private int m_scriptMS = 0; private int m_rootAgents; private int m_childAgents; private int m_numPrim; private int m_inPacketsPerSecond; private int m_outPacketsPerSecond; private int m_activePrim; private int m_unAckedBytes; private int m_pendingDownloads; private int m_pendingUploads = 0; // FIXME: Not currently filled in private int m_activeScripts; private int m_scriptLinesPerSecond; private int m_objectCapacity = 45000; private Scene m_scene; private RegionInfo ReportingRegion; private Timer m_report = new Timer(); private IEstateModule estateModule; public SimStatsReporter(Scene scene) { m_scene = scene; m_reportedFpsCorrectionFactor = scene.MinFrameSeconds * m_nominalReportedFps; m_statsUpdateFactor = (float)(m_statsUpdatesEveryMS / 1000); ReportingRegion = scene.RegionInfo; m_objectCapacity = scene.RegionInfo.ObjectCapacity; m_report.AutoReset = true; m_report.Interval = m_statsUpdatesEveryMS; m_report.Elapsed += TriggerStatsHeartbeat; m_report.Enabled = true; if (StatsManager.SimExtraStats != null) OnSendStatsResult += StatsManager.SimExtraStats.ReceiveClassicSimStatsPacket; /// At the moment, we'll only report if a frame is over 120% of target, since commonly frames are a bit /// longer than ideal (which in itself is a concern). SlowFramesStatReportThreshold = (int)Math.Ceiling(scene.MinFrameTicks * 1.2); SlowFramesStat = new Stat( "SlowFrames", "Slow Frames", "Number of frames where frame time has been significantly longer than the desired frame time.", " frames", "scene", m_scene.Name, StatType.Push, null, StatVerbosity.Info); StatsManager.RegisterStat(SlowFramesStat); } public void Close() { m_report.Elapsed -= TriggerStatsHeartbeat; m_report.Close(); } /// <summary> /// Sets the number of milliseconds between stat updates. /// </summary> /// <param name='ms'></param> public void SetUpdateMS(int ms) { m_statsUpdatesEveryMS = ms; m_statsUpdateFactor = (float)(m_statsUpdatesEveryMS / 1000); m_report.Interval = m_statsUpdatesEveryMS; } private void TriggerStatsHeartbeat(object sender, EventArgs args) { try { statsHeartBeat(sender, args); } catch (Exception e) { m_log.Warn(string.Format( "[SIM STATS REPORTER] Update for {0} failed with exception ", m_scene.RegionInfo.RegionName), e); } } private void statsHeartBeat(object sender, EventArgs e) { if (!m_scene.Active) return; SimStatsPacket.StatBlock[] sb = new SimStatsPacket.StatBlock[22]; SimStatsPacket.RegionBlock rb = new SimStatsPacket.RegionBlock(); // Know what's not thread safe in Mono... modifying timers. // m_log.Debug("Firing Stats Heart Beat"); lock (m_report) { uint regionFlags = 0; try { if (estateModule == null) estateModule = m_scene.RequestModuleInterface<IEstateModule>(); regionFlags = estateModule != null ? estateModule.GetRegionFlags() : (uint) 0; } catch (Exception) { // leave region flags at 0 } #region various statistic googly moogly // We're going to lie about the FPS because we've been lying since 2008. The actual FPS is currently // locked at a maximum of 11. Maybe at some point this can change so that we're not lying. int reportedFPS = (int)(m_fps * m_reportedFpsCorrectionFactor); // save the reported value so there is something available for llGetRegionFPS lastReportedSimFPS = reportedFPS / m_statsUpdateFactor; float physfps = ((m_pfps / 1000)); //if (physfps > 600) //physfps = physfps - (physfps - 600); if (physfps < 0) physfps = 0; #endregion m_rootAgents = m_scene.SceneGraph.GetRootAgentCount(); m_childAgents = m_scene.SceneGraph.GetChildAgentCount(); m_numPrim = m_scene.SceneGraph.GetTotalObjectsCount(); m_activePrim = m_scene.SceneGraph.GetActiveObjectsCount(); m_activeScripts = m_scene.SceneGraph.GetActiveScriptsCount(); // FIXME: Checking for stat sanity is a complex approach. What we really need to do is fix the code // so that stat numbers are always consistent. CheckStatSanity(); //Our time dilation is 0.91 when we're running a full speed, // therefore to make sure we get an appropriate range, // we have to factor in our error. (0.10f * statsUpdateFactor) // multiplies the fix for the error times the amount of times it'll occur a second // / 10 divides the value by the number of times the sim heartbeat runs (10fps) // Then we divide the whole amount by the amount of seconds pass in between stats updates. // 'statsUpdateFactor' is how often stats packets are sent in seconds. Used below to change // values to X-per-second values. uint thisFrame = m_scene.Frame; float framesUpdated = (float)(thisFrame - m_lastUpdateFrame) * m_reportedFpsCorrectionFactor; m_lastUpdateFrame = thisFrame; // Avoid div-by-zero if somehow we've not updated any frames. if (framesUpdated == 0) framesUpdated = 1; for (int i = 0; i < 22; i++) { sb[i] = new SimStatsPacket.StatBlock(); } sb[0].StatID = (uint) Stats.TimeDilation; sb[0].StatValue = (Single.IsNaN(m_timeDilation)) ? 0.1f : m_timeDilation ; //((((m_timeDilation + (0.10f * statsUpdateFactor)) /10) / statsUpdateFactor)); sb[1].StatID = (uint) Stats.SimFPS; sb[1].StatValue = reportedFPS / m_statsUpdateFactor; sb[2].StatID = (uint) Stats.PhysicsFPS; sb[2].StatValue = physfps / m_statsUpdateFactor; sb[3].StatID = (uint) Stats.AgentUpdates; sb[3].StatValue = (m_agentUpdates / m_statsUpdateFactor); sb[4].StatID = (uint) Stats.Agents; sb[4].StatValue = m_rootAgents; sb[5].StatID = (uint) Stats.ChildAgents; sb[5].StatValue = m_childAgents; sb[6].StatID = (uint) Stats.TotalPrim; sb[6].StatValue = m_numPrim; sb[7].StatID = (uint) Stats.ActivePrim; sb[7].StatValue = m_activePrim; sb[8].StatID = (uint)Stats.FrameMS; sb[8].StatValue = m_frameMS / framesUpdated; sb[9].StatID = (uint)Stats.NetMS; sb[9].StatValue = m_netMS / framesUpdated; sb[10].StatID = (uint)Stats.PhysicsMS; sb[10].StatValue = m_physicsMS / framesUpdated; sb[11].StatID = (uint)Stats.ImageMS ; sb[11].StatValue = m_imageMS / framesUpdated; sb[12].StatID = (uint)Stats.OtherMS; sb[12].StatValue = m_otherMS / framesUpdated; sb[13].StatID = (uint)Stats.InPacketsPerSecond; sb[13].StatValue = (m_inPacketsPerSecond / m_statsUpdateFactor); sb[14].StatID = (uint)Stats.OutPacketsPerSecond; sb[14].StatValue = (m_outPacketsPerSecond / m_statsUpdateFactor); sb[15].StatID = (uint)Stats.UnAckedBytes; sb[15].StatValue = m_unAckedBytes; sb[16].StatID = (uint)Stats.AgentMS; sb[16].StatValue = m_agentMS / framesUpdated; sb[17].StatID = (uint)Stats.PendingDownloads; sb[17].StatValue = m_pendingDownloads; sb[18].StatID = (uint)Stats.PendingUploads; sb[18].StatValue = m_pendingUploads; sb[19].StatID = (uint)Stats.ActiveScripts; sb[19].StatValue = m_activeScripts; sb[20].StatID = (uint)Stats.ScriptLinesPerSecond; sb[20].StatValue = m_scriptLinesPerSecond / m_statsUpdateFactor; sb[21].StatID = (uint)Stats.SimSpareMs; sb[21].StatValue = m_spareMS / framesUpdated; for (int i = 0; i < 22; i++) { lastReportedSimStats[i] = sb[i].StatValue; } SimStats simStats = new SimStats( ReportingRegion.RegionLocX, ReportingRegion.RegionLocY, regionFlags, (uint)m_objectCapacity, rb, sb, m_scene.RegionInfo.originRegionID); handlerSendStatResult = OnSendStatsResult; if (handlerSendStatResult != null) { handlerSendStatResult(simStats); } // Extra statistics that aren't currently sent to clients lock (m_lastReportedExtraSimStats) { m_lastReportedExtraSimStats[LastReportedObjectUpdateStatName] = m_objectUpdates / m_statsUpdateFactor; m_lastReportedExtraSimStats[SlowFramesStat.ShortName] = (float)SlowFramesStat.Value; Dictionary<string, float> physicsStats = m_scene.PhysicsScene.GetStats(); if (physicsStats != null) { foreach (KeyValuePair<string, float> tuple in physicsStats) { // FIXME: An extremely dirty hack to divide MS stats per frame rather than per second // Need to change things so that stats source can indicate whether they are per second or // per frame. if (tuple.Key.EndsWith("MS")) m_lastReportedExtraSimStats[tuple.Key] = tuple.Value / framesUpdated; else m_lastReportedExtraSimStats[tuple.Key] = tuple.Value / m_statsUpdateFactor; } } } ResetValues(); } } private void ResetValues() { m_timeDilation = 0; m_fps = 0; m_pfps = 0; m_agentUpdates = 0; m_objectUpdates = 0; //m_inPacketsPerSecond = 0; //m_outPacketsPerSecond = 0; m_unAckedBytes = 0; m_scriptLinesPerSecond = 0; m_frameMS = 0; m_agentMS = 0; m_netMS = 0; m_physicsMS = 0; m_imageMS = 0; m_otherMS = 0; m_spareMS = 0; //Ckrinke This variable is not used, so comment to remove compiler warning until it is used. //Ckrinke m_scriptMS = 0; } # region methods called from Scene // The majority of these functions are additive // so that you can easily change the amount of // seconds in between sim stats updates public void AddTimeDilation(float td) { //float tdsetting = td; //if (tdsetting > 1.0f) //tdsetting = (tdsetting - (tdsetting - 0.91f)); //if (tdsetting < 0) //tdsetting = 0.0f; m_timeDilation = td; } internal void CheckStatSanity() { if (m_rootAgents < 0 || m_childAgents < 0) { handlerStatsIncorrect = OnStatsIncorrect; if (handlerStatsIncorrect != null) { handlerStatsIncorrect(); } } if (m_rootAgents == 0 && m_childAgents == 0) { m_unAckedBytes = 0; } } public void AddFPS(int frames) { m_fps += frames; } public void AddPhysicsFPS(float frames) { m_pfps += frames; } public void AddObjectUpdates(int numUpdates) { m_objectUpdates += numUpdates; } public void AddAgentUpdates(int numUpdates) { m_agentUpdates += numUpdates; } public void AddInPackets(int numPackets) { m_inPacketsPerSecond = numPackets; } public void AddOutPackets(int numPackets) { m_outPacketsPerSecond = numPackets; } public void AddunAckedBytes(int numBytes) { m_unAckedBytes += numBytes; if (m_unAckedBytes < 0) m_unAckedBytes = 0; } public void addFrameMS(int ms) { m_frameMS += ms; // At the moment, we'll only report if a frame is over 120% of target, since commonly frames are a bit // longer than ideal due to the inaccuracy of the Sleep in Scene.Update() (which in itself is a concern). if (ms > SlowFramesStatReportThreshold) SlowFramesStat.Value++; } public void AddSpareMS(int ms) { m_spareMS += ms; } public void addNetMS(int ms) { m_netMS += ms; } public void addAgentMS(int ms) { m_agentMS += ms; } public void addPhysicsMS(int ms) { m_physicsMS += ms; } public void addImageMS(int ms) { m_imageMS += ms; } public void addOtherMS(int ms) { m_otherMS += ms; } public void AddPendingDownloads(int count) { m_pendingDownloads += count; if (m_pendingDownloads < 0) m_pendingDownloads = 0; //m_log.InfoFormat("[stats]: Adding {0} to pending downloads to make {1}", count, m_pendingDownloads); } public void addScriptLines(int count) { m_scriptLinesPerSecond += count; } public void AddPacketsStats(int inPackets, int outPackets, int unAckedBytes) { AddInPackets(inPackets); AddOutPackets(outPackets); AddunAckedBytes(unAckedBytes); } #endregion public Dictionary<string, float> GetExtraSimStats() { lock (m_lastReportedExtraSimStats) return new Dictionary<string, float>(m_lastReportedExtraSimStats); } } }
// ----------------------------------------------------------------------- // <copyright file="GossipState.cs" company="Asynkron AB"> // Copyright (C) 2015-2021 Asynkron AB All rights reserved // </copyright> // ----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Google.Protobuf; using Google.Protobuf.WellKnownTypes; using Microsoft.Extensions.Logging; using Proto.Logging; namespace Proto.Cluster.Gossip { public static class GossipStateManagement { private static readonly ILogger Logger = Log.CreateLogger("GossipStateManagement"); private static GossipKeyValue EnsureEntryExists(GossipState.Types.GossipMemberState memberState, string key) { if (memberState.Values.TryGetValue(key, out var value)) return value; value = new GossipKeyValue(); memberState.Values.Add(key, value); return value; } public static GossipState.Types.GossipMemberState EnsureMemberStateExists(GossipState state, string memberId) { if (state.Members.TryGetValue(memberId, out var memberState)) return memberState; memberState = new GossipState.Types.GossipMemberState(); state.Members.Add(memberId, memberState); return memberState; } public static IReadOnlyCollection<GossipUpdate> MergeState(GossipState localState, GossipState remoteState, out GossipState mergedState) { mergedState = localState.Clone(); var updates = new List<GossipUpdate>(); foreach (var (memberId, remoteMemberState) in remoteState.Members) { //this entry does not exist in newState, just copy all of it if (!mergedState.Members.ContainsKey(memberId)) { mergedState.Members.Add(memberId, remoteMemberState); foreach (var entry in remoteMemberState.Values) { updates.Add(new GossipUpdate(memberId,entry.Key,entry.Value.Value,entry.Value.SequenceNumber)); } continue; } //this entry exists in both newState and remoteState, we should merge them var newMemberState = mergedState.Members[memberId]; foreach (var (key, remoteValue) in remoteMemberState.Values) { //this entry does not exist in newMemberState, just copy all of it if (!newMemberState.Values.ContainsKey(key)) { newMemberState.Values.Add(key, remoteValue); updates.Add(new GossipUpdate(memberId,key,remoteValue.Value,remoteValue.SequenceNumber)); continue; } var newValue = newMemberState.Values[key]; //remote value is older, ignore if (remoteValue.SequenceNumber <= newValue.SequenceNumber) continue; //just replace the existing value newMemberState.Values[key] = remoteValue; updates.Add(new GossipUpdate(memberId,key,remoteValue.Value,remoteValue.SequenceNumber)); } } return updates; } public static void SetKey(GossipState state, string key, IMessage value, string memberId, ref long sequenceNo) { //if entry does not exist, add it var memberState = EnsureMemberStateExists(state, memberId); var entry = EnsureEntryExists(memberState, key); sequenceNo++; entry.SequenceNumber = sequenceNo; entry.Value = Any.Pack(value); } public static (ImmutableDictionary<string, long> pendingOffsets, GossipState state) FilterGossipStateForMember(GossipState state, ImmutableDictionary<string, long> offsets, string targetMemberId) { var newState = new GossipState(); var pendingOffsets = offsets; //for each member foreach (var (memberId, memberState) in state.Members) { //we dont need to send back state to the owner of the state if (memberId == targetMemberId) { continue; } //create an empty state var newMemberState = new GossipState.Types.GossipMemberState(); var watermarkKey = $"{targetMemberId}.{memberId}"; //get the watermark offsets.TryGetValue(watermarkKey, out long watermark); var newWatermark = watermark; //for each value in member state foreach (var (key, value) in memberState.Values) { if (value.SequenceNumber <= watermark) continue; if (value.SequenceNumber > newWatermark) newWatermark = value.SequenceNumber; newMemberState.Values.Add(key, value); } //don't send memberStates that we have no new data for if (newMemberState.Values.Count > 0) { newState.Members.Add(memberId, newMemberState); } pendingOffsets = pendingOffsets.SetItem(watermarkKey, newWatermark); } //make sure to clone to make it a separate copy, avoid race conditions on mutate return (pendingOffsets, newState.Clone()); } public static (bool Consensus, ulong TopologyHash) CheckConsensus(IContext ctx, GossipState state, string myId, ImmutableHashSet<string> members) { var logger = ctx.Logger()?.BeginMethodScope(); try { var hashes = new List<(string MemberId,ulong TopologyHash)>(); if (state.Members.Count == 0) { logger?.LogDebug("No members found for consensus check"); } logger?.LogDebug("Checking consensus"); foreach (var (memberId, memberState) in state.Members) { //skip banned members if (!members.Contains(memberId)) { logger?.LogDebug("Member is not part of cluster {MemberId}", memberId); continue; } var topology = memberState.GetTopology(); //member does not yet have a topology, default to empty if (topology == null) { if (memberId == myId) { logger?.LogDebug("I can't find myself"); } else { logger?.LogDebug("Remote: {OtherMemberId} has no topology using TopologyHash 0", memberId); } hashes.Add((memberId,0)); continue; } hashes.Add((memberId,topology.TopologyHash)); logger?.LogDebug("Remote: {OtherMemberId} - {OtherTopologyHash} - {OtherMemberCount}", memberId, topology.TopologyHash, topology.Members.Count); } var first = hashes.FirstOrDefault(); if (hashes.All(h => h.TopologyHash == first.TopologyHash) && first.TopologyHash != 0) { Logger.LogDebug("Reached Consensus {TopologyHash} - {State}", first.TopologyHash, state); logger?.LogDebug("Reached Consensus {TopologyHash} - {State}", first.TopologyHash, state); //all members have the same hash return (true, first.TopologyHash); } Logger.LogDebug("No Consensus {Hashes}, {State}", hashes.Select(h => h.TopologyHash), state); logger?.LogDebug("No Consensus {Hashes}, {State}", hashes.Select(h => h.TopologyHash), state); return (false, 0); } catch (Exception x) { logger?.LogError(x, "Check Consensus failed"); Logger.LogError(x, "Check Consensus failed"); return (false, 0); } // hashes.Add(topology.GetMembershipHashCode()); // // _memberState = _memberState.SetItem(ctn.MemberId, ctn); // var excludeBannedMembers = _memberState.Keys.Where(k => _bannedMembers.Contains(k)); // _memberState = _memberState.RemoveRange(excludeBannedMembers); // // var everyoneInAgreement = _memberState.Values.All(x => x.MembershipHashCode == _currentMembershipHashCode); // // if (everyoneInAgreement && !_topologyConsensus.Task.IsCompleted) // { // //anyone awaiting this instance will now proceed // Logger.LogInformation("[MemberList] Topology consensus"); // _topologyConsensus.TrySetResult(true); // var leaderId = LeaderElection.Elect(_memberState); // var newLeader = _members[leaderId]; // if (!newLeader.Equals(_leader)) // { // _leader = newLeader; // _system.EventStream.Publish(new LeaderElected(newLeader)); // // // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression // if (_leader.Id == _system.Id) // { // Logger.LogInformation("[MemberList] I am leader {Id}", _leader.Id); // } // else // { // Logger.LogInformation("[MemberList] Member {Id} is leader", _leader.Id); // } // } // } // else if (!everyoneInAgreement && _topologyConsensus.Task.IsCompleted) // { // //we toggled from consensus to not consensus. // //create a new completion source for new awaiters to await // _topologyConsensus = new TaskCompletionSource<bool>(); // } // // // // Logger.LogDebug("[MemberList] Got ClusterTopologyNotification {ClusterTopologyNotification}, Consensus {Consensus}, Members {Members}", ctn, everyoneInAgreement,_memberState.Count); // } } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gagr = Google.Api.Gax.ResourceNames; using gcgv = Google.Cloud.Gaming.V1; using sys = System; namespace Google.Cloud.Gaming.V1 { /// <summary>Resource name for the <c>GameServerDeployment</c> resource.</summary> public sealed partial class GameServerDeploymentName : gax::IResourceName, sys::IEquatable<GameServerDeploymentName> { /// <summary>The possible contents of <see cref="GameServerDeploymentName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}</c>. /// </summary> ProjectLocationDeployment = 1, } private static gax::PathTemplate s_projectLocationDeployment = new gax::PathTemplate("projects/{project}/locations/{location}/gameServerDeployments/{deployment}"); /// <summary>Creates a <see cref="GameServerDeploymentName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="GameServerDeploymentName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static GameServerDeploymentName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new GameServerDeploymentName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="GameServerDeploymentName"/> with the pattern /// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// A new instance of <see cref="GameServerDeploymentName"/> constructed from the provided ids. /// </returns> public static GameServerDeploymentName FromProjectLocationDeployment(string projectId, string locationId, string deploymentId) => new GameServerDeploymentName(ResourceNameType.ProjectLocationDeployment, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), deploymentId: gax::GaxPreconditions.CheckNotNullOrEmpty(deploymentId, nameof(deploymentId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="GameServerDeploymentName"/> with pattern /// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="GameServerDeploymentName"/> with pattern /// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}</c>. /// </returns> public static string Format(string projectId, string locationId, string deploymentId) => FormatProjectLocationDeployment(projectId, locationId, deploymentId); /// <summary> /// Formats the IDs into the string representation of this <see cref="GameServerDeploymentName"/> with pattern /// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="GameServerDeploymentName"/> with pattern /// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}</c>. /// </returns> public static string FormatProjectLocationDeployment(string projectId, string locationId, string deploymentId) => s_projectLocationDeployment.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(deploymentId, nameof(deploymentId))); /// <summary> /// Parses the given resource name string into a new <see cref="GameServerDeploymentName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="gameServerDeploymentName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="GameServerDeploymentName"/> if successful.</returns> public static GameServerDeploymentName Parse(string gameServerDeploymentName) => Parse(gameServerDeploymentName, false); /// <summary> /// Parses the given resource name string into a new <see cref="GameServerDeploymentName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="gameServerDeploymentName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="GameServerDeploymentName"/> if successful.</returns> public static GameServerDeploymentName Parse(string gameServerDeploymentName, bool allowUnparsed) => TryParse(gameServerDeploymentName, allowUnparsed, out GameServerDeploymentName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="GameServerDeploymentName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="gameServerDeploymentName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="GameServerDeploymentName"/>, or <c>null</c> if parsing /// failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string gameServerDeploymentName, out GameServerDeploymentName result) => TryParse(gameServerDeploymentName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="GameServerDeploymentName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="gameServerDeploymentName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="GameServerDeploymentName"/>, or <c>null</c> if parsing /// failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string gameServerDeploymentName, bool allowUnparsed, out GameServerDeploymentName result) { gax::GaxPreconditions.CheckNotNull(gameServerDeploymentName, nameof(gameServerDeploymentName)); gax::TemplatedResourceName resourceName; if (s_projectLocationDeployment.TryParseName(gameServerDeploymentName, out resourceName)) { result = FromProjectLocationDeployment(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(gameServerDeploymentName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private GameServerDeploymentName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string deploymentId = null, string locationId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; DeploymentId = deploymentId; LocationId = locationId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="GameServerDeploymentName"/> class from the component parts of /// pattern <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param> public GameServerDeploymentName(string projectId, string locationId, string deploymentId) : this(ResourceNameType.ProjectLocationDeployment, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), deploymentId: gax::GaxPreconditions.CheckNotNullOrEmpty(deploymentId, nameof(deploymentId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Deployment</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string DeploymentId { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationDeployment: return s_projectLocationDeployment.Expand(ProjectId, LocationId, DeploymentId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as GameServerDeploymentName); /// <inheritdoc/> public bool Equals(GameServerDeploymentName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(GameServerDeploymentName a, GameServerDeploymentName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(GameServerDeploymentName a, GameServerDeploymentName b) => !(a == b); } /// <summary>Resource name for the <c>GameServerDeploymentRollout</c> resource.</summary> public sealed partial class GameServerDeploymentRolloutName : gax::IResourceName, sys::IEquatable<GameServerDeploymentRolloutName> { /// <summary>The possible contents of <see cref="GameServerDeploymentRolloutName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout</c>. /// </summary> ProjectLocationDeployment = 1, } private static gax::PathTemplate s_projectLocationDeployment = new gax::PathTemplate("projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout"); /// <summary> /// Creates a <see cref="GameServerDeploymentRolloutName"/> containing an unparsed resource name. /// </summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="GameServerDeploymentRolloutName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static GameServerDeploymentRolloutName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new GameServerDeploymentRolloutName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="GameServerDeploymentRolloutName"/> with the pattern /// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// A new instance of <see cref="GameServerDeploymentRolloutName"/> constructed from the provided ids. /// </returns> public static GameServerDeploymentRolloutName FromProjectLocationDeployment(string projectId, string locationId, string deploymentId) => new GameServerDeploymentRolloutName(ResourceNameType.ProjectLocationDeployment, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), deploymentId: gax::GaxPreconditions.CheckNotNullOrEmpty(deploymentId, nameof(deploymentId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="GameServerDeploymentRolloutName"/> with /// pattern <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="GameServerDeploymentRolloutName"/> with pattern /// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout</c>. /// </returns> public static string Format(string projectId, string locationId, string deploymentId) => FormatProjectLocationDeployment(projectId, locationId, deploymentId); /// <summary> /// Formats the IDs into the string representation of this <see cref="GameServerDeploymentRolloutName"/> with /// pattern <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="GameServerDeploymentRolloutName"/> with pattern /// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout</c>. /// </returns> public static string FormatProjectLocationDeployment(string projectId, string locationId, string deploymentId) => s_projectLocationDeployment.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(deploymentId, nameof(deploymentId))); /// <summary> /// Parses the given resource name string into a new <see cref="GameServerDeploymentRolloutName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="gameServerDeploymentRolloutName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <returns>The parsed <see cref="GameServerDeploymentRolloutName"/> if successful.</returns> public static GameServerDeploymentRolloutName Parse(string gameServerDeploymentRolloutName) => Parse(gameServerDeploymentRolloutName, false); /// <summary> /// Parses the given resource name string into a new <see cref="GameServerDeploymentRolloutName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="gameServerDeploymentRolloutName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="GameServerDeploymentRolloutName"/> if successful.</returns> public static GameServerDeploymentRolloutName Parse(string gameServerDeploymentRolloutName, bool allowUnparsed) => TryParse(gameServerDeploymentRolloutName, allowUnparsed, out GameServerDeploymentRolloutName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="GameServerDeploymentRolloutName"/> /// instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="gameServerDeploymentRolloutName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="GameServerDeploymentRolloutName"/>, or <c>null</c> if /// parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string gameServerDeploymentRolloutName, out GameServerDeploymentRolloutName result) => TryParse(gameServerDeploymentRolloutName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="GameServerDeploymentRolloutName"/> /// instance; optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="gameServerDeploymentRolloutName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="GameServerDeploymentRolloutName"/>, or <c>null</c> if /// parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string gameServerDeploymentRolloutName, bool allowUnparsed, out GameServerDeploymentRolloutName result) { gax::GaxPreconditions.CheckNotNull(gameServerDeploymentRolloutName, nameof(gameServerDeploymentRolloutName)); gax::TemplatedResourceName resourceName; if (s_projectLocationDeployment.TryParseName(gameServerDeploymentRolloutName, out resourceName)) { result = FromProjectLocationDeployment(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(gameServerDeploymentRolloutName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private GameServerDeploymentRolloutName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string deploymentId = null, string locationId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; DeploymentId = deploymentId; LocationId = locationId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="GameServerDeploymentRolloutName"/> class from the component parts /// of pattern <c>projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="deploymentId">The <c>Deployment</c> ID. Must not be <c>null</c> or empty.</param> public GameServerDeploymentRolloutName(string projectId, string locationId, string deploymentId) : this(ResourceNameType.ProjectLocationDeployment, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), deploymentId: gax::GaxPreconditions.CheckNotNullOrEmpty(deploymentId, nameof(deploymentId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Deployment</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string DeploymentId { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationDeployment: return s_projectLocationDeployment.Expand(ProjectId, LocationId, DeploymentId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as GameServerDeploymentRolloutName); /// <inheritdoc/> public bool Equals(GameServerDeploymentRolloutName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(GameServerDeploymentRolloutName a, GameServerDeploymentRolloutName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(GameServerDeploymentRolloutName a, GameServerDeploymentRolloutName b) => !(a == b); } public partial class ListGameServerDeploymentsRequest { /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class GetGameServerDeploymentRequest { /// <summary> /// <see cref="gcgv::GameServerDeploymentName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcgv::GameServerDeploymentName GameServerDeploymentName { get => string.IsNullOrEmpty(Name) ? null : gcgv::GameServerDeploymentName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class GetGameServerDeploymentRolloutRequest { /// <summary> /// <see cref="gcgv::GameServerDeploymentName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcgv::GameServerDeploymentName GameServerDeploymentName { get => string.IsNullOrEmpty(Name) ? null : gcgv::GameServerDeploymentName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class CreateGameServerDeploymentRequest { /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class DeleteGameServerDeploymentRequest { /// <summary> /// <see cref="gcgv::GameServerDeploymentName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcgv::GameServerDeploymentName GameServerDeploymentName { get => string.IsNullOrEmpty(Name) ? null : gcgv::GameServerDeploymentName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class GameServerDeployment { /// <summary> /// <see cref="gcgv::GameServerDeploymentName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcgv::GameServerDeploymentName GameServerDeploymentName { get => string.IsNullOrEmpty(Name) ? null : gcgv::GameServerDeploymentName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class GameServerDeploymentRollout { /// <summary> /// <see cref="gcgv::GameServerDeploymentRolloutName"/>-typed view over the <see cref="Name"/> resource name /// property. /// </summary> public gcgv::GameServerDeploymentRolloutName GameServerDeploymentRolloutName { get => string.IsNullOrEmpty(Name) ? null : gcgv::GameServerDeploymentRolloutName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
using System; using System.Linq; using NUnit.Framework; using VkNet.Enums; using VkNet.Model.RequestParams; namespace VkNet.Tests.Categories.BotsLongPoll { [TestFixture] public class BotsLongPollGroupTest : BotsLongPollBaseTest { [Test] public void GetBotsLongPollHistory_GroupChangePhotoTest() { ReadCategoryJsonPath(nameof(GetBotsLongPollHistory_GroupChangePhotoTest)); const int userId = 123; const int groupId = 1234; const int id = 4444; var botsLongPollHistory = Api.Groups.GetBotsLongPollHistory(new BotsLongPollHistoryParams { Key = "test", Server = "https://vk.com", Ts = "0", Wait = 10 }); var update = botsLongPollHistory.Updates.First(); Assert.AreEqual(groupId, update.GroupId); Assert.AreEqual(userId, update.GroupChangePhoto.UserId); Assert.AreEqual(-groupId, update.GroupChangePhoto.Photo.OwnerId); Assert.AreEqual(id, update.GroupChangePhoto.Photo.Id); } [Test] public void GetBotsLongPollHistory_GroupJoinTest() { ReadCategoryJsonPath(nameof(GetBotsLongPollHistory_GroupJoinTest)); const int userId = 321; const int groupId = 1234; const GroupJoinType joinType = GroupJoinType.Request; var botsLongPollHistory = Api.Groups.GetBotsLongPollHistory(new BotsLongPollHistoryParams { Key = "test", Server = "https://vk.com", Ts = "0", Wait = 10 }); var update = botsLongPollHistory.Updates.First(); Assert.AreEqual(groupId, update.GroupId); Assert.AreEqual(userId, update.GroupJoin.UserId); Assert.AreEqual(joinType, update.GroupJoin.JoinType); } [Test] public void GetBotsLongPollHistory_GroupLeaveTest() { ReadCategoryJsonPath(nameof(GetBotsLongPollHistory_GroupLeaveTest)); const int userId = 321; const int groupId = 1234; var botsLongPollHistory = Api.Groups.GetBotsLongPollHistory(new BotsLongPollHistoryParams { Key = "test", Server = "https://vk.com", Ts = "0", Wait = 10 }); var update = botsLongPollHistory.Updates.First(); Assert.AreEqual(groupId, update.GroupId); Assert.AreEqual(userId, update.GroupLeave.UserId); Assert.IsFalse(update.GroupLeave.IsSelf); } [Test] public void GetBotsLongPollHistory_GroupLeaveSelfTest() { ReadCategoryJsonPath(nameof(GetBotsLongPollHistory_GroupLeaveSelfTest)); const int userId = 321; const int groupId = 1234; var botsLongPollHistory = Api.Groups.GetBotsLongPollHistory(new BotsLongPollHistoryParams { Key = "test", Server = "https://vk.com", Ts = "0", Wait = 10 }); var update = botsLongPollHistory.Updates.First(); Assert.AreEqual(groupId, update.GroupId); Assert.AreEqual(userId, update.GroupLeave.UserId); Assert.IsTrue(update.GroupLeave.IsSelf); } [Test] public void GetBotsLongPollHistory_GroupOfficersEditTest() { ReadCategoryJsonPath(nameof(GetBotsLongPollHistory_GroupOfficersEditTest)); const int userId = 321; const int groupId = 1234; const GroupOfficerLevel oldLevel = GroupOfficerLevel.Admin; const GroupOfficerLevel newLevel = GroupOfficerLevel.Editor; var botsLongPollHistory = Api.Groups.GetBotsLongPollHistory(new BotsLongPollHistoryParams { Key = "test", Server = "https://vk.com", Ts = "0", Wait = 10 }); var update = botsLongPollHistory.Updates.First(); Assert.AreEqual(groupId, update.GroupId); Assert.AreEqual(userId, update.GroupOfficersEdit.UserId); Assert.AreEqual(oldLevel, update.GroupOfficersEdit.LevelOld); Assert.AreEqual(newLevel, update.GroupOfficersEdit.LevelNew); } [Test] public void GetBotsLongPollHistory_UserBlockTest() { ReadCategoryJsonPath(nameof(GetBotsLongPollHistory_UserBlockTest)); const int userId = 321; const int groupId = 1234; const int adminId = 123; const string comment = "test"; const BanReason reason = BanReason.Other; var botsLongPollHistory = Api.Groups.GetBotsLongPollHistory(new BotsLongPollHistoryParams { Key = "test", Server = "https://vk.com", Ts = "0", Wait = 10 }); var update = botsLongPollHistory.Updates.First(); Assert.AreEqual(groupId, update.GroupId); Assert.AreEqual(userId, update.UserBlock.UserId); Assert.AreEqual(adminId, update.UserBlock.AdminId); Assert.AreEqual(comment, update.UserBlock.Comment); Assert.AreEqual(reason, update.UserBlock.Reason); Assert.IsNull(update.UserBlock.UnblockDate); } [Test] public void GetBotsLongPollHistory_UserBlockTemporaryTest() { ReadCategoryJsonPath(nameof(GetBotsLongPollHistory_UserBlockTemporaryTest)); const int userId = 321; const int groupId = 1234; const int adminId = 123; const string comment = "test"; const BanReason reason = BanReason.IrrelevantMessages; var unblockDate = new DateTime(2018, 8, 6, 21, 0, 0); var botsLongPollHistory = Api.Groups.GetBotsLongPollHistory(new BotsLongPollHistoryParams { Key = "test", Server = "https://vk.com", Ts = "0", Wait = 10 }); var update = botsLongPollHistory.Updates.First(); Assert.AreEqual(groupId, update.GroupId); Assert.AreEqual(userId, update.UserBlock.UserId); Assert.AreEqual(adminId, update.UserBlock.AdminId); Assert.AreEqual(comment, update.UserBlock.Comment); Assert.AreEqual(reason, update.UserBlock.Reason); Assert.AreEqual(unblockDate, update.UserBlock.UnblockDate); } [Test] public void GetBotsLongPollHistory_UserUnblockTest() { ReadCategoryJsonPath(nameof(GetBotsLongPollHistory_UserUnblockTest)); const int userId = 321; const int groupId = 1234; const int adminId = 123; var botsLongPollHistory = Api.Groups.GetBotsLongPollHistory(new BotsLongPollHistoryParams { Key = "test", Server = "https://vk.com", Ts = "0", Wait = 10 }); var update = botsLongPollHistory.Updates.First(); Assert.AreEqual(groupId, update.GroupId); Assert.AreEqual(userId, update.UserUnblock.UserId); Assert.AreEqual(adminId, update.UserUnblock.AdminId); Assert.IsFalse(update.UserUnblock.ByEndDate); } [Test] public void GetBotsLongPollHistory_UserUnblockByEndDateTest() { ReadCategoryJsonPath(nameof(GetBotsLongPollHistory_UserUnblockByEndDateTest)); const int userId = 321; const int groupId = 1234; const int adminId = 123; var botsLongPollHistory = Api.Groups.GetBotsLongPollHistory(new BotsLongPollHistoryParams { Key = "test", Server = "https://vk.com", Ts = "0", Wait = 10 }); var update = botsLongPollHistory.Updates.First(); Assert.AreEqual(groupId, update.GroupId); Assert.AreEqual(userId, update.UserUnblock.UserId); Assert.AreEqual(adminId, update.UserUnblock.AdminId); Assert.IsTrue(update.UserUnblock.ByEndDate); } [Test] public void GetBotsLongPollHistory_PollVoteNewTest() { ReadCategoryJsonPath(nameof(GetBotsLongPollHistory_PollVoteNewTest)); const int userId = 123; const int groupId = 1234; const int optionId = 3333; const int pollId = 4444; var botsLongPollHistory = Api.Groups.GetBotsLongPollHistory(new BotsLongPollHistoryParams { Key = "test", Server = "https://vk.com", Ts = "0", Wait = 10 }); var update = botsLongPollHistory.Updates.First(); Assert.AreEqual(groupId, update.GroupId); Assert.AreEqual(userId, update.PollVoteNew.UserId); Assert.AreEqual(optionId, update.PollVoteNew.OptionId); Assert.AreEqual(pollId, update.PollVoteNew.PollId); } } }
using System; using System.Runtime.InteropServices; namespace SharpShell.Interop { /// <summary> /// Exposes methods that manipulate and interact with image lists. /// </summary> [ComImport] [Guid("46EB5926-582E-4017-9FDF-E8998DAA0950")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IImageList { /// <summary> /// Adds an image or images to an image list. /// </summary> /// <param name="hbmImage">A handle to the bitmap that contains the image or images. The number of images is inferred from the width of the bitmap.</param> /// <param name="hbmMask">A handle to the bitmap that contains the mask. If no mask is used with the image list, this parameter is ignored.</param> /// <param name="pi">When this method returns, contains a pointer to the index of the first new image. If the method fails to successfully add the new image, this value is -1.</param> /// <returns>If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [PreserveSig] int Add(IntPtr hbmImage, IntPtr hbmMask, ref int pi); /// <summary> /// Replaces an image with an icon or cursor. /// </summary> /// <param name="i">A value of type int that contains the index of the image to replace. If i is -1, the function adds the image to the end of the list.</param> /// <param name="hicon">A handle to the icon or cursor that contains the bitmap and mask for the new image.</param> /// <param name="pi">A pointer to an int that will contain the index of the image on return if successful, or -1 otherwise.</param> /// <returns>If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [PreserveSig] int ReplaceIcon(int i, IntPtr hicon, ref int pi); /// <summary> /// Adds a specified image to the list of images used as overlay masks. An image list can have up to four overlay masks in Common Controls version 4.70 and earlier, and up to 15 in version 4.71 or later. The method assigns an overlay mask index to the specified image. /// </summary> /// <param name="iImage">A value of type int that contains the zero-based index of an image in the image list. This index identifies the image to use as an overlay mask.</param> /// <param name="iOverlay">A value of type int that contains the one-based index of the overlay mask.</param> /// <returns>If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [PreserveSig] int SetOverlayImage(int iImage, int iOverlay); /// <summary> /// Replaces an image in an image list with a new image. /// </summary> /// <param name="i">A value of type int that contains the index of the image to replace.</param> /// <param name="hbmImage">A handle to the bitmap that contains the image.</param> /// <param name="hbmMask">A handle to the bitmap that contains the mask. If no mask is used with the image list, this parameter is ignored.</param> /// <returns>If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [PreserveSig] int Replace(int i, IntPtr hbmImage, IntPtr hbmMask); /// <summary> /// Adds an image or images to an image list, generating a mask from the specified bitmap. /// </summary> /// <param name="hbmImage">A handle to the bitmap that contains one or more images. The number of images is inferred from the width of the bitmap.</param> /// <param name="crMask">The color used to generate the mask. Each pixel of this color in the specified bitmap is changed to black, and the corresponding bit in the mask is set to 1.</param> /// <param name="pi">A pointer to an int that contains the index of the first new image when it returns, if successful, or -1 otherwise.</param> /// <returns>If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [PreserveSig] int AddMasked(IntPtr hbmImage, int crMask, ref int pi); /// <summary> /// Draws an image list item in the specified device context. /// </summary> /// <param name="pimldp">A pointer to an IMAGELISTDRAWPARAMS structure that contains the drawing parameters.</param> /// <returns>If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [PreserveSig] int Draw( ref IMAGELISTDRAWPARAMS pimldp); /// <summary> /// Removes an image from an image list. /// </summary> /// <param name="i">A value of type int that contains the index of the image to remove. If this parameter is -1, the method removes all images.</param> /// <returns>If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [PreserveSig] int Remove(int i); /// <summary> /// Creates an icon from an image and a mask in an image list. /// </summary> /// <param name="i">A value of type int that contains the index of the image.</param> /// <param name="flags">A combination of flags that specify the drawing style. For a list of values, see IImageList::Draw.</param> /// <param name="picon">A pointer to an int that contains the handle to the icon if successful, or NULL if otherwise.</param> /// <returns>If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [PreserveSig] int GetIcon(int i, int flags, ref IntPtr picon); /// <summary> /// Gets information about an image. /// </summary> /// <param name="i">A value of type int that contains the index of the image.</param> /// <param name="pImageInfo">A pointer to an IMAGEINFO structure that receives information about the image. The information in this structure can directly manipulate the bitmaps of the image.</param> /// <returns>If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [PreserveSig] int GetImageInfo(int i, ref IMAGEINFO pImageInfo); /// <summary> /// Copies images from a given image list. /// </summary> /// <param name="iDst">A value of type int that contains the zero-based index of the destination image for the copy operation.</param> /// <param name="punkSrc">A pointer to the IUnknown interface for the source image list.</param> /// <param name="iSrc">A value of type int that contains the zero-based index of the source image for the copy operation.</param> /// <param name="uFlags">A value that specifies the type of copy operation to be made.</param> /// <returns>If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [PreserveSig] int Copy(int iDst, IImageList punkSrc, int iSrc, int uFlags); /// <summary> /// Creates a new image by combining two existing images. This method also creates a new image list in which to store the image. /// </summary> /// <param name="i1">A value of type int that contains the index of the first existing image.</param> /// <param name="punk2">A pointer to the IUnknown interface of the image list that contains the second image.</param> /// <param name="i2">A value of type int that contains the index of the second existing image.</param> /// <param name="dx">A value of type int that contains the x-component of the offset of the second image relative to the first image.</param> /// <param name="dy">A value of type int that contains the y-component of the offset of the second image relative to the first image.</param> /// <param name="riid">An IID of the interface for the new image list.</param> /// <param name="ppv">A raw pointer to the interface for the new image list.</param> /// <returns>If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [PreserveSig] int Merge(int i1, IImageList punk2, int i2, int dx, int dy, ref Guid riid, ref IntPtr ppv); /// <summary> /// Clones an existing image list. /// </summary> /// <param name="riid">An IID for the new image list.</param> /// <param name="ppv">The address of a pointer to the interface for the new image list.</param> /// <returns>If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [PreserveSig] int Clone(ref Guid riid, ref IntPtr ppv); /// <summary> /// Gets an image's bounding rectangle. /// </summary> /// <param name="i">A value of type int that contains the index of the image.</param> /// <param name="prc">A pointer to a RECT that contains the bounding rectangle when the method returns.</param> /// <returns>If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [PreserveSig] int GetImageRect(int i, ref RECT prc); /// <summary> /// Gets the dimensions of images in an image list. All images in an image list have the same dimensions. /// </summary> /// <param name="cx">A pointer to an int that receives the width, in pixels, of each image.</param> /// <param name="cy">A pointer to an int that receives the height, in pixels, of each image.</param> /// <returns>If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [PreserveSig] int GetIconSize(ref int cx, ref int cy); /// <summary> /// Sets the dimensions of images in an image list and removes all images from the list. /// </summary> /// <param name="cx">A value of type int that contains the width, in pixels, of the images in the image list. All images in an image list have the same dimensions.</param> /// <param name="cy">A value of type int that contains the height, in pixels, of the images in the image list. All images in an image list have the same dimensions.</param> /// <returns>If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [PreserveSig] int SetIconSize(int cx, int cy); /// <summary> /// Gets the number of images in an image list. /// </summary> /// <param name="pi">A pointer to an int that contains the number of images when the method returns.</param> /// <returns>If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [PreserveSig] int GetImageCount(ref int pi); /// <summary> /// Resizes an existing image list. /// </summary> /// <param name="uNewCount">A value that specifies the new size of the image list.</param> /// <returns>If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [PreserveSig] int SetImageCount(int uNewCount); /// <summary> /// Sets the background color for an image list. This method only functions if you add an icon to the image list or use the IImageList::AddMasked method to add a black and white bitmap. Without a mask, the entire image draws, and the background color is not visible. /// </summary> /// <param name="clrBk">The background color to set. If this parameter is set to CLR_NONE, then images draw transparently using the mask.</param> /// <param name="pclr">A pointer to a COLORREF that contains the previous background color on return if successful, or CLR_NONE otherwise.</param> /// <returns>If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [PreserveSig] int SetBkColor(int clrBk, ref int pclr); /// <summary> /// Gets the current background color for an image list. /// </summary> /// <param name="pclr">A pointer to a COLORREF that contains the background color when the method returns.</param> /// <returns>If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [PreserveSig] int GetBkColor(ref int pclr); /// <summary> /// Begins dragging an image. /// </summary> /// <param name="iTrack">A value of type int that contains the index of the image to drag.</param> /// <param name="dxHotspot">A value of type int that contains the x-component of the drag position relative to the upper-left corner of the image.</param> /// <param name="dyHotspot">A value of type int that contains the y-component of the drag position relative to the upper-left corner of the image.</param> /// <returns>If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [PreserveSig] int BeginDrag(int iTrack, int dxHotspot, int dyHotspot); /// <summary> /// Ends a drag operation. /// </summary> /// <returns>If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [PreserveSig] int EndDrag(); /// <summary> /// Locks updates to the specified window during a drag operation and displays the drag image at the specified position within the window. /// </summary> /// <param name="hwndLock">A handle to the window that owns the drag image.</param> /// <param name="x">The x-coordinate at which to display the drag image. The coordinate is relative to the upper-left corner of the window, not the client area.</param> /// <param name="y">The y-coordinate at which to display the drag image. The coordinate is relative to the upper-left corner of the window, not the client area.</param> /// <returns>If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [PreserveSig] int DragEnter(IntPtr hwndLock, int x, int y); /// <summary> /// Unlocks the specified window and hides the drag image, which enables the window to update. /// </summary> /// <param name="hwndLock">A handle to the window that contains the drag image.</param> /// <returns>If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [PreserveSig] int DragLeave(IntPtr hwndLock); /// <summary> /// Moves the image that is being dragged during a drag-and-drop operation. This function is typically called in response to a WM_MOUSEMOVE message. /// </summary> /// <param name="x">A value of type int that contains the x-coordinate where the drag image appears. The coordinate is relative to the upper-left corner of the window, not the client area.</param> /// <param name="y">A value of type int that contains the y-coordinate where the drag image appears. The coordinate is relative to the upper-left corner of the window, not the client area.</param> /// <returns>If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [PreserveSig] int DragMove(int x, int y); /// <summary> /// Creates a new drag image by combining the specified image, which is typically a mouse cursor image, with the current drag image. /// </summary> /// <param name="punk">A pointer to the IUnknown interface that accesses the image list interface, which contains the new image to combine with the drag image.</param> /// <param name="iDrag">A value of type int that contains the index of the new image to combine with the drag image.</param> /// <param name="dxHotspot">A value of type int that contains the x-component of the hot spot within the new image.</param> /// <param name="dyHotspot">A value of type int that contains the x-component of the hot spot within the new image.</param> /// <returns>If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [PreserveSig] int SetDragCursorImage(ref IImageList punk, int iDrag, int dxHotspot, int dyHotspot); /// <summary> /// Shows or hides the image being dragged. /// </summary> /// <param name="fShow">A value that specifies whether to show or hide the image being dragged. Specify TRUE to show the image or FALSE to hide the image.</param> /// <returns>If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [PreserveSig] int DragShowNolock(int fShow); /// <summary> /// Gets the temporary image list that is used for the drag image. The function also retrieves the current drag position and the offset of the drag image relative to the drag position. /// </summary> /// <param name="ppt">A pointer to a POINT structure that receives the current drag position. Can be NULL.</param> /// <param name="pptHotspot">A pointer to a POINT structure that receives the offset of the drag image relative to the drag position. Can be NULL.</param> /// <param name="riid">An IID for the image list.</param> /// <param name="ppv">The address of a pointer to the interface for the image list if successful, NULL otherwise.</param> /// <returns>If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [PreserveSig] int GetDragImage(ref POINT ppt, ref POINT pptHotspot, ref Guid riid, ref IntPtr ppv); /// <summary> /// Gets the flags of an image. /// </summary> /// <param name="i">A value of type int that contains the index of the images whose flags need to be retrieved.</param> /// <param name="dwFlags">A pointer to a DWORD that contains the flags when the method returns. One of the following values:</param> /// <returns>If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [PreserveSig] int GetItemFlags(int i, ref int dwFlags); /// <summary> /// Retrieves a specified image from the list of images used as overlay masks. /// </summary> /// <param name="iOverlay">A value of type int that contains the one-based index of the overlay mask.</param> /// <param name="piIndex">A pointer to an int that receives the zero-based index of an image in the image list. This index identifies the image that is used as an overlay mask.</param> /// <returns>If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns> [PreserveSig] int GetOverlayImage(int iOverlay, ref int piIndex); }; }
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using System.Text; using System.Collections.Generic; using Adaptive.Agrona; namespace Adaptive.Archiver.Codecs { public class ListRecordingRequestDecoder { public const ushort BLOCK_LENGTH = 24; public const ushort TEMPLATE_ID = 10; public const ushort SCHEMA_ID = 101; public const ushort SCHEMA_VERSION = 6; private ListRecordingRequestDecoder _parentMessage; private IDirectBuffer _buffer; protected int _offset; protected int _limit; protected int _actingBlockLength; protected int _actingVersion; public ListRecordingRequestDecoder() { _parentMessage = this; } public ushort SbeBlockLength() { return BLOCK_LENGTH; } public ushort SbeTemplateId() { return TEMPLATE_ID; } public ushort SbeSchemaId() { return SCHEMA_ID; } public ushort SbeSchemaVersion() { return SCHEMA_VERSION; } public string SbeSemanticType() { return ""; } public IDirectBuffer Buffer() { return _buffer; } public int Offset() { return _offset; } public ListRecordingRequestDecoder Wrap( IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion) { this._buffer = buffer; this._offset = offset; this._actingBlockLength = actingBlockLength; this._actingVersion = actingVersion; Limit(offset + actingBlockLength); return this; } public int EncodedLength() { return _limit - _offset; } public int Limit() { return _limit; } public void Limit(int limit) { this._limit = limit; } public static int ControlSessionIdId() { return 1; } public static int ControlSessionIdSinceVersion() { return 0; } public static int ControlSessionIdEncodingOffset() { return 0; } public static int ControlSessionIdEncodingLength() { return 8; } public static string ControlSessionIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long ControlSessionIdNullValue() { return -9223372036854775808L; } public static long ControlSessionIdMinValue() { return -9223372036854775807L; } public static long ControlSessionIdMaxValue() { return 9223372036854775807L; } public long ControlSessionId() { return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian); } public static int CorrelationIdId() { return 2; } public static int CorrelationIdSinceVersion() { return 0; } public static int CorrelationIdEncodingOffset() { return 8; } public static int CorrelationIdEncodingLength() { return 8; } public static string CorrelationIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long CorrelationIdNullValue() { return -9223372036854775808L; } public static long CorrelationIdMinValue() { return -9223372036854775807L; } public static long CorrelationIdMaxValue() { return 9223372036854775807L; } public long CorrelationId() { return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian); } public static int RecordingIdId() { return 3; } public static int RecordingIdSinceVersion() { return 0; } public static int RecordingIdEncodingOffset() { return 16; } public static int RecordingIdEncodingLength() { return 8; } public static string RecordingIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long RecordingIdNullValue() { return -9223372036854775808L; } public static long RecordingIdMinValue() { return -9223372036854775807L; } public static long RecordingIdMaxValue() { return 9223372036854775807L; } public long RecordingId() { return _buffer.GetLong(_offset + 16, ByteOrder.LittleEndian); } public override string ToString() { return AppendTo(new StringBuilder(100)).ToString(); } public StringBuilder AppendTo(StringBuilder builder) { int originalLimit = Limit(); Limit(_offset + _actingBlockLength); builder.Append("[ListRecordingRequest](sbeTemplateId="); builder.Append(TEMPLATE_ID); builder.Append("|sbeSchemaId="); builder.Append(SCHEMA_ID); builder.Append("|sbeSchemaVersion="); if (_parentMessage._actingVersion != SCHEMA_VERSION) { builder.Append(_parentMessage._actingVersion); builder.Append('/'); } builder.Append(SCHEMA_VERSION); builder.Append("|sbeBlockLength="); if (_actingBlockLength != BLOCK_LENGTH) { builder.Append(_actingBlockLength); builder.Append('/'); } builder.Append(BLOCK_LENGTH); builder.Append("):"); //Token{signal=BEGIN_FIELD, name='controlSessionId', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("ControlSessionId="); builder.Append(ControlSessionId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='correlationId', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("CorrelationId="); builder.Append(CorrelationId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='recordingId', referencedName='null', description='null', id=3, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=16, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("RecordingId="); builder.Append(RecordingId()); Limit(originalLimit); return builder; } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V9.Services { /// <summary>Settings for <see cref="ReachPlanServiceClient"/> instances.</summary> public sealed partial class ReachPlanServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="ReachPlanServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="ReachPlanServiceSettings"/>.</returns> public static ReachPlanServiceSettings GetDefault() => new ReachPlanServiceSettings(); /// <summary>Constructs a new <see cref="ReachPlanServiceSettings"/> object with default settings.</summary> public ReachPlanServiceSettings() { } private ReachPlanServiceSettings(ReachPlanServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); ListPlannableLocationsSettings = existing.ListPlannableLocationsSettings; ListPlannableProductsSettings = existing.ListPlannableProductsSettings; GenerateProductMixIdeasSettings = existing.GenerateProductMixIdeasSettings; GenerateReachForecastSettings = existing.GenerateReachForecastSettings; OnCopy(existing); } partial void OnCopy(ReachPlanServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>ReachPlanServiceClient.ListPlannableLocations</c> and /// <c>ReachPlanServiceClient.ListPlannableLocationsAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings ListPlannableLocationsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>ReachPlanServiceClient.ListPlannableProducts</c> and <c>ReachPlanServiceClient.ListPlannableProductsAsync</c> /// . /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings ListPlannableProductsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>ReachPlanServiceClient.GenerateProductMixIdeas</c> and /// <c>ReachPlanServiceClient.GenerateProductMixIdeasAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GenerateProductMixIdeasSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>ReachPlanServiceClient.GenerateReachForecast</c> and <c>ReachPlanServiceClient.GenerateReachForecastAsync</c> /// . /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GenerateReachForecastSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="ReachPlanServiceSettings"/> object.</returns> public ReachPlanServiceSettings Clone() => new ReachPlanServiceSettings(this); } /// <summary> /// Builder class for <see cref="ReachPlanServiceClient"/> to provide simple configuration of credentials, endpoint /// etc. /// </summary> internal sealed partial class ReachPlanServiceClientBuilder : gaxgrpc::ClientBuilderBase<ReachPlanServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public ReachPlanServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public ReachPlanServiceClientBuilder() { UseJwtAccessWithScopes = ReachPlanServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref ReachPlanServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<ReachPlanServiceClient> task); /// <summary>Builds the resulting client.</summary> public override ReachPlanServiceClient Build() { ReachPlanServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<ReachPlanServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<ReachPlanServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private ReachPlanServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return ReachPlanServiceClient.Create(callInvoker, Settings); } private async stt::Task<ReachPlanServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return ReachPlanServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => ReachPlanServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => ReachPlanServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => ReachPlanServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>ReachPlanService client wrapper, for convenient use.</summary> /// <remarks> /// Reach Plan Service gives users information about audience size that can /// be reached through advertisement on YouTube. In particular, /// GenerateReachForecast provides estimated number of people of specified /// demographics that can be reached by an ad in a given market by a campaign of /// certain duration with a defined budget. /// </remarks> public abstract partial class ReachPlanServiceClient { /// <summary> /// The default endpoint for the ReachPlanService service, which is a host of "googleads.googleapis.com" and a /// port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default ReachPlanService scopes.</summary> /// <remarks> /// The default ReachPlanService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="ReachPlanServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="ReachPlanServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="ReachPlanServiceClient"/>.</returns> public static stt::Task<ReachPlanServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new ReachPlanServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="ReachPlanServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="ReachPlanServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="ReachPlanServiceClient"/>.</returns> public static ReachPlanServiceClient Create() => new ReachPlanServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="ReachPlanServiceClient"/> which uses the specified call invoker for remote operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="ReachPlanServiceSettings"/>.</param> /// <returns>The created <see cref="ReachPlanServiceClient"/>.</returns> internal static ReachPlanServiceClient Create(grpccore::CallInvoker callInvoker, ReachPlanServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } ReachPlanService.ReachPlanServiceClient grpcClient = new ReachPlanService.ReachPlanServiceClient(callInvoker); return new ReachPlanServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC ReachPlanService client</summary> public virtual ReachPlanService.ReachPlanServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the list of plannable locations (for example, countries &amp;amp; DMAs). /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual ListPlannableLocationsResponse ListPlannableLocations(ListPlannableLocationsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the list of plannable locations (for example, countries &amp;amp; DMAs). /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<ListPlannableLocationsResponse> ListPlannableLocationsAsync(ListPlannableLocationsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the list of plannable locations (for example, countries &amp;amp; DMAs). /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<ListPlannableLocationsResponse> ListPlannableLocationsAsync(ListPlannableLocationsRequest request, st::CancellationToken cancellationToken) => ListPlannableLocationsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the list of per-location plannable YouTube ad formats with allowed /// targeting. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual ListPlannableProductsResponse ListPlannableProducts(ListPlannableProductsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the list of per-location plannable YouTube ad formats with allowed /// targeting. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<ListPlannableProductsResponse> ListPlannableProductsAsync(ListPlannableProductsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the list of per-location plannable YouTube ad formats with allowed /// targeting. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<ListPlannableProductsResponse> ListPlannableProductsAsync(ListPlannableProductsRequest request, st::CancellationToken cancellationToken) => ListPlannableProductsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the list of per-location plannable YouTube ad formats with allowed /// targeting. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="plannableLocationId"> /// Required. The ID of the selected location for planning. To list the available /// plannable location ids use [ReachPlanService.ListPlannableLocations][google.ads.googleads.v9.services.ReachPlanService.ListPlannableLocations]. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual ListPlannableProductsResponse ListPlannableProducts(string plannableLocationId, gaxgrpc::CallSettings callSettings = null) => ListPlannableProducts(new ListPlannableProductsRequest { PlannableLocationId = gax::GaxPreconditions.CheckNotNullOrEmpty(plannableLocationId, nameof(plannableLocationId)), }, callSettings); /// <summary> /// Returns the list of per-location plannable YouTube ad formats with allowed /// targeting. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="plannableLocationId"> /// Required. The ID of the selected location for planning. To list the available /// plannable location ids use [ReachPlanService.ListPlannableLocations][google.ads.googleads.v9.services.ReachPlanService.ListPlannableLocations]. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<ListPlannableProductsResponse> ListPlannableProductsAsync(string plannableLocationId, gaxgrpc::CallSettings callSettings = null) => ListPlannableProductsAsync(new ListPlannableProductsRequest { PlannableLocationId = gax::GaxPreconditions.CheckNotNullOrEmpty(plannableLocationId, nameof(plannableLocationId)), }, callSettings); /// <summary> /// Returns the list of per-location plannable YouTube ad formats with allowed /// targeting. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="plannableLocationId"> /// Required. The ID of the selected location for planning. To list the available /// plannable location ids use [ReachPlanService.ListPlannableLocations][google.ads.googleads.v9.services.ReachPlanService.ListPlannableLocations]. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<ListPlannableProductsResponse> ListPlannableProductsAsync(string plannableLocationId, st::CancellationToken cancellationToken) => ListPlannableProductsAsync(plannableLocationId, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Generates a product mix ideas given a set of preferences. This method /// helps the advertiser to obtain a good mix of ad formats and budget /// allocations based on its preferences. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [ReachPlanError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual GenerateProductMixIdeasResponse GenerateProductMixIdeas(GenerateProductMixIdeasRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Generates a product mix ideas given a set of preferences. This method /// helps the advertiser to obtain a good mix of ad formats and budget /// allocations based on its preferences. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [ReachPlanError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<GenerateProductMixIdeasResponse> GenerateProductMixIdeasAsync(GenerateProductMixIdeasRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Generates a product mix ideas given a set of preferences. This method /// helps the advertiser to obtain a good mix of ad formats and budget /// allocations based on its preferences. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [ReachPlanError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<GenerateProductMixIdeasResponse> GenerateProductMixIdeasAsync(GenerateProductMixIdeasRequest request, st::CancellationToken cancellationToken) => GenerateProductMixIdeasAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Generates a product mix ideas given a set of preferences. This method /// helps the advertiser to obtain a good mix of ad formats and budget /// allocations based on its preferences. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [ReachPlanError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer. /// </param> /// <param name="plannableLocationId"> /// Required. The ID of the location, this is one of the ids returned by /// [ReachPlanService.ListPlannableLocations][google.ads.googleads.v9.services.ReachPlanService.ListPlannableLocations]. /// </param> /// <param name="currencyCode"> /// Required. Currency code. /// Three-character ISO 4217 currency code. /// </param> /// <param name="budgetMicros"> /// Required. Total budget. /// Amount in micros. One million is equivalent to one unit. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual GenerateProductMixIdeasResponse GenerateProductMixIdeas(string customerId, string plannableLocationId, string currencyCode, long budgetMicros, gaxgrpc::CallSettings callSettings = null) => GenerateProductMixIdeas(new GenerateProductMixIdeasRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), PlannableLocationId = gax::GaxPreconditions.CheckNotNullOrEmpty(plannableLocationId, nameof(plannableLocationId)), CurrencyCode = gax::GaxPreconditions.CheckNotNullOrEmpty(currencyCode, nameof(currencyCode)), BudgetMicros = budgetMicros, }, callSettings); /// <summary> /// Generates a product mix ideas given a set of preferences. This method /// helps the advertiser to obtain a good mix of ad formats and budget /// allocations based on its preferences. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [ReachPlanError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer. /// </param> /// <param name="plannableLocationId"> /// Required. The ID of the location, this is one of the ids returned by /// [ReachPlanService.ListPlannableLocations][google.ads.googleads.v9.services.ReachPlanService.ListPlannableLocations]. /// </param> /// <param name="currencyCode"> /// Required. Currency code. /// Three-character ISO 4217 currency code. /// </param> /// <param name="budgetMicros"> /// Required. Total budget. /// Amount in micros. One million is equivalent to one unit. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<GenerateProductMixIdeasResponse> GenerateProductMixIdeasAsync(string customerId, string plannableLocationId, string currencyCode, long budgetMicros, gaxgrpc::CallSettings callSettings = null) => GenerateProductMixIdeasAsync(new GenerateProductMixIdeasRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), PlannableLocationId = gax::GaxPreconditions.CheckNotNullOrEmpty(plannableLocationId, nameof(plannableLocationId)), CurrencyCode = gax::GaxPreconditions.CheckNotNullOrEmpty(currencyCode, nameof(currencyCode)), BudgetMicros = budgetMicros, }, callSettings); /// <summary> /// Generates a product mix ideas given a set of preferences. This method /// helps the advertiser to obtain a good mix of ad formats and budget /// allocations based on its preferences. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [ReachPlanError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer. /// </param> /// <param name="plannableLocationId"> /// Required. The ID of the location, this is one of the ids returned by /// [ReachPlanService.ListPlannableLocations][google.ads.googleads.v9.services.ReachPlanService.ListPlannableLocations]. /// </param> /// <param name="currencyCode"> /// Required. Currency code. /// Three-character ISO 4217 currency code. /// </param> /// <param name="budgetMicros"> /// Required. Total budget. /// Amount in micros. One million is equivalent to one unit. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<GenerateProductMixIdeasResponse> GenerateProductMixIdeasAsync(string customerId, string plannableLocationId, string currencyCode, long budgetMicros, st::CancellationToken cancellationToken) => GenerateProductMixIdeasAsync(customerId, plannableLocationId, currencyCode, budgetMicros, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Generates a reach forecast for a given targeting / product mix. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RangeError]() /// [ReachPlanError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual GenerateReachForecastResponse GenerateReachForecast(GenerateReachForecastRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Generates a reach forecast for a given targeting / product mix. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RangeError]() /// [ReachPlanError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<GenerateReachForecastResponse> GenerateReachForecastAsync(GenerateReachForecastRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Generates a reach forecast for a given targeting / product mix. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RangeError]() /// [ReachPlanError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<GenerateReachForecastResponse> GenerateReachForecastAsync(GenerateReachForecastRequest request, st::CancellationToken cancellationToken) => GenerateReachForecastAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Generates a reach forecast for a given targeting / product mix. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RangeError]() /// [ReachPlanError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer. /// </param> /// <param name="campaignDuration"> /// Required. Campaign duration. /// </param> /// <param name="plannedProducts"> /// Required. The products to be forecast. /// The max number of allowed planned products is 15. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual GenerateReachForecastResponse GenerateReachForecast(string customerId, CampaignDuration campaignDuration, scg::IEnumerable<PlannedProduct> plannedProducts, gaxgrpc::CallSettings callSettings = null) => GenerateReachForecast(new GenerateReachForecastRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), CampaignDuration = gax::GaxPreconditions.CheckNotNull(campaignDuration, nameof(campaignDuration)), PlannedProducts = { gax::GaxPreconditions.CheckNotNull(plannedProducts, nameof(plannedProducts)), }, }, callSettings); /// <summary> /// Generates a reach forecast for a given targeting / product mix. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RangeError]() /// [ReachPlanError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer. /// </param> /// <param name="campaignDuration"> /// Required. Campaign duration. /// </param> /// <param name="plannedProducts"> /// Required. The products to be forecast. /// The max number of allowed planned products is 15. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<GenerateReachForecastResponse> GenerateReachForecastAsync(string customerId, CampaignDuration campaignDuration, scg::IEnumerable<PlannedProduct> plannedProducts, gaxgrpc::CallSettings callSettings = null) => GenerateReachForecastAsync(new GenerateReachForecastRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), CampaignDuration = gax::GaxPreconditions.CheckNotNull(campaignDuration, nameof(campaignDuration)), PlannedProducts = { gax::GaxPreconditions.CheckNotNull(plannedProducts, nameof(plannedProducts)), }, }, callSettings); /// <summary> /// Generates a reach forecast for a given targeting / product mix. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RangeError]() /// [ReachPlanError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer. /// </param> /// <param name="campaignDuration"> /// Required. Campaign duration. /// </param> /// <param name="plannedProducts"> /// Required. The products to be forecast. /// The max number of allowed planned products is 15. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<GenerateReachForecastResponse> GenerateReachForecastAsync(string customerId, CampaignDuration campaignDuration, scg::IEnumerable<PlannedProduct> plannedProducts, st::CancellationToken cancellationToken) => GenerateReachForecastAsync(customerId, campaignDuration, plannedProducts, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>ReachPlanService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Reach Plan Service gives users information about audience size that can /// be reached through advertisement on YouTube. In particular, /// GenerateReachForecast provides estimated number of people of specified /// demographics that can be reached by an ad in a given market by a campaign of /// certain duration with a defined budget. /// </remarks> public sealed partial class ReachPlanServiceClientImpl : ReachPlanServiceClient { private readonly gaxgrpc::ApiCall<ListPlannableLocationsRequest, ListPlannableLocationsResponse> _callListPlannableLocations; private readonly gaxgrpc::ApiCall<ListPlannableProductsRequest, ListPlannableProductsResponse> _callListPlannableProducts; private readonly gaxgrpc::ApiCall<GenerateProductMixIdeasRequest, GenerateProductMixIdeasResponse> _callGenerateProductMixIdeas; private readonly gaxgrpc::ApiCall<GenerateReachForecastRequest, GenerateReachForecastResponse> _callGenerateReachForecast; /// <summary> /// Constructs a client wrapper for the ReachPlanService service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="ReachPlanServiceSettings"/> used within this client.</param> public ReachPlanServiceClientImpl(ReachPlanService.ReachPlanServiceClient grpcClient, ReachPlanServiceSettings settings) { GrpcClient = grpcClient; ReachPlanServiceSettings effectiveSettings = settings ?? ReachPlanServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callListPlannableLocations = clientHelper.BuildApiCall<ListPlannableLocationsRequest, ListPlannableLocationsResponse>(grpcClient.ListPlannableLocationsAsync, grpcClient.ListPlannableLocations, effectiveSettings.ListPlannableLocationsSettings); Modify_ApiCall(ref _callListPlannableLocations); Modify_ListPlannableLocationsApiCall(ref _callListPlannableLocations); _callListPlannableProducts = clientHelper.BuildApiCall<ListPlannableProductsRequest, ListPlannableProductsResponse>(grpcClient.ListPlannableProductsAsync, grpcClient.ListPlannableProducts, effectiveSettings.ListPlannableProductsSettings); Modify_ApiCall(ref _callListPlannableProducts); Modify_ListPlannableProductsApiCall(ref _callListPlannableProducts); _callGenerateProductMixIdeas = clientHelper.BuildApiCall<GenerateProductMixIdeasRequest, GenerateProductMixIdeasResponse>(grpcClient.GenerateProductMixIdeasAsync, grpcClient.GenerateProductMixIdeas, effectiveSettings.GenerateProductMixIdeasSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callGenerateProductMixIdeas); Modify_GenerateProductMixIdeasApiCall(ref _callGenerateProductMixIdeas); _callGenerateReachForecast = clientHelper.BuildApiCall<GenerateReachForecastRequest, GenerateReachForecastResponse>(grpcClient.GenerateReachForecastAsync, grpcClient.GenerateReachForecast, effectiveSettings.GenerateReachForecastSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callGenerateReachForecast); Modify_GenerateReachForecastApiCall(ref _callGenerateReachForecast); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_ListPlannableLocationsApiCall(ref gaxgrpc::ApiCall<ListPlannableLocationsRequest, ListPlannableLocationsResponse> call); partial void Modify_ListPlannableProductsApiCall(ref gaxgrpc::ApiCall<ListPlannableProductsRequest, ListPlannableProductsResponse> call); partial void Modify_GenerateProductMixIdeasApiCall(ref gaxgrpc::ApiCall<GenerateProductMixIdeasRequest, GenerateProductMixIdeasResponse> call); partial void Modify_GenerateReachForecastApiCall(ref gaxgrpc::ApiCall<GenerateReachForecastRequest, GenerateReachForecastResponse> call); partial void OnConstruction(ReachPlanService.ReachPlanServiceClient grpcClient, ReachPlanServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC ReachPlanService client</summary> public override ReachPlanService.ReachPlanServiceClient GrpcClient { get; } partial void Modify_ListPlannableLocationsRequest(ref ListPlannableLocationsRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_ListPlannableProductsRequest(ref ListPlannableProductsRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_GenerateProductMixIdeasRequest(ref GenerateProductMixIdeasRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_GenerateReachForecastRequest(ref GenerateReachForecastRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the list of plannable locations (for example, countries &amp;amp; DMAs). /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override ListPlannableLocationsResponse ListPlannableLocations(ListPlannableLocationsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListPlannableLocationsRequest(ref request, ref callSettings); return _callListPlannableLocations.Sync(request, callSettings); } /// <summary> /// Returns the list of plannable locations (for example, countries &amp;amp; DMAs). /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<ListPlannableLocationsResponse> ListPlannableLocationsAsync(ListPlannableLocationsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListPlannableLocationsRequest(ref request, ref callSettings); return _callListPlannableLocations.Async(request, callSettings); } /// <summary> /// Returns the list of per-location plannable YouTube ad formats with allowed /// targeting. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override ListPlannableProductsResponse ListPlannableProducts(ListPlannableProductsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListPlannableProductsRequest(ref request, ref callSettings); return _callListPlannableProducts.Sync(request, callSettings); } /// <summary> /// Returns the list of per-location plannable YouTube ad formats with allowed /// targeting. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<ListPlannableProductsResponse> ListPlannableProductsAsync(ListPlannableProductsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListPlannableProductsRequest(ref request, ref callSettings); return _callListPlannableProducts.Async(request, callSettings); } /// <summary> /// Generates a product mix ideas given a set of preferences. This method /// helps the advertiser to obtain a good mix of ad formats and budget /// allocations based on its preferences. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [ReachPlanError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override GenerateProductMixIdeasResponse GenerateProductMixIdeas(GenerateProductMixIdeasRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GenerateProductMixIdeasRequest(ref request, ref callSettings); return _callGenerateProductMixIdeas.Sync(request, callSettings); } /// <summary> /// Generates a product mix ideas given a set of preferences. This method /// helps the advertiser to obtain a good mix of ad formats and budget /// allocations based on its preferences. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [ReachPlanError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<GenerateProductMixIdeasResponse> GenerateProductMixIdeasAsync(GenerateProductMixIdeasRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GenerateProductMixIdeasRequest(ref request, ref callSettings); return _callGenerateProductMixIdeas.Async(request, callSettings); } /// <summary> /// Generates a reach forecast for a given targeting / product mix. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RangeError]() /// [ReachPlanError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override GenerateReachForecastResponse GenerateReachForecast(GenerateReachForecastRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GenerateReachForecastRequest(ref request, ref callSettings); return _callGenerateReachForecast.Sync(request, callSettings); } /// <summary> /// Generates a reach forecast for a given targeting / product mix. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RangeError]() /// [ReachPlanError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<GenerateReachForecastResponse> GenerateReachForecastAsync(GenerateReachForecastRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GenerateReachForecastRequest(ref request, ref callSettings); return _callGenerateReachForecast.Async(request, callSettings); } } }
// This file has been modified with contributions by forum user hugo http://www.fyireporting.com/forum/viewtopic.php?t=552 /* * This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson, * the work of Kim Sheffield and the fyiReporting project. * * Prior Copyrights: * _________________________________________________________ * |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others| * | (http://reportfu.org) | * ========================================================= * _________________________________________________________ * |Copyright (C) 2004-2008 fyiReporting Software, LLC | * |For additional information, email [email protected] | * |or visit the website www.fyiReporting.com. | * ========================================================= * * License: * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; using System.Xml; using System.Globalization; namespace Reporting.RdlDesign { /// <summary> /// Summary description for StyleCtl. /// </summary> internal class StyleTextCtl : System.Windows.Forms.UserControl, IProperty { private List<XmlNode> _ReportItems; private DesignXmlDraw _Draw; private string _DataSetName; private bool fHorzAlign, fFormat, fDirection, fWritingMode, fTextDecoration; private bool fColor, fVerticalAlign, fFontStyle, fFontWeight, fFontSize, fFontFamily; private bool fValue; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label lFont; private System.Windows.Forms.Button bFont; private System.Windows.Forms.ComboBox cbHorzAlign; private System.Windows.Forms.ComboBox cbFormat; private System.Windows.Forms.ComboBox cbDirection; private System.Windows.Forms.ComboBox cbWritingMode; private System.Windows.Forms.Label label2; private System.Windows.Forms.ComboBox cbTextDecoration; private System.Windows.Forms.Button bColor; private System.Windows.Forms.Label label9; private System.Windows.Forms.ComboBox cbColor; private System.Windows.Forms.ComboBox cbVerticalAlign; private System.Windows.Forms.Label label3; private System.Windows.Forms.ComboBox cbFontStyle; private System.Windows.Forms.ComboBox cbFontWeight; private System.Windows.Forms.Label label10; private System.Windows.Forms.ComboBox cbFontSize; private System.Windows.Forms.Label label11; private System.Windows.Forms.ComboBox cbFontFamily; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Label lblValue; private System.Windows.Forms.ComboBox cbValue; private System.Windows.Forms.Button bValueExpr; private System.Windows.Forms.Button bFamily; private System.Windows.Forms.Button bStyle; private System.Windows.Forms.Button bColorEx; private System.Windows.Forms.Button bSize; private System.Windows.Forms.Button bWeight; private System.Windows.Forms.Button button2; private System.Windows.Forms.Button bAlignment; private System.Windows.Forms.Button bDirection; private System.Windows.Forms.Button bVertical; private System.Windows.Forms.Button bWrtMode; private System.Windows.Forms.Button bFormat; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; internal StyleTextCtl(DesignXmlDraw dxDraw, List<XmlNode> styles) { _ReportItems = styles; _Draw = dxDraw; // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // Initialize form using the style node values InitTextStyles(); } private void InitTextStyles() { cbColor.Items.AddRange(StaticLists.ColorList); XmlNode sNode = _ReportItems[0]; if (_ReportItems.Count > 1) { cbValue.Text = "Group Selected"; cbValue.Enabled = false; lblValue.Enabled = false; } else if (sNode.Name == "Textbox") { XmlNode vNode = _Draw.GetNamedChildNode(sNode, "Value"); if (vNode != null) cbValue.Text = vNode.InnerText; // now populate the combo box // Find the dataregion that contains the Textbox (if any) for (XmlNode pNode = sNode.ParentNode; pNode != null; pNode = pNode.ParentNode) { if (pNode.Name == "List" || pNode.Name == "Table" || pNode.Name == "Matrix" || pNode.Name == "Chart") { _DataSetName = _Draw.GetDataSetNameValue(pNode); if (_DataSetName != null) // found it { string[] f = _Draw.GetFields(_DataSetName, true); if (f != null) cbValue.Items.AddRange(f); } } } // parameters string[] ps = _Draw.GetReportParameters(true); if (ps != null) cbValue.Items.AddRange(ps); // globals cbValue.Items.AddRange(StaticLists.GlobalList); } else if (sNode.Name == "Title" || sNode.Name == "fyi:Title2" || sNode.Name == "Title2")// 20022008 AJM GJL { lblValue.Text = "Caption"; // Note: label needs to equal the element name XmlNode vNode = _Draw.GetNamedChildNode(sNode, "Caption"); if (vNode != null) cbValue.Text = vNode.InnerText; } else { lblValue.Visible = false; cbValue.Visible = false; bValueExpr.Visible = false; } sNode = _Draw.GetNamedChildNode(sNode, "Style"); string sFontStyle="Normal"; string sFontFamily="Arial"; string sFontWeight="Normal"; string sFontSize="10pt"; string sTextDecoration="None"; string sHorzAlign="General"; string sVerticalAlign="Top"; string sColor="Black"; string sFormat=""; string sDirection="LTR"; string sWritingMode="lr-tb"; foreach (XmlNode lNode in sNode) { if (lNode.NodeType != XmlNodeType.Element) continue; switch (lNode.Name) { case "FontStyle": sFontStyle = lNode.InnerText; break; case "FontFamily": sFontFamily = lNode.InnerText; break; case "FontWeight": sFontWeight = lNode.InnerText; break; case "FontSize": sFontSize = lNode.InnerText; break; case "TextDecoration": sTextDecoration = lNode.InnerText; break; case "TextAlign": sHorzAlign = lNode.InnerText; break; case "VerticalAlign": sVerticalAlign = lNode.InnerText; break; case "Color": sColor = lNode.InnerText; break; case "Format": sFormat = lNode.InnerText; break; case "Direction": sDirection = lNode.InnerText; break; case "WritingMode": sWritingMode = lNode.InnerText; break; } } // Population Font Family dropdown foreach (FontFamily ff in FontFamily.Families) { cbFontFamily.Items.Add(ff.Name); } this.cbFontStyle.Text = sFontStyle; this.cbFontFamily.Text = sFontFamily; this.cbFontWeight.Text = sFontWeight; this.cbFontSize.Text = sFontSize; this.cbTextDecoration.Text = sTextDecoration; this.cbHorzAlign.Text = sHorzAlign; this.cbVerticalAlign.Text = sVerticalAlign; this.cbColor.Text = sColor; this.cbFormat.Text = sFormat; this.cbDirection.Text = sDirection; this.cbWritingMode.Text = sWritingMode; fHorzAlign = fFormat = fDirection = fWritingMode = fTextDecoration = fColor = fVerticalAlign = fFontStyle = fFontWeight = fFontSize = fFontFamily = fValue = false; return; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.label8 = new System.Windows.Forms.Label(); this.lFont = new System.Windows.Forms.Label(); this.bFont = new System.Windows.Forms.Button(); this.cbVerticalAlign = new System.Windows.Forms.ComboBox(); this.cbHorzAlign = new System.Windows.Forms.ComboBox(); this.cbFormat = new System.Windows.Forms.ComboBox(); this.cbDirection = new System.Windows.Forms.ComboBox(); this.cbWritingMode = new System.Windows.Forms.ComboBox(); this.label2 = new System.Windows.Forms.Label(); this.cbTextDecoration = new System.Windows.Forms.ComboBox(); this.bColor = new System.Windows.Forms.Button(); this.label9 = new System.Windows.Forms.Label(); this.cbColor = new System.Windows.Forms.ComboBox(); this.label3 = new System.Windows.Forms.Label(); this.cbFontStyle = new System.Windows.Forms.ComboBox(); this.cbFontWeight = new System.Windows.Forms.ComboBox(); this.label10 = new System.Windows.Forms.Label(); this.cbFontSize = new System.Windows.Forms.ComboBox(); this.label11 = new System.Windows.Forms.Label(); this.cbFontFamily = new System.Windows.Forms.ComboBox(); this.lblValue = new System.Windows.Forms.Label(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.button2 = new System.Windows.Forms.Button(); this.bWeight = new System.Windows.Forms.Button(); this.bSize = new System.Windows.Forms.Button(); this.bColorEx = new System.Windows.Forms.Button(); this.bStyle = new System.Windows.Forms.Button(); this.bFamily = new System.Windows.Forms.Button(); this.cbValue = new System.Windows.Forms.ComboBox(); this.bValueExpr = new System.Windows.Forms.Button(); this.bAlignment = new System.Windows.Forms.Button(); this.bDirection = new System.Windows.Forms.Button(); this.bVertical = new System.Windows.Forms.Button(); this.bWrtMode = new System.Windows.Forms.Button(); this.bFormat = new System.Windows.Forms.Button(); this.groupBox1.SuspendLayout(); this.SuspendLayout(); // // label4 // this.label4.Location = new System.Drawing.Point(16, 232); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(48, 16); this.label4.TabIndex = 3; this.label4.Text = "Format"; // // label5 // this.label5.Location = new System.Drawing.Point(216, 168); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(48, 16); this.label5.TabIndex = 4; this.label5.Text = "Vertical"; // // label6 // this.label6.Location = new System.Drawing.Point(16, 168); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(56, 16); this.label6.TabIndex = 5; this.label6.Text = "Alignment"; // // label7 // this.label7.Location = new System.Drawing.Point(16, 200); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(56, 16); this.label7.TabIndex = 6; this.label7.Text = "Direction"; // // label8 // this.label8.Location = new System.Drawing.Point(216, 200); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(80, 16); this.label8.TabIndex = 7; this.label8.Text = "Writing Mode"; // // lFont // this.lFont.Location = new System.Drawing.Point(16, 16); this.lFont.Name = "lFont"; this.lFont.Size = new System.Drawing.Size(40, 16); this.lFont.TabIndex = 8; this.lFont.Text = "Family"; // // bFont // this.bFont.Location = new System.Drawing.Point(401, 16); this.bFont.Name = "bFont"; this.bFont.Size = new System.Drawing.Size(24, 21); this.bFont.TabIndex = 4; this.bFont.Text = "..."; this.bFont.Click += new System.EventHandler(this.bFont_Click); // // cbVerticalAlign // this.cbVerticalAlign.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbVerticalAlign.Items.AddRange(new object[] { "Top", "Middle", "Bottom"}); this.cbVerticalAlign.Location = new System.Drawing.Point(304, 168); this.cbVerticalAlign.Name = "cbVerticalAlign"; this.cbVerticalAlign.Size = new System.Drawing.Size(72, 21); this.cbVerticalAlign.TabIndex = 5; this.cbVerticalAlign.SelectedIndexChanged += new System.EventHandler(this.cbVerticalAlign_TextChanged); this.cbVerticalAlign.TextChanged += new System.EventHandler(this.cbVerticalAlign_TextChanged); // // cbHorzAlign // this.cbHorzAlign.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbHorzAlign.Items.AddRange(new object[] { "Left", "Center", "Right", "General", "Justified"}); this.cbHorzAlign.Location = new System.Drawing.Point(80, 168); this.cbHorzAlign.Name = "cbHorzAlign"; this.cbHorzAlign.Size = new System.Drawing.Size(64, 21); this.cbHorzAlign.TabIndex = 3; this.cbHorzAlign.SelectedIndexChanged += new System.EventHandler(this.cbHorzAlign_TextChanged); this.cbHorzAlign.TextChanged += new System.EventHandler(this.cbHorzAlign_TextChanged); // // cbFormat // this.cbFormat.Items.AddRange(new object[] { "None", "", "#,##0", "#,##0.00", "0", "0.00", "", "MM/dd/yyyy", "dddd, MMMM dd, yyyy", "dddd, MMMM dd, yyyy HH:mm", "dddd, MMMM dd, yyyy HH:mm:ss", "MM/dd/yyyy HH:mm", "MM/dd/yyyy HH:mm:ss", "MMMM dd", "Ddd, dd MMM yyyy HH\':\'mm\'\"ss \'GMT\'", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm:ss GMT", "HH:mm", "HH:mm:ss", "yyyy-MM-dd HH:mm:ss"}); this.cbFormat.Location = new System.Drawing.Point(80, 232); this.cbFormat.Name = "cbFormat"; this.cbFormat.Size = new System.Drawing.Size(296, 21); this.cbFormat.TabIndex = 11; this.cbFormat.TextChanged += new System.EventHandler(this.cbFormat_TextChanged); // // cbDirection // this.cbDirection.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbDirection.Items.AddRange(new object[] { "LTR", "RTL"}); this.cbDirection.Location = new System.Drawing.Point(80, 200); this.cbDirection.Name = "cbDirection"; this.cbDirection.Size = new System.Drawing.Size(64, 21); this.cbDirection.TabIndex = 7; this.cbDirection.SelectedIndexChanged += new System.EventHandler(this.cbDirection_TextChanged); this.cbDirection.TextChanged += new System.EventHandler(this.cbDirection_TextChanged); // // cbWritingMode // this.cbWritingMode.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbWritingMode.Items.AddRange(new object[] { "lr-tb", "tb-rl"}); this.cbWritingMode.Location = new System.Drawing.Point(304, 200); this.cbWritingMode.Name = "cbWritingMode"; this.cbWritingMode.Size = new System.Drawing.Size(72, 21); this.cbWritingMode.TabIndex = 9; this.cbWritingMode.SelectedIndexChanged += new System.EventHandler(this.cbWritingMode_TextChanged); this.cbWritingMode.TextChanged += new System.EventHandler(this.cbWritingMode_TextChanged); // // label2 // this.label2.Location = new System.Drawing.Point(224, 80); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(64, 23); this.label2.TabIndex = 19; this.label2.Text = "Decoration"; // // cbTextDecoration // this.cbTextDecoration.Items.AddRange(new object[] { "None", "Underline", "Overline", "LineThrough"}); this.cbTextDecoration.Location = new System.Drawing.Point(288, 80); this.cbTextDecoration.Name = "cbTextDecoration"; this.cbTextDecoration.Size = new System.Drawing.Size(80, 21); this.cbTextDecoration.TabIndex = 12; this.cbTextDecoration.SelectedIndexChanged += new System.EventHandler(this.cbTextDecoration_TextChanged); this.cbTextDecoration.TextChanged += new System.EventHandler(this.cbTextDecoration_TextChanged); // // bColor // this.bColor.Location = new System.Drawing.Point(200, 80); this.bColor.Name = "bColor"; this.bColor.Size = new System.Drawing.Size(24, 21); this.bColor.TabIndex = 11; this.bColor.Text = "..."; this.bColor.Click += new System.EventHandler(this.bColor_Click); // // label9 // this.label9.Location = new System.Drawing.Point(16, 80); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(48, 16); this.label9.TabIndex = 22; this.label9.Text = "Color"; // // cbColor // this.cbColor.Location = new System.Drawing.Point(72, 80); this.cbColor.Name = "cbColor"; this.cbColor.Size = new System.Drawing.Size(96, 21); this.cbColor.TabIndex = 9; this.cbColor.TextChanged += new System.EventHandler(this.cbColor_TextChanged); // // label3 // this.label3.Location = new System.Drawing.Point(16, 48); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(40, 16); this.label3.TabIndex = 25; this.label3.Text = "Style"; // // cbFontStyle // this.cbFontStyle.Items.AddRange(new object[] { "Normal", "Italic"}); this.cbFontStyle.Location = new System.Drawing.Point(72, 48); this.cbFontStyle.Name = "cbFontStyle"; this.cbFontStyle.Size = new System.Drawing.Size(96, 21); this.cbFontStyle.TabIndex = 5; this.cbFontStyle.TextChanged += new System.EventHandler(this.cbFontStyle_TextChanged); // // cbFontWeight // this.cbFontWeight.Items.AddRange(new object[] { "Lighter", "Normal", "Bold", "Bolder", "100", "200", "300", "400", "500", "600", "700", "800", "900"}); this.cbFontWeight.Location = new System.Drawing.Point(264, 48); this.cbFontWeight.Name = "cbFontWeight"; this.cbFontWeight.Size = new System.Drawing.Size(104, 21); this.cbFontWeight.TabIndex = 7; this.cbFontWeight.TextChanged += new System.EventHandler(this.cbFontWeight_TextChanged); // // label10 // this.label10.Location = new System.Drawing.Point(224, 48); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(40, 16); this.label10.TabIndex = 27; this.label10.Text = "Weight"; // // cbFontSize // this.cbFontSize.Items.AddRange(new object[] { "8pt", "9pt", "10pt", "11pt", "12pt", "14pt", "16pt", "18pt", "20pt", "22pt", "24pt", "26pt", "28pt", "36pt", "48pt", "72pt"}); this.cbFontSize.Location = new System.Drawing.Point(264, 16); this.cbFontSize.Name = "cbFontSize"; this.cbFontSize.Size = new System.Drawing.Size(104, 21); this.cbFontSize.TabIndex = 2; this.cbFontSize.TextChanged += new System.EventHandler(this.cbFontSize_TextChanged); // // label11 // this.label11.Location = new System.Drawing.Point(224, 16); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(40, 16); this.label11.TabIndex = 29; this.label11.Text = "Size"; // // cbFontFamily // this.cbFontFamily.Items.AddRange(new object[] { "Arial"}); this.cbFontFamily.Location = new System.Drawing.Point(72, 16); this.cbFontFamily.Name = "cbFontFamily"; this.cbFontFamily.Size = new System.Drawing.Size(96, 21); this.cbFontFamily.TabIndex = 0; this.cbFontFamily.TextChanged += new System.EventHandler(this.cbFontFamily_TextChanged); // // lblValue // this.lblValue.Location = new System.Drawing.Point(8, 16); this.lblValue.Name = "lblValue"; this.lblValue.Size = new System.Drawing.Size(56, 23); this.lblValue.TabIndex = 30; this.lblValue.Text = "Value"; // // groupBox1 // this.groupBox1.Controls.Add(this.button2); this.groupBox1.Controls.Add(this.bWeight); this.groupBox1.Controls.Add(this.bSize); this.groupBox1.Controls.Add(this.bColorEx); this.groupBox1.Controls.Add(this.bStyle); this.groupBox1.Controls.Add(this.bFamily); this.groupBox1.Controls.Add(this.lFont); this.groupBox1.Controls.Add(this.bFont); this.groupBox1.Controls.Add(this.label2); this.groupBox1.Controls.Add(this.cbTextDecoration); this.groupBox1.Controls.Add(this.bColor); this.groupBox1.Controls.Add(this.label9); this.groupBox1.Controls.Add(this.cbColor); this.groupBox1.Controls.Add(this.label3); this.groupBox1.Controls.Add(this.cbFontStyle); this.groupBox1.Controls.Add(this.cbFontWeight); this.groupBox1.Controls.Add(this.label10); this.groupBox1.Controls.Add(this.cbFontSize); this.groupBox1.Controls.Add(this.label11); this.groupBox1.Controls.Add(this.cbFontFamily); this.groupBox1.Location = new System.Drawing.Point(8, 40); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(432, 112); this.groupBox1.TabIndex = 2; this.groupBox1.TabStop = false; this.groupBox1.Text = "Font"; // // button2 // this.button2.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button2.Location = new System.Drawing.Point(376, 80); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(24, 21); this.button2.TabIndex = 13; this.button2.Tag = "decoration"; this.button2.Text = "fx"; this.button2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.button2.Click += new System.EventHandler(this.bExpr_Click); // // bWeight // this.bWeight.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bWeight.Location = new System.Drawing.Point(376, 48); this.bWeight.Name = "bWeight"; this.bWeight.Size = new System.Drawing.Size(24, 21); this.bWeight.TabIndex = 8; this.bWeight.Tag = "weight"; this.bWeight.Text = "fx"; this.bWeight.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bWeight.Click += new System.EventHandler(this.bExpr_Click); // // bSize // this.bSize.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bSize.Location = new System.Drawing.Point(376, 16); this.bSize.Name = "bSize"; this.bSize.Size = new System.Drawing.Size(24, 21); this.bSize.TabIndex = 3; this.bSize.Tag = "size"; this.bSize.Text = "fx"; this.bSize.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bSize.Click += new System.EventHandler(this.bExpr_Click); // // bColorEx // this.bColorEx.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bColorEx.Location = new System.Drawing.Point(176, 80); this.bColorEx.Name = "bColorEx"; this.bColorEx.Size = new System.Drawing.Size(24, 21); this.bColorEx.TabIndex = 10; this.bColorEx.Tag = "color"; this.bColorEx.Text = "fx"; this.bColorEx.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bColorEx.Click += new System.EventHandler(this.bExpr_Click); // // bStyle // this.bStyle.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bStyle.Location = new System.Drawing.Point(176, 48); this.bStyle.Name = "bStyle"; this.bStyle.Size = new System.Drawing.Size(24, 21); this.bStyle.TabIndex = 6; this.bStyle.Tag = "style"; this.bStyle.Text = "fx"; this.bStyle.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bStyle.Click += new System.EventHandler(this.bExpr_Click); // // bFamily // this.bFamily.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bFamily.Location = new System.Drawing.Point(176, 16); this.bFamily.Name = "bFamily"; this.bFamily.Size = new System.Drawing.Size(24, 21); this.bFamily.TabIndex = 1; this.bFamily.Tag = "family"; this.bFamily.Text = "fx"; this.bFamily.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bFamily.Click += new System.EventHandler(this.bExpr_Click); // // cbValue // this.cbValue.Location = new System.Drawing.Point(64, 16); this.cbValue.Name = "cbValue"; this.cbValue.Size = new System.Drawing.Size(344, 21); this.cbValue.TabIndex = 0; this.cbValue.Text = "comboBox1"; this.cbValue.TextChanged += new System.EventHandler(this.cbValue_TextChanged); // // bValueExpr // this.bValueExpr.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bValueExpr.Location = new System.Drawing.Point(414, 16); this.bValueExpr.Name = "bValueExpr"; this.bValueExpr.Size = new System.Drawing.Size(24, 21); this.bValueExpr.TabIndex = 1; this.bValueExpr.Tag = "value"; this.bValueExpr.Text = "fx"; this.bValueExpr.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bValueExpr.Click += new System.EventHandler(this.bExpr_Click); // // bAlignment // this.bAlignment.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bAlignment.Location = new System.Drawing.Point(152, 168); this.bAlignment.Name = "bAlignment"; this.bAlignment.Size = new System.Drawing.Size(24, 21); this.bAlignment.TabIndex = 4; this.bAlignment.Tag = "halign"; this.bAlignment.Text = "fx"; this.bAlignment.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bAlignment.Click += new System.EventHandler(this.bExpr_Click); // // bDirection // this.bDirection.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bDirection.Location = new System.Drawing.Point(152, 200); this.bDirection.Name = "bDirection"; this.bDirection.Size = new System.Drawing.Size(24, 21); this.bDirection.TabIndex = 8; this.bDirection.Tag = "direction"; this.bDirection.Text = "fx"; this.bDirection.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bDirection.Click += new System.EventHandler(this.bExpr_Click); // // bVertical // this.bVertical.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bVertical.Location = new System.Drawing.Point(384, 168); this.bVertical.Name = "bVertical"; this.bVertical.Size = new System.Drawing.Size(24, 21); this.bVertical.TabIndex = 6; this.bVertical.Tag = "valign"; this.bVertical.Text = "fx"; this.bVertical.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bVertical.Click += new System.EventHandler(this.bExpr_Click); // // bWrtMode // this.bWrtMode.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bWrtMode.Location = new System.Drawing.Point(384, 200); this.bWrtMode.Name = "bWrtMode"; this.bWrtMode.Size = new System.Drawing.Size(24, 21); this.bWrtMode.TabIndex = 10; this.bWrtMode.Tag = "writing"; this.bWrtMode.Text = "fx"; this.bWrtMode.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bWrtMode.Click += new System.EventHandler(this.bExpr_Click); // // bFormat // this.bFormat.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bFormat.Location = new System.Drawing.Point(384, 232); this.bFormat.Name = "bFormat"; this.bFormat.Size = new System.Drawing.Size(24, 21); this.bFormat.TabIndex = 12; this.bFormat.Tag = "format"; this.bFormat.Text = "fx"; this.bFormat.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bFormat.Click += new System.EventHandler(this.bExpr_Click); // // StyleTextCtl // this.Controls.Add(this.bFormat); this.Controls.Add(this.bWrtMode); this.Controls.Add(this.bVertical); this.Controls.Add(this.bDirection); this.Controls.Add(this.bAlignment); this.Controls.Add(this.bValueExpr); this.Controls.Add(this.cbValue); this.Controls.Add(this.groupBox1); this.Controls.Add(this.lblValue); this.Controls.Add(this.cbWritingMode); this.Controls.Add(this.cbDirection); this.Controls.Add(this.cbFormat); this.Controls.Add(this.cbHorzAlign); this.Controls.Add(this.cbVerticalAlign); this.Controls.Add(this.label8); this.Controls.Add(this.label7); this.Controls.Add(this.label6); this.Controls.Add(this.label5); this.Controls.Add(this.label4); this.Name = "StyleTextCtl"; this.Size = new System.Drawing.Size(456, 280); this.groupBox1.ResumeLayout(false); this.ResumeLayout(false); } #endregion public bool IsValid() { if (fFontSize) { try { if (!this.cbFontSize.Text.Trim().StartsWith("=")) DesignerUtility.ValidateSize(this.cbFontSize.Text, false, false); } catch (Exception e) { MessageBox.Show(e.Message, "Invalid Font Size"); return false; } } return true; } public void Apply() { // take information in control and apply to all the style nodes // Only change information that has been marked as modified; // this way when group is selected it is possible to change just // the items you want and keep the rest the same. foreach (XmlNode riNode in this._ReportItems) ApplyChanges(riNode); fHorzAlign = fFormat = fDirection = fWritingMode = fTextDecoration = fColor = fVerticalAlign = fFontStyle = fFontWeight = fFontSize = fFontFamily = fValue = false; } public void ApplyChanges(XmlNode node) { if (cbValue.Enabled) { if (fValue) _Draw.SetElement(node, lblValue.Text, cbValue.Text); // only adjust value when single item selected } XmlNode sNode = _Draw.GetNamedChildNode(node, "Style"); if (fFontStyle) _Draw.SetElement(sNode, "FontStyle", cbFontStyle.Text); if (fFontFamily) _Draw.SetElement(sNode, "FontFamily", cbFontFamily.Text); if (fFontWeight) _Draw.SetElement(sNode, "FontWeight", cbFontWeight.Text); if (fFontSize) { float size=10; size = DesignXmlDraw.GetSize(cbFontSize.Text); if (size <= 0) { size = DesignXmlDraw.GetSize(cbFontSize.Text+"pt"); // Try assuming pt if (size <= 0) // still no good size = 10; // just set default value } string rs = string.Format(NumberFormatInfo.InvariantInfo, "{0:0.#}pt", size); _Draw.SetElement(sNode, "FontSize", rs); // force to string } if (fTextDecoration) _Draw.SetElement(sNode, "TextDecoration", cbTextDecoration.Text); if (fHorzAlign) _Draw.SetElement(sNode, "TextAlign", cbHorzAlign.Text); if (fVerticalAlign) _Draw.SetElement(sNode, "VerticalAlign", cbVerticalAlign.Text); if (fColor) _Draw.SetElement(sNode, "Color", cbColor.Text); if (fFormat) { if (cbFormat.Text.Length == 0) // Don't put out a format if no format value _Draw.RemoveElement(sNode, "Format"); else _Draw.SetElement(sNode, "Format", cbFormat.Text); } if (fDirection) _Draw.SetElement(sNode, "Direction", cbDirection.Text); if (fWritingMode) _Draw.SetElement(sNode, "WritingMode", cbWritingMode.Text); return; } private void bFont_Click(object sender, System.EventArgs e) { FontDialog fd = new FontDialog(); fd.ShowColor = true; // STYLE System.Drawing.FontStyle fs = 0; if (cbFontStyle.Text == "Italic") fs |= System.Drawing.FontStyle.Italic; if (cbTextDecoration.Text == "Underline") fs |= FontStyle.Underline; else if (cbTextDecoration.Text == "LineThrough") fs |= FontStyle.Strikeout; // WEIGHT switch (cbFontWeight.Text) { case "Bold": case "Bolder": case "500": case "600": case "700": case "800": case "900": fs |= System.Drawing.FontStyle.Bold; break; default: break; } float size=10; size = DesignXmlDraw.GetSize(cbFontSize.Text); if (size <= 0) { size = DesignXmlDraw.GetSize(cbFontSize.Text+"pt"); // Try assuming pt if (size <= 0) // still no good size = 10; // just set default value } Font drawFont = new Font(cbFontFamily.Text, size, fs); // si.FontSize already in points fd.Font = drawFont; fd.Color = DesignerUtility.ColorFromHtml(cbColor.Text, System.Drawing.Color.Black); try { DialogResult dr = fd.ShowDialog(); if (dr != DialogResult.OK) { drawFont.Dispose(); return; } // Apply all the font info cbFontWeight.Text = fd.Font.Bold ? "Bold" : "Normal"; cbFontStyle.Text = fd.Font.Italic ? "Italic" : "Normal"; cbFontFamily.Text = fd.Font.FontFamily.Name; cbFontSize.Text = fd.Font.Size.ToString() + "pt"; cbColor.Text = ColorTranslator.ToHtml(fd.Color); if (fd.Font.Underline) this.cbTextDecoration.Text = "Underline"; else if (fd.Font.Strikeout) this.cbTextDecoration.Text = "LineThrough"; else this.cbTextDecoration.Text = "None"; drawFont.Dispose(); } finally { fd.Dispose(); } return; } private void bColor_Click(object sender, System.EventArgs e) { using (ColorDialog cd = new ColorDialog()) { cd.AnyColor = true; cd.FullOpen = true; cd.CustomColors = RdlDesignerForm.CustomColors; cd.Color = DesignerUtility.ColorFromHtml(cbColor.Text, System.Drawing.Color.Black); if (cd.ShowDialog() != DialogResult.OK) return; RdlDesignerForm.CustomColors = cd.CustomColors; if (sender == this.bColor) cbColor.Text = ColorTranslator.ToHtml(cd.Color); } return; } private void cbValue_TextChanged(object sender, System.EventArgs e) { fValue = true; } private void cbFontFamily_TextChanged(object sender, System.EventArgs e) { fFontFamily = true; } private void cbFontSize_TextChanged(object sender, System.EventArgs e) { fFontSize = true; } private void cbFontStyle_TextChanged(object sender, System.EventArgs e) { fFontStyle = true; } private void cbFontWeight_TextChanged(object sender, System.EventArgs e) { fFontWeight = true; } private void cbColor_TextChanged(object sender, System.EventArgs e) { fColor = true; } private void cbTextDecoration_TextChanged(object sender, System.EventArgs e) { fTextDecoration = true; } private void cbHorzAlign_TextChanged(object sender, System.EventArgs e) { fHorzAlign = true; } private void cbVerticalAlign_TextChanged(object sender, System.EventArgs e) { fVerticalAlign = true; } private void cbDirection_TextChanged(object sender, System.EventArgs e) { fDirection = true; } private void cbWritingMode_TextChanged(object sender, System.EventArgs e) { fWritingMode = true; } private void cbFormat_TextChanged(object sender, System.EventArgs e) { fFormat = true; } private void bExpr_Click(object sender, System.EventArgs e) { Button b = sender as Button; if (b == null) return; Control c = null; bool bColor=false; switch (b.Tag as string) { case "value": c = cbValue; break; case "family": c = cbFontFamily; break; case "style": c = cbFontStyle; break; case "color": c = cbColor; bColor = true; break; case "size": c = cbFontSize; break; case "weight": c = cbFontWeight; break; case "decoration": c = cbTextDecoration; break; case "halign": c = cbHorzAlign; break; case "valign": c = cbVerticalAlign; break; case "direction": c = cbDirection; break; case "writing": c = cbWritingMode; break; case "format": c = cbFormat; break; } if (c == null) return; XmlNode sNode = _ReportItems[0]; using (DialogExprEditor ee = new DialogExprEditor(_Draw, c.Text, sNode, bColor)) { DialogResult dr = ee.ShowDialog(); if (dr == DialogResult.OK) c.Text = ee.Expression; } return; } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gcdcv = Google.Cloud.Dialogflow.Cx.V3; using sys = System; namespace Google.Cloud.Dialogflow.Cx.V3 { /// <summary>Resource name for the <c>TransitionRouteGroup</c> resource.</summary> public sealed partial class TransitionRouteGroupName : gax::IResourceName, sys::IEquatable<TransitionRouteGroupName> { /// <summary>The possible contents of <see cref="TransitionRouteGroupName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c> /// projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}</c> /// . /// </summary> ProjectLocationAgentFlowTransitionRouteGroup = 1, } private static gax::PathTemplate s_projectLocationAgentFlowTransitionRouteGroup = new gax::PathTemplate("projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}"); /// <summary>Creates a <see cref="TransitionRouteGroupName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="TransitionRouteGroupName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static TransitionRouteGroupName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new TransitionRouteGroupName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="TransitionRouteGroupName"/> with the pattern /// <c> /// projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}</c> /// . /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="flowId">The <c>Flow</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="transitionRouteGroupId"> /// The <c>TransitionRouteGroup</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns> /// A new instance of <see cref="TransitionRouteGroupName"/> constructed from the provided ids. /// </returns> public static TransitionRouteGroupName FromProjectLocationAgentFlowTransitionRouteGroup(string projectId, string locationId, string agentId, string flowId, string transitionRouteGroupId) => new TransitionRouteGroupName(ResourceNameType.ProjectLocationAgentFlowTransitionRouteGroup, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), agentId: gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)), flowId: gax::GaxPreconditions.CheckNotNullOrEmpty(flowId, nameof(flowId)), transitionRouteGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(transitionRouteGroupId, nameof(transitionRouteGroupId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="TransitionRouteGroupName"/> with pattern /// <c> /// projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}</c> /// . /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="flowId">The <c>Flow</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="transitionRouteGroupId"> /// The <c>TransitionRouteGroup</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns> /// The string representation of this <see cref="TransitionRouteGroupName"/> with pattern /// <c> /// projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}</c> /// . /// </returns> public static string Format(string projectId, string locationId, string agentId, string flowId, string transitionRouteGroupId) => FormatProjectLocationAgentFlowTransitionRouteGroup(projectId, locationId, agentId, flowId, transitionRouteGroupId); /// <summary> /// Formats the IDs into the string representation of this <see cref="TransitionRouteGroupName"/> with pattern /// <c> /// projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}</c> /// . /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="flowId">The <c>Flow</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="transitionRouteGroupId"> /// The <c>TransitionRouteGroup</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns> /// The string representation of this <see cref="TransitionRouteGroupName"/> with pattern /// <c> /// projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}</c> /// . /// </returns> public static string FormatProjectLocationAgentFlowTransitionRouteGroup(string projectId, string locationId, string agentId, string flowId, string transitionRouteGroupId) => s_projectLocationAgentFlowTransitionRouteGroup.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)), gax::GaxPreconditions.CheckNotNullOrEmpty(flowId, nameof(flowId)), gax::GaxPreconditions.CheckNotNullOrEmpty(transitionRouteGroupId, nameof(transitionRouteGroupId))); /// <summary> /// Parses the given resource name string into a new <see cref="TransitionRouteGroupName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c> /// projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="transitionRouteGroupName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="TransitionRouteGroupName"/> if successful.</returns> public static TransitionRouteGroupName Parse(string transitionRouteGroupName) => Parse(transitionRouteGroupName, false); /// <summary> /// Parses the given resource name string into a new <see cref="TransitionRouteGroupName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c> /// projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="transitionRouteGroupName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="TransitionRouteGroupName"/> if successful.</returns> public static TransitionRouteGroupName Parse(string transitionRouteGroupName, bool allowUnparsed) => TryParse(transitionRouteGroupName, allowUnparsed, out TransitionRouteGroupName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="TransitionRouteGroupName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c> /// projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="transitionRouteGroupName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="TransitionRouteGroupName"/>, or <c>null</c> if parsing /// failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string transitionRouteGroupName, out TransitionRouteGroupName result) => TryParse(transitionRouteGroupName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="TransitionRouteGroupName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c> /// projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="transitionRouteGroupName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="TransitionRouteGroupName"/>, or <c>null</c> if parsing /// failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string transitionRouteGroupName, bool allowUnparsed, out TransitionRouteGroupName result) { gax::GaxPreconditions.CheckNotNull(transitionRouteGroupName, nameof(transitionRouteGroupName)); gax::TemplatedResourceName resourceName; if (s_projectLocationAgentFlowTransitionRouteGroup.TryParseName(transitionRouteGroupName, out resourceName)) { result = FromProjectLocationAgentFlowTransitionRouteGroup(resourceName[0], resourceName[1], resourceName[2], resourceName[3], resourceName[4]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(transitionRouteGroupName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private TransitionRouteGroupName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string agentId = null, string flowId = null, string locationId = null, string projectId = null, string transitionRouteGroupId = null) { Type = type; UnparsedResource = unparsedResourceName; AgentId = agentId; FlowId = flowId; LocationId = locationId; ProjectId = projectId; TransitionRouteGroupId = transitionRouteGroupId; } /// <summary> /// Constructs a new instance of a <see cref="TransitionRouteGroupName"/> class from the component parts of /// pattern /// <c> /// projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="flowId">The <c>Flow</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="transitionRouteGroupId"> /// The <c>TransitionRouteGroup</c> ID. Must not be <c>null</c> or empty. /// </param> public TransitionRouteGroupName(string projectId, string locationId, string agentId, string flowId, string transitionRouteGroupId) : this(ResourceNameType.ProjectLocationAgentFlowTransitionRouteGroup, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), agentId: gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)), flowId: gax::GaxPreconditions.CheckNotNullOrEmpty(flowId, nameof(flowId)), transitionRouteGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(transitionRouteGroupId, nameof(transitionRouteGroupId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Agent</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string AgentId { get; } /// <summary> /// The <c>Flow</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string FlowId { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>TransitionRouteGroup</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed /// resource name. /// </summary> public string TransitionRouteGroupId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationAgentFlowTransitionRouteGroup: return s_projectLocationAgentFlowTransitionRouteGroup.Expand(ProjectId, LocationId, AgentId, FlowId, TransitionRouteGroupId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as TransitionRouteGroupName); /// <inheritdoc/> public bool Equals(TransitionRouteGroupName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(TransitionRouteGroupName a, TransitionRouteGroupName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(TransitionRouteGroupName a, TransitionRouteGroupName b) => !(a == b); } public partial class TransitionRouteGroup { /// <summary> /// <see cref="gcdcv::TransitionRouteGroupName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdcv::TransitionRouteGroupName TransitionRouteGroupName { get => string.IsNullOrEmpty(Name) ? null : gcdcv::TransitionRouteGroupName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ListTransitionRouteGroupsRequest { /// <summary><see cref="FlowName"/>-typed view over the <see cref="Parent"/> resource name property.</summary> public FlowName ParentAsFlowName { get => string.IsNullOrEmpty(Parent) ? null : FlowName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class GetTransitionRouteGroupRequest { /// <summary> /// <see cref="gcdcv::TransitionRouteGroupName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdcv::TransitionRouteGroupName TransitionRouteGroupName { get => string.IsNullOrEmpty(Name) ? null : gcdcv::TransitionRouteGroupName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class CreateTransitionRouteGroupRequest { /// <summary><see cref="FlowName"/>-typed view over the <see cref="Parent"/> resource name property.</summary> public FlowName ParentAsFlowName { get => string.IsNullOrEmpty(Parent) ? null : FlowName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class DeleteTransitionRouteGroupRequest { /// <summary> /// <see cref="gcdcv::TransitionRouteGroupName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdcv::TransitionRouteGroupName TransitionRouteGroupName { get => string.IsNullOrEmpty(Name) ? null : gcdcv::TransitionRouteGroupName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Reflection.Emit { public enum FlowControl { Branch = 0, Break = 1, Call = 2, Cond_Branch = 3, Meta = 4, Next = 5, [System.ObsoleteAttribute("This API has been deprecated. https://go.microsoft.com/fwlink/?linkid=14202")] Phi = 6, Return = 7, Throw = 8, } public partial struct OpCode { private object _dummy; public System.Reflection.Emit.FlowControl FlowControl { get { throw null; } } public string Name { get { throw null; } } public System.Reflection.Emit.OpCodeType OpCodeType { get { throw null; } } public System.Reflection.Emit.OperandType OperandType { get { throw null; } } public int Size { get { throw null; } } public System.Reflection.Emit.StackBehaviour StackBehaviourPop { get { throw null; } } public System.Reflection.Emit.StackBehaviour StackBehaviourPush { get { throw null; } } public short Value { get { throw null; } } public override bool Equals(object obj) { throw null; } public bool Equals(System.Reflection.Emit.OpCode obj) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(System.Reflection.Emit.OpCode a, System.Reflection.Emit.OpCode b) { throw null; } public static bool operator !=(System.Reflection.Emit.OpCode a, System.Reflection.Emit.OpCode b) { throw null; } public override string ToString() { throw null; } } public partial class OpCodes { internal OpCodes() { } public static readonly System.Reflection.Emit.OpCode Add; public static readonly System.Reflection.Emit.OpCode Add_Ovf; public static readonly System.Reflection.Emit.OpCode Add_Ovf_Un; public static readonly System.Reflection.Emit.OpCode And; public static readonly System.Reflection.Emit.OpCode Arglist; public static readonly System.Reflection.Emit.OpCode Beq; public static readonly System.Reflection.Emit.OpCode Beq_S; public static readonly System.Reflection.Emit.OpCode Bge; public static readonly System.Reflection.Emit.OpCode Bge_S; public static readonly System.Reflection.Emit.OpCode Bge_Un; public static readonly System.Reflection.Emit.OpCode Bge_Un_S; public static readonly System.Reflection.Emit.OpCode Bgt; public static readonly System.Reflection.Emit.OpCode Bgt_S; public static readonly System.Reflection.Emit.OpCode Bgt_Un; public static readonly System.Reflection.Emit.OpCode Bgt_Un_S; public static readonly System.Reflection.Emit.OpCode Ble; public static readonly System.Reflection.Emit.OpCode Ble_S; public static readonly System.Reflection.Emit.OpCode Ble_Un; public static readonly System.Reflection.Emit.OpCode Ble_Un_S; public static readonly System.Reflection.Emit.OpCode Blt; public static readonly System.Reflection.Emit.OpCode Blt_S; public static readonly System.Reflection.Emit.OpCode Blt_Un; public static readonly System.Reflection.Emit.OpCode Blt_Un_S; public static readonly System.Reflection.Emit.OpCode Bne_Un; public static readonly System.Reflection.Emit.OpCode Bne_Un_S; public static readonly System.Reflection.Emit.OpCode Box; public static readonly System.Reflection.Emit.OpCode Br; public static readonly System.Reflection.Emit.OpCode Break; public static readonly System.Reflection.Emit.OpCode Brfalse; public static readonly System.Reflection.Emit.OpCode Brfalse_S; public static readonly System.Reflection.Emit.OpCode Brtrue; public static readonly System.Reflection.Emit.OpCode Brtrue_S; public static readonly System.Reflection.Emit.OpCode Br_S; public static readonly System.Reflection.Emit.OpCode Call; public static readonly System.Reflection.Emit.OpCode Calli; public static readonly System.Reflection.Emit.OpCode Callvirt; public static readonly System.Reflection.Emit.OpCode Castclass; public static readonly System.Reflection.Emit.OpCode Ceq; public static readonly System.Reflection.Emit.OpCode Cgt; public static readonly System.Reflection.Emit.OpCode Cgt_Un; public static readonly System.Reflection.Emit.OpCode Ckfinite; public static readonly System.Reflection.Emit.OpCode Clt; public static readonly System.Reflection.Emit.OpCode Clt_Un; public static readonly System.Reflection.Emit.OpCode Constrained; public static readonly System.Reflection.Emit.OpCode Conv_I; public static readonly System.Reflection.Emit.OpCode Conv_I1; public static readonly System.Reflection.Emit.OpCode Conv_I2; public static readonly System.Reflection.Emit.OpCode Conv_I4; public static readonly System.Reflection.Emit.OpCode Conv_I8; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I1; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I1_Un; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I2; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I2_Un; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I4; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I4_Un; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I8; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I8_Un; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I_Un; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U1; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U1_Un; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U2; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U2_Un; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U4; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U4_Un; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U8; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U8_Un; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U_Un; public static readonly System.Reflection.Emit.OpCode Conv_R4; public static readonly System.Reflection.Emit.OpCode Conv_R8; public static readonly System.Reflection.Emit.OpCode Conv_R_Un; public static readonly System.Reflection.Emit.OpCode Conv_U; public static readonly System.Reflection.Emit.OpCode Conv_U1; public static readonly System.Reflection.Emit.OpCode Conv_U2; public static readonly System.Reflection.Emit.OpCode Conv_U4; public static readonly System.Reflection.Emit.OpCode Conv_U8; public static readonly System.Reflection.Emit.OpCode Cpblk; public static readonly System.Reflection.Emit.OpCode Cpobj; public static readonly System.Reflection.Emit.OpCode Div; public static readonly System.Reflection.Emit.OpCode Div_Un; public static readonly System.Reflection.Emit.OpCode Dup; public static readonly System.Reflection.Emit.OpCode Endfilter; public static readonly System.Reflection.Emit.OpCode Endfinally; public static readonly System.Reflection.Emit.OpCode Initblk; public static readonly System.Reflection.Emit.OpCode Initobj; public static readonly System.Reflection.Emit.OpCode Isinst; public static readonly System.Reflection.Emit.OpCode Jmp; public static readonly System.Reflection.Emit.OpCode Ldarg; public static readonly System.Reflection.Emit.OpCode Ldarga; public static readonly System.Reflection.Emit.OpCode Ldarga_S; public static readonly System.Reflection.Emit.OpCode Ldarg_0; public static readonly System.Reflection.Emit.OpCode Ldarg_1; public static readonly System.Reflection.Emit.OpCode Ldarg_2; public static readonly System.Reflection.Emit.OpCode Ldarg_3; public static readonly System.Reflection.Emit.OpCode Ldarg_S; public static readonly System.Reflection.Emit.OpCode Ldc_I4; public static readonly System.Reflection.Emit.OpCode Ldc_I4_0; public static readonly System.Reflection.Emit.OpCode Ldc_I4_1; public static readonly System.Reflection.Emit.OpCode Ldc_I4_2; public static readonly System.Reflection.Emit.OpCode Ldc_I4_3; public static readonly System.Reflection.Emit.OpCode Ldc_I4_4; public static readonly System.Reflection.Emit.OpCode Ldc_I4_5; public static readonly System.Reflection.Emit.OpCode Ldc_I4_6; public static readonly System.Reflection.Emit.OpCode Ldc_I4_7; public static readonly System.Reflection.Emit.OpCode Ldc_I4_8; public static readonly System.Reflection.Emit.OpCode Ldc_I4_M1; public static readonly System.Reflection.Emit.OpCode Ldc_I4_S; public static readonly System.Reflection.Emit.OpCode Ldc_I8; public static readonly System.Reflection.Emit.OpCode Ldc_R4; public static readonly System.Reflection.Emit.OpCode Ldc_R8; public static readonly System.Reflection.Emit.OpCode Ldelem; public static readonly System.Reflection.Emit.OpCode Ldelema; public static readonly System.Reflection.Emit.OpCode Ldelem_I; public static readonly System.Reflection.Emit.OpCode Ldelem_I1; public static readonly System.Reflection.Emit.OpCode Ldelem_I2; public static readonly System.Reflection.Emit.OpCode Ldelem_I4; public static readonly System.Reflection.Emit.OpCode Ldelem_I8; public static readonly System.Reflection.Emit.OpCode Ldelem_R4; public static readonly System.Reflection.Emit.OpCode Ldelem_R8; public static readonly System.Reflection.Emit.OpCode Ldelem_Ref; public static readonly System.Reflection.Emit.OpCode Ldelem_U1; public static readonly System.Reflection.Emit.OpCode Ldelem_U2; public static readonly System.Reflection.Emit.OpCode Ldelem_U4; public static readonly System.Reflection.Emit.OpCode Ldfld; public static readonly System.Reflection.Emit.OpCode Ldflda; public static readonly System.Reflection.Emit.OpCode Ldftn; public static readonly System.Reflection.Emit.OpCode Ldind_I; public static readonly System.Reflection.Emit.OpCode Ldind_I1; public static readonly System.Reflection.Emit.OpCode Ldind_I2; public static readonly System.Reflection.Emit.OpCode Ldind_I4; public static readonly System.Reflection.Emit.OpCode Ldind_I8; public static readonly System.Reflection.Emit.OpCode Ldind_R4; public static readonly System.Reflection.Emit.OpCode Ldind_R8; public static readonly System.Reflection.Emit.OpCode Ldind_Ref; public static readonly System.Reflection.Emit.OpCode Ldind_U1; public static readonly System.Reflection.Emit.OpCode Ldind_U2; public static readonly System.Reflection.Emit.OpCode Ldind_U4; public static readonly System.Reflection.Emit.OpCode Ldlen; public static readonly System.Reflection.Emit.OpCode Ldloc; public static readonly System.Reflection.Emit.OpCode Ldloca; public static readonly System.Reflection.Emit.OpCode Ldloca_S; public static readonly System.Reflection.Emit.OpCode Ldloc_0; public static readonly System.Reflection.Emit.OpCode Ldloc_1; public static readonly System.Reflection.Emit.OpCode Ldloc_2; public static readonly System.Reflection.Emit.OpCode Ldloc_3; public static readonly System.Reflection.Emit.OpCode Ldloc_S; public static readonly System.Reflection.Emit.OpCode Ldnull; public static readonly System.Reflection.Emit.OpCode Ldobj; public static readonly System.Reflection.Emit.OpCode Ldsfld; public static readonly System.Reflection.Emit.OpCode Ldsflda; public static readonly System.Reflection.Emit.OpCode Ldstr; public static readonly System.Reflection.Emit.OpCode Ldtoken; public static readonly System.Reflection.Emit.OpCode Ldvirtftn; public static readonly System.Reflection.Emit.OpCode Leave; public static readonly System.Reflection.Emit.OpCode Leave_S; public static readonly System.Reflection.Emit.OpCode Localloc; public static readonly System.Reflection.Emit.OpCode Mkrefany; public static readonly System.Reflection.Emit.OpCode Mul; public static readonly System.Reflection.Emit.OpCode Mul_Ovf; public static readonly System.Reflection.Emit.OpCode Mul_Ovf_Un; public static readonly System.Reflection.Emit.OpCode Neg; public static readonly System.Reflection.Emit.OpCode Newarr; public static readonly System.Reflection.Emit.OpCode Newobj; public static readonly System.Reflection.Emit.OpCode Nop; public static readonly System.Reflection.Emit.OpCode Not; public static readonly System.Reflection.Emit.OpCode Or; public static readonly System.Reflection.Emit.OpCode Pop; public static readonly System.Reflection.Emit.OpCode Prefix1; public static readonly System.Reflection.Emit.OpCode Prefix2; public static readonly System.Reflection.Emit.OpCode Prefix3; public static readonly System.Reflection.Emit.OpCode Prefix4; public static readonly System.Reflection.Emit.OpCode Prefix5; public static readonly System.Reflection.Emit.OpCode Prefix6; public static readonly System.Reflection.Emit.OpCode Prefix7; public static readonly System.Reflection.Emit.OpCode Prefixref; public static readonly System.Reflection.Emit.OpCode Readonly; public static readonly System.Reflection.Emit.OpCode Refanytype; public static readonly System.Reflection.Emit.OpCode Refanyval; public static readonly System.Reflection.Emit.OpCode Rem; public static readonly System.Reflection.Emit.OpCode Rem_Un; public static readonly System.Reflection.Emit.OpCode Ret; public static readonly System.Reflection.Emit.OpCode Rethrow; public static readonly System.Reflection.Emit.OpCode Shl; public static readonly System.Reflection.Emit.OpCode Shr; public static readonly System.Reflection.Emit.OpCode Shr_Un; public static readonly System.Reflection.Emit.OpCode Sizeof; public static readonly System.Reflection.Emit.OpCode Starg; public static readonly System.Reflection.Emit.OpCode Starg_S; public static readonly System.Reflection.Emit.OpCode Stelem; public static readonly System.Reflection.Emit.OpCode Stelem_I; public static readonly System.Reflection.Emit.OpCode Stelem_I1; public static readonly System.Reflection.Emit.OpCode Stelem_I2; public static readonly System.Reflection.Emit.OpCode Stelem_I4; public static readonly System.Reflection.Emit.OpCode Stelem_I8; public static readonly System.Reflection.Emit.OpCode Stelem_R4; public static readonly System.Reflection.Emit.OpCode Stelem_R8; public static readonly System.Reflection.Emit.OpCode Stelem_Ref; public static readonly System.Reflection.Emit.OpCode Stfld; public static readonly System.Reflection.Emit.OpCode Stind_I; public static readonly System.Reflection.Emit.OpCode Stind_I1; public static readonly System.Reflection.Emit.OpCode Stind_I2; public static readonly System.Reflection.Emit.OpCode Stind_I4; public static readonly System.Reflection.Emit.OpCode Stind_I8; public static readonly System.Reflection.Emit.OpCode Stind_R4; public static readonly System.Reflection.Emit.OpCode Stind_R8; public static readonly System.Reflection.Emit.OpCode Stind_Ref; public static readonly System.Reflection.Emit.OpCode Stloc; public static readonly System.Reflection.Emit.OpCode Stloc_0; public static readonly System.Reflection.Emit.OpCode Stloc_1; public static readonly System.Reflection.Emit.OpCode Stloc_2; public static readonly System.Reflection.Emit.OpCode Stloc_3; public static readonly System.Reflection.Emit.OpCode Stloc_S; public static readonly System.Reflection.Emit.OpCode Stobj; public static readonly System.Reflection.Emit.OpCode Stsfld; public static readonly System.Reflection.Emit.OpCode Sub; public static readonly System.Reflection.Emit.OpCode Sub_Ovf; public static readonly System.Reflection.Emit.OpCode Sub_Ovf_Un; public static readonly System.Reflection.Emit.OpCode Switch; public static readonly System.Reflection.Emit.OpCode Tailcall; public static readonly System.Reflection.Emit.OpCode Throw; public static readonly System.Reflection.Emit.OpCode Unaligned; public static readonly System.Reflection.Emit.OpCode Unbox; public static readonly System.Reflection.Emit.OpCode Unbox_Any; public static readonly System.Reflection.Emit.OpCode Volatile; public static readonly System.Reflection.Emit.OpCode Xor; public static bool TakesSingleByteArgument(System.Reflection.Emit.OpCode inst) { throw null; } } public enum OpCodeType { [System.ObsoleteAttribute("This API has been deprecated. https://go.microsoft.com/fwlink/?linkid=14202")] Annotation = 0, Macro = 1, Nternal = 2, Objmodel = 3, Prefix = 4, Primitive = 5, } public enum OperandType { InlineBrTarget = 0, InlineField = 1, InlineI = 2, InlineI8 = 3, InlineMethod = 4, InlineNone = 5, [System.ObsoleteAttribute("This API has been deprecated. https://go.microsoft.com/fwlink/?linkid=14202")] InlinePhi = 6, InlineR = 7, InlineSig = 9, InlineString = 10, InlineSwitch = 11, InlineTok = 12, InlineType = 13, InlineVar = 14, ShortInlineBrTarget = 15, ShortInlineI = 16, ShortInlineR = 17, ShortInlineVar = 18, } public enum PackingSize { Size1 = 1, Size128 = 128, Size16 = 16, Size2 = 2, Size32 = 32, Size4 = 4, Size64 = 64, Size8 = 8, Unspecified = 0, } public enum StackBehaviour { Pop0 = 0, Pop1 = 1, Pop1_pop1 = 2, Popi = 3, Popi_pop1 = 4, Popi_popi = 5, Popi_popi8 = 6, Popi_popi_popi = 7, Popi_popr4 = 8, Popi_popr8 = 9, Popref = 10, Popref_pop1 = 11, Popref_popi = 12, Popref_popi_pop1 = 28, Popref_popi_popi = 13, Popref_popi_popi8 = 14, Popref_popi_popr4 = 15, Popref_popi_popr8 = 16, Popref_popi_popref = 17, Push0 = 18, Push1 = 19, Push1_push1 = 20, Pushi = 21, Pushi8 = 22, Pushr4 = 23, Pushr8 = 24, Pushref = 25, Varpop = 26, Varpush = 27, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.Text.Tests { public class EncoderConvert2Encoder : Encoder { private Encoder _encoder = null; public EncoderConvert2Encoder() { _encoder = Encoding.UTF8.GetEncoder(); } public override int GetByteCount(char[] chars, int index, int count, bool flush) { if (index >= count) throw new ArgumentException(); return _encoder.GetByteCount(chars, index, count, flush); } public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, bool flush) { return _encoder.GetBytes(chars, charIndex, charCount, bytes, byteIndex, flush); } } // Convert(System.Char[],System.Int32,System.Int32,System.Byte[],System.Int32,System.Int32,System.Boolean,System.Int32@,System.Int32@,System.Boolean@) public class EncoderConvert2 { private const int c_SIZE_OF_ARRAY = 256; private readonly RandomDataGenerator _generator = new RandomDataGenerator(); public static IEnumerable<object[]> Encoders_RandomInput() { yield return new object[] { Encoding.ASCII.GetEncoder() }; yield return new object[] { Encoding.UTF8.GetEncoder() }; yield return new object[] { Encoding.Unicode.GetEncoder() }; } public static IEnumerable<object[]> Encoders_Convert() { yield return new object[] { Encoding.ASCII.GetEncoder(), 1 }; yield return new object[] { Encoding.UTF8.GetEncoder(), 1 }; yield return new object[] { Encoding.Unicode.GetEncoder(), 2 }; } // Call Convert to convert an arbitrary character array encoders [Theory] [MemberData(nameof(Encoders_RandomInput))] public void EncoderConvertRandomCharArray(Encoder encoder) { char[] chars = new char[c_SIZE_OF_ARRAY]; byte[] bytes = new byte[c_SIZE_OF_ARRAY]; for (int i = 0; i < chars.Length; ++i) { chars[i] = _generator.GetChar(-55); } int charsUsed; int bytesUsed; bool completed; encoder.Convert(chars, 0, chars.Length, bytes, 0, bytes.Length, false, out charsUsed, out bytesUsed, out completed); // set flush to true and try again encoder.Convert(chars, 0, chars.Length, bytes, 0, bytes.Length, true, out charsUsed, out bytesUsed, out completed); } // Call Convert to convert a ASCII character array encoders [Theory] [MemberData(nameof(Encoders_Convert))] public void EncoderConvertASCIICharArray(Encoder encoder, int multiplier) { char[] chars = "TestLibrary.TestFramework.BeginScenario".ToCharArray(); byte[] bytes = new byte[chars.Length * multiplier]; VerificationHelper(encoder, chars, 0, chars.Length, bytes, 0, bytes.Length, false, chars.Length, chars.Length * multiplier, expectedCompleted: true); VerificationHelper(encoder, chars, 0, chars.Length, bytes, 0, bytes.Length, true, chars.Length, chars.Length * multiplier, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 0, bytes, 0, 0, true, 0, 0, expectedCompleted: true); } // Call Convert to convert a ASCII character array with user implemented encoder [Fact] public void EncoderCustomConvertASCIICharArray() { char[] chars = "TestLibrary.TestFramework.BeginScenario".ToCharArray(); byte[] bytes = new byte[chars.Length]; Encoder encoder = new EncoderConvert2Encoder(); VerificationHelper(encoder, chars, 0, chars.Length, bytes, 0, bytes.Length, false, chars.Length, chars.Length, expectedCompleted: true); VerificationHelper(encoder, chars, 0, chars.Length, bytes, 0, bytes.Length, true, chars.Length, chars.Length, expectedCompleted: true); } // Call Convert to convert partial of a ASCII character array with UTF8 encoder [Fact] public void EncoderUTF8ConvertASCIICharArrayPartial() { char[] chars = "TestLibrary.TestFramework.BeginScenario".ToCharArray(); byte[] bytes = new byte[chars.Length]; Encoder encoder = Encoding.UTF8.GetEncoder(); VerificationHelper(encoder, chars, 0, 1, bytes, 0, 1, false, 1, 1, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 1, bytes, 0, 1, true, 1, 1, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 0, 1, false, 1, 1, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 0, 1, true, 1, 1, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 1, 1, false, 1, 1, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 1, 1, true, 1, 1, expectedCompleted: true); // Verify maxBytes is large than character count VerificationHelper(encoder, chars, 0, chars.Length - 1, bytes, 0, bytes.Length, false, chars.Length - 1, chars.Length - 1, expectedCompleted: true); VerificationHelper(encoder, chars, 1, chars.Length - 1, bytes, 0, bytes.Length, true, chars.Length - 1, chars.Length - 1, expectedCompleted: true); } // Call Convert to convert partial of a ASCII character array with Unicode encoder [Fact] public void EncoderUnicodeConvertASCIICharArrayPartial() { char[] chars = "TestLibrary.TestFramework.BeginScenario".ToCharArray(); byte[] bytes = new byte[chars.Length * 2]; Encoder encoder = Encoding.Unicode.GetEncoder(); VerificationHelper(encoder, chars, 0, 1, bytes, 0, 2, false, 1, 2, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 1, bytes, 0, 2, true, 1, 2, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 0, 2, false, 1, 2, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 0, 2, true, 1, 2, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 1, 2, false, 1, 2, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 1, 2, true, 1, 2, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 1, bytes, 0, bytes.Length, false, 1, 2, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 1, bytes, 0, bytes.Length, true, 1, 2, expectedCompleted: true); } // Call Convert to convert a Unicode character array with Unicode encoder [Fact] public void EncoderUnicodeConvertUnicodeCharArray() { char[] chars = "\u8FD9\u4E2A\u4E00\u4E2A\u6D4B\u8BD5".ToCharArray(); byte[] bytes = new byte[chars.Length * 2]; Encoder encoder = Encoding.Unicode.GetEncoder(); VerificationHelper(encoder, chars, 0, chars.Length, bytes, 0, bytes.Length, false, chars.Length, bytes.Length, expectedCompleted: true); VerificationHelper(encoder, chars, 0, chars.Length, bytes, 0, bytes.Length, true, chars.Length, bytes.Length, expectedCompleted: true); } // Call Convert to convert partial of a Unicode character array with Unicode encoder [Fact] public void EncoderUnicodeConvertUnicodeCharArrayPartial() { char[] chars = "\u8FD9\u4E2A\u4E00\u4E2A\u6D4B\u8BD5".ToCharArray(); byte[] bytes = new byte[chars.Length * 2]; Encoder encoder = Encoding.Unicode.GetEncoder(); VerificationHelper(encoder, chars, 0, 1, bytes, 0, 2, false, 1, 2, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 1, bytes, 0, 2, true, 1, 2, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 0, 2, false, 1, 2, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 0, 2, true, 1, 2, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 1, 2, false, 1, 2, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 1, 2, true, 1, 2, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 1, bytes, 0, bytes.Length, false, 1, 2, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 1, bytes, 0, bytes.Length, true, 1, 2, expectedCompleted: true); } // Call Convert to convert partial of a ASCII character array with ASCII encoder [Fact] public void EncoderASCIIConvertASCIICharArrayPartial() { char[] chars = "TestLibrary.TestFramework.BeginScenario".ToCharArray(); byte[] bytes = new byte[chars.Length]; Encoder encoder = Encoding.ASCII.GetEncoder(); VerificationHelper(encoder, chars, 0, 1, bytes, 0, 1, false, 1, 1, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 1, bytes, 0, 1, true, 1, 1, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 0, 1, false, 1, 1, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 0, 1, true, 1, 1, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 1, 1, false, 1, 1, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 1, 1, true, 1, 1, expectedCompleted: true); // Verify maxBytes is large than character count VerificationHelper(encoder, chars, 0, chars.Length - 1, bytes, 0, bytes.Length, false, chars.Length - 1, chars.Length - 1, expectedCompleted: true); VerificationHelper(encoder, chars, 1, chars.Length - 1, bytes, 0, bytes.Length, true, chars.Length - 1, chars.Length - 1, expectedCompleted: true); } // Call Convert to convert partial of a Unicode character array with ASCII encoder [Fact] public void EncoderASCIIConvertUnicodeCharArrayPartial() { char[] chars = "\uD83D\uDE01Test".ToCharArray(); byte[] bytes = new byte[chars.Length * 2]; Encoder encoder = Encoding.ASCII.GetEncoder(); VerificationHelper(encoder, chars, 0, 1, bytes, 0, 1, true, 1, 1, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 1, bytes, 0, 1, false, 1, 1, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 2, bytes, 0, 2, false, 2, 2, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 4, bytes, 0, 4, false, 4, 4, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 4, bytes, 0, 4, true, 4, 4, expectedCompleted: true); VerificationHelper(encoder, chars, 2, 2, bytes, 0, 2, true, 2, 2, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 3, bytes, 1, 3, false, 3, 3, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 3, bytes, 1, 5, true, 3, 3, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 1, bytes, 0, bytes.Length, false, 1, 1, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 0, bytes.Length, true, 1, 1, expectedCompleted: true); } // Call Convert to convert partial of a Unicode character array with UTF8 encoder [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // [ActiveIssue(11057)] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "coreclr #23020 is not fixed in netfx.")] public void EncoderUTF8ConvertUnicodeCharArrayPartial() { char[] chars = "\uD83D\uDE01Test".ToCharArray(); byte[] bytes = new byte[chars.Length * 2]; Encoder encoder = Encoding.UTF8.GetEncoder(); VerificationHelper(encoder, chars, 0, 1, bytes, 0, 3, true, 1, 3, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 2, bytes, 0, 7, false, 2, 4, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 4, bytes, 0, 6, false, 4, 6, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 4, bytes, 0, 6, true, 4, 6, expectedCompleted: true); VerificationHelper(encoder, chars, 2, 2, bytes, 0, 2, true, 2, 2, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 3, bytes, 1, 3, false, 1, 3, expectedCompleted: false); VerificationHelper(encoder, chars, 1, 3, bytes, 1, 5, true, 3, 5, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 1, bytes, 0, bytes.Length, false, 1, 0, expectedCompleted: false); VerificationHelper(encoder, chars, 1, 1, bytes, 0, bytes.Length, true, 1, 4, expectedCompleted: true); } // Call Convert to convert partial of a ASCII+Unicode character array with ASCII encoder [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // [ActiveIssue(11057)] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "coreclr #23020 is not fixed in netfx.")] public void EncoderASCIIConvertMixedASCIIUnicodeCharArrayPartial() { char[] chars = "T\uD83D\uDE01est".ToCharArray(); byte[] bytes = new byte[chars.Length * 2]; Encoder encoder = Encoding.ASCII.GetEncoder(); VerificationHelper(encoder, chars, 0, 1, bytes, 0, 1, true, 1, 1, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 4, bytes, 0, 1, false, 3, 1, expectedCompleted: false); VerificationHelper(encoder, chars, 3, 1, bytes, 0, 2, false, 0, 2, expectedCompleted: false); VerificationHelper(encoder, chars, 3, 1, bytes, 0, 2, false, 1, 1, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 5, bytes, 0, 5, false, 5, 5, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 4, bytes, 0, 4, true, 4, 4, expectedCompleted: true); VerificationHelper(encoder, chars, 2, 2, bytes, 0, 2, true, 2, 2, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 3, bytes, 1, 5, false, 3, 3, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 3, bytes, 1, 3, true, 3, 3, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 2, bytes, 0, bytes.Length, false, 2, 2, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 0, bytes.Length, true, 1, 1, expectedCompleted: true); } // Call Convert to convert partial of a ASCII+Unicode character array with UTF8 encoder [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // [ActiveIssue(11057)] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "coreclr #23020 is not fixed in netfx.")] public void EncoderUTF8ConvertMixedASCIIUnicodeCharArrayPartial() { char[] chars = "T\uD83D\uDE01est".ToCharArray(); byte[] bytes = new byte[chars.Length * 2]; Encoder encoder = Encoding.UTF8.GetEncoder(); VerificationHelper(encoder, chars, 0, 1, bytes, 0, 1, true, 1, 1, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 2, bytes, 0, 1, false, 2, 1, expectedCompleted: false); VerificationHelper(encoder, chars, 2, 1, bytes, 0, 5, false, 1, 4, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 2, bytes, 0, 7, false, 2, 4, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 5, bytes, 0, 7, false, 5, 7, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 4, bytes, 0, 6, true, 4, 6, expectedCompleted: true); VerificationHelper(encoder, chars, 2, 2, bytes, 0, 3, true, 1, 3, expectedCompleted: false); VerificationHelper(encoder, chars, 1, 3, bytes, 1, 5, false, 3, 5, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 3, bytes, 1, 5, true, 3, 5, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 2, bytes, 0, bytes.Length, false, 2, 1, expectedCompleted: false); VerificationHelper(encoder, chars, 2, 2, bytes, 0, bytes.Length, false, 2, 5, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 0, bytes.Length, true, 1, 3, expectedCompleted: true); } private void VerificationHelper(Encoder encoder, char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, int expectedCharsUsed, int expectedBytesUsed, bool expectedCompleted) { int charsUsed; int bytesUsed; bool completed; encoder.Convert(chars, charIndex, charCount, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out completed); Assert.Equal(expectedCharsUsed, charsUsed); Assert.Equal(expectedBytesUsed, bytesUsed); Assert.Equal(expectedCompleted, completed); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // // Don't override IsAlwaysNormalized because it is just a Unicode Transformation and could be confused. // using System.Diagnostics; using System.Runtime.InteropServices; namespace System.Text { public class UTF7Encoding : Encoding { private const string base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; // 0123456789111111111122222222223333333333444444444455555555556666 // 012345678901234567890123456789012345678901234567890123 // These are the characters that can be directly encoded in UTF7. private const string directChars = "\t\n\r '(),-./0123456789:?ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; // These are the characters that can be optionally directly encoded in UTF7. private const string optionalChars = "!\"#$%&*;<=>@[]^_`{|}"; // Used by Encoding.UTF7 for lazy initialization // The initialization code will not be run until a static member of the class is referenced internal static readonly UTF7Encoding s_default = new UTF7Encoding(); // The set of base 64 characters. private byte[] _base64Bytes = null!; // The decoded bits for every base64 values. This array has a size of 128 elements. // The index is the code point value of the base 64 characters. The value is -1 if // the code point is not a valid base 64 character. Otherwise, the value is a value // from 0 ~ 63. private sbyte[] _base64Values = null!; // The array to decide if a Unicode code point below 0x80 can be directly encoded in UTF7. // This array has a size of 128. private bool[] _directEncode = null!; private readonly bool _allowOptionals; private const int UTF7_CODEPAGE = 65000; public UTF7Encoding() : this(false) { } public UTF7Encoding(bool allowOptionals) : base(UTF7_CODEPAGE) // Set the data item. { // Allowing optionals? _allowOptionals = allowOptionals; // Make our tables MakeTables(); } private void MakeTables() { // Build our tables _base64Bytes = new byte[64]; for (int i = 0; i < 64; i++) _base64Bytes[i] = (byte)base64Chars[i]; _base64Values = new sbyte[128]; for (int i = 0; i < 128; i++) _base64Values[i] = -1; for (int i = 0; i < 64; i++) _base64Values[_base64Bytes[i]] = (sbyte)i; _directEncode = new bool[128]; int count = directChars.Length; for (int i = 0; i < count; i++) { _directEncode[directChars[i]] = true; } if (_allowOptionals) { count = optionalChars.Length; for (int i = 0; i < count; i++) { _directEncode[optionalChars[i]] = true; } } } // We go ahead and set this because Encoding expects it, however nothing can fall back in UTF7. internal sealed override void SetDefaultFallbacks() { // UTF7 had an odd decoderFallback behavior, and the Encoder fallback // is irrelevant because we encode surrogates individually and never check for unmatched ones // (so nothing can fallback during encoding) this.encoderFallback = new EncoderReplacementFallback(string.Empty); this.decoderFallback = new DecoderUTF7Fallback(); } public override bool Equals(object? value) { if (value is UTF7Encoding that) { return (_allowOptionals == that._allowOptionals) && (EncoderFallback.Equals(that.EncoderFallback)) && (DecoderFallback.Equals(that.DecoderFallback)); } return false; } // Compared to all the other encodings, variations of UTF7 are unlikely public override int GetHashCode() { return this.CodePage + this.EncoderFallback.GetHashCode() + this.DecoderFallback.GetHashCode(); } // The following methods are copied from EncodingNLS.cs. // Unfortunately EncodingNLS.cs is internal and we're public, so we have to re-implement them here. // These should be kept in sync for the following classes: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // Returns the number of bytes required to encode a range of characters in // a character array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetByteCount(char[] chars, int index, int count) { // Validate input parameters if (chars == null) throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - index < count) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); // If no input, return 0, avoid fixed empty array problem if (count == 0) return 0; // Just call the pointer version fixed (char* pChars = chars) return GetByteCount(pChars + index, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetByteCount(string s) { // Validate input if (s == null) throw new ArgumentNullException(nameof(s)); fixed (char* pChars = s) return GetByteCount(pChars, s.Length, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] public override unsafe int GetByteCount(char* chars, int count) { // Validate Parameters if (chars == null) throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); // Call it with empty encoder return GetByteCount(chars, count, null); } // Parent method is safe. // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding public override unsafe int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (s == null || bytes == null) throw new ArgumentNullException(s == null ? nameof(s) : nameof(bytes), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); if (s.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(s), SR.ArgumentOutOfRange_IndexCount); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.ArgumentOutOfRange_Index); int byteCount = bytes.Length - byteIndex; fixed (char* pChars = s) fixed (byte* pBytes = &MemoryMarshal.GetReference((Span<byte>)bytes)) return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null); } // Encodes a range of characters in a character array into a range of bytes // in a byte array. An exception occurs if the byte array is not large // enough to hold the complete encoding of the characters. The // GetByteCount method can be used to determine the exact number of // bytes that will be produced for a given range of characters. // Alternatively, the GetMaxByteCount method can be used to // determine the maximum number of bytes that will be produced for a given // number of characters, regardless of the actual character values. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.ArgumentOutOfRange_Index); // If nothing to encode return 0, avoid fixed problem if (charCount == 0) return 0; // Just call pointer version int byteCount = bytes.Length - byteIndex; fixed (char* pChars = chars) fixed (byte* pBytes = &MemoryMarshal.GetReference((Span<byte>)bytes)) // Remember that byteCount is # to decode, not size of array. return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); return GetBytes(chars, charCount, bytes, byteCount, null); } // Returns the number of characters produced by decoding a range of bytes // in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetCharCount(byte[] bytes, int index, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); // If no input just return 0, fixed doesn't like 0 length arrays. if (count == 0) return 0; // Just call pointer version fixed (byte* pBytes = bytes) return GetCharCount(pBytes + index, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] public override unsafe int GetCharCount(byte* bytes, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); return GetCharCount(bytes, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); if (charIndex < 0 || charIndex > chars.Length) throw new ArgumentOutOfRangeException(nameof(charIndex), SR.ArgumentOutOfRange_Index); // If no input, return 0 & avoid fixed problem if (byteCount == 0) return 0; // Just call pointer version int charCount = chars.Length - charIndex; fixed (byte* pBytes = bytes) fixed (char* pChars = &MemoryMarshal.GetReference((Span<char>)chars)) // Remember that charCount is # to decode, not size of array return GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); return GetChars(bytes, byteCount, chars, charCount, null); } // Returns a string containing the decoded representation of a range of // bytes in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe string GetString(byte[] bytes, int index, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); // Avoid problems with empty input buffer if (count == 0) return string.Empty; fixed (byte* pBytes = bytes) return string.CreateStringFromEncoding( pBytes + index, count, this); } // // End of standard methods copied from EncodingNLS.cs // internal sealed override unsafe int GetByteCount(char* chars, int count, EncoderNLS? baseEncoder) { Debug.Assert(chars != null, "[UTF7Encoding.GetByteCount]chars!=null"); Debug.Assert(count >= 0, "[UTF7Encoding.GetByteCount]count >=0"); // Just call GetBytes with bytes == null return GetBytes(chars, count, null, 0, baseEncoder); } internal sealed override unsafe int GetBytes( char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS? baseEncoder) { Debug.Assert(byteCount >= 0, "[UTF7Encoding.GetBytes]byteCount >=0"); Debug.Assert(chars != null, "[UTF7Encoding.GetBytes]chars!=null"); Debug.Assert(charCount >= 0, "[UTF7Encoding.GetBytes]charCount >=0"); // Get encoder info UTF7Encoding.Encoder? encoder = (UTF7Encoding.Encoder?)baseEncoder; // Default bits & count int bits = 0; int bitCount = -1; // prepare our helpers Encoding.EncodingByteBuffer buffer = new Encoding.EncodingByteBuffer( this, encoder, bytes, byteCount, chars, charCount); if (encoder != null) { bits = encoder.bits; bitCount = encoder.bitCount; // May have had too many left over while (bitCount >= 6) { bitCount -= 6; // If we fail we'll never really have enough room if (!buffer.AddByte(_base64Bytes[(bits >> bitCount) & 0x3F])) ThrowBytesOverflow(encoder, buffer.Count == 0); } } while (buffer.MoreData) { char currentChar = buffer.GetNextChar(); if (currentChar < 0x80 && _directEncode[currentChar]) { if (bitCount >= 0) { if (bitCount > 0) { // Try to add the next byte if (!buffer.AddByte(_base64Bytes[bits << 6 - bitCount & 0x3F])) break; // Stop here, didn't throw bitCount = 0; } // Need to get emit '-' and our char, 2 bytes total if (!buffer.AddByte((byte)'-')) break; // Stop here, didn't throw bitCount = -1; } // Need to emit our char if (!buffer.AddByte((byte)currentChar)) break; // Stop here, didn't throw } else if (bitCount < 0 && currentChar == '+') { if (!buffer.AddByte((byte)'+', (byte)'-')) break; // Stop here, didn't throw } else { if (bitCount < 0) { // Need to emit a + and 12 bits (3 bytes) // Only 12 of the 16 bits will be emitted this time, the other 4 wait 'til next time if (!buffer.AddByte((byte)'+')) break; // Stop here, didn't throw // We're now in bit mode, but haven't stored data yet bitCount = 0; } // Add our bits bits = bits << 16 | currentChar; bitCount += 16; while (bitCount >= 6) { bitCount -= 6; if (!buffer.AddByte(_base64Bytes[(bits >> bitCount) & 0x3F])) { bitCount += 6; // We didn't use these bits buffer.GetNextChar(); // We're processing this char still, but AddByte // --'d it when we ran out of space break; // Stop here, not enough room for bytes } } if (bitCount >= 6) break; // Didn't have room to encode enough bits } } // Now if we have bits left over we have to encode them. // MustFlush may have been cleared by encoding.ThrowBytesOverflow earlier if converting if (bitCount >= 0 && (encoder == null || encoder.MustFlush)) { // Do we have bits we have to stick in? if (bitCount > 0) { if (buffer.AddByte(_base64Bytes[(bits << (6 - bitCount)) & 0x3F])) { // Emitted spare bits, 0 bits left bitCount = 0; } } // If converting and failed bitCount above, then we'll fail this too if (buffer.AddByte((byte)'-')) { // turned off bit mode'; bits = 0; bitCount = -1; } else // If not successful, convert will maintain state for next time, also // AddByte will have decremented our char count, however we need it to remain the same buffer.GetNextChar(); } // Do we have an encoder we're allowed to use? // bytes == null if counting, so don't use encoder then if (bytes != null && encoder != null) { // We already cleared bits & bitcount for mustflush case encoder.bits = bits; encoder.bitCount = bitCount; encoder._charsUsed = buffer.CharsUsed; } return buffer.Count; } internal sealed override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS? baseDecoder) { Debug.Assert(count >= 0, "[UTF7Encoding.GetCharCount]count >=0"); Debug.Assert(bytes != null, "[UTF7Encoding.GetCharCount]bytes!=null"); // Just call GetChars with null char* to do counting return GetChars(bytes, count, null, 0, baseDecoder); } internal sealed override unsafe int GetChars( byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS? baseDecoder) { Debug.Assert(byteCount >= 0, "[UTF7Encoding.GetChars]byteCount >=0"); Debug.Assert(bytes != null, "[UTF7Encoding.GetChars]bytes!=null"); Debug.Assert(charCount >= 0, "[UTF7Encoding.GetChars]charCount >=0"); // Might use a decoder UTF7Encoding.Decoder? decoder = (UTF7Encoding.Decoder?)baseDecoder; // Get our output buffer info. Encoding.EncodingCharBuffer buffer = new Encoding.EncodingCharBuffer( this, decoder, chars, charCount, bytes, byteCount); // Get decoder info int bits = 0; int bitCount = -1; bool firstByte = false; if (decoder != null) { bits = decoder.bits; bitCount = decoder.bitCount; firstByte = decoder.firstByte; Debug.Assert(!firstByte || decoder.bitCount <= 0, "[UTF7Encoding.GetChars]If remembered bits, then first byte flag shouldn't be set"); } // We may have had bits in the decoder that we couldn't output last time, so do so now if (bitCount >= 16) { // Check our decoder buffer if (!buffer.AddChar((char)((bits >> (bitCount - 16)) & 0xFFFF))) ThrowCharsOverflow(decoder, true); // Always throw, they need at least 1 char even in Convert // Used this one, clean up extra bits bitCount -= 16; } // Loop through the input while (buffer.MoreData) { byte currentByte = buffer.GetNextByte(); int c; if (bitCount >= 0) { // // Modified base 64 encoding. // sbyte v; if (currentByte < 0x80 && ((v = _base64Values[currentByte]) >= 0)) { firstByte = false; bits = (bits << 6) | ((byte)v); bitCount += 6; if (bitCount >= 16) { c = (bits >> (bitCount - 16)) & 0xFFFF; bitCount -= 16; } // If not enough bits just continue else continue; } else { // If it wasn't a base 64 byte, everything's going to turn off base 64 mode bitCount = -1; if (currentByte != '-') { // >= 0x80 (because of 1st if statemtn) // We need this check since the _base64Values[b] check below need b <= 0x7f. // This is not a valid base 64 byte. Terminate the shifted-sequence and // emit this byte. // not in base 64 table // According to the RFC 1642 and the example code of UTF-7 // in Unicode 2.0, we should just zero-extend the invalid UTF7 byte // Chars won't be updated unless this works, try to fallback if (!buffer.Fallback(currentByte)) break; // Stop here, didn't throw // Used that byte, we're done with it continue; } // // The encoding for '+' is "+-". // if (firstByte) c = '+'; // We just turn it off if not emitting a +, so we're done. else continue; } // // End of modified base 64 encoding block. // } else if (currentByte == '+') { // // Found the start of a modified base 64 encoding block or a plus sign. // bitCount = 0; firstByte = true; continue; } else { // Normal character if (currentByte >= 0x80) { // Try to fallback if (!buffer.Fallback(currentByte)) break; // Stop here, didn't throw // Done falling back continue; } // Use the normal character c = currentByte; } if (c >= 0) { // Check our buffer if (!buffer.AddChar((char)c)) { // No room. If it was a plain char we'll try again later. // Note, we'll consume this byte and stick it in decoder, even if we can't output it if (bitCount >= 0) // Can we rememmber this byte (char) { buffer.AdjustBytes(+1); // Need to readd the byte that AddChar subtracted when it failed bitCount += 16; // We'll still need that char we have in our bits } break; // didn't throw, stop } } } // Stick stuff in the decoder if we can (chars == null if counting, so don't store decoder) if (chars != null && decoder != null) { // MustFlush? (Could've been cleared by ThrowCharsOverflow if Convert & didn't reach end of buffer) if (decoder.MustFlush) { // RFC doesn't specify what would happen if we have non-0 leftover bits, we just drop them decoder.bits = 0; decoder.bitCount = -1; decoder.firstByte = false; } else { decoder.bits = bits; decoder.bitCount = bitCount; decoder.firstByte = firstByte; } decoder._bytesUsed = buffer.BytesUsed; } // else ignore any hanging bits. // Return our count return buffer.Count; } public override System.Text.Decoder GetDecoder() { return new UTF7Encoding.Decoder(this); } public override System.Text.Encoder GetEncoder() { return new UTF7Encoding.Encoder(this); } public override int GetMaxByteCount(int charCount) { if (charCount < 0) throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); // Suppose that every char can not be direct-encoded, we know that // a byte can encode 6 bits of the Unicode character. And we will // also need two extra bytes for the shift-in ('+') and shift-out ('-') mark. // Therefore, the max byte should be: // byteCount = 2 + Math.Ceiling((double)charCount * 16 / 6); // That is always <= 2 + 3 * charCount; // Longest case is alternating encoded, direct, encoded data for 5 + 1 + 5... bytes per char. // UTF7 doesn't have left over surrogates, but if no input we may need an output - to turn off // encoding if MustFlush is true. // Its easiest to think of this as 2 bytes to turn on/off the base64 mode, then 3 bytes per char. // 3 bytes is 18 bits of encoding, which is more than we need, but if its direct encoded then 3 // bytes allows us to turn off and then back on base64 mode if necessary. // Note that UTF7 encoded surrogates individually and isn't worried about mismatches, so all // code points are encodable int UTF7. long byteCount = (long)charCount * 3 + 2; // check for overflow if (byteCount > 0x7fffffff) throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_GetByteCountOverflow); return (int)byteCount; } public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); // Worst case is 1 char per byte. Minimum 1 for left over bits in case decoder is being flushed // Also note that we ignore extra bits (per spec), so UTF7 doesn't have unknown in this direction. int charCount = byteCount; if (charCount == 0) charCount = 1; return charCount; } // Of all the amazing things... This MUST be Decoder so that our com name // for System.Text.Decoder doesn't change private sealed class Decoder : DecoderNLS { /*private*/ internal int bits; /*private*/ internal int bitCount; /*private*/ internal bool firstByte; public Decoder(UTF7Encoding encoding) : base(encoding) { // base calls reset } public override void Reset() { this.bits = 0; this.bitCount = -1; this.firstByte = false; if (_fallbackBuffer != null) _fallbackBuffer.Reset(); } // Anything left in our encoder? internal override bool HasState => // NOTE: This forces the last -, which some encoder might not encode. If we // don't see it we don't think we're done reading. this.bitCount != -1; } // Of all the amazing things... This MUST be Encoder so that our com name // for System.Text.Encoder doesn't change private sealed class Encoder : EncoderNLS { /*private*/ internal int bits; /*private*/ internal int bitCount; public Encoder(UTF7Encoding encoding) : base(encoding) { // base calls reset } public override void Reset() { this.bitCount = -1; this.bits = 0; if (_fallbackBuffer != null) _fallbackBuffer.Reset(); } // Anything left in our encoder? internal override bool HasState => this.bits != 0 || this.bitCount != -1; } // Preexisting UTF7 behavior for bad bytes was just to spit out the byte as the next char // and turn off base64 mode if it was in that mode. We still exit the mode, but now we fallback. private sealed class DecoderUTF7Fallback : DecoderFallback { // Default replacement fallback uses no best fit and ? replacement string public override DecoderFallbackBuffer CreateFallbackBuffer() => new DecoderUTF7FallbackBuffer(); // Maximum number of characters that this instance of this fallback could return public override int MaxCharCount => 1; // returns 1 char per bad byte public override bool Equals(object? value) => value is DecoderUTF7Fallback; public override int GetHashCode() => 984; } private sealed class DecoderUTF7FallbackBuffer : DecoderFallbackBuffer { // Store our default string private char cFallback = (char)0; private int iCount = -1; private int iSize; // Fallback Methods public override bool Fallback(byte[] bytesUnknown, int index) { // We expect no previous fallback in our buffer Debug.Assert(iCount < 0, "[DecoderUTF7FallbackBuffer.Fallback] Can't have recursive fallbacks"); Debug.Assert(bytesUnknown.Length == 1, "[DecoderUTF7FallbackBuffer.Fallback] Only possible fallback case should be 1 unknown byte"); // Go ahead and get our fallback cFallback = (char)bytesUnknown[0]; // Any of the fallback characters can be handled except for 0 if (cFallback == 0) { return false; } iCount = iSize = 1; return true; } public override char GetNextChar() { if (iCount-- > 0) return cFallback; // Note: this means that 0 in UTF7 stream will never be emitted. return (char)0; } public override bool MovePrevious() { if (iCount >= 0) { iCount++; } // return true if we were allowed to do this return iCount >= 0 && iCount <= iSize; } // Return # of chars left in this fallback public override int Remaining => (iCount > 0) ? iCount : 0; // Clear the buffer public override unsafe void Reset() { iCount = -1; byteStart = null; } // This version just counts the fallback and doesn't actually copy anything. internal override unsafe int InternalFallback(byte[] bytes, byte* pBytes) // Right now this has both bytes and bytes[], since we might have extra bytes, hence the // array, and we might need the index, hence the byte* { // We expect no previous fallback in our buffer Debug.Assert(iCount < 0, "[DecoderUTF7FallbackBuffer.InternalFallback] Can't have recursive fallbacks"); if (bytes.Length != 1) { throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex); } // Can't fallback a byte 0, so return for that case, 1 otherwise. return bytes[0] == 0 ? 0 : 1; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using Xunit; namespace System.Linq.Tests { public class QueryableTests { [Fact] public void AsQueryable() { Assert.NotNull(((IEnumerable)(new int[] { })).AsQueryable()); } [Fact] public void AsQueryableT() { Assert.NotNull((new int[] { }).AsQueryable()); } [Fact] public void NullAsQueryableT() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).AsQueryable()); } [Fact] public void NullAsQueryable() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable)null).AsQueryable()); } private class NonGenericEnumerableSoWeDontNeedADependencyOnTheAssemblyWithNonGeneric : IEnumerable { public IEnumerator GetEnumerator() { yield break; } } [Fact] public void NonGenericToQueryable() { Assert.Throws<ArgumentException>(() => new NonGenericEnumerableSoWeDontNeedADependencyOnTheAssemblyWithNonGeneric().AsQueryable()); } [Fact] public void ReturnsSelfIfPossible() { IEnumerable<int> query = Enumerable.Repeat(1, 2).AsQueryable(); Assert.Same(query, query.AsQueryable()); } [Fact] public void ReturnsSelfIfPossibleNonGeneric() { IEnumerable query = Enumerable.Repeat(1, 2).AsQueryable(); Assert.Same(query, query.AsQueryable()); } [Fact] public static void QueryableOfQueryable() { IQueryable<int> queryable1 = new [] { 1, 2, 3 }.AsQueryable(); IQueryable<int>[] queryableArray1 = { queryable1, queryable1 }; IQueryable<IQueryable<int>> queryable2 = queryableArray1.AsQueryable(); ParameterExpression expression1 = Expression.Parameter(typeof(IQueryable<int>), "i"); ParameterExpression[] expressionArray1 = { expression1 }; IQueryable<IQueryable<int>> queryable3 = queryable2.Select(Expression.Lambda<Func<IQueryable<int>, IQueryable<int>>>(expression1, expressionArray1)); int i = queryable3.Count(); Assert.Equal(2, i); } [Fact] public static void MatchSequencePattern() { // If a change to Queryable has required a change to the exception list in this test // make the same change at src/System.Linq/tests/ConsistencyTests.cs MethodInfo enumerableNotInQueryable = GetMissingExtensionMethod( typeof(Enumerable), typeof(Queryable), new [] { "ToLookup", "ToDictionary", "ToArray", "AsEnumerable", "ToList", "Fold", "LeftJoin", "Append", "Prepend", "ToHashSet" } ); Assert.True(enumerableNotInQueryable == null, string.Format("Enumerable method {0} not defined by Queryable", enumerableNotInQueryable)); MethodInfo queryableNotInEnumerable = GetMissingExtensionMethod( typeof(Queryable), typeof(Enumerable), new [] { "AsQueryable" } ); Assert.True(queryableNotInEnumerable == null, string.Format("Queryable method {0} not defined by Enumerable", queryableNotInEnumerable)); } private static MethodInfo GetMissingExtensionMethod(Type a, Type b, IEnumerable<string> excludedMethods) { var dex = new HashSet<string>(excludedMethods); var aMethods = a.GetMethods(BindingFlags.Static | BindingFlags.Public) .Where(m => m.CustomAttributes.Any(c => c.AttributeType == typeof(ExtensionAttribute))) .ToLookup(m => m.Name); MethodComparer mc = new MethodComparer(); var bMethods = b.GetMethods(BindingFlags.Static | BindingFlags.Public) .Where(m => m.CustomAttributes.Any(c => c.AttributeType == typeof(ExtensionAttribute))) .ToLookup(m => m, mc); foreach (var group in aMethods.Where(g => !dex.Contains(g.Key))) { foreach (MethodInfo m in group) { if (!bMethods.Contains(m)) return m; } } return null; } private class MethodComparer : IEqualityComparer<MethodInfo> { public int GetHashCode(MethodInfo m) => m.Name.GetHashCode(); public bool Equals(MethodInfo a, MethodInfo b) { if (a.Name != b.Name) return false; ParameterInfo[] pas = a.GetParameters(); ParameterInfo[] pbs = b.GetParameters(); if (pas.Length != pbs.Length) return false; Type[] aArgs = a.GetGenericArguments(); Type[] bArgs = b.GetGenericArguments(); for (int i = 0, n = pas.Length; i < n; i++) { ParameterInfo pa = pas[i]; ParameterInfo pb = pbs[i]; Type ta = Strip(pa.ParameterType); Type tb = Strip(pb.ParameterType); if (ta.IsGenericType && tb.IsGenericType) { if (ta.GetGenericTypeDefinition() != tb.GetGenericTypeDefinition()) { return false; } } else if (ta.IsGenericParameter && tb.IsGenericParameter) { return Array.IndexOf(aArgs, ta) == Array.IndexOf(bArgs, tb); } else if (ta != tb) { return false; } } return true; } private Type Strip(Type t) { if (t.IsGenericType) { Type g = t; if (!g.IsGenericTypeDefinition) { g = t.GetGenericTypeDefinition(); } if (g == typeof(IQueryable<>) || g == typeof(IEnumerable<>)) { return typeof(IEnumerable); } if (g == typeof(Expression<>)) { return t.GetGenericArguments()[0]; } if (g == typeof(IOrderedEnumerable<>) || g == typeof(IOrderedQueryable<>)) { return typeof(IOrderedQueryable); } } else { if (t == typeof(IQueryable)) { return typeof(IEnumerable); } } return t; } } } }
//--------------------------------------------------------------------- // <copyright file="TypeSystem.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] //--------------------------------------------------------------------- namespace System.Data.Objects.ELinq { using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; /// <summary> /// Static utility class. Replica of query\DLinq\TypeSystem.cs /// </summary> internal static class TypeSystem { private static readonly MethodInfo s_getDefaultMethod = typeof(TypeSystem).GetMethod( "GetDefault", BindingFlags.Static | BindingFlags.NonPublic); private static T GetDefault<T>() { return default(T); } [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] internal static object GetDefaultValue(Type type) { // null is always the default for non value types and Nullable<> if (!type.IsValueType || (type.IsGenericType && typeof(Nullable<>) == type.GetGenericTypeDefinition())) { return null; } MethodInfo getDefaultMethod = s_getDefaultMethod.MakeGenericMethod(type); object defaultValue = getDefaultMethod.Invoke(null, new object[] { }); return defaultValue; } internal static bool IsSequenceType(Type seqType) { return FindIEnumerable(seqType) != null; } internal static Type GetDelegateType(IEnumerable<Type> inputTypes, Type returnType) { EntityUtil.CheckArgumentNull(returnType, "returnType"); // Determine Func<> type (generic args are the input parameter types plus the return type) inputTypes = inputTypes ?? Enumerable.Empty<Type>(); int argCount = inputTypes.Count(); Type[] typeArgs = new Type[argCount + 1]; int i = 0; foreach (Type typeArg in inputTypes) { typeArgs[i++] = typeArg; } typeArgs[i] = returnType; // Find appropriate Func<> Type delegateType; switch (argCount) { case 0: delegateType = typeof(Func<>); break; case 1: delegateType = typeof(Func<,>); break; case 2: delegateType = typeof(Func<,,>); break; case 3: delegateType = typeof(Func<,,,>); break; case 4: delegateType = typeof(Func<,,,,>); break; case 5: delegateType = typeof(Func<,,,,,>); break; case 6: delegateType = typeof(Func<,,,,,,>); break; case 7: delegateType = typeof(Func<,,,,,,,>); break; case 8: delegateType = typeof(Func<,,,,,,,,>); break; case 9: delegateType = typeof(Func<,,,,,,,,,>); break; case 10: delegateType = typeof(Func<,,,,,,,,,,>); break; case 11: delegateType = typeof(Func<,,,,,,,,,,,>); break; case 12: delegateType = typeof(Func<,,,,,,,,,,,,>); break; case 13: delegateType = typeof(Func<,,,,,,,,,,,,,>); break; case 14: delegateType = typeof(Func<,,,,,,,,,,,,,,>); break; case 15: delegateType = typeof(Func<,,,,,,,,,,,,,,,>); break; default: Debug.Fail("unexpected argument count"); delegateType = null; break; } delegateType = delegateType.MakeGenericType(typeArgs); return delegateType; } internal static Expression EnsureType(Expression expression, Type requiredType) { Debug.Assert(null != expression, "expression required"); Debug.Assert(null != requiredType, "requiredType"); if (expression.Type != requiredType) { expression = Expression.Convert(expression, requiredType); } return expression; } /// <summary> /// Resolves MemberInfo to a property or field. /// </summary> /// <param name="member">Member to test.</param> /// <param name="name">Name of member.</param> /// <param name="type">Type of member.</param> /// <returns>Given member normalized as a property or field.</returns> internal static MemberInfo PropertyOrField(MemberInfo member, out string name, out Type type) { name = null; type = null; if (member.MemberType == MemberTypes.Field) { FieldInfo field = (FieldInfo)member; name = field.Name; type = field.FieldType; return field; } else if (member.MemberType == MemberTypes.Property) { PropertyInfo property = (PropertyInfo)member; if (0 != property.GetIndexParameters().Length) { // don't support indexed properties throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_PropertyIndexNotSupported); } name = property.Name; type = property.PropertyType; return property; } else if (member.MemberType == MemberTypes.Method) { // this may be a property accessor in disguise (if it's a RuntimeMethodHandle) MethodInfo method = (MethodInfo)member; if (method.IsSpecialName) // property accessor methods must set IsSpecialName { // try to find a property with the given getter foreach (PropertyInfo property in method.DeclaringType.GetProperties( BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) { if (property.CanRead && (property.GetGetMethod(true) == method)) { return PropertyOrField(property, out name, out type); } } } } throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_NotPropertyOrField(member.Name)); } private static Type FindIEnumerable(Type seqType) { // Ignores "terminal" primitive types in the EDM although they may implement IEnumerable<> if (seqType == null || seqType == typeof(string) || seqType == typeof(byte[])) return null; if (seqType.IsArray) return typeof(IEnumerable<>).MakeGenericType(seqType.GetElementType()); if (seqType.IsGenericType) { foreach (Type arg in seqType.GetGenericArguments()) { Type ienum = typeof(IEnumerable<>).MakeGenericType(arg); if (ienum.IsAssignableFrom(seqType)) { return ienum; } } } Type[] ifaces = seqType.GetInterfaces(); if (ifaces != null && ifaces.Length > 0) { foreach (Type iface in ifaces) { Type ienum = FindIEnumerable(iface); if (ienum != null) return ienum; } } if (seqType.BaseType != null && seqType.BaseType != typeof(object)) { return FindIEnumerable(seqType.BaseType); } return null; } internal static Type GetElementType(Type seqType) { Type ienum = FindIEnumerable(seqType); if (ienum == null) return seqType; return ienum.GetGenericArguments()[0]; } internal static bool IsNullableType(Type type) { var nonNullableType = GetNonNullableType(type); return nonNullableType != null && nonNullableType != type; } internal static Type GetNonNullableType(Type type) { if (type != null) { return Nullable.GetUnderlyingType(type) ?? type; } return null; } internal static bool IsImplementationOfGenericInterfaceMethod(this MethodInfo test, Type match, out Type[] genericTypeArguments) { genericTypeArguments = null; // check requirements for a match if (null == test || null == match || !match.IsInterface || !match.IsGenericTypeDefinition || null == test.DeclaringType) { return false; } // we might be looking at the interface implementation directly if (test.DeclaringType.IsInterface && test.DeclaringType.IsGenericType && test.DeclaringType.GetGenericTypeDefinition() == match) { return true; } // figure out if we implement the interface foreach (Type testInterface in test.DeclaringType.GetInterfaces()) { if (testInterface.IsGenericType && testInterface.GetGenericTypeDefinition() == match) { // check if the method aligns var map = test.DeclaringType.GetInterfaceMap(testInterface); if (map.TargetMethods.Contains(test)) { genericTypeArguments = testInterface.GetGenericArguments(); return true; } } } return false; } internal static bool IsImplementationOf(this PropertyInfo propertyInfo, Type interfaceType) { Debug.Assert(interfaceType.IsInterface, "Ensure interfaceType is an interface before calling IsImplementationOf"); // Find the property with the corresponding name on the interface, if present PropertyInfo interfaceProp = interfaceType.GetProperty(propertyInfo.Name, BindingFlags.Public | BindingFlags.Instance); if (null == interfaceProp) { return false; } // If the declaring type is an interface, compare directly. if (propertyInfo.DeclaringType.IsInterface) { return interfaceProp.Equals(propertyInfo); } Debug.Assert(Enumerable.Contains(propertyInfo.DeclaringType.GetInterfaces(), interfaceType), "Ensure propertyInfo.DeclaringType implements interfaceType before calling IsImplementationOf"); bool result = false; // Get the get_<Property> method from the interface property. MethodInfo getInterfaceProp = interfaceProp.GetGetMethod(); // Retrieve the interface mapping for the interface on the candidate property's declaring type. InterfaceMapping interfaceMap = propertyInfo.DeclaringType.GetInterfaceMap(interfaceType); // Find the index of the interface's get_<Property> method in the interface methods of the interface map int propIndex = Array.IndexOf(interfaceMap.InterfaceMethods, getInterfaceProp); // Find the method on the property's declaring type that is the target of the interface's get_<Property> method. // This method will be at the same index in the interface mapping's target methods as the get_<Property> interface method index. MethodInfo[] targetMethods = interfaceMap.TargetMethods; if (propIndex > -1 && propIndex < targetMethods.Length) { // If the get method of the referenced property is the target of the get_<Property> method in this interface mapping, // then the property is the implementation of the interface's corresponding property. MethodInfo getPropertyMethod = propertyInfo.GetGetMethod(); if (getPropertyMethod != null) { result = getPropertyMethod.Equals(targetMethods[propIndex]); } } return result; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; using Test.Utilities; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UsePropertiesWhereAppropriateAnalyzer, Microsoft.CodeQuality.CSharp.Analyzers.ApiDesignGuidelines.CSharpUsePropertiesWhereAppropriateFixer>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UsePropertiesWhereAppropriateAnalyzer, Microsoft.CodeQuality.VisualBasic.Analyzers.ApiDesignGuidelines.BasicUsePropertiesWhereAppropriateFixer>; namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests { public class UsePropertiesWhereAppropriateTests { [Fact] public async Task CSharp_CA1024NoDiagnosticCasesAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Collections; public class GenericType<T> { } public class Base { public virtual int GetSomething() { return 0; } public virtual int GetOverloadedMethod() { return 1; } public virtual int GetOverloadedMethod(int i) { return i; } } public class Class1 : Base { private string fileName = """"; // 1) Returns void public void GetWronglyNamedMethod() { } // 2) Not a method public string LogFile { get { return fileName; } } // 3) Returns an array type public int[] GetValues() { return null; } // 4) Has parameters public int[] GetMethodWithParameters(int p) { return new int[] { p }; } // 5a) Name doesn't start with a 'Get' public int SomeMethod() { return 0; } // 5b) First compound word is not 'Get' public int GetterMethod() { return 0; } // 6) Generic method public object GetGenericMethod<T>() { return new GenericType<T>(); } // 7) Override public override int GetSomething() { return 1; } // 8) Method with overloads public override int GetOverloadedMethod() { return 1; } public override int GetOverloadedMethod(int i) { return i; } // 9) Methods with special name public override int GetHashCode() { return 0; } public IEnumerator GetEnumerator() { return null; } public ref string GetPinnableReference() // If the method isn't ref-returning, there will be a diagnostic. { return ref fileName; } // 10) Method with invocation expressions public int GetSomethingWithInvocation() { Console.WriteLine(this); return 0; } // 11) Method named 'Get' public string Get() { return fileName; } // 12) Private method private string GetSomethingPrivate() { return fileName; } // 13) Internal method internal string GetSomethingInternal() { return fileName; } } public class Class2 { private string fileName = """"; public ref readonly string GetPinnableReference() // If the method isn't ref-returning, there will be a diagnostic. { return ref fileName; } } "); } [Fact] public async Task CSharp_CA1024DiagnosticCasesAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class { private string fileName = ""data.txt""; public string GetFileName() { return fileName; } public string Get_FileName2() { return fileName; } public string Get123() { return fileName; } protected string GetFileNameProtected() { return fileName; } public int GetPinnableReference() // Not a ref-return method. { return 0; } } ", GetCA1024CSharpResultAt(6, 19, "GetFileName"), GetCA1024CSharpResultAt(11, 19, "Get_FileName2"), GetCA1024CSharpResultAt(16, 19, "Get123"), GetCA1024CSharpResultAt(21, 22, "GetFileNameProtected"), GetCA1024CSharpResultAt(26, 16, "GetPinnableReference")); } [Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")] public async Task CSharp_CA1024NoDiagnosticCases_InternalAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class { private string fileName = ""data.txt""; internal string GetFileName() { return fileName; } private string Get_FileName2() { return fileName; } private class InnerClass { private string fileName = ""data.txt""; public string Get123() { return fileName; } } } "); } [Fact] public async Task VisualBasic_CA1024NoDiagnosticCasesAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System.Collections Public Class Base Public Overridable Function GetSomething() As Integer Return 0 End Function End Class Public Class Class1 Inherits Base Private fileName As String ' 1) Returns void Public Sub GetWronglyNamedMethod() End Sub ' 2) Not a method Public ReadOnly Property LogFile() As String Get Return fileName End Get End Property ' 3) Returns an array type Public Function GetValues() As Integer() Return Nothing End Function ' 4) Has parameters Public Function GetMethodWithParameters(p As Integer) As Integer() Return New Integer() {p} End Function ' 5a) Name doesn't start with a 'Get' Public Function SomeMethod() As Integer Return 0 End Function ' 5b) First compound word is not 'Get' Public Function GetterMethod() As Integer Return 0 End Function ' 6) Generic method Public Function GetGenericMethod(Of T)() As Object Return New GenericType(Of T)() End Function ' 7) Override Public Overrides Function GetSomething() As Integer Return 1 End Function ' 8) Method with overloads Public Function GetOverloadedMethod() As Integer Return 1 End Function Public Function GetOverloadedMethod(i As Integer) As Integer Return i End Function ' 9) Methods with special name Public Overloads Function GetHashCode() As Integer Return 0 End Function Public Function GetEnumerator() As IEnumerator Return Nothing End Function ' 10) Method with invocation expressions Public Function GetSomethingWithInvocation() As Integer System.Console.WriteLine(Me) Return 0 End Function ' 11) Method named 'Get' Public Function [Get]() As String Return fileName End Function ' 12) Private method Private Function GetSomethingPrivate() As String Return fileName End Function ' 13) Friend method Friend Function GetSomethingInternal() As String Return fileName End Function End Class Public Class GenericType(Of T) End Class "); } [Fact] public async Task CSharp_CA1024NoDiagnosticOnUnboundMethodCallerAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public class class1 { public int GetSomethingWithUnboundInvocation() { Console.WriteLine(this); return 0; } } "); } [Fact] public async Task VisualBasic_CA1024NoDiagnosticOnUnboundMethodCallerAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System Public Class class1 Public Function GetSomethingWithUnboundInvocation() As Integer Console.WriteLine(Me) Return 0 End Function End Class "); } [Fact] public async Task VisualBasic_CA1024DiagnosticCasesAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class Class1 Private fileName As String Public Function GetFileName() As String Return filename End Function Public Function Get_FileName2() As String Return filename End Function Public Function Get123() As String Return filename End Function Protected Function GetFileNameProtected() As String Return filename End Function End Class ", GetCA1024BasicResultAt(5, 21, "GetFileName"), GetCA1024BasicResultAt(9, 21, "Get_FileName2"), GetCA1024BasicResultAt(13, 21, "Get123"), GetCA1024BasicResultAt(17, 24, "GetFileNameProtected")); } [Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")] public async Task VisualBasic_CA1024NoDiagnosticCases_InternalAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class Class1 Private fileName As String Friend Function GetFileName() As String Return filename End Function Private Function Get_FileName2() As String Return filename End Function Private Class InnerClass Private fileName As String Public Function Get123() As String Return filename End Function End Class End Class "); } [Fact, WorkItem(1551, "https://github.com/dotnet/roslyn-analyzers/issues/1551")] public async Task CA1024_ExplicitInterfaceImplementation_NoDiagnosticAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public interface ISomething { object GetContent(); } public class Something : ISomething { object ISomething.GetContent() { return null; } } "); } [Fact, WorkItem(1551, "https://github.com/dotnet/roslyn-analyzers/issues/1551")] public async Task CA1024_ImplicitInterfaceImplementation_NoDiagnosticAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public interface ISomething { object GetContent(); } public class Something : ISomething { public object GetContent() { return null; } } "); } [Fact, WorkItem(3877, "https://github.com/dotnet/roslyn-analyzers/issues/3877")] public async Task CA1024_ReturnsTask_NoDiagnosticAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System.Threading.Tasks; public class Something { public Task GetTask() => default(Task); public Task<int> GetGenericTask() => default(Task<int>); public ValueTask GetValueTask() => default(ValueTask); public ValueTask<int> GetGenericValueTask() => default(ValueTask<int>); } "); await VerifyVB.VerifyAnalyzerAsync(@" Imports System.Threading.Tasks Public Class Something Public Function GetTask() As Task Return Nothing End Function Public Function GetGenericTask() As Task(Of Integer) Return Nothing End Function Public Function GetValueTask() As ValueTask Return Nothing End Function Public Function GetGenericValueTask() As ValueTask(Of Integer) Return Nothing End Function End Class "); } [Fact, WorkItem(4623, "https://github.com/dotnet/roslyn-analyzers/issues/4623")] public async Task AwaiterPattern_INotifyCompletion_NoDiagnosticAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Runtime.CompilerServices; public class DummyAwaiter : INotifyCompletion { public object GetResult() => null; public bool IsCompleted => false; public void OnCompleted(Action continuation) => throw null; }"); } [Fact, WorkItem(4623, "https://github.com/dotnet/roslyn-analyzers/issues/4623")] public async Task AwaiterPattern_ICriticalNotifyCompletion_NoDiagnosticAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Runtime.CompilerServices; public class DummyAwaiter : ICriticalNotifyCompletion { public object GetResult() => null; public bool IsCompleted => false; public void OnCompleted(Action continuation) => throw null; public void UnsafeOnCompleted(Action continuation) => throw null; }"); } [Fact, WorkItem(4623, "https://github.com/dotnet/roslyn-analyzers/issues/4623")] public async Task AwaitablePattern_NoDiagnosticAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Runtime.CompilerServices; public class DummyAwaitable { public DummyAwaiter GetAwaiter() => new DummyAwaiter(); } public class DummyAwaiter : INotifyCompletion { public void GetResult() { } public bool IsCompleted => false; public void OnCompleted(Action continuation) => throw null; }"); } private static DiagnosticResult GetCA1024CSharpResultAt(int line, int column, string methodName) #pragma warning disable RS0030 // Do not used banned APIs => VerifyCS.Diagnostic() .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(methodName); private static DiagnosticResult GetCA1024BasicResultAt(int line, int column, string methodName) #pragma warning disable RS0030 // Do not used banned APIs => VerifyVB.Diagnostic() .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(methodName); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void MoveMaskVector128SByte() { var test = new SimdScalarUnaryOpConvertTest__MoveMaskVector128SByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimdScalarUnaryOpConvertTest__MoveMaskVector128SByte { private struct TestStruct { public Vector128<SByte> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld), ref Unsafe.As<SByte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); return testStruct; } public void RunStructFldScenario(SimdScalarUnaryOpConvertTest__MoveMaskVector128SByte testClass) { var result = Sse2.MoveMask(_fld); testClass.ValidateResult(_fld, result); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static SByte[] _data = new SByte[Op1ElementCount]; private static Vector128<SByte> _clsVar; private Vector128<SByte> _fld; private SimdScalarUnaryOpTest__DataTable<SByte> _dataTable; static SimdScalarUnaryOpConvertTest__MoveMaskVector128SByte() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar), ref Unsafe.As<SByte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); } public SimdScalarUnaryOpConvertTest__MoveMaskVector128SByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld), ref Unsafe.As<SByte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new SimdScalarUnaryOpTest__DataTable<SByte>(_data, LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.MoveMask( Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr) ); ValidateResult(_dataTable.inArrayPtr, result); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.MoveMask( Sse2.LoadVector128((SByte*)(_dataTable.inArrayPtr)) ); ValidateResult(_dataTable.inArrayPtr, result); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.MoveMask( Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArrayPtr)) ); ValidateResult(_dataTable.inArrayPtr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.MoveMask), new Type[] { typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr) }); ValidateResult(_dataTable.inArrayPtr, (Int32)(result)); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.MoveMask), new Type[] { typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Sse2.LoadVector128((SByte*)(_dataTable.inArrayPtr)) }); ValidateResult(_dataTable.inArrayPtr, (Int32)(result)); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.MoveMask), new Type[] { typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArrayPtr)) }); ValidateResult(_dataTable.inArrayPtr, (Int32)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.MoveMask( _clsVar ); ValidateResult(_clsVar, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr); var result = Sse2.MoveMask(firstOp); ValidateResult(firstOp, result); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Sse2.LoadVector128((SByte*)(_dataTable.inArrayPtr)); var result = Sse2.MoveMask(firstOp); ValidateResult(firstOp, result); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArrayPtr)); var result = Sse2.MoveMask(firstOp); ValidateResult(firstOp, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimdScalarUnaryOpConvertTest__MoveMaskVector128SByte(); var result = Sse2.MoveMask(test._fld); ValidateResult(test._fld, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.MoveMask(_fld); ValidateResult(_fld, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.MoveMask(test._fld); ValidateResult(test._fld, result); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<SByte> firstOp, Int32 result, [CallerMemberName] string method = "") { SByte[] inArray = new SByte[Op1ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray[0]), firstOp); ValidateResult(inArray, result, method); } private void ValidateResult(void* firstOp, Int32 result, [CallerMemberName] string method = "") { SByte[] inArray = new SByte[Op1ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray, result, method); } private void ValidateResult(SByte[] firstOp, Int32 result, [CallerMemberName] string method = "") { bool succeeded = true; if ((firstOp[0] >= 0) != ((result & 1) == 0)) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.MoveMask)}<Int32>(Vector128<SByte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: result"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace DecisionsCoreProxy.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.OrTools.Sat; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; /// <summary> /// This model solves a multicommodity mono-routing problem with /// capacity constraints and a max usage cost structure. This means /// that given a graph with capacity on edges, and a set of demands /// (source, destination, traffic), the goal is to assign one unique /// path for each demand such that the cost is minimized. The cost is /// defined by the maximum ratio utilization (traffic/capacity) for all /// arcs. There is also a penalty associated with an traffic of an arc /// being above the comfort zone, 85% of the capacity by default. /// Please note that constraint programming is well suited here because /// we cannot have multiple active paths for a single demand. /// Otherwise, a approach based on a linear solver is a better match. /// A random problem generator is also included. /// </summary> public class NetworkRoutingSat { private static int clients = 0; // Number of network clients nodes. If equal to zero, then all // backbones nodes are also client nodes. private static int backbones = 0; // "Number of backbone nodes" private static int demands = 0; // "Number of network demands." private static int trafficMin = 0; // "Min traffic of a demand." private static int trafficMax = 0; // "Max traffic of a demand." private static int minClientDegree = 0; //"Min number of connections from a client to the backbone." private static int maxClientDegree = 0; //"Max number of connections from a client to the backbone." private static int minBackboneDegree = 0; //"Min number of connections from a backbone node to the rest of the // backbone nodes." private static int maxBackboneDegree = 0; // "Max number of connections from a backbone node to // the rest of the backbone nodes." private static int maxCapacity = 0; //"Max traffic on any arc." private static int fixedChargeCost = 0; //"Fixed charged cost when using an arc." private static int seed = 0; //"Random seed" private static double comfortZone = 0.85; // "Above this limit in 1/1000th, the link is said to // be congested." private static int extraHops = 6; // "When creating all paths for a demand, we look at paths with // maximum length 'shortest path + extra_hops'" private static int maxPaths = 1200; //"Max number of possible paths for a demand." private static bool printModel = false; //"Print details of the model." private static string parameters = ""; // "Sat parameters." private const long kDisconnectedDistance = -1L; static void Main(string[] args) { readArgs(args); var builder = new NetworkRoutingDataBuilder(); var data = builder.BuildModelFromParameters(clients, backbones, demands, trafficMin, trafficMax, minClientDegree, maxClientDegree, minBackboneDegree, maxBackboneDegree, maxCapacity, fixedChargeCost, seed); var solver = new NetworkRoutingSolver(); solver.Init(data, extraHops, maxPaths); var cost = solver.Solve(); Console.WriteLine($"Final cost = {cost}"); } private static void readArgs(string[] args) { readInt(args, ref clients, nameof(clients)); readInt(args, ref backbones, nameof(backbones)); readInt(args, ref demands, nameof(demands)); readInt(args, ref trafficMin, nameof(trafficMin)); readInt(args, ref trafficMax, nameof(trafficMax)); readInt(args, ref minClientDegree, nameof(minClientDegree)); readInt(args, ref maxClientDegree, nameof(maxClientDegree)); readInt(args, ref minBackboneDegree, nameof(minBackboneDegree)); readInt(args, ref maxBackboneDegree, nameof(maxBackboneDegree)); readInt(args, ref maxCapacity, nameof(maxCapacity)); readInt(args, ref fixedChargeCost, nameof(fixedChargeCost)); readInt(args, ref seed, nameof(seed)); readDouble(args, ref comfortZone, nameof(comfortZone)); readInt(args, ref extraHops, nameof(extraHops)); readInt(args, ref maxPaths, nameof(maxPaths)); readBoolean(args, ref printModel, nameof(printModel)); readString(args, ref parameters, nameof(parameters)); } private static void readDouble(string[] args, ref double setting, string arg) { var v = getArgValue(args, arg); if (v.IsSet) { setting = Convert.ToDouble(v.Value); } } private static void readInt(string[] args, ref int setting, string arg) { var v = getArgValue(args, arg); if (v.IsSet) { setting = Convert.ToInt32(v.Value); } } private static void readBoolean(string[] args, ref bool setting, string arg) { var v = getArgValue(args, arg); if (v.IsSet) { setting = Convert.ToBoolean(v.Value); } } private static void readString(string[] args, ref string setting, string arg) { var v = getArgValue(args, arg); if (v.IsSet) { setting = v.Value; } } private static (bool IsSet, string Value) getArgValue(string[] args, string arg) { string lookup = $"--{arg}="; var item = args.FirstOrDefault(x => x.StartsWith(lookup)); if (string.IsNullOrEmpty(item)) { return (false, string.Empty); } return (true, item.Replace(lookup, string.Empty)); } /// <summary> /// Contains problem data. It assumes capacities are symmetrical: /// (capacity(i->j) == capacity(j->i)). /// Demands are not symmetrical. /// </summary> public class NetworkRoutingData { private Dictionary<(int source, int destination), int> _arcs = new Dictionary<(int source, int destination), int>(); private Dictionary<(int node1, int node2), int> _demands = new Dictionary<(int node1, int node2), int>(); public int NumberOfNodes { get; set; } = -1; public int NumberOfArcs { get { return _arcs.Count(); } } public int NumberOfDemands { get { return _demands.Count(); } } public int MaximumCapacity { get; set; } = -1; public int FixedChargeCost { get; set; } = -1; public string Name { get; set; } = string.Empty; public void AddDemand(int source, int destination, int traffic) { var pair = (source, destination); if (!_demands.ContainsKey(pair)) _demands.Add(pair, traffic); } public void AddArc(int node1, int node2, int capacity) { _arcs.Add((Math.Min(node1, node2), Math.Max(node1, node2)), capacity); } public int Demand(int source, int destination) { var pair = (source, destination); if (_demands.TryGetValue(pair, out var demand)) return demand; return 0; } public int Capacity(int node1, int node2) { var pair = (Math.Min(node1, node2), Math.Max(node1, node2)); if (_arcs.TryGetValue(pair, out var capacity)) return capacity; return 0; } } /// <summary> /// Random generator of problem. This generator creates a random /// problem. This problem uses a special topology. There are /// 'numBackbones' nodes and 'numClients' nodes. if 'numClients' is /// null, then all backbones nodes are also client nodes. All traffic /// originates and terminates in client nodes. Each client node is /// connected to 'minClientDegree' - 'maxClientDegree' backbone /// nodes. Each backbone node is connected to 'minBackboneDegree' - /// 'maxBackboneDegree' other backbone nodes. There are 'numDemands' /// demands, with a traffic between 'trafficMin' and 'trafficMax'. /// Each arc has a capacity of 'maxCapacity'. Using an arc incurs a /// fixed cost of 'fixedChargeCost'. /// </summary> public class NetworkRoutingDataBuilder { private List<List<bool>> _network; private List<int> _degrees; private Random _random; public NetworkRoutingData BuildModelFromParameters(int numClients, int numBackbones, int numDemands, int trafficMin, int trafficMax, int minClientDegree, int maxClientDegree, int minBackboneDegree, int maxBackboneDegree, int maxCapacity, int fixedChargeCost, int seed) { Debug.Assert(numBackbones >= 1); Debug.Assert(numClients >= 0); Debug.Assert(numDemands >= 1); Debug.Assert(numDemands <= (numClients == 0 ? numBackbones * numBackbones : numClients * numBackbones)); Debug.Assert(maxClientDegree >= minClientDegree); Debug.Assert(maxBackboneDegree >= minBackboneDegree); Debug.Assert(trafficMax >= 1); Debug.Assert(trafficMax >= trafficMin); Debug.Assert(trafficMin >= 1); Debug.Assert(maxBackboneDegree >= 2); Debug.Assert(maxClientDegree >= 2); Debug.Assert(maxClientDegree <= numBackbones); Debug.Assert(maxBackboneDegree <= numBackbones); Debug.Assert(maxCapacity >= 1); int size = numBackbones + numClients; initData(size, seed); buildGraph(numClients, numBackbones, minClientDegree, maxClientDegree, minBackboneDegree, maxBackboneDegree); NetworkRoutingData data = new NetworkRoutingData(); createDemands(numClients, numBackbones, numDemands, trafficMin, trafficMax, data); fillData(numClients, numBackbones, numDemands, trafficMin, trafficMax, minClientDegree, maxClientDegree, minBackboneDegree, maxBackboneDegree, maxCapacity, fixedChargeCost, seed, data); return data; } private void initData(int size, int seed) { _network = new List<List<bool>>(size); for (int i = 0; i < size; i++) { _network.Add(new List<bool>(size)); for (int j = 0; j < size; j++) { _network[i].Add(false); } } _degrees = new List<int>(size); for (int i = 0; i < size; i++) { _degrees.Add(0); } _random = new Random(seed); } private void buildGraph(int numClients, int numBackbones, int minClientDegree, int maxClientDegree, int minBackboneDegree, int maxBackboneDegree) { int size = numBackbones + numClients; for (int i = 1; i < numBackbones; i++) { int j = randomUniform(i); addEdge(i, j); } List<int> notFull = new List<int>(); HashSet<int> toComplete = new HashSet<int>(); for (int i = 0; i < numBackbones; i++) { if (_degrees[i] < minBackboneDegree) { toComplete.Add(i); } if (_degrees[i] < maxBackboneDegree) { notFull.Add(i); } } while (toComplete.Any() && notFull.Count > 1) { int node1 = getNextToComplete(toComplete); int node2 = node1; while (node2 == node1 || _degrees[node2] >= maxBackboneDegree) { node2 = randomUniform(numBackbones); } addEdge(node1, node2); if (_degrees[node1] >= minBackboneDegree) { toComplete.Remove(node1); } if (_degrees[node2] >= minBackboneDegree) { toComplete.Remove(node2); } if (_degrees[node1] >= maxBackboneDegree) { notFull.Remove(node1); } if (_degrees[node2] >= maxBackboneDegree) { notFull.Remove(node2); } } // Then create the client nodes connected to the backbone nodes. // If numClient is 0, then backbone nodes are also client nodes. for (int i = numBackbones; i < size; i++) { int degree = randomInInterval(minClientDegree, maxClientDegree); while (_degrees[i] < degree) { int j = randomUniform(numBackbones); if (!_network[i][j]) { addEdge(i, j); } } } } private int getNextToComplete(HashSet<int> toComplete) { return toComplete.Last(); } private void createDemands(int numClients, int numBackbones, int numDemands, int trafficMin, int trafficMax, NetworkRoutingData data) { while (data.NumberOfDemands < numDemands) { int source = randomClient(numClients, numBackbones); int dest = source; while (dest == source) { dest = randomClient(numClients, numBackbones); } int traffic = randomInInterval(trafficMin, trafficMax); data.AddDemand(source, dest, traffic); } } private void fillData(int numClients, int numBackbones, int numDemands, int trafficMin, int trafficMax, int minClientDegree, int maxClientDegree, int minBackboneDegree, int maxBackboneDegree, int maxCapacity, int fixedChargeCost, int seed, NetworkRoutingData data) { int size = numBackbones + numClients; string name = $"mp_c{numClients}_b{numBackbones}_d{numDemands}.t{trafficMin}-{trafficMax}.cd{minClientDegree}-{maxClientDegree}.bd{minBackboneDegree}-{maxBackboneDegree}.mc{maxCapacity}.fc{fixedChargeCost}.s{seed}"; data.Name = name; data.NumberOfNodes = size; int numArcs = 0; for (int i = 0; i < size - 1; i++) { for (int j = i + 1; j < size; j++) { if (_network[i][j]) { data.AddArc(i, j, maxCapacity); numArcs++; } } } data.MaximumCapacity = maxCapacity; data.FixedChargeCost = fixedChargeCost; } private void addEdge(int i, int j) { _degrees[i]++; _degrees[j]++; _network[i][j] = true; _network[j][i] = true; } private int randomInInterval(int intervalMin, int intervalMax) { var p = randomUniform(intervalMax - intervalMin + 1) + intervalMin; return p; } private int randomClient(int numClients, int numBackbones) { var p = (numClients == 0) ? randomUniform(numBackbones) : randomUniform(numClients) + numBackbones; return p; } private int randomUniform(int max) { var r = _random.Next(max); return r; } } [DebuggerDisplay("Source {Source} Destination {Destination} Traffic {Traffic}")] public struct Demand { public Demand(int source, int destination, int traffic) { Source = source; Destination = destination; Traffic = traffic; } public int Source { get; } public int Destination { get; } public int Traffic { get; } } public class NetworkRoutingSolver { private List<(long source, long destination, int arcId)> _arcsData = new List<(long source, long destination, int arcId)>(); private List<int> _arcCapacity = new List<int>(); private List<Demand> _demands = new List<Demand>(); private List<int> _allMinPathLengths = new List<int>(); private List<List<int>> _capacity; private List<List<HashSet<int>>> _allPaths; public int NumberOfNodes { get; private set; } = -1; private int countArcs { get { return _arcsData.Count / 2; } } public void ComputeAllPathsForOneDemandAndOnePathLength(int demandIndex, int maxLength, int maxPaths) { // We search for paths of length exactly 'maxLength'. CpModel cpModel = new CpModel(); var arcVars = new List<IntVar>(); var nodeVars = new List<IntVar>(); for (int i = 0; i < maxLength; i++) { nodeVars.Add(cpModel.NewIntVar(0, NumberOfNodes - 1, string.Empty)); } for (int i = 0; i < maxLength - 1; i++) { arcVars.Add(cpModel.NewIntVar(-1, countArcs - 1, string.Empty)); } var arcs = getArcsData(); for (int i = 0; i < maxLength - 1; i++) { var tmpVars = new List<IntVar>(); tmpVars.Add(nodeVars[i]); tmpVars.Add(nodeVars[i + 1]); tmpVars.Add(arcVars[i]); var table = cpModel.AddAllowedAssignments(tmpVars, arcs); } var demand = _demands[demandIndex]; cpModel.Add(nodeVars[0] == demand.Source); cpModel.Add(nodeVars[maxLength - 1] == demand.Destination); cpModel.AddAllDifferent(arcVars); cpModel.AddAllDifferent(nodeVars); var solver = new CpSolver(); solver.StringParameters = "enumerate_all_solutions:true"; var solutionPrinter = new FeasibleSolutionChecker(demandIndex, ref _allPaths, maxLength, arcVars, maxPaths, nodeVars); var status = solver.Solve(cpModel, solutionPrinter); } private long[,] getArcsData() { long[,] arcs = new long[_arcsData.Count, 3]; for (int i = 0; i < _arcsData.Count; i++) { var data = _arcsData[i]; arcs[i, 0] = data.source; arcs[i, 1] = data.destination; arcs[i, 2] = data.arcId; } return arcs; } public int ComputeAllPaths(int extraHops, int maxPaths) { int numPaths = 0; for (int demandIndex = 0; demandIndex < _demands.Count; demandIndex++) { int minPathLength = _allMinPathLengths[demandIndex]; for (int maxLength = minPathLength + 1; maxLength <= minPathLength + extraHops + 1; maxLength++) { ComputeAllPathsForOneDemandAndOnePathLength(demandIndex, maxLength, maxPaths); if (_allPaths[demandIndex].Count >= maxPaths) break; } numPaths += _allPaths[demandIndex].Count; } return numPaths; } public void AddArcData(long source, long destination, int arcId) { _arcsData.Add((source, destination, arcId)); } public void InitArcInfo(NetworkRoutingData data) { int numArcs = data.NumberOfArcs; _capacity = new List<List<int>>(NumberOfNodes); for (int nodeIndex = 0; nodeIndex < NumberOfNodes; nodeIndex++) { _capacity.Add(new List<int>(NumberOfNodes)); for (int i = 0; i < NumberOfNodes; i++) { _capacity[nodeIndex].Add(0); } } int arcId = 0; for (int i = 0; i < NumberOfNodes - 1; i++) { for (int j = i + 1; j < NumberOfNodes; j++) { int capacity = data.Capacity(i, j); if (capacity > 0) { AddArcData(i, j, arcId); AddArcData(j, i, arcId); arcId++; _arcCapacity.Add(capacity); _capacity[i][j] = capacity; _capacity[j][i] = capacity; if (printModel) { Console.WriteLine($"Arc {i} <-> {j} with capacity {capacity}"); } } } } Debug.Assert(arcId == numArcs); } public int InitDemandInfo(NetworkRoutingData data) { int numDemands = data.NumberOfDemands; int totalDemand = 0; for (int i = 0; i < NumberOfNodes; i++) { for (int j = 0; j < NumberOfNodes; j++) { int traffic = data.Demand(i, j); if (traffic > 0) { _demands.Add(new Demand(i, j, traffic)); totalDemand += traffic; } } } Debug.Assert(numDemands == _demands.Count); return totalDemand; } public long InitShortestPaths(NetworkRoutingData data) { int numDemands = data.NumberOfDemands; long totalCumulatedTraffic = 0L; _allMinPathLengths.Clear(); var paths = new List<int>(); for (int demandIndex = 0; demandIndex < numDemands; demandIndex++) { paths.Clear(); var demand = _demands[demandIndex]; var r = DijkstraShortestPath(NumberOfNodes, demand.Source, demand.Destination, ((int x, int y)p) => hasArc(p.x, p.y), kDisconnectedDistance, paths); _allMinPathLengths.Add(paths.Count - 1); var minPathLength = _allMinPathLengths[demandIndex]; totalCumulatedTraffic += minPathLength * demand.Traffic; } return totalCumulatedTraffic; } public int InitPaths(NetworkRoutingData data, int extraHops, int maxPaths) { var numDemands = data.NumberOfDemands; Console.WriteLine("Computing all possible paths "); Console.WriteLine($" - extra hops = {extraHops}"); Console.WriteLine($" - max paths per demand = {maxPaths}"); _allPaths = new List<List<HashSet<int>>>(numDemands); var numPaths = ComputeAllPaths(extraHops, maxPaths); for (int demandIndex = 0; demandIndex < numDemands; demandIndex++) { var demand = _demands[demandIndex]; Console.WriteLine( $"Demand from {demand.Source} to {demand.Destination} with traffic {demand.Traffic}, amd {_allPaths[demandIndex].Count} possible paths."); } return numPaths; } public void Init(NetworkRoutingData data, int extraHops, int maxPaths) { Console.WriteLine($"Model {data.Name}"); NumberOfNodes = data.NumberOfNodes; var numArcs = data.NumberOfArcs; var numDemands = data.NumberOfDemands; InitArcInfo(data); var totalDemand = InitDemandInfo(data); var totalAccumulatedTraffic = InitShortestPaths(data); var numPaths = InitPaths(data, extraHops, maxPaths); Console.WriteLine("Model created:"); Console.WriteLine($" - {NumberOfNodes} nodes"); Console.WriteLine($" - {numArcs} arcs"); Console.WriteLine($" - {numDemands} demands"); Console.WriteLine($" - a total traffic of {totalDemand}"); Console.WriteLine($" - a minimum cumulated traffic of {totalAccumulatedTraffic}"); Console.WriteLine($" - {numPaths} possible paths for all demands"); } private long hasArc(int i, int j) { if (_capacity[i][j] > 0) return 1; else return kDisconnectedDistance; } public long Solve() { Console.WriteLine("Solving model"); var numDemands = _demands.Count; var numArcs = countArcs; CpModel cpModel = new CpModel(); var pathVars = new List<List<IntVar>>(numDemands); for (int demandIndex = 0; demandIndex < numDemands; demandIndex++) { pathVars.Add(new List<IntVar>()); for (int arc = 0; arc < numArcs; arc++) { pathVars[demandIndex].Add(cpModel.NewBoolVar("")); } long[,] tuples = new long[_allPaths[demandIndex].Count, numArcs]; int pathCount = 0; foreach (var set in _allPaths[demandIndex]) { foreach (var arc in set) { tuples[pathCount, arc] = 1; } pathCount++; } var pathCt = cpModel.AddAllowedAssignments(pathVars[demandIndex], tuples); } var trafficVars = new List<IntVar>(numArcs); var normalizedTrafficVars = new List<IntVar>(numArcs); var comfortableTrafficVars = new List<IntVar>(numArcs); long maxNormalizedTraffic = 0; for (int arcIndex = 0; arcIndex < numArcs; arcIndex++) { long sumOfTraffic = 0; var vars = new List<IntVar>(); var traffics = new List<int>(); for (int i = 0; i < pathVars.Count; i++) { sumOfTraffic += _demands[i].Traffic; vars.Add(pathVars[i][arcIndex]); traffics.Add(_demands[i].Traffic); } var sum = LinearExpr.ScalProd(vars, traffics); var trafficVar = cpModel.NewIntVar(0, sumOfTraffic, $"trafficVar{arcIndex}"); trafficVars.Add(trafficVar); cpModel.Add(sum == trafficVar); var capacity = _arcCapacity[arcIndex]; var scaledTraffic = cpModel.NewIntVar(0, sumOfTraffic * 1000, $"scaledTrafficVar{arcIndex}"); var scaledTrafficVar = trafficVar * 1000; cpModel.Add(scaledTrafficVar == scaledTraffic); var normalizedTraffic = cpModel.NewIntVar(0, sumOfTraffic * 1000 / capacity, $"normalizedTraffic{arcIndex}"); maxNormalizedTraffic = Math.Max(maxNormalizedTraffic, sumOfTraffic * 1000 / capacity); cpModel.AddDivisionEquality(normalizedTraffic, scaledTraffic, cpModel.NewConstant(capacity)); normalizedTrafficVars.Add(normalizedTraffic); var comfort = cpModel.NewBoolVar($"comfort{arcIndex}"); var safeCapacity = (long)(capacity * comfortZone); cpModel.Add(trafficVar > safeCapacity).OnlyEnforceIf(comfort); cpModel.Add(trafficVar <= safeCapacity).OnlyEnforceIf(comfort.Not()); comfortableTrafficVars.Add(comfort); } var maxUsageCost = cpModel.NewIntVar(0, maxNormalizedTraffic, "maxUsageCost"); cpModel.AddMaxEquality(maxUsageCost, normalizedTrafficVars); var obj = new List<IntVar>() { maxUsageCost }; obj.AddRange(comfortableTrafficVars); cpModel.Minimize(LinearExpr.Sum(obj)); CpSolver solver = new CpSolver(); solver.StringParameters = parameters + " enumerate_all_solutions:true"; CpSolverStatus status = solver.Solve(cpModel, new FeasibleSolutionChecker2(maxUsageCost, comfortableTrafficVars, trafficVars)); return (long)solver.ObjectiveValue; } } private class DijkstraSP { private const long kInfinity = long.MaxValue / 2; private readonly Func<(int, int), long> _graph; private readonly int[] _predecessor; private readonly List<Element> _elements; private readonly AdjustablePriorityQueue<Element> _frontier; private readonly List<int> _notVisited = new List<int>(); private readonly List<int> _addedToFrontier = new List<int>(); public DijkstraSP(int nodeCount, int startNode, Func<(int, int), long> graph, long disconnectedDistance) { NodeCount = nodeCount; StartNode = startNode; this._graph = graph; DisconnectedDistance = disconnectedDistance; _predecessor = new int[nodeCount]; _elements = new List<Element>(nodeCount); _frontier = new AdjustablePriorityQueue<Element>(); } public int NodeCount { get; } public int StartNode { get; } public long DisconnectedDistance { get; } public bool ShortestPath(int endNode, List<int> nodes) { initialize(); bool found = false; while (!_frontier.IsEmpty) { long distance; int node = selectClosestNode(out distance); if (distance == kInfinity) { found = false; break; } else if (node == endNode) { found = true; break; } update(node); } if (found) { findPath(endNode, nodes); } return found; } private void initialize() { for (int i = 0; i < NodeCount; i++) { _elements.Add(new Element { Node = i }); if (i == StartNode) { _predecessor[i] = -1; _elements[i].Distance = 0; _frontier.Add(_elements[i]); } else { _elements[i].Distance = kInfinity; _predecessor[i] = StartNode; _notVisited.Add(i); } } } private int selectClosestNode(out long distance) { var node = _frontier.Top().Node; distance = _frontier.Top().Distance; _frontier.Pop(); _notVisited.Remove(node); _addedToFrontier.Remove(node); return node; } private void update(int node) { foreach (var otherNode in _notVisited) { var graphNode = _graph((node, otherNode)); if (graphNode != DisconnectedDistance) { if (!_addedToFrontier.Contains(otherNode)) { _frontier.Add(_elements[otherNode]); _addedToFrontier.Add(otherNode); } var otherDistance = _elements[node].Distance + graphNode; if (_elements[otherNode].Distance > otherDistance) { _elements[otherNode].Distance = otherDistance; _frontier.NoteChangedPriority(_elements[otherNode]); _predecessor[otherNode] = node; } } } } private void findPath(int dest, List<int> nodes) { var j = dest; nodes.Add(j); while (_predecessor[j] != -1) { nodes.Add(_predecessor[j]); j = _predecessor[j]; } } } public static bool DijkstraShortestPath(int nodeCount, int startNode, int endNode, Func<(int, int), long> graph, long disconnectedDistance, List<int> nodes) { DijkstraSP bf = new DijkstraSP(nodeCount, startNode, graph, disconnectedDistance); return bf.ShortestPath(endNode, nodes); } [DebuggerDisplay("Node = {Node}, HeapIndex = {HeapIndex}, Distance = {Distance}")] private class Element : IHasHeapIndex, IComparable<Element> { public int HeapIndex { get; set; } = -1; public long Distance { get; set; } = 0; public int Node { get; set; } = -1; public int CompareTo(Element other) { if (this.Distance > other.Distance) return -1; if (this.Distance < other.Distance) return 1; return 0; } } private class AdjustablePriorityQueue<T> where T : class, IHasHeapIndex, IComparable<T> { private readonly List<T> _elems = new List<T>(); public void Add(T val) { _elems.Add(val); adjustUpwards(_elems.Count - 1); } public void Remove(T val) { var i = val.HeapIndex; if (i == _elems.Count - 1) { _elems.RemoveAt(_elems.Count - 1); return; } _elems[i] = _elems.Last(); _elems[i].HeapIndex = i; _elems.RemoveAt(_elems.Count - 1); NoteChangedPriority(_elems[i]); } public bool Contains(T val) { var i = val.HeapIndex; if (i < 0 || i >= _elems.Count || _elems[i].CompareTo(val) != 0) return false; return true; } public T Top() { return _elems[0]; } public void Pop() { Remove(Top()); } public int Size() { return _elems.Count; } public bool IsEmpty { get { return !_elems.Any(); } } public void Clear() { _elems.Clear(); } public void CheckValid() { for (int i = 0; i < _elems.Count; i++) { var leftChild = 1 + 2 * i; if (leftChild < _elems.Count) { var compare = _elems[i].CompareTo(_elems[leftChild]); Debug.Assert(compare >= 0); } int rightChild = leftChild + 1; if (rightChild < _elems.Count) { var compare = _elems[i].CompareTo(_elems[rightChild]); Debug.Assert(compare >= 0); } } } public void NoteChangedPriority(T val) { if (_elems.Count == 0) return; var i = val.HeapIndex; var parent = (i - 1) / 2; if (_elems[parent].CompareTo(val) == -1) { adjustUpwards(i); } else { adjustDownwards(i); } } private void adjustUpwards(int i) { var t = _elems[i]; while (i > 0) { var parent = (i - 1) / 2; if (_elems[parent].CompareTo(t) != -1) { break; } _elems[i] = _elems[parent]; _elems[i].HeapIndex = i; i = parent; } _elems[i] = t; t.HeapIndex = i; } private void adjustDownwards(int i) { var t = _elems[i]; while (true) { var leftChild = 1 + 2 * i; if (leftChild >= _elems.Count) { break; } var rightChild = leftChild + 1; var next = (rightChild < _elems.Count && _elems[leftChild].CompareTo(_elems[rightChild]) == -1) ? rightChild : leftChild; if (t.CompareTo(_elems[next]) != -1) { break; } _elems[i] = _elems[next]; _elems[i].HeapIndex = i; i = next; } _elems[i] = t; t.HeapIndex = i; } } public interface IHasHeapIndex { int HeapIndex { get; set; } } private class FeasibleSolutionChecker : CpSolverSolutionCallback { public FeasibleSolutionChecker(int demandIndex, ref List<List<HashSet<int>>> allPaths, int maxLength, List<IntVar> arcVars, int maxPaths, List<IntVar> nodeVars) { DemandIndex = demandIndex; AllPaths = allPaths; MaxLength = maxLength; ArcVars = arcVars; MaxPaths = maxPaths; NodeVars = nodeVars; } public int DemandIndex { get; } public List<List<HashSet<int>>> AllPaths { get; } public int MaxLength { get; } public List<IntVar> ArcVars { get; } public int MaxPaths { get; } public List<IntVar> NodeVars { get; } public override void OnSolutionCallback() { if (AllPaths.Count < DemandIndex + 1) AllPaths.Add(new List<HashSet<int>>()); int pathId = AllPaths[DemandIndex].Count; AllPaths[DemandIndex].Add(new HashSet<int>()); for (int i = 0; i < MaxLength - 1; i++) { int arc = (int)this.SolutionIntegerValue(ArcVars[i].GetIndex()); AllPaths[DemandIndex][pathId].Add(arc); } if (AllPaths[DemandIndex].Count() >= MaxPaths) { StopSearch(); } } } private class FeasibleSolutionChecker2 : CpSolverSolutionCallback { public IntVar MaxUsageCost { get; } public List<IntVar> ComfortableTrafficVars { get; } public List<IntVar> TrafficVars { get; } private int _numSolutions = 0; public FeasibleSolutionChecker2(IntVar maxUsageCost, List<IntVar> comfortableTrafficVars, List<IntVar> trafficVars) { MaxUsageCost = maxUsageCost; ComfortableTrafficVars = comfortableTrafficVars; TrafficVars = trafficVars; } public override void OnSolutionCallback() { Console.WriteLine($"Solution {_numSolutions}"); var percent = SolutionIntegerValue(MaxUsageCost.GetIndex()) / 10.0; int numNonComfortableArcs = 0; foreach (var comfort in ComfortableTrafficVars) { numNonComfortableArcs += SolutionBooleanValue(comfort.GetIndex()) ? 1 : 0; } if (numNonComfortableArcs > 0) { Console.WriteLine( $"*** Found a solution with a max usage of {percent}%, and {numNonComfortableArcs} links above the comfort zone"); } else { Console.WriteLine($"*** Found a solution with a max usage of {percent}%"); } _numSolutions++; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading.Tasks; using System.Windows.Input; using System.Xml.Linq; using Windows.ApplicationModel.DataTransfer; using Windows.Graphics.Imaging; using Windows.Storage; using Windows.Storage.Pickers; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media.Imaging; using GalaSoft.MvvmLight.Command; using Koopakiller.Apps.UwpAppDevelopmentHelper.Converter; using Koopakiller.Apps.UwpAppDevelopmentHelper.Helper; using Koopakiller.Apps.UwpAppDevelopmentHelper.Model; namespace Koopakiller.Apps.UwpAppDevelopmentHelper.ViewModel { public class SingleFontIconViewModel : ViewModelBase, IHistoryItemTarget { private IList<char> _chars; #region .ctor public SingleFontIconViewModel() { this.Tags = new ObservableCollection<string>(); ((ObservableCollection<string>)this.Tags).CollectionChanged += (s, e) => { // ReSharper disable once ExplicitCallerInfoArgument this.RaisePropertyChanged(nameof(this.JoinedTags)); }; this.Chars = new List<char>(); this.CopyCommand = new RelayCommand<string>(this.ExecuteCopy); this.NavigateBackCommand = new RelayCommand(this.NavigateBack); this.SaveFontIconImageCommand = new RelayCommand<FontIcon>(async fi => await this.SaveFontImageIconAsync(fi)); if (this.IsInDesignMode) { this.Chars.Add('\ue00a'); this.Chars.Add('\ue082'); this.Chars.Add('\ue0b4'); this.Chars.Add('\ue0b5'); this.Chars.Add('\ue113'); this.Chars.Add('\ue1cf'); this.Chars.Add('\ue249'); this.Chars.Add('\ue735'); this.Tags.Add("star"); this.Tags.Add("favorite"); this.Tags.Add("fill"); this.EnumValue = "RatingStarFillLegacy"; this.Description = "Solid star"; } } #endregion #region Properties public IList<char> Chars { get { return this._chars; } set { this._chars = value; this.RaisePropertyChanged(); if (this._chars != null) { this.SelectedChar = this.Chars.FirstOrDefault(); } } } public IList<string> Tags { get; set; } public string JoinedTags => string.Join(", ", this.Tags); public string Description { get; set; } public string EnumValue { get; set; } public char SelectedChar { get; set; } public ICommand CopyCommand { get; } public ICommand NavigateBackCommand { get; } public ICommand SaveFontIconImageCommand { get; } public IReadOnlyCollection<double> CommonFontSizes { get; } = new double[] { 8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48, 72, 96, 144, 192, 288, 384, 576 }; #endregion private void ExecuteCopy(string s) { var code = Convert.ToString(this.SelectedChar, 16); switch (s) { case "XAML": // XAML / XML s = "&#x" + code + ";"; break; case "C#": // C# / C++ / F# s = "\\u" + code + ""; break; case "VB": // Visual Basic s = "ChrW(&H" + code + ")"; break; case "FontIconWithFontFamily": s = "<FontIcon FontFamily=\"Segoe MDL2 Assets\" Glyph=\"&#x" + code + ";\" />"; break; case "FontIcon": s = "<FontIcon Glyph=\"&#x" + code + ";\" />"; break; case "EnumValue": s = this.EnumValue; break; case "Description": s = this.Description; break; case "JoinedTags": s = this.JoinedTags; break; default: throw new ArgumentException(); } var dataPackage = new DataPackage(); dataPackage.SetText(s); dataPackage.RequestedOperation = DataPackageOperation.Copy; Clipboard.SetContent(dataPackage); } private void NavigateBack() { NavigationHelper.NavigateToExisting(this.Caller); } private async Task SaveFontImageIconAsync(FontIcon fi) { var file = await this.PickImageFileAsync(); if (file == null) { return; } var rtb = new RenderTargetBitmap(); await rtb.RenderAsync(fi, (int)fi.ActualWidth, (int)fi.ActualHeight); await this.SaveSoftwareBitmapToFile(rtb, file); } private async Task<StorageFile> PickImageFileAsync() { var fsp = new FileSavePicker { SuggestedStartLocation = PickerLocationId.PicturesLibrary, SuggestedFileName = "MDL2 Asset " + CharToHex(this.SelectedChar), }; fsp.FileTypeChoices.Add("Portable Network Graphic - PNG Image", new List<string>() { ".png" }); fsp.FileTypeChoices.Add("JPEG Image", new List<string>() { ".jpg", ".jpeg" }); fsp.FileTypeChoices.Add("TIFF Image", new List<string>() { ".tif", ".tiff" }); fsp.FileTypeChoices.Add("BMP Image", new List<string>() { ".bmp" }); fsp.FileTypeChoices.Add("GIF Image", new List<string>() { ".gif" }); return await fsp.PickSaveFileAsync(); } private async Task SaveSoftwareBitmapToFile(RenderTargetBitmap rtb, IStorageFile outputFile) { using (var stream = await outputFile.OpenAsync(FileAccessMode.ReadWrite)) { Guid encoderId; switch (outputFile.FileType.ToLower()) { case ".png": encoderId = BitmapEncoder.PngEncoderId; break; case ".jpg": case ".jpeg": encoderId = BitmapEncoder.JpegEncoderId; break; case ".gif": encoderId = BitmapEncoder.GifEncoderId; break; case ".tif": case ".tiff": encoderId = BitmapEncoder.TiffEncoderId; break; case ".bmp": encoderId = BitmapEncoder.BmpEncoderId; break; default: encoderId = BitmapEncoder.PngEncoderId; break; } var encoder = await BitmapEncoder.CreateAsync(encoderId, stream); var bytes = (await rtb.GetPixelsAsync()).ToArray(); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)rtb.PixelWidth, (uint)rtb.PixelHeight, 96, 96, bytes); encoder.IsThumbnailGenerated = true; try { await encoder.FlushAsync(); } catch (Exception err) when (err.HResult == unchecked((int)0x88982F81)) { encoder.IsThumbnailGenerated = false; } if (encoder.IsThumbnailGenerated == false) { await encoder.FlushAsync(); } } } private static string CharToHex(char chr) { return Convert.ToString(chr, 16); } #region IHistoryItemTarget public XElement Serialize() { var cth = new CharToHexConverter(); var el = new XElement(nameof(SingleFontIconViewModel)); el.Add(new XElement("Chars", this.Chars.Select(x => new XElement("Char", cth.Convert(x))))); el.Add(new XElement("Tags", this.Tags.Select(x => new XElement("Tag", x)))); el.Add(new XElement("Description", this.Description)); return el; } public void Load(XElement data) { var cth = new CharToHexConverter(); this.Chars.Clear(); foreach (var chr in data.Element("Chars").Elements("Char").Select(x => cth.ConvertBack(x.Value))) { this.Chars.Add(chr); } this.Tags.Clear(); foreach (var tag in data.Element("Tags").Elements("Tag").Select(x => x.Value)) { this.Tags.Add(tag); } this.Description = data.Element("Description").Value; } public ViewModelBase PreviewViewModel { get { var vm = new SingleFontIconPreviewViewModel() { Char = this.Chars.FirstOrDefault() }; return vm; } } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using FluentAssertions; using Microsoft.Its.Domain.Api.Tests.Infrastructure; using Microsoft.Its.Domain.Serialization; using Microsoft.Its.Domain.Sql; using Microsoft.Its.Recipes; using Moq; using NUnit.Framework; using Sample.Domain.Api.Controllers; using Sample.Domain.Ordering; using Sample.Domain.Ordering.Commands; namespace Microsoft.Its.Domain.Api.Tests { [TestFixture] public class CommandDispatchTests { // this is a shim to make sure that the Sample.Domain.Api assembly is loaded into the AppDomain, otherwise Web API won't discover the controller type private static object workaround = typeof (OrderApiController); [TestFixtureSetUp] public void TestFixtureSetUp() { TestSetUp.EnsureEventStoreIsInitialized(); } [SetUp] public void SetUp() { Command<Order>.AuthorizeDefault = (order, command) => true; } [Test] public async Task Posting_command_JSON_applies_a_command_with_the_specified_name_to_an_aggregate_with_the_specified_id() { var order = new Order(Guid.NewGuid(), new Order.CustomerInfoChanged { CustomerName = "Joe" }); await order.SaveToEventStore(); var json = new AddItem { Quantity = 5, Price = 19.99m, ProductName = "Bag o' Treats" }.ToJson(); var request = new HttpRequestMessage(HttpMethod.Post, string.Format("http://contoso.com/orders/{0}/additem", order.Id)) { Content = new StringContent(json, Encoding.UTF8, "application/json") }; var testApi = new TestApi<Order>(); var client = testApi.GetClient(); var response = client.SendAsync(request).Result; response.StatusCode.Should().Be(HttpStatusCode.OK); var updatedOrder = await new SqlEventSourcedRepository<Order>().GetLatest(order.Id); updatedOrder.Items.Single().Quantity.Should().Be(5); } [Test] public async Task Posting_an_invalid_command_does_not_affect_the_aggregate_state() { var order = new Order(Guid.NewGuid(), new Order.CustomerInfoChanged { CustomerName = "Joe" }, new Order.Fulfilled()); await order.SaveToEventStore(); var json = new AddItem { Quantity = 5, Price = 19.99m, ProductName = "Bag o' Treats" }.ToJson(); var request = new HttpRequestMessage(HttpMethod.Post, string.Format("http://contoso.com/orders/{0}/additem", order.Id)) { Content = new StringContent(json, Encoding.UTF8, "application/json") }; var testApi = new TestApi<Order>(); var client = testApi.GetClient(); var response = client.SendAsync(request).Result; response.StatusCode.Should().Be(HttpStatusCode.BadRequest); var updatedOrder = await new SqlEventSourcedRepository<Order>().GetLatest(order.Id); updatedOrder.Items.Count().Should().Be(0); } [Test] public async Task Posting_an_invalid_create_command_returns_400_Bad_request() { var testApi = new TestApi<Order>(); var response = await testApi.GetClient() .PostAsJsonAsync(string.Format("http://contoso.com/orders/createorder/{0}", Any.Guid()), new object()); response.ShouldFailWith(HttpStatusCode.BadRequest); } [Test] public void Posting_command_JSON_to_a_nonexistent_aggregate_returns_404_Not_found() { var request = new HttpRequestMessage(HttpMethod.Post, string.Format("http://contoso.com/orders/{0}/cancel", Guid.NewGuid())) { Content = new StringContent(new Cancel().ToJson(), Encoding.UTF8, "application/json") }; var client = new TestApi<Order>().GetClient(); var response = client.SendAsync(request).Result; response.StatusCode.Should().Be(HttpStatusCode.NotFound); } [Test] public async Task Posting_unauthorized_command_JSON_returns_403_Forbidden() { var order = new Order(Guid.NewGuid(), new Order.CustomerInfoChanged { CustomerName = "Joe" }, new Order.Fulfilled()); await order.SaveToEventStore(); Command<Order>.AuthorizeDefault = (o, command) => false; var request = new HttpRequestMessage(HttpMethod.Post, string.Format("http://contoso.com/orders/{0}/cancel", order.Id)) { Content = new StringContent(new Cancel().ToJson(), Encoding.UTF8, "application/json") }; var client = new TestApi<Order>().GetClient(); var response = await client.SendAsync(request); response.StatusCode.Should().Be(HttpStatusCode.Forbidden); } [Test] public async Task Posting_a_command_that_causes_a_concurrency_error_returns_409_Conflict() { var order = new Order(Guid.NewGuid(), new Order.CustomerInfoChanged { CustomerName = "Joe" }); var testApi = new TestApi<Order>(); var repository = new Mock<IEventSourcedRepository<Order>>(); repository.Setup(r => r.GetLatest(It.IsAny<Guid>())) .Returns(Task.FromResult(order)); repository.Setup(r => r.Save(It.IsAny<Order>())) .Throws(new ConcurrencyException("oops!", new IEvent[0], new Exception("inner oops"))); testApi.Container.Register(c => repository.Object); var client = testApi.GetClient(); var response = await client.PostAsJsonAsync(string.Format("http://contoso.com/orders/{0}/additem", order.Id), new { Price = 3m, ProductName = Any.Word() }); response.ShouldFailWith(HttpStatusCode.Conflict); } [Test] public async Task Posting_a_constructor_command_creates_a_new_aggregate_instance() { var testApi = new TestApi<Order>(); var orderId = Any.Guid(); var response = await testApi.GetClient() .PostAsJsonAsync(string.Format("http://contoso.com/orders/createorder/{0}", orderId), new CreateOrder(Any.FullName())); response.ShouldSucceed(HttpStatusCode.Created); } [Test] public async Task Posting_a_second_constructor_command_with_the_same_aggregate_id_results_in_a_409_Conflict() { // arrange var testApi = new TestApi<Order>(); var orderId = Any.Guid(); await testApi.GetClient() .PostAsJsonAsync(string.Format("http://contoso.com/orders/createorder/{0}", orderId), new CreateOrder(Any.FullName())); // act var response = await testApi.GetClient() .PostAsJsonAsync(string.Format("http://contoso.com/orders/createorder/{0}", orderId), new CreateOrder(Any.FullName())); // assert response.ShouldFailWith(HttpStatusCode.Conflict); } [Test] public async Task An_ETag_header_is_applied_to_the_command() { var order = new Order(Guid.NewGuid(), new Order.CustomerInfoChanged { CustomerName = "Joe" }); await order.SaveToEventStore(); var json = new AddItem { Quantity = 5, Price = 19.99m, ProductName = "Bag o' Treats" }.ToJson(); var etag = new EntityTagHeaderValue("\"" + Any.Guid() + "\""); Func<HttpRequestMessage> createRequest = () => { var request = new HttpRequestMessage(HttpMethod.Post, string.Format("http://contoso.com/orders/{0}/additem", order.Id)) { Content = new StringContent(json, Encoding.UTF8, "application/json"), }; request.Headers.IfNoneMatch.Add(etag); return request; }; var testApi = new TestApi<Order>(); var client = testApi.GetClient(); // act: send the request twice var response1 = await client.SendAsync(createRequest()); var response2 = await client.SendAsync(createRequest()); // assert response1.ShouldSucceed(HttpStatusCode.OK); response2.ShouldFailWith(HttpStatusCode.NotModified); var updatedOrder = await new SqlEventSourcedRepository<Order>().GetLatest(order.Id); updatedOrder.Items.Single().Quantity.Should().Be(5); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: reporting/rpc/front_desk_reporting_svc.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace HOLMS.Types.Reporting.RPC { /// <summary>Holder for reflection information generated from reporting/rpc/front_desk_reporting_svc.proto</summary> public static partial class FrontDeskReportingSvcReflection { #region Descriptor /// <summary>File descriptor for reporting/rpc/front_desk_reporting_svc.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static FrontDeskReportingSvcReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CixyZXBvcnRpbmcvcnBjL2Zyb250X2Rlc2tfcmVwb3J0aW5nX3N2Yy5wcm90", "bxIZaG9sbXMudHlwZXMucmVwb3J0aW5nLnJwYxogaWFtL3N0YWZmX21lbWJl", "cl9pbmRpY2F0b3IucHJvdG8aHXByaW1pdGl2ZS9wYl9sb2NhbF9kYXRlLnBy", "b3RvGjhyZXBvcnRpbmcvaW5wdXRfcGFyYW1zL2Zyb250X2Rlc2tfcmVwb3J0", "X21hbmlmZXN0cy5wcm90bxoscmVwb3J0aW5nL291dHB1dHMvaHRtbF9yZXBv", "cnRfcmVzcG9uc2UucHJvdG8aMnRlbmFuY3lfY29uZmlnL2luZGljYXRvcnMv", "cHJvcGVydHlfaW5kaWNhdG9yLnByb3RvIrEDCiFGcm9udERlc2tCYXRjaFJl", "cG9ydGluZ1N2Y1JlcXVlc3QSTAoKcHJvcGVydGllcxgBIAMoCzI4LmhvbG1z", "LnR5cGVzLnRlbmFuY3lfY29uZmlnLmluZGljYXRvcnMuUHJvcGVydHlJbmRp", "Y2F0b3ISbgoeY2FsZW5kYXJfZGF0ZV9yZXBvcnRzX21hbmlmZXN0GAIgASgL", "MkYuaG9sbXMudHlwZXMucmVwb3J0aW5nLmlucHV0X3BhcmFtcy5Gcm9udERl", "c2tDdXJyZW50RGF0ZVJlcG9ydE1hbmlmZXN0Em8KHm9wc2RhdGVfcmFuZ2Vf", "cmVwb3J0c19tYW5pZmVzdBgDIAEoCzJHLmhvbG1zLnR5cGVzLnJlcG9ydGlu", "Zy5pbnB1dF9wYXJhbXMuRnJvbnREZXNrT3BzZGF0ZVJhbmdlUmVwb3J0TWFu", "aWZlc3QSGgoSaW5jbHVkZV9jaGVja2VkX2luGAQgASgIEhsKE2luY2x1ZGVf", "Y2hlY2tlZF9vdXQYBSABKAgSJAocaW5jbHVkZV9jaGVja2VkX2luX2RhdGVy", "YW5nZRgGIAEoCCKtAQooRnJvbnREZXNrUmVwb3J0aW5nU3ZjSG91c2VrZWVw", "aW5nUmVxdWVzdBI8Cg1zdGFmZl9tZW1iZXJzGAEgAygLMiUuaG9sbXMudHlw", "ZXMuaWFtLlN0YWZmTWVtYmVySW5kaWNhdG9yEhEKCWFkZF9ub3RlcxgCIAEo", "CRIwCgRkYXRlGAMgASgLMiIuaG9sbXMudHlwZXMucHJpbWl0aXZlLlBiTG9j", "YWxEYXRlMr0CChVGcm9udERlc2tSZXBvcnRpbmdTdmMShgEKE0dldEZyb250", "RGVza1JlcG9ydHMSPC5ob2xtcy50eXBlcy5yZXBvcnRpbmcucnBjLkZyb250", "RGVza0JhdGNoUmVwb3J0aW5nU3ZjUmVxdWVzdBoxLmhvbG1zLnR5cGVzLnJl", "cG9ydGluZy5vdXRwdXRzLkh0bWxSZXBvcnRSZXNwb25zZRKaAQogR2V0SG91", "c2VrZWVwaW5nQXNzaWdubWVudHNSZXBvcnQSQy5ob2xtcy50eXBlcy5yZXBv", "cnRpbmcucnBjLkZyb250RGVza1JlcG9ydGluZ1N2Y0hvdXNla2VlcGluZ1Jl", "cXVlc3QaMS5ob2xtcy50eXBlcy5yZXBvcnRpbmcub3V0cHV0cy5IdG1sUmVw", "b3J0UmVzcG9uc2VCHKoCGUhPTE1TLlR5cGVzLlJlcG9ydGluZy5SUENiBnBy", "b3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::HOLMS.Types.IAM.StaffMemberIndicatorReflection.Descriptor, global::HOLMS.Types.Primitive.PbLocalDateReflection.Descriptor, global::HOLMS.Types.Reporting.ReportParams.FrontDeskReportManifestsReflection.Descriptor, global::HOLMS.Types.Reporting.Outputs.HtmlReportResponseReflection.Descriptor, global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicatorReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Reporting.RPC.FrontDeskBatchReportingSvcRequest), global::HOLMS.Types.Reporting.RPC.FrontDeskBatchReportingSvcRequest.Parser, new[]{ "Properties", "CalendarDateReportsManifest", "OpsdateRangeReportsManifest", "IncludeCheckedIn", "IncludeCheckedOut", "IncludeCheckedInDaterange" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Reporting.RPC.FrontDeskReportingSvcHousekeepingRequest), global::HOLMS.Types.Reporting.RPC.FrontDeskReportingSvcHousekeepingRequest.Parser, new[]{ "StaffMembers", "AddNotes", "Date" }, null, null, null) })); } #endregion } #region Messages public sealed partial class FrontDeskBatchReportingSvcRequest : pb::IMessage<FrontDeskBatchReportingSvcRequest> { private static readonly pb::MessageParser<FrontDeskBatchReportingSvcRequest> _parser = new pb::MessageParser<FrontDeskBatchReportingSvcRequest>(() => new FrontDeskBatchReportingSvcRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<FrontDeskBatchReportingSvcRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Reporting.RPC.FrontDeskReportingSvcReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public FrontDeskBatchReportingSvcRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public FrontDeskBatchReportingSvcRequest(FrontDeskBatchReportingSvcRequest other) : this() { properties_ = other.properties_.Clone(); CalendarDateReportsManifest = other.calendarDateReportsManifest_ != null ? other.CalendarDateReportsManifest.Clone() : null; OpsdateRangeReportsManifest = other.opsdateRangeReportsManifest_ != null ? other.OpsdateRangeReportsManifest.Clone() : null; includeCheckedIn_ = other.includeCheckedIn_; includeCheckedOut_ = other.includeCheckedOut_; includeCheckedInDaterange_ = other.includeCheckedInDaterange_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public FrontDeskBatchReportingSvcRequest Clone() { return new FrontDeskBatchReportingSvcRequest(this); } /// <summary>Field number for the "properties" field.</summary> public const int PropertiesFieldNumber = 1; private static readonly pb::FieldCodec<global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator> _repeated_properties_codec = pb::FieldCodec.ForMessage(10, global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator.Parser); private readonly pbc::RepeatedField<global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator> properties_ = new pbc::RepeatedField<global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator> Properties { get { return properties_; } } /// <summary>Field number for the "calendar_date_reports_manifest" field.</summary> public const int CalendarDateReportsManifestFieldNumber = 2; private global::HOLMS.Types.Reporting.ReportParams.FrontDeskCurrentDateReportManifest calendarDateReportsManifest_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Reporting.ReportParams.FrontDeskCurrentDateReportManifest CalendarDateReportsManifest { get { return calendarDateReportsManifest_; } set { calendarDateReportsManifest_ = value; } } /// <summary>Field number for the "opsdate_range_reports_manifest" field.</summary> public const int OpsdateRangeReportsManifestFieldNumber = 3; private global::HOLMS.Types.Reporting.ReportParams.FrontDeskOpsdateRangeReportManifest opsdateRangeReportsManifest_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Reporting.ReportParams.FrontDeskOpsdateRangeReportManifest OpsdateRangeReportsManifest { get { return opsdateRangeReportsManifest_; } set { opsdateRangeReportsManifest_ = value; } } /// <summary>Field number for the "include_checked_in" field.</summary> public const int IncludeCheckedInFieldNumber = 4; private bool includeCheckedIn_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool IncludeCheckedIn { get { return includeCheckedIn_; } set { includeCheckedIn_ = value; } } /// <summary>Field number for the "include_checked_out" field.</summary> public const int IncludeCheckedOutFieldNumber = 5; private bool includeCheckedOut_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool IncludeCheckedOut { get { return includeCheckedOut_; } set { includeCheckedOut_ = value; } } /// <summary>Field number for the "include_checked_in_daterange" field.</summary> public const int IncludeCheckedInDaterangeFieldNumber = 6; private bool includeCheckedInDaterange_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool IncludeCheckedInDaterange { get { return includeCheckedInDaterange_; } set { includeCheckedInDaterange_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as FrontDeskBatchReportingSvcRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(FrontDeskBatchReportingSvcRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!properties_.Equals(other.properties_)) return false; if (!object.Equals(CalendarDateReportsManifest, other.CalendarDateReportsManifest)) return false; if (!object.Equals(OpsdateRangeReportsManifest, other.OpsdateRangeReportsManifest)) return false; if (IncludeCheckedIn != other.IncludeCheckedIn) return false; if (IncludeCheckedOut != other.IncludeCheckedOut) return false; if (IncludeCheckedInDaterange != other.IncludeCheckedInDaterange) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= properties_.GetHashCode(); if (calendarDateReportsManifest_ != null) hash ^= CalendarDateReportsManifest.GetHashCode(); if (opsdateRangeReportsManifest_ != null) hash ^= OpsdateRangeReportsManifest.GetHashCode(); if (IncludeCheckedIn != false) hash ^= IncludeCheckedIn.GetHashCode(); if (IncludeCheckedOut != false) hash ^= IncludeCheckedOut.GetHashCode(); if (IncludeCheckedInDaterange != false) hash ^= IncludeCheckedInDaterange.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { properties_.WriteTo(output, _repeated_properties_codec); if (calendarDateReportsManifest_ != null) { output.WriteRawTag(18); output.WriteMessage(CalendarDateReportsManifest); } if (opsdateRangeReportsManifest_ != null) { output.WriteRawTag(26); output.WriteMessage(OpsdateRangeReportsManifest); } if (IncludeCheckedIn != false) { output.WriteRawTag(32); output.WriteBool(IncludeCheckedIn); } if (IncludeCheckedOut != false) { output.WriteRawTag(40); output.WriteBool(IncludeCheckedOut); } if (IncludeCheckedInDaterange != false) { output.WriteRawTag(48); output.WriteBool(IncludeCheckedInDaterange); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += properties_.CalculateSize(_repeated_properties_codec); if (calendarDateReportsManifest_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(CalendarDateReportsManifest); } if (opsdateRangeReportsManifest_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(OpsdateRangeReportsManifest); } if (IncludeCheckedIn != false) { size += 1 + 1; } if (IncludeCheckedOut != false) { size += 1 + 1; } if (IncludeCheckedInDaterange != false) { size += 1 + 1; } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(FrontDeskBatchReportingSvcRequest other) { if (other == null) { return; } properties_.Add(other.properties_); if (other.calendarDateReportsManifest_ != null) { if (calendarDateReportsManifest_ == null) { calendarDateReportsManifest_ = new global::HOLMS.Types.Reporting.ReportParams.FrontDeskCurrentDateReportManifest(); } CalendarDateReportsManifest.MergeFrom(other.CalendarDateReportsManifest); } if (other.opsdateRangeReportsManifest_ != null) { if (opsdateRangeReportsManifest_ == null) { opsdateRangeReportsManifest_ = new global::HOLMS.Types.Reporting.ReportParams.FrontDeskOpsdateRangeReportManifest(); } OpsdateRangeReportsManifest.MergeFrom(other.OpsdateRangeReportsManifest); } if (other.IncludeCheckedIn != false) { IncludeCheckedIn = other.IncludeCheckedIn; } if (other.IncludeCheckedOut != false) { IncludeCheckedOut = other.IncludeCheckedOut; } if (other.IncludeCheckedInDaterange != false) { IncludeCheckedInDaterange = other.IncludeCheckedInDaterange; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { properties_.AddEntriesFrom(input, _repeated_properties_codec); break; } case 18: { if (calendarDateReportsManifest_ == null) { calendarDateReportsManifest_ = new global::HOLMS.Types.Reporting.ReportParams.FrontDeskCurrentDateReportManifest(); } input.ReadMessage(calendarDateReportsManifest_); break; } case 26: { if (opsdateRangeReportsManifest_ == null) { opsdateRangeReportsManifest_ = new global::HOLMS.Types.Reporting.ReportParams.FrontDeskOpsdateRangeReportManifest(); } input.ReadMessage(opsdateRangeReportsManifest_); break; } case 32: { IncludeCheckedIn = input.ReadBool(); break; } case 40: { IncludeCheckedOut = input.ReadBool(); break; } case 48: { IncludeCheckedInDaterange = input.ReadBool(); break; } } } } } public sealed partial class FrontDeskReportingSvcHousekeepingRequest : pb::IMessage<FrontDeskReportingSvcHousekeepingRequest> { private static readonly pb::MessageParser<FrontDeskReportingSvcHousekeepingRequest> _parser = new pb::MessageParser<FrontDeskReportingSvcHousekeepingRequest>(() => new FrontDeskReportingSvcHousekeepingRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<FrontDeskReportingSvcHousekeepingRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Reporting.RPC.FrontDeskReportingSvcReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public FrontDeskReportingSvcHousekeepingRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public FrontDeskReportingSvcHousekeepingRequest(FrontDeskReportingSvcHousekeepingRequest other) : this() { staffMembers_ = other.staffMembers_.Clone(); addNotes_ = other.addNotes_; Date = other.date_ != null ? other.Date.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public FrontDeskReportingSvcHousekeepingRequest Clone() { return new FrontDeskReportingSvcHousekeepingRequest(this); } /// <summary>Field number for the "staff_members" field.</summary> public const int StaffMembersFieldNumber = 1; private static readonly pb::FieldCodec<global::HOLMS.Types.IAM.StaffMemberIndicator> _repeated_staffMembers_codec = pb::FieldCodec.ForMessage(10, global::HOLMS.Types.IAM.StaffMemberIndicator.Parser); private readonly pbc::RepeatedField<global::HOLMS.Types.IAM.StaffMemberIndicator> staffMembers_ = new pbc::RepeatedField<global::HOLMS.Types.IAM.StaffMemberIndicator>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::HOLMS.Types.IAM.StaffMemberIndicator> StaffMembers { get { return staffMembers_; } } /// <summary>Field number for the "add_notes" field.</summary> public const int AddNotesFieldNumber = 2; private string addNotes_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string AddNotes { get { return addNotes_; } set { addNotes_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "date" field.</summary> public const int DateFieldNumber = 3; private global::HOLMS.Types.Primitive.PbLocalDate date_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.PbLocalDate Date { get { return date_; } set { date_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as FrontDeskReportingSvcHousekeepingRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(FrontDeskReportingSvcHousekeepingRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!staffMembers_.Equals(other.staffMembers_)) return false; if (AddNotes != other.AddNotes) return false; if (!object.Equals(Date, other.Date)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= staffMembers_.GetHashCode(); if (AddNotes.Length != 0) hash ^= AddNotes.GetHashCode(); if (date_ != null) hash ^= Date.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { staffMembers_.WriteTo(output, _repeated_staffMembers_codec); if (AddNotes.Length != 0) { output.WriteRawTag(18); output.WriteString(AddNotes); } if (date_ != null) { output.WriteRawTag(26); output.WriteMessage(Date); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += staffMembers_.CalculateSize(_repeated_staffMembers_codec); if (AddNotes.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(AddNotes); } if (date_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Date); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(FrontDeskReportingSvcHousekeepingRequest other) { if (other == null) { return; } staffMembers_.Add(other.staffMembers_); if (other.AddNotes.Length != 0) { AddNotes = other.AddNotes; } if (other.date_ != null) { if (date_ == null) { date_ = new global::HOLMS.Types.Primitive.PbLocalDate(); } Date.MergeFrom(other.Date); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { staffMembers_.AddEntriesFrom(input, _repeated_staffMembers_codec); break; } case 18: { AddNotes = input.ReadString(); break; } case 26: { if (date_ == null) { date_ = new global::HOLMS.Types.Primitive.PbLocalDate(); } input.ReadMessage(date_); break; } } } } } #endregion } #endregion Designer generated code
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using Lucene.Net.Index; using Lucene.Net.Store; using NUnit.Framework; using WhitespaceAnalyzer = Lucene.Net.Analysis.WhitespaceAnalyzer; using Document = Lucene.Net.Documents.Document; using Field = Lucene.Net.Documents.Field; using IndexWriter = Lucene.Net.Index.IndexWriter; using Term = Lucene.Net.Index.Term; using ParseException = Lucene.Net.QueryParsers.ParseException; using QueryParser = Lucene.Net.QueryParsers.QueryParser; using RAMDirectory = Lucene.Net.Store.RAMDirectory; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; namespace Lucene.Net.Search { /// <summary>Test BooleanQuery2 against BooleanQuery by overriding the standard query parser. /// This also tests the scoring order of BooleanQuery. /// </summary> [TestFixture] public class TestBoolean2:LuceneTestCase { [Serializable] private class AnonymousClassDefaultSimilarity:DefaultSimilarity { public AnonymousClassDefaultSimilarity(TestBoolean2 enclosingInstance) { InitBlock(enclosingInstance); } private void InitBlock(TestBoolean2 enclosingInstance) { this.enclosingInstance = enclosingInstance; } private TestBoolean2 enclosingInstance; public TestBoolean2 Enclosing_Instance { get { return enclosingInstance; } } public override float Coord(int overlap, int maxOverlap) { return overlap / ((float) maxOverlap - 1); } } private IndexSearcher searcher; private IndexSearcher bigSearcher; private IndexReader reader; private static int NUM_EXTRA_DOCS = 6000; public const System.String field = "field"; private Directory dir2; private int mulFactor; [SetUp] public override void SetUp() { base.SetUp(); RAMDirectory directory = new RAMDirectory(); IndexWriter writer = new IndexWriter(directory, new WhitespaceAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED); for (int i = 0; i < docFields.Length; i++) { Document document = new Document(); document.Add(new Field(field, docFields[i], Field.Store.NO, Field.Index.ANALYZED)); writer.AddDocument(document); } writer.Close(); searcher = new IndexSearcher(directory, true); // Make big index dir2 = new MockRAMDirectory(directory); // First multiply small test index: mulFactor = 1; int docCount = 0; do { Directory copy = new RAMDirectory(dir2); IndexWriter indexWriter = new IndexWriter(dir2, new WhitespaceAnalyzer(), IndexWriter.MaxFieldLength.UNLIMITED); indexWriter.AddIndexesNoOptimize(new[] {copy}); docCount = indexWriter.MaxDoc(); indexWriter.Close(); mulFactor *= 2; } while (docCount < 3000); IndexWriter w = new IndexWriter(dir2, new WhitespaceAnalyzer(), IndexWriter.MaxFieldLength.UNLIMITED); Document doc = new Document(); doc.Add(new Field("field2", "xxx", Field.Store.NO, Field.Index.ANALYZED)); for (int i = 0; i < NUM_EXTRA_DOCS / 2; i++) { w.AddDocument(doc); } doc = new Document(); doc.Add(new Field("field2", "big bad bug", Field.Store.NO, Field.Index.ANALYZED)); for (int i = 0; i < NUM_EXTRA_DOCS / 2; i++) { w.AddDocument(doc); } // optimize to 1 segment w.Optimize(); reader = w.GetReader(); w.Close(); bigSearcher = new IndexSearcher(reader); } [TearDown] public override void TearDown() { reader.Close(); dir2.Close(); } private System.String[] docFields = new System.String[]{"w1 w2 w3 w4 w5", "w1 w3 w2 w3", "w1 xx w2 yy w3", "w1 w3 xx w2 yy w3"}; public virtual Query MakeQuery(System.String queryText) { Query q = (new QueryParser(Util.Version.LUCENE_CURRENT, field, new WhitespaceAnalyzer())).Parse(queryText); return q; } public virtual void QueriesTest(System.String queryText, int[] expDocNrs) { //System.out.println(); //System.out.println("Query: " + queryText); Query query1 = MakeQuery(queryText); TopScoreDocCollector collector = TopScoreDocCollector.Create(1000, false); searcher.Search(query1, null, collector); ScoreDoc[] hits1 = collector.TopDocs().ScoreDocs; Query query2 = MakeQuery(queryText); // there should be no need to parse again... collector = TopScoreDocCollector.Create(1000, true); searcher.Search(query2, null, collector); ScoreDoc[] hits2 = collector.TopDocs().ScoreDocs; Assert.AreEqual(mulFactor*collector.internalTotalHits, bigSearcher.Search(query1, 1).TotalHits); CheckHits.CheckHitsQuery(query2, hits1, hits2, expDocNrs); } [Test] public virtual void TestQueries01() { System.String queryText = "+w3 +xx"; int[] expDocNrs = new int[]{2, 3}; QueriesTest(queryText, expDocNrs); } [Test] public virtual void TestQueries02() { System.String queryText = "+w3 xx"; int[] expDocNrs = new int[]{2, 3, 1, 0}; QueriesTest(queryText, expDocNrs); } [Test] public virtual void TestQueries03() { System.String queryText = "w3 xx"; int[] expDocNrs = new int[]{2, 3, 1, 0}; QueriesTest(queryText, expDocNrs); } [Test] public virtual void TestQueries04() { System.String queryText = "w3 -xx"; int[] expDocNrs = new int[]{1, 0}; QueriesTest(queryText, expDocNrs); } [Test] public virtual void TestQueries05() { System.String queryText = "+w3 -xx"; int[] expDocNrs = new int[]{1, 0}; QueriesTest(queryText, expDocNrs); } [Test] public virtual void TestQueries06() { System.String queryText = "+w3 -xx -w5"; int[] expDocNrs = new int[]{1}; QueriesTest(queryText, expDocNrs); } [Test] public virtual void TestQueries07() { System.String queryText = "-w3 -xx -w5"; int[] expDocNrs = new int[]{}; QueriesTest(queryText, expDocNrs); } [Test] public virtual void TestQueries08() { System.String queryText = "+w3 xx -w5"; int[] expDocNrs = new int[]{2, 3, 1}; QueriesTest(queryText, expDocNrs); } [Test] public virtual void TestQueries09() { System.String queryText = "+w3 +xx +w2 zz"; int[] expDocNrs = new int[]{2, 3}; QueriesTest(queryText, expDocNrs); } [Test] public virtual void TestQueries10() { System.String queryText = "+w3 +xx +w2 zz"; int[] expDocNrs = new int[]{2, 3}; searcher.Similarity = new AnonymousClassDefaultSimilarity(this); QueriesTest(queryText, expDocNrs); } [Test] public virtual void TestRandomQueries() { System.Random rnd = NewRandom(); System.String[] vals = new System.String[]{"w1", "w2", "w3", "w4", "w5", "xx", "yy", "zzz"}; int tot = 0; BooleanQuery q1 = null; try { // increase number of iterations for more complete testing for (int i = 0; i < 1000; i++) { int level = rnd.Next(3); q1 = RandBoolQuery(new System.Random(rnd.Next(System.Int32.MaxValue)), rnd.Next(0, 2) == 0 ? false : true, level, field, vals, null); // Can't sort by relevance since floating point numbers may not quite // match up. Sort sort = Sort.INDEXORDER; QueryUtils.Check(q1, searcher); TopFieldCollector collector = TopFieldCollector.Create(sort, 1000, false, true, true, true); searcher.Search(q1, null, collector); ScoreDoc[] hits1 = collector.TopDocs().ScoreDocs; collector = TopFieldCollector.Create(sort, 1000, false, true, true, false); searcher.Search(q1, null, collector); ScoreDoc[] hits2 = collector.TopDocs().ScoreDocs; tot += hits2.Length; CheckHits.CheckEqual(q1, hits1, hits2); BooleanQuery q3 = new BooleanQuery(); q3.Add(q1, Occur.SHOULD); q3.Add(new PrefixQuery(new Term("field2", "b")), Occur.SHOULD); TopDocs hits4 = bigSearcher.Search(q3, 1); Assert.AreEqual(mulFactor*collector.internalTotalHits + NUM_EXTRA_DOCS/2, hits4.TotalHits); } } catch (System.Exception e) { // For easier debugging System.Console.Out.WriteLine("failed query: " + q1); throw e; } // System.out.println("Total hits:"+tot); } // used to set properties or change every BooleanQuery // generated from randBoolQuery. public interface Callback { void PostCreate(BooleanQuery q); } // Random rnd is passed in so that the exact same random query may be created // more than once. public static BooleanQuery RandBoolQuery(System.Random rnd, bool allowMust, int level, System.String field, System.String[] vals, TestBoolean2.Callback cb) { BooleanQuery current = new BooleanQuery(rnd.Next() < 0); for (int i = 0; i < rnd.Next(vals.Length) + 1; i++) { int qType = 0; // term query if (level > 0) { qType = rnd.Next(10); } Query q; if (qType < 3) { q = new TermQuery(new Term(field, vals[rnd.Next(vals.Length)])); } else if (qType < 7) { q = new WildcardQuery(new Term(field, "w*")); } else { q = RandBoolQuery(rnd, allowMust, level - 1, field, vals, cb); } int r = rnd.Next(10); Occur occur; if (r < 2) { occur = Occur.MUST_NOT; } else if (r < 5) { occur = allowMust ? Occur.MUST : Occur.SHOULD; } else { occur = Occur.SHOULD; } current.Add(q, occur); } if (cb != null) cb.PostCreate(current); return current; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; using System.Net.Internals; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; namespace System.Net { /// <devdoc> /// <para>Provides simple /// domain name resolution functionality.</para> /// </devdoc> public static class Dns { // Host names any longer than this automatically fail at the winsock level. // If the host name is 255 chars, the last char must be a dot. private const int MaxHostName = 255; internal static IPHostEntry InternalGetHostByName(string hostName, bool includeIPv6) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Socket, "DNS", "GetHostByName", hostName); IPHostEntry ipHostEntry = null; if (GlobalLog.IsEnabled) { GlobalLog.Print("Dns.GetHostByName: " + hostName); } NameResolutionPal.EnsureSocketsAreInitialized(); if (hostName.Length > MaxHostName // If 255 chars, the last one must be a dot. || hostName.Length == MaxHostName && hostName[MaxHostName - 1] != '.') { throw new ArgumentOutOfRangeException(nameof(hostName), SR.Format(SR.net_toolong, "hostName", MaxHostName.ToString(NumberFormatInfo.CurrentInfo))); } // // IPv6 Changes: IPv6 requires the use of getaddrinfo() rather // than the traditional IPv4 gethostbyaddr() / gethostbyname(). // getaddrinfo() is also protocol independent in that it will also // resolve IPv4 names / addresses. As a result, it is the preferred // resolution mechanism on platforms that support it (Windows 5.1+). // If getaddrinfo() is unsupported, IPv6 resolution does not work. // // Consider : If IPv6 is disabled, we could detect IPv6 addresses // and throw an unsupported platform exception. // // Note : Whilst getaddrinfo is available on WinXP+, we only // use it if IPv6 is enabled (platform is part of that // decision). This is done to minimize the number of // possible tests that are needed. // if (includeIPv6 || SocketProtocolSupportPal.OSSupportsIPv6) { // // IPv6 enabled: use getaddrinfo() to obtain DNS information. // int nativeErrorCode; SocketError errorCode = NameResolutionPal.TryGetAddrInfo(hostName, out ipHostEntry, out nativeErrorCode); if (errorCode != SocketError.Success) { throw SocketExceptionFactory.CreateSocketException(errorCode, nativeErrorCode); } } else { ipHostEntry = NameResolutionPal.GetHostByName(hostName); } if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Socket, "DNS", "GetHostByName", ipHostEntry); return ipHostEntry; } // GetHostByName // Does internal IPAddress reverse and then forward lookups (for Legacy and current public methods). internal static IPHostEntry InternalGetHostByAddress(IPAddress address, bool includeIPv6) { if (GlobalLog.IsEnabled) { GlobalLog.Print("Dns.InternalGetHostByAddress: " + address.ToString()); } // // IPv6 Changes: We need to use the new getnameinfo / getaddrinfo functions // for resolution of IPv6 addresses. // if (SocketProtocolSupportPal.OSSupportsIPv6 || includeIPv6) { // // Try to get the data for the host from it's address // // We need to call getnameinfo first, because getaddrinfo w/ the ipaddress string // will only return that address and not the full list. // Do a reverse lookup to get the host name. SocketError errorCode; int nativeErrorCode; string name = NameResolutionPal.TryGetNameInfo(address, out errorCode, out nativeErrorCode); if (errorCode == SocketError.Success) { // Do the forward lookup to get the IPs for that host name IPHostEntry hostEntry; errorCode = NameResolutionPal.TryGetAddrInfo(name, out hostEntry, out nativeErrorCode); if (errorCode == SocketError.Success) return hostEntry; if (NetEventSource.Log.IsEnabled()) { NetEventSource.Exception( NetEventSource.ComponentType.Socket, "DNS", "InternalGetHostByAddress", SocketExceptionFactory.CreateSocketException(errorCode, nativeErrorCode)); } // One of two things happened: // 1. There was a ptr record in dns, but not a corollary A/AAA record. // 2. The IP was a local (non-loopback) IP that resolved to a connection specific dns suffix. // - Workaround, Check "Use this connection's dns suffix in dns registration" on that network // adapter's advanced dns settings. // Just return the resolved host name and no IPs. return hostEntry; } throw SocketExceptionFactory.CreateSocketException(errorCode, nativeErrorCode); } // // If IPv6 is not enabled (maybe config switch) but we've been // given an IPv6 address then we need to bail out now. // else { if (address.AddressFamily == AddressFamily.InterNetworkV6) { // // Protocol not supported // throw new SocketException((int)SocketError.ProtocolNotSupported); } // // Use gethostbyaddr() to try to resolve the IP address // // End IPv6 Changes // return NameResolutionPal.GetHostByAddr(address); } } // InternalGetHostByAddress /***************************************************************************** Function : gethostname Abstract: Queries the hostname from DNS Input Parameters: Returns: String ******************************************************************************/ /// <devdoc> /// <para>Gets the host name of the local machine.</para> /// </devdoc> public static string GetHostName() { if (GlobalLog.IsEnabled) { GlobalLog.Print("Dns.GetHostName"); } return NameResolutionPal.GetHostName(); } private class ResolveAsyncResult : ContextAwareResult { // Forward lookup internal ResolveAsyncResult(string hostName, object myObject, bool includeIPv6, object myState, AsyncCallback myCallBack) : base(myObject, myState, myCallBack) { this.hostName = hostName; this.includeIPv6 = includeIPv6; } // Reverse lookup internal ResolveAsyncResult(IPAddress address, object myObject, bool includeIPv6, object myState, AsyncCallback myCallBack) : base(myObject, myState, myCallBack) { this.includeIPv6 = includeIPv6; this.address = address; } internal readonly string hostName; internal bool includeIPv6; internal IPAddress address; } private static void ResolveCallback(object context) { ResolveAsyncResult result = (ResolveAsyncResult)context; IPHostEntry hostEntry; try { if (result.address != null) { hostEntry = InternalGetHostByAddress(result.address, result.includeIPv6); } else { hostEntry = InternalGetHostByName(result.hostName, result.includeIPv6); } } catch (OutOfMemoryException) { throw; } catch (Exception exception) { result.InvokeCallback(exception); return; } result.InvokeCallback(hostEntry); } // Helpers for async GetHostByName, ResolveToAddresses, and Resolve - they're almost identical // If hostName is an IPString and justReturnParsedIP==true then no reverse lookup will be attempted, but the original address is returned. private static IAsyncResult HostResolutionBeginHelper(string hostName, bool justReturnParsedIp, AsyncCallback requestCallback, object state) { if (hostName == null) { throw new ArgumentNullException(nameof(hostName)); } if (GlobalLog.IsEnabled) { GlobalLog.Print("Dns.HostResolutionBeginHelper: " + hostName); } // See if it's an IP Address. IPAddress address; ResolveAsyncResult asyncResult; if (IPAddress.TryParse(hostName, out address)) { if ((address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))) { throw new ArgumentException(SR.net_invalid_ip_addr, "hostNameOrAddress"); } asyncResult = new ResolveAsyncResult(address, null, true, state, requestCallback); if (justReturnParsedIp) { IPHostEntry hostEntry = NameResolutionUtilities.GetUnresolvedAnswer(address); asyncResult.StartPostingAsyncOp(false); asyncResult.InvokeCallback(hostEntry); asyncResult.FinishPostingAsyncOp(); return asyncResult; } } else { asyncResult = new ResolveAsyncResult(hostName, null, true, state, requestCallback); } // Set up the context, possibly flow. asyncResult.StartPostingAsyncOp(false); // Start the resolve. Task.Factory.StartNew( s => ResolveCallback(s), asyncResult, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); // Finish the flowing, maybe it completed? This does nothing if we didn't initiate the flowing above. asyncResult.FinishPostingAsyncOp(); return asyncResult; } private static IAsyncResult HostResolutionBeginHelper(IPAddress address, bool flowContext, bool includeIPv6, AsyncCallback requestCallback, object state) { if (address == null) { throw new ArgumentNullException(nameof(address)); } if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any)) { throw new ArgumentException(SR.net_invalid_ip_addr, nameof(address)); } if (GlobalLog.IsEnabled) { GlobalLog.Print("Dns.HostResolutionBeginHelper: " + address); } // Set up the context, possibly flow. ResolveAsyncResult asyncResult = new ResolveAsyncResult(address, null, includeIPv6, state, requestCallback); if (flowContext) { asyncResult.StartPostingAsyncOp(false); } // Start the resolve. Task.Factory.StartNew( s => ResolveCallback(s), asyncResult, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); // Finish the flowing, maybe it completed? This does nothing if we didn't initiate the flowing above. asyncResult.FinishPostingAsyncOp(); return asyncResult; } private static IPHostEntry HostResolutionEndHelper(IAsyncResult asyncResult) { // // parameter validation // if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } ResolveAsyncResult castedResult = asyncResult as ResolveAsyncResult; if (castedResult == null) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } if (castedResult.EndCalled) { throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndResolve")); } if (GlobalLog.IsEnabled) { GlobalLog.Print("Dns.HostResolutionEndHelper"); } castedResult.InternalWaitForCompletion(); castedResult.EndCalled = true; Exception exception = castedResult.Result as Exception; if (exception != null) { throw exception; } return (IPHostEntry)castedResult.Result; } private static IAsyncResult BeginGetHostEntry(string hostNameOrAddress, AsyncCallback requestCallback, object stateObject) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Socket, "DNS", "BeginGetHostEntry", hostNameOrAddress); IAsyncResult asyncResult = HostResolutionBeginHelper(hostNameOrAddress, false, requestCallback, stateObject); if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Socket, "DNS", "BeginGetHostEntry", asyncResult); return asyncResult; } // BeginResolve private static IAsyncResult BeginGetHostEntry(IPAddress address, AsyncCallback requestCallback, object stateObject) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Socket, "DNS", "BeginGetHostEntry", address); IAsyncResult asyncResult = HostResolutionBeginHelper(address, true, true, requestCallback, stateObject); if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Socket, "DNS", "BeginGetHostEntry", asyncResult); return asyncResult; } // BeginResolve private static IPHostEntry EndGetHostEntry(IAsyncResult asyncResult) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Socket, "DNS", "EndGetHostEntry", asyncResult); IPHostEntry ipHostEntry = HostResolutionEndHelper(asyncResult); if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Socket, "DNS", "EndGetHostEntry", ipHostEntry); return ipHostEntry; } // EndResolve() private static IAsyncResult BeginGetHostAddresses(string hostNameOrAddress, AsyncCallback requestCallback, object state) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Socket, "DNS", "BeginGetHostAddresses", hostNameOrAddress); IAsyncResult asyncResult = HostResolutionBeginHelper(hostNameOrAddress, true, requestCallback, state); if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Socket, "DNS", "BeginGetHostAddresses", asyncResult); return asyncResult; } // BeginResolve private static IPAddress[] EndGetHostAddresses(IAsyncResult asyncResult) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Socket, "DNS", "EndGetHostAddresses", asyncResult); IPHostEntry ipHostEntry = HostResolutionEndHelper(asyncResult); if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Socket, "DNS", "EndGetHostAddresses", ipHostEntry); return ipHostEntry.AddressList; } // EndResolveToAddresses //************* Task-based async public methods ************************* public static Task<IPAddress[]> GetHostAddressesAsync(string hostNameOrAddress) { return Task<IPAddress[]>.Factory.FromAsync( (arg, requestCallback, stateObject) => BeginGetHostAddresses(arg, requestCallback, stateObject), asyncResult => EndGetHostAddresses(asyncResult), hostNameOrAddress, null); } public static Task<IPHostEntry> GetHostEntryAsync(IPAddress address) { return Task<IPHostEntry>.Factory.FromAsync( (arg, requestCallback, stateObject) => BeginGetHostEntry(arg, requestCallback, stateObject), asyncResult => EndGetHostEntry(asyncResult), address, null); } public static Task<IPHostEntry> GetHostEntryAsync(string hostNameOrAddress) { return Task<IPHostEntry>.Factory.FromAsync( (arg, requestCallback, stateObject) => BeginGetHostEntry(arg, requestCallback, stateObject), asyncResult => EndGetHostEntry(asyncResult), hostNameOrAddress, null); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; namespace DotBPE.Baseline.Extensions { public static class StringUtils { public static string GetNewToken() { return GetRandomString(40); } public static string ToJTokenPath(this string path) { if (path.StartsWith("$")) return path; var sb = new StringBuilder(); var parts = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < parts.Length; i++) { if (Char.IsNumber(parts[i][0])) sb.Append("[").Append(parts[i]).Append("]"); else { sb.Append(parts[i]); } if (i < parts.Length - 1 && !Char.IsNumber(parts[i + 1][0])) sb.Append("."); } return sb.ToString(); } public static string GetRandomString(int length, string allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") { if (length < 0) throw new ArgumentOutOfRangeException(nameof(length), "length cannot be less than zero."); if (string.IsNullOrEmpty(allowedChars)) throw new ArgumentException("allowedChars may not be empty."); const int byteSize = 0x100; var allowedCharSet = new HashSet<char>(allowedChars).ToArray(); if (byteSize < allowedCharSet.Length) throw new ArgumentException($"allowedChars may contain no more than {byteSize} characters."); using (var rng = new RNGCryptoServiceProvider()) { var result = new StringBuilder(); var buf = new byte[128]; while (result.Length < length) { rng.GetBytes(buf); for (var i = 0; i < buf.Length && result.Length < length; ++i) { var outOfRangeStart = byteSize - (byteSize % allowedCharSet.Length); if (outOfRangeStart <= buf[i]) continue; result.Append(allowedCharSet[buf[i] % allowedCharSet.Length]); } } return result.ToString(); } } } public static class StringExtensions { private static readonly Regex _splitNameRegex = new Regex(@"[\W_]+"); private static readonly Regex _properWordRegex = new Regex(@"([A-Z][a-z]*)|([0-9]+)"); public static string ToSaltedHash(this string password, string salt) { byte[] passwordBytes = Encoding.Unicode.GetBytes(password); byte[] saltBytes = Convert.FromBase64String(salt); var hashStrategy = HashAlgorithm.Create("HMACSHA256") as KeyedHashAlgorithm; if (hashStrategy.Key.Length == saltBytes.Length) hashStrategy.Key = saltBytes; else if (hashStrategy.Key.Length < saltBytes.Length) { var keyBytes = new byte[hashStrategy.Key.Length]; Buffer.BlockCopy(saltBytes, 0, keyBytes, 0, keyBytes.Length); hashStrategy.Key = keyBytes; } else { var keyBytes = new byte[hashStrategy.Key.Length]; for (int i = 0; i < keyBytes.Length;) { int len = Math.Min(saltBytes.Length, keyBytes.Length - i); Buffer.BlockCopy(saltBytes, 0, keyBytes, i, len); i += len; } hashStrategy.Key = keyBytes; } byte[] result = hashStrategy.ComputeHash(passwordBytes); return Convert.ToBase64String(result); } public static string ToDelimitedString<T>(this IEnumerable<T> values, string delimiter) { var sb = new StringBuilder(); foreach (var i in values) { if (sb.Length > 0) sb.Append(delimiter); sb.Append(i.ToString()); } return sb.ToString(); } public static string ToDelimitedString(this IEnumerable<string> values) { return ToDelimitedString(values, ","); } public static string ToDelimitedString(this IEnumerable<string> values, string delimiter) { var sb = new StringBuilder(); foreach (var i in values) { if (sb.Length > 0) sb.Append(delimiter); sb.Append(i); } return sb.ToString(); } public static string ToLowerUnderscoredWords(this string value) { var builder = new StringBuilder(value.Length + 10); for (int index = 0; index < value.Length; index++) { char c = value[index]; if (Char.IsUpper(c)) { if (index > 0 && value[index - 1] != '_') builder.Append('_'); builder.Append(Char.ToLower(c)); } else { builder.Append(c); } } return builder.ToString(); } public static bool AnyWildcardMatches(this string value, IEnumerable<string> patternsToMatch, bool ignoreCase = false) { if (ignoreCase) value = value.ToLower(); return patternsToMatch.Any(pattern => CheckForMatch(pattern, value, ignoreCase)); } private static bool CheckForMatch(string pattern, string value, bool ignoreCase = true) { bool startsWithWildcard = pattern.StartsWith("*"); if (startsWithWildcard) pattern = pattern.Substring(1); bool endsWithWildcard = pattern.EndsWith("*"); if (endsWithWildcard) pattern = pattern.Substring(0, pattern.Length - 1); if (ignoreCase) pattern = pattern.ToLower(); if (startsWithWildcard && endsWithWildcard) return value.Contains(pattern); if (startsWithWildcard) return value.EndsWith(pattern); if (endsWithWildcard) return value.StartsWith(pattern); return value.Equals(pattern); } public static string ToConcatenatedString<T>(this IEnumerable<T> values, Func<T, string> stringSelector) { return values.ToConcatenatedString(stringSelector, String.Empty); } public static string ToConcatenatedString<T>(this IEnumerable<T> values, Func<T, string> action, string separator) { var sb = new StringBuilder(); foreach (var item in values) { if (sb.Length > 0) sb.Append(separator); sb.Append(action(item)); } return sb.ToString(); } public static string DefaultAndNormalize(this string s) { if (String.IsNullOrEmpty(s)) return String.Empty; return s.RemoveNonAlphaNumeric().ToLowerInvariant(); } public static string RemoveNonNumeric(this string s) { return new string(Array.FindAll(s.ToCharArray(), Char.IsDigit)); } public static string RemoveNonAlphaNumeric(this string s) { return new string(Array.FindAll(s.ToCharArray(), Char.IsLetterOrDigit)); } public static string RemoveWhiteSpace(this string s) { return new string(Array.FindAll(s.ToCharArray(), c => !Char.IsWhiteSpace(c))); } public static string ReplaceFirst(this string s, string find, string replace) { var i = s.IndexOf(find); if (i >= 0) { var pre = s.Substring(0, i); var post = s.Substring(i + find.Length); return String.Concat(pre, replace, post); } return s; } public static IEnumerable<string> SplitLines(this string text) { return text.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).Where(l => !String.IsNullOrWhiteSpace(l)).Select(l => l.Trim()); } public static string StripInvisible(this string s) { return s .Replace("\r\n", " ") .Replace('\n', ' ') .Replace('\t', ' '); } public static string NormalizeLineEndings(this string text, string lineEnding = null) { if (String.IsNullOrEmpty(lineEnding)) lineEnding = Environment.NewLine; text = text.Replace("\r\n", "\n"); if (lineEnding != "\n") text = text.Replace("\r\n", lineEnding); return text; } public static string Truncate(this string text, int keep) { if (String.IsNullOrEmpty(text)) return String.Empty; string buffer = NormalizeLineEndings(text); if (buffer.Length <= keep) return buffer; return String.Concat(buffer.Substring(0, keep - 3), "..."); } public static string Truncate(this string text, int length, string ellipsis, bool keepFullWordAtEnd) { if (String.IsNullOrEmpty(text)) return String.Empty; if (text.Length < length) return text; text = text.Substring(0, length); if (keepFullWordAtEnd && text.LastIndexOf(' ') > 0) text = text.Substring(0, text.LastIndexOf(' ')); return $"{text}{ellipsis}"; } public static string ToLowerFiltered(this string value, char[] charsToRemove) { var builder = new StringBuilder(value.Length); for (int index = 0; index < value.Length; index++) { char c = value[index]; if (Char.IsUpper(c)) c = Char.ToLower(c); bool includeChar = true; for (int i = 0; i < charsToRemove.Length; i++) { if (charsToRemove[i] == c) { includeChar = false; break; } } if (includeChar) builder.Append(c); } return builder.ToString(); } public static string[] SplitAndTrim(this string s, params string[] separator) { if (s.IsNullOrEmpty()) return new string[0]; var result = ((separator == null) || (separator.Length == 0)) ? s.Split((char[])null, StringSplitOptions.RemoveEmptyEntries) : s.Split(separator, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < result.Length; i++) result[i] = result[i].Trim(); return result; } public static string[] SplitAndTrim(this string s, params char[] separator) { if (s.IsNullOrEmpty()) return new string[0]; var result = s.Split(separator, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < result.Length; i++) result[i] = result[i].Trim(); return result; } public static bool IsNullOrEmpty(this string item) { return String.IsNullOrEmpty(item); } public static bool IsNullOrWhiteSpace(this string item) { return String.IsNullOrEmpty(item) || item.All(Char.IsWhiteSpace); } public static string HexEscape(this string value, params char[] anyCharOf) { if (string.IsNullOrEmpty(value)) return value; if (anyCharOf == null || anyCharOf.Length == 0) return value; var encodeCharMap = new HashSet<char>(anyCharOf); var sb = new StringBuilder(); var textLength = value.Length; for (var i = 0; i < textLength; i++) { var c = value[i]; if (encodeCharMap.Contains(c)) { sb.Append('%' + ((int)c).ToString("x")); } else { sb.Append(c); } } return sb.ToString(); } private static readonly Regex _entityResolver = new Regex("([&][#](?'decimal'[0-9]+);)|([&][#][(x|X)](?'hex'[0-9a-fA-F]+);)|([&](?'html'\\w+);)"); public static string HtmlEntityEncode(this string value) { return HtmlEntityEncode(value, true); } public static string HtmlEntityEncode(this string value, bool encodeTagsToo) { string str = string.Empty; foreach (char ch in value) { int num = (int)ch; switch (num) { case 38: if (encodeTagsToo) { str = str + "&amp;"; break; } else break; case 60: if (encodeTagsToo) { str = str + "&lt;"; break; } else break; case 62: if (encodeTagsToo) { str = str + "&gt;"; break; } else break; default: str = (int)ch < 32 || (int)ch > 126 ? str + "&#" + num.ToString((IFormatProvider)NumberFormatInfo.InvariantInfo) + ";" : str + (object)ch; break; } } return str; } public static string HtmlEntityDecode(this string encodedText) { return _entityResolver.Replace(encodedText, new MatchEvaluator(ResolveEntityAngleAmp)); } public static string HtmlEntityDecode(this string encodedText, bool encodeTagsToo) { if (encodeTagsToo) return _entityResolver.Replace(encodedText, new MatchEvaluator(ResolveEntityAngleAmp)); else return _entityResolver.Replace(encodedText, new MatchEvaluator(ResolveEntityNotAngleAmp)); } private static string ResolveEntityNotAngleAmp(Match matchToProcess) { string str; if (matchToProcess.Groups["decimal"].Success) str = Convert.ToChar(Convert.ToInt32(matchToProcess.Groups["decimal"].Value)).ToString(); else if (matchToProcess.Groups["hex"].Success) str = Convert.ToChar(HexToInt(matchToProcess.Groups["hex"].Value)).ToString(); else if (matchToProcess.Groups["html"].Success) { string entity = matchToProcess.Groups["html"].Value; switch (entity.ToLower()) { case "lt": case "gt": case "amp": str = "&" + entity + ";"; break; default: str = EntityLookup(entity); break; } } else str = "X"; return str; } private static string ResolveEntityAngleAmp(Match matchToProcess) { return !matchToProcess.Groups["decimal"].Success ? (!matchToProcess.Groups["hex"].Success ? (!matchToProcess.Groups["html"].Success ? "Y" : EntityLookup(matchToProcess.Groups["html"].Value)) : Convert.ToChar(HexToInt(matchToProcess.Groups["hex"].Value)).ToString()) : Convert.ToChar(Convert.ToInt32(matchToProcess.Groups["decimal"].Value)).ToString(); } public static int HexToInt(string hexstr) { int num = 0; hexstr = hexstr.ToUpper(); char[] chArray = hexstr.ToCharArray(); for (int index = chArray.Length - 1; index >= 0; --index) { if ((int)chArray[index] >= 48 && (int)chArray[index] <= 57) num += ((int)chArray[index] - 48) * (int)Math.Pow(16.0, (double)(chArray.Length - 1 - index)); else if ((int)chArray[index] >= 65 && (int)chArray[index] <= 70) { num += ((int)chArray[index] - 55) * (int)Math.Pow(16.0, (double)(chArray.Length - 1 - index)); } else { num = 0; break; } } return num; } private static string EntityLookup(string entity) { string str = ""; switch (entity) { case "Aacute": str = Convert.ToChar(193).ToString(); break; case "aacute": str = Convert.ToChar(225).ToString(); break; case "acirc": str = Convert.ToChar(226).ToString(); break; case "Acirc": str = Convert.ToChar(194).ToString(); break; case "acute": str = Convert.ToChar(180).ToString(); break; case "AElig": str = Convert.ToChar(198).ToString(); break; case "aelig": str = Convert.ToChar(230).ToString(); break; case "Agrave": str = Convert.ToChar(192).ToString(); break; case "agrave": str = Convert.ToChar(224).ToString(); break; case "alefsym": str = Convert.ToChar(8501).ToString(); break; case "Alpha": str = Convert.ToChar(913).ToString(); break; case "alpha": str = Convert.ToChar(945).ToString(); break; case "amp": str = Convert.ToChar(38).ToString(); break; case "and": str = Convert.ToChar(8743).ToString(); break; case "ang": str = Convert.ToChar(8736).ToString(); break; case "aring": str = Convert.ToChar(229).ToString(); break; case "Aring": str = Convert.ToChar(197).ToString(); break; case "asymp": str = Convert.ToChar(8776).ToString(); break; case "Atilde": str = Convert.ToChar(195).ToString(); break; case "atilde": str = Convert.ToChar(227).ToString(); break; case "auml": str = Convert.ToChar(228).ToString(); break; case "Auml": str = Convert.ToChar(196).ToString(); break; case "bdquo": str = Convert.ToChar(8222).ToString(); break; case "Beta": str = Convert.ToChar(914).ToString(); break; case "beta": str = Convert.ToChar(946).ToString(); break; case "brvbar": str = Convert.ToChar(166).ToString(); break; case "bull": str = Convert.ToChar(8226).ToString(); break; case "cap": str = Convert.ToChar(8745).ToString(); break; case "Ccedil": str = Convert.ToChar(199).ToString(); break; case "ccedil": str = Convert.ToChar(231).ToString(); break; case "cedil": str = Convert.ToChar(184).ToString(); break; case "cent": str = Convert.ToChar(162).ToString(); break; case "chi": str = Convert.ToChar(967).ToString(); break; case "Chi": str = Convert.ToChar(935).ToString(); break; case "circ": str = Convert.ToChar(710).ToString(); break; case "clubs": str = Convert.ToChar(9827).ToString(); break; case "cong": str = Convert.ToChar(8773).ToString(); break; case "copy": str = Convert.ToChar(169).ToString(); break; case "crarr": str = Convert.ToChar(8629).ToString(); break; case "cup": str = Convert.ToChar(8746).ToString(); break; case "curren": str = Convert.ToChar(164).ToString(); break; case "dagger": str = Convert.ToChar(8224).ToString(); break; case "Dagger": str = Convert.ToChar(8225).ToString(); break; case "darr": str = Convert.ToChar(8595).ToString(); break; case "dArr": str = Convert.ToChar(8659).ToString(); break; case "deg": str = Convert.ToChar(176).ToString(); break; case "Delta": str = Convert.ToChar(916).ToString(); break; case "delta": str = Convert.ToChar(948).ToString(); break; case "diams": str = Convert.ToChar(9830).ToString(); break; case "divide": str = Convert.ToChar(247).ToString(); break; case "eacute": str = Convert.ToChar(233).ToString(); break; case "Eacute": str = Convert.ToChar(201).ToString(); break; case "Ecirc": str = Convert.ToChar(202).ToString(); break; case "ecirc": str = Convert.ToChar(234).ToString(); break; case "Egrave": str = Convert.ToChar(200).ToString(); break; case "egrave": str = Convert.ToChar(232).ToString(); break; case "empty": str = Convert.ToChar(8709).ToString(); break; case "emsp": str = Convert.ToChar(8195).ToString(); break; case "ensp": str = Convert.ToChar(8194).ToString(); break; case "epsilon": str = Convert.ToChar(949).ToString(); break; case "Epsilon": str = Convert.ToChar(917).ToString(); break; case "equiv": str = Convert.ToChar(8801).ToString(); break; case "Eta": str = Convert.ToChar(919).ToString(); break; case "eta": str = Convert.ToChar(951).ToString(); break; case "eth": str = Convert.ToChar(240).ToString(); break; case "ETH": str = Convert.ToChar(208).ToString(); break; case "Euml": str = Convert.ToChar(203).ToString(); break; case "euml": str = Convert.ToChar(235).ToString(); break; case "euro": str = Convert.ToChar(8364).ToString(); break; case "exist": str = Convert.ToChar(8707).ToString(); break; case "fnof": str = Convert.ToChar(402).ToString(); break; case "forall": str = Convert.ToChar(8704).ToString(); break; case "frac12": str = Convert.ToChar(189).ToString(); break; case "frac14": str = Convert.ToChar(188).ToString(); break; case "frac34": str = Convert.ToChar(190).ToString(); break; case "frasl": str = Convert.ToChar(8260).ToString(); break; case "gamma": str = Convert.ToChar(947).ToString(); break; case "Gamma": str = Convert.ToChar(915).ToString(); break; case "ge": str = Convert.ToChar(8805).ToString(); break; case "gt": str = Convert.ToChar(62).ToString(); break; case "hArr": str = Convert.ToChar(8660).ToString(); break; case "harr": str = Convert.ToChar(8596).ToString(); break; case "hearts": str = Convert.ToChar(9829).ToString(); break; case "hellip": str = Convert.ToChar(8230).ToString(); break; case "Iacute": str = Convert.ToChar(205).ToString(); break; case "iacute": str = Convert.ToChar(237).ToString(); break; case "icirc": str = Convert.ToChar(238).ToString(); break; case "Icirc": str = Convert.ToChar(206).ToString(); break; case "iexcl": str = Convert.ToChar(161).ToString(); break; case "Igrave": str = Convert.ToChar(204).ToString(); break; case "igrave": str = Convert.ToChar(236).ToString(); break; case "image": str = Convert.ToChar(8465).ToString(); break; case "infin": str = Convert.ToChar(8734).ToString(); break; case "int": str = Convert.ToChar(8747).ToString(); break; case "Iota": str = Convert.ToChar(921).ToString(); break; case "iota": str = Convert.ToChar(953).ToString(); break; case "iquest": str = Convert.ToChar(191).ToString(); break; case "isin": str = Convert.ToChar(8712).ToString(); break; case "iuml": str = Convert.ToChar(239).ToString(); break; case "Iuml": str = Convert.ToChar(207).ToString(); break; case "kappa": str = Convert.ToChar(954).ToString(); break; case "Kappa": str = Convert.ToChar(922).ToString(); break; case "Lambda": str = Convert.ToChar(923).ToString(); break; case "lambda": str = Convert.ToChar(955).ToString(); break; case "lang": str = Convert.ToChar(9001).ToString(); break; case "laquo": str = Convert.ToChar(171).ToString(); break; case "larr": str = Convert.ToChar(8592).ToString(); break; case "lArr": str = Convert.ToChar(8656).ToString(); break; case "lceil": str = Convert.ToChar(8968).ToString(); break; case "ldquo": str = Convert.ToChar(8220).ToString(); break; case "le": str = Convert.ToChar(8804).ToString(); break; case "lfloor": str = Convert.ToChar(8970).ToString(); break; case "lowast": str = Convert.ToChar(8727).ToString(); break; case "loz": str = Convert.ToChar(9674).ToString(); break; case "lrm": str = Convert.ToChar(8206).ToString(); break; case "lsaquo": str = Convert.ToChar(8249).ToString(); break; case "lsquo": str = Convert.ToChar(8216).ToString(); break; case "lt": str = Convert.ToChar(60).ToString(); break; case "macr": str = Convert.ToChar(175).ToString(); break; case "mdash": str = Convert.ToChar(8212).ToString(); break; case "micro": str = Convert.ToChar(181).ToString(); break; case "middot": str = Convert.ToChar(183).ToString(); break; case "minus": str = Convert.ToChar(8722).ToString(); break; case "Mu": str = Convert.ToChar(924).ToString(); break; case "mu": str = Convert.ToChar(956).ToString(); break; case "nabla": str = Convert.ToChar(8711).ToString(); break; case "nbsp": str = Convert.ToChar(160).ToString(); break; case "ndash": str = Convert.ToChar(8211).ToString(); break; case "ne": str = Convert.ToChar(8800).ToString(); break; case "ni": str = Convert.ToChar(8715).ToString(); break; case "not": str = Convert.ToChar(172).ToString(); break; case "notin": str = Convert.ToChar(8713).ToString(); break; case "nsub": str = Convert.ToChar(8836).ToString(); break; case "ntilde": str = Convert.ToChar(241).ToString(); break; case "Ntilde": str = Convert.ToChar(209).ToString(); break; case "Nu": str = Convert.ToChar(925).ToString(); break; case "nu": str = Convert.ToChar(957).ToString(); break; case "oacute": str = Convert.ToChar(243).ToString(); break; case "Oacute": str = Convert.ToChar(211).ToString(); break; case "Ocirc": str = Convert.ToChar(212).ToString(); break; case "ocirc": str = Convert.ToChar(244).ToString(); break; case "OElig": str = Convert.ToChar(338).ToString(); break; case "oelig": str = Convert.ToChar(339).ToString(); break; case "ograve": str = Convert.ToChar(242).ToString(); break; case "Ograve": str = Convert.ToChar(210).ToString(); break; case "oline": str = Convert.ToChar(8254).ToString(); break; case "Omega": str = Convert.ToChar(937).ToString(); break; case "omega": str = Convert.ToChar(969).ToString(); break; case "Omicron": str = Convert.ToChar(927).ToString(); break; case "omicron": str = Convert.ToChar(959).ToString(); break; case "oplus": str = Convert.ToChar(8853).ToString(); break; case "or": str = Convert.ToChar(8744).ToString(); break; case "ordf": str = Convert.ToChar(170).ToString(); break; case "ordm": str = Convert.ToChar(186).ToString(); break; case "Oslash": str = Convert.ToChar(216).ToString(); break; case "oslash": str = Convert.ToChar(248).ToString(); break; case "otilde": str = Convert.ToChar(245).ToString(); break; case "Otilde": str = Convert.ToChar(213).ToString(); break; case "otimes": str = Convert.ToChar(8855).ToString(); break; case "Ouml": str = Convert.ToChar(214).ToString(); break; case "ouml": str = Convert.ToChar(246).ToString(); break; case "para": str = Convert.ToChar(182).ToString(); break; case "part": str = Convert.ToChar(8706).ToString(); break; case "permil": str = Convert.ToChar(8240).ToString(); break; case "perp": str = Convert.ToChar(8869).ToString(); break; case "Phi": str = Convert.ToChar(934).ToString(); break; case "phi": str = Convert.ToChar(966).ToString(); break; case "Pi": str = Convert.ToChar(928).ToString(); break; case "pi": str = Convert.ToChar(960).ToString(); break; case "piv": str = Convert.ToChar(982).ToString(); break; case "plusmn": str = Convert.ToChar(177).ToString(); break; case "pound": str = Convert.ToChar(163).ToString(); break; case "Prime": str = Convert.ToChar(8243).ToString(); break; case "prime": str = Convert.ToChar(8242).ToString(); break; case "prod": str = Convert.ToChar(8719).ToString(); break; case "prop": str = Convert.ToChar(8733).ToString(); break; case "psi": str = Convert.ToChar(968).ToString(); break; case "Psi": str = Convert.ToChar(936).ToString(); break; case "quot": str = Convert.ToChar(34).ToString(); break; case "radic": str = Convert.ToChar(8730).ToString(); break; case "rang": str = Convert.ToChar(9002).ToString(); break; case "raquo": str = Convert.ToChar(187).ToString(); break; case "rarr": str = Convert.ToChar(8594).ToString(); break; case "rArr": str = Convert.ToChar(8658).ToString(); break; case "rceil": str = Convert.ToChar(8969).ToString(); break; case "rdquo": str = Convert.ToChar(8221).ToString(); break; case "real": str = Convert.ToChar(8476).ToString(); break; case "reg": str = Convert.ToChar(174).ToString(); break; case "rfloor": str = Convert.ToChar(8971).ToString(); break; case "rho": str = Convert.ToChar(961).ToString(); break; case "Rho": str = Convert.ToChar(929).ToString(); break; case "rlm": str = Convert.ToChar(8207).ToString(); break; case "rsaquo": str = Convert.ToChar(8250).ToString(); break; case "rsquo": str = Convert.ToChar(8217).ToString(); break; case "sbquo": str = Convert.ToChar(8218).ToString(); break; case "Scaron": str = Convert.ToChar(352).ToString(); break; case "scaron": str = Convert.ToChar(353).ToString(); break; case "sdot": str = Convert.ToChar(8901).ToString(); break; case "sect": str = Convert.ToChar(167).ToString(); break; case "shy": str = Convert.ToChar(173).ToString(); break; case "sigma": str = Convert.ToChar(963).ToString(); break; case "Sigma": str = Convert.ToChar(931).ToString(); break; case "sigmaf": str = Convert.ToChar(962).ToString(); break; case "sim": str = Convert.ToChar(8764).ToString(); break; case "spades": str = Convert.ToChar(9824).ToString(); break; case "sub": str = Convert.ToChar(8834).ToString(); break; case "sube": str = Convert.ToChar(8838).ToString(); break; case "sum": str = Convert.ToChar(8721).ToString(); break; case "sup": str = Convert.ToChar(8835).ToString(); break; case "sup1": str = Convert.ToChar(185).ToString(); break; case "sup2": str = Convert.ToChar(178).ToString(); break; case "sup3": str = Convert.ToChar(179).ToString(); break; case "supe": str = Convert.ToChar(8839).ToString(); break; case "szlig": str = Convert.ToChar(223).ToString(); break; case "Tau": str = Convert.ToChar(932).ToString(); break; case "tau": str = Convert.ToChar(964).ToString(); break; case "there4": str = Convert.ToChar(8756).ToString(); break; case "theta": str = Convert.ToChar(952).ToString(); break; case "Theta": str = Convert.ToChar(920).ToString(); break; case "thetasym": str = Convert.ToChar(977).ToString(); break; case "thinsp": str = Convert.ToChar(8201).ToString(); break; case "thorn": str = Convert.ToChar(254).ToString(); break; case "THORN": str = Convert.ToChar(222).ToString(); break; case "tilde": str = Convert.ToChar(732).ToString(); break; case "times": str = Convert.ToChar(215).ToString(); break; case "trade": str = Convert.ToChar(8482).ToString(); break; case "Uacute": str = Convert.ToChar(218).ToString(); break; case "uacute": str = Convert.ToChar(250).ToString(); break; case "uarr": str = Convert.ToChar(8593).ToString(); break; case "uArr": str = Convert.ToChar(8657).ToString(); break; case "Ucirc": str = Convert.ToChar(219).ToString(); break; case "ucirc": str = Convert.ToChar(251).ToString(); break; case "Ugrave": str = Convert.ToChar(217).ToString(); break; case "ugrave": str = Convert.ToChar(249).ToString(); break; case "uml": str = Convert.ToChar(168).ToString(); break; case "upsih": str = Convert.ToChar(978).ToString(); break; case "Upsilon": str = Convert.ToChar(933).ToString(); break; case "upsilon": str = Convert.ToChar(965).ToString(); break; case "Uuml": str = Convert.ToChar(220).ToString(); break; case "uuml": str = Convert.ToChar(252).ToString(); break; case "weierp": str = Convert.ToChar(8472).ToString(); break; case "Xi": str = Convert.ToChar(926).ToString(); break; case "xi": str = Convert.ToChar(958).ToString(); break; case "yacute": str = Convert.ToChar(253).ToString(); break; case "Yacute": str = Convert.ToChar(221).ToString(); break; case "yen": str = Convert.ToChar(165).ToString(); break; case "Yuml": str = Convert.ToChar(376).ToString(); break; case "yuml": str = Convert.ToChar((int)byte.MaxValue).ToString(); break; case "zeta": str = Convert.ToChar(950).ToString(); break; case "Zeta": str = Convert.ToChar(918).ToString(); break; case "zwj": str = Convert.ToChar(8205).ToString(); break; case "zwnj": str = Convert.ToChar(8204).ToString(); break; } return str; } // TODO: Add support for detecting the culture number separators as well as suffix (Ex. 100d) public static bool IsNumeric(this string value) { if (String.IsNullOrEmpty(value)) return false; for (int i = 0; i < value.Length; i++) { if (Char.IsNumber(value[i])) continue; if (i == 0 && value[i] == '-') continue; return false; } return true; } /// <summary> /// Determines whether the specified string is not <see cref="IsNullOrEmpty"/>. /// </summary> /// <param name="value">The value to check.</param> /// <returns> /// <c>true</c> if the specified <paramref name="value"/> is not <see cref="IsNullOrEmpty"/>; otherwise, <c>false</c>. /// </returns> public static bool HasValue(this string value) { return !string.IsNullOrEmpty(value); } /// <summary> /// Uses the string as a format /// </summary> /// <param name="format">A string reference</param> /// <param name="args">Object parameters that should be formatted</param> /// <returns>Formatted string</returns> public static string FormatWith(this string format, params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); return string.Format(format, args); } /// <summary> /// Converts a string to use camelCase. /// </summary> /// <param name="value">The value.</param> /// <returns>The to camel case. </returns> public static string ToCamelCase(this string value) { if (string.IsNullOrEmpty(value)) return value; string output = ToPascalCase(value); if (output.Length > 2) return char.ToLower(output[0]) + output.Substring(1); return output.ToLower(); } /// <summary> /// Converts a string to use PascalCase. /// </summary> /// <param name="value">Text to convert</param> /// <returns>The string</returns> public static string ToPascalCase(this string value) { return value.ToPascalCase(_splitNameRegex); } /// <summary> /// Converts a string to use PascalCase. /// </summary> /// <param name="value">Text to convert</param> /// <param name="splitRegex">Regular Expression to split words on.</param> /// <returns>The string</returns> public static string ToPascalCase(this string value, Regex splitRegex) { if (string.IsNullOrEmpty(value)) return value; var mixedCase = value.IsMixedCase(); var names = splitRegex.Split(value); var output = new StringBuilder(); if (names.Length > 1) { foreach (string name in names) { if (name.Length > 1) { output.Append(char.ToUpper(name[0])); output.Append(mixedCase ? name.Substring(1) : name.Substring(1).ToLower()); } else { output.Append(name); } } } else if (value.Length > 1) { output.Append(char.ToUpper(value[0])); output.Append(mixedCase ? value.Substring(1) : value.Substring(1).ToLower()); } else { output.Append(value.ToUpper()); } return output.ToString(); } /// <summary> /// Takes a NameIdentifier and spaces it out into words "Name Identifier". /// </summary> /// <param name="value">The value to convert.</param> /// <returns>The string</returns> public static string ToTitle(this string value) { if (string.IsNullOrEmpty(value)) return value; value = ToPascalCase(value); MatchCollection words = _properWordRegex.Matches(value); var spacedName = new StringBuilder(); foreach (Match word in words) { spacedName.Append(word.Value); spacedName.Append(' '); } // remove last space spacedName.Length = spacedName.Length - 1; return spacedName.ToString(); } /// <summary> /// Does string contain both uppercase and lowercase characters? /// </summary> /// <param name="s">The value.</param> /// <returns>True if contain mixed case.</returns> public static bool IsMixedCase(this string s) { if (s.IsNullOrEmpty()) return false; var containsUpper = s.Any(Char.IsUpper); var containsLower = s.Any(Char.IsLower); return containsLower && containsUpper; } public static string EnsureEndsWith(this string s, string ending) { if (s == null) return null; return s.EndsWith(ending) ? s : string.Concat(s, ending); } public static string TakeFirst(this string s, int howMany = 1) { if (s.IsNullOrEmpty()) return String.Empty; if (s.Length <= howMany) return s; return s.Substring(0, howMany); } /// <summary> /// Compares a string against a wildcard pattern. /// </summary> /// <param name="input">The string to match.</param> /// <param name="mask">The wildcard pattern.</param> /// <returns><c>true</c> if the pattern is matched; otherwise <c>false</c></returns> public static bool Like(this string input, string mask) { var inputEnumerator = input.GetEnumerator(); var maskEnumerator = mask.GetEnumerator(); return Like(inputEnumerator, maskEnumerator); } private static bool Like(CharEnumerator inputEnumerator, CharEnumerator maskEnumerator) { while (maskEnumerator.MoveNext()) { switch (maskEnumerator.Current) { case '?': if (!inputEnumerator.MoveNext()) return false; break; case '*': do { var inputTryAhead = (CharEnumerator)inputEnumerator.Clone(); var maskTryAhead = (CharEnumerator)maskEnumerator.Clone(); if (Like(inputTryAhead, maskTryAhead)) return true; } while (inputEnumerator.MoveNext()); return false; case '\\': // escape maskEnumerator.MoveNext(); goto default; default: if (!inputEnumerator.MoveNext() || inputEnumerator.Current != maskEnumerator.Current) return false; break; } } return !inputEnumerator.MoveNext(); } public static bool IsJson(this string value) { return value.GetJsonType() != JsonType.None; } public static JsonType GetJsonType(this string value) { if (String.IsNullOrEmpty(value)) return JsonType.None; for (int i = 0; i < value.Length; i++) { if (Char.IsWhiteSpace(value[i])) continue; if (value[i] == '{') return JsonType.Object; if (value[i] == '[') return JsonType.Array; break; } return JsonType.None; } } public enum JsonType : byte { None, Object, Array } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Dynamic.Utils; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; namespace System.Dynamic { /// <summary> /// Represents an object with members that can be dynamically added and removed at runtime. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] public sealed class ExpandoObject : IDynamicMetaObjectProvider, IDictionary<string, object>, INotifyPropertyChanged { internal readonly object LockObject; // the readonly field is used for locking the Expando object private ExpandoData _data; // the data currently being held by the Expando object private int _count; // the count of available members internal readonly static object Uninitialized = new object(); // A marker object used to identify that a value is uninitialized. internal const int AmbiguousMatchFound = -2; // The value is used to indicate there exists ambiguous match in the Expando object internal const int NoMatch = -1; // The value is used to indicate there is no matching member private PropertyChangedEventHandler _propertyChanged; /// <summary> /// Creates a new ExpandoObject with no members. /// </summary> public ExpandoObject() { _data = ExpandoData.Empty; LockObject = new object(); } #region Get/Set/Delete Helpers /// <summary> /// Try to get the data stored for the specified class at the specified index. If the /// class has changed a full lookup for the slot will be performed and the correct /// value will be retrieved. /// </summary> internal bool TryGetValue(object indexClass, int index, string name, bool ignoreCase, out object value) { // read the data now. The data is immutable so we get a consistent view. // If there's a concurrent writer they will replace data and it just appears // that we won the race ExpandoData data = _data; if (data.Class != indexClass || ignoreCase) { /* Re-search for the index matching the name here if * 1) the class has changed, we need to get the correct index and return * the value there. * 2) the search is case insensitive: * a. the member specified by index may be deleted, but there might be other * members matching the name if the binder is case insensitive. * b. the member that exactly matches the name didn't exist before and exists now, * need to find the exact match. */ index = data.Class.GetValueIndex(name, ignoreCase, this); if (index == ExpandoObject.AmbiguousMatchFound) { throw Error.AmbiguousMatchInExpandoObject(name); } } if (index == ExpandoObject.NoMatch) { value = null; return false; } // Capture the value into a temp, so it doesn't get mutated after we check // for Uninitialized. object temp = data[index]; if (temp == Uninitialized) { value = null; return false; } // index is now known to be correct value = temp; return true; } /// <summary> /// Sets the data for the specified class at the specified index. If the class has /// changed then a full look for the slot will be performed. If the new class does /// not have the provided slot then the Expando's class will change. Only case sensitive /// setter is supported in ExpandoObject. /// </summary> internal void TrySetValue(object indexClass, int index, object value, string name, bool ignoreCase, bool add) { ExpandoData data; object oldValue; lock (LockObject) { data = _data; if (data.Class != indexClass || ignoreCase) { // The class has changed or we are doing a case-insensitive search, // we need to get the correct index and set the value there. If we // don't have the value then we need to promote the class - that // should only happen when we have multiple concurrent writers. index = data.Class.GetValueIndex(name, ignoreCase, this); if (index == ExpandoObject.AmbiguousMatchFound) { throw Error.AmbiguousMatchInExpandoObject(name); } if (index == ExpandoObject.NoMatch) { // Before creating a new class with the new member, need to check // if there is the exact same member but is deleted. We should reuse // the class if there is such a member. int exactMatch = ignoreCase ? data.Class.GetValueIndexCaseSensitive(name) : index; if (exactMatch != ExpandoObject.NoMatch) { Debug.Assert(data[exactMatch] == Uninitialized); index = exactMatch; } else { ExpandoClass newClass = data.Class.FindNewClass(name); data = PromoteClassCore(data.Class, newClass); // After the class promotion, there must be an exact match, // so we can do case-sensitive search here. index = data.Class.GetValueIndexCaseSensitive(name); Debug.Assert(index != ExpandoObject.NoMatch); } } } // Setting an uninitialized member increases the count of available members oldValue = data[index]; if (oldValue == Uninitialized) { _count++; } else if (add) { throw Error.SameKeyExistsInExpando(name); } data[index] = value; } // Notify property changed outside the lock PropertyChangedEventHandler propertyChanged = _propertyChanged; if (propertyChanged != null && value != oldValue) { propertyChanged(this, new PropertyChangedEventArgs(data.Class.Keys[index])); } } /// <summary> /// Deletes the data stored for the specified class at the specified index. /// </summary> internal bool TryDeleteValue(object indexClass, int index, string name, bool ignoreCase, object deleteValue) { ExpandoData data; lock (LockObject) { data = _data; if (data.Class != indexClass || ignoreCase) { // the class has changed or we are doing a case-insensitive search, // we need to get the correct index. If there is no associated index // we simply can't have the value and we return false. index = data.Class.GetValueIndex(name, ignoreCase, this); if (index == ExpandoObject.AmbiguousMatchFound) { throw Error.AmbiguousMatchInExpandoObject(name); } } if (index == ExpandoObject.NoMatch) { return false; } object oldValue = data[index]; if (oldValue == Uninitialized) { return false; } // Make sure the value matches, if requested. // // It's a shame we have to call Equals with the lock held but // there doesn't seem to be a good way around that, and // ConcurrentDictionary in mscorlib does the same thing. if (deleteValue != Uninitialized && !object.Equals(oldValue, deleteValue)) { return false; } data[index] = Uninitialized; // Deleting an available member decreases the count of available members _count--; } // Notify property changed outside the lock PropertyChangedEventHandler propertyChanged = _propertyChanged; if (propertyChanged != null) { propertyChanged(this, new PropertyChangedEventArgs(data.Class.Keys[index])); } return true; } /// <summary> /// Returns true if the member at the specified index has been deleted, /// otherwise false. Call this function holding the lock. /// </summary> internal bool IsDeletedMember(int index) { Debug.Assert(index >= 0 && index <= _data.Length); if (index == _data.Length) { // The member is a newly added by SetMemberBinder and not in data yet return false; } return _data[index] == ExpandoObject.Uninitialized; } /// <summary> /// Exposes the ExpandoClass which we've associated with this /// Expando object. Used for type checks in rules. /// </summary> internal ExpandoClass Class { get { return _data.Class; } } /// <summary> /// Promotes the class from the old type to the new type and returns the new /// ExpandoData object. /// </summary> private ExpandoData PromoteClassCore(ExpandoClass oldClass, ExpandoClass newClass) { Debug.Assert(oldClass != newClass); lock (LockObject) { if (_data.Class == oldClass) { _data = _data.UpdateClass(newClass); } return _data; } } /// <summary> /// Internal helper to promote a class. Called from our RuntimeOps helper. This /// version simply doesn't expose the ExpandoData object which is a private /// data structure. /// </summary> internal void PromoteClass(object oldClass, object newClass) { PromoteClassCore((ExpandoClass)oldClass, (ExpandoClass)newClass); } #endregion #region IDynamicMetaObjectProvider Members DynamicMetaObject IDynamicMetaObjectProvider.GetMetaObject(Expression parameter) { return new MetaExpando(parameter, this); } #endregion #region Helper methods private void TryAddMember(string key, object value) { ContractUtils.RequiresNotNull(key, nameof(key)); // Pass null to the class, which forces lookup. TrySetValue(null, -1, value, key, false, true); } private bool TryGetValueForKey(string key, out object value) { // Pass null to the class, which forces lookup. return TryGetValue(null, -1, key, false, out value); } private bool ExpandoContainsKey(string key) { return _data.Class.GetValueIndexCaseSensitive(key) >= 0; } // We create a non-generic type for the debug view for each different collection type // that uses DebuggerTypeProxy, instead of defining a generic debug view type and // using different instantiations. The reason for this is that support for generics // with using DebuggerTypeProxy is limited. For C#, DebuggerTypeProxy supports only // open types (from MSDN http://msdn.microsoft.com/en-us/library/d8eyd8zc.aspx). private sealed class KeyCollectionDebugView { private ICollection<string> _collection; public KeyCollectionDebugView(ICollection<string> collection) { Debug.Assert(collection != null); _collection = collection; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public string[] Items { get { string[] items = new string[_collection.Count]; _collection.CopyTo(items, 0); return items; } } } [DebuggerTypeProxy(typeof(KeyCollectionDebugView))] [DebuggerDisplay("Count = {Count}")] private class KeyCollection : ICollection<string> { private readonly ExpandoObject _expando; private readonly int _expandoVersion; private readonly int _expandoCount; private readonly ExpandoData _expandoData; internal KeyCollection(ExpandoObject expando) { lock (expando.LockObject) { _expando = expando; _expandoVersion = expando._data.Version; _expandoCount = expando._count; _expandoData = expando._data; } } private void CheckVersion() { if (_expando._data.Version != _expandoVersion || _expandoData != _expando._data) { //the underlying expando object has changed throw Error.CollectionModifiedWhileEnumerating(); } } #region ICollection<string> Members public void Add(string item) { throw Error.CollectionReadOnly(); } public void Clear() { throw Error.CollectionReadOnly(); } public bool Contains(string item) { lock (_expando.LockObject) { CheckVersion(); return _expando.ExpandoContainsKey(item); } } public void CopyTo(string[] array, int arrayIndex) { ContractUtils.RequiresNotNull(array, nameof(array)); ContractUtils.RequiresArrayRange(array, arrayIndex, _expandoCount, nameof(arrayIndex), nameof(Count)); lock (_expando.LockObject) { CheckVersion(); ExpandoData data = _expando._data; for (int i = 0; i < data.Class.Keys.Length; i++) { if (data[i] != Uninitialized) { array[arrayIndex++] = data.Class.Keys[i]; } } } } public int Count { get { CheckVersion(); return _expandoCount; } } public bool IsReadOnly { get { return true; } } public bool Remove(string item) { throw Error.CollectionReadOnly(); } #endregion #region IEnumerable<string> Members public IEnumerator<string> GetEnumerator() { for (int i = 0, n = _expandoData.Class.Keys.Length; i < n; i++) { CheckVersion(); if (_expandoData[i] != Uninitialized) { yield return _expandoData.Class.Keys[i]; } } } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion } // We create a non-generic type for the debug view for each different collection type // that uses DebuggerTypeProxy, instead of defining a generic debug view type and // using different instantiations. The reason for this is that support for generics // with using DebuggerTypeProxy is limited. For C#, DebuggerTypeProxy supports only // open types (from MSDN http://msdn.microsoft.com/en-us/library/d8eyd8zc.aspx). private sealed class ValueCollectionDebugView { private ICollection<object> _collection; public ValueCollectionDebugView(ICollection<object> collection) { Debug.Assert(collection != null); _collection = collection; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public object[] Items { get { object[] items = new object[_collection.Count]; _collection.CopyTo(items, 0); return items; } } } [DebuggerTypeProxy(typeof(ValueCollectionDebugView))] [DebuggerDisplay("Count = {Count}")] private class ValueCollection : ICollection<object> { private readonly ExpandoObject _expando; private readonly int _expandoVersion; private readonly int _expandoCount; private readonly ExpandoData _expandoData; internal ValueCollection(ExpandoObject expando) { lock (expando.LockObject) { _expando = expando; _expandoVersion = expando._data.Version; _expandoCount = expando._count; _expandoData = expando._data; } } private void CheckVersion() { if (_expando._data.Version != _expandoVersion || _expandoData != _expando._data) { //the underlying expando object has changed throw Error.CollectionModifiedWhileEnumerating(); } } #region ICollection<string> Members public void Add(object item) { throw Error.CollectionReadOnly(); } public void Clear() { throw Error.CollectionReadOnly(); } public bool Contains(object item) { lock (_expando.LockObject) { CheckVersion(); ExpandoData data = _expando._data; for (int i = 0; i < data.Class.Keys.Length; i++) { // See comment in TryDeleteValue; it's okay to call // object.Equals with the lock held. if (object.Equals(data[i], item)) { return true; } } return false; } } public void CopyTo(object[] array, int arrayIndex) { ContractUtils.RequiresNotNull(array, nameof(array)); ContractUtils.RequiresArrayRange(array, arrayIndex, _expandoCount, nameof(arrayIndex), nameof(Count)); lock (_expando.LockObject) { CheckVersion(); ExpandoData data = _expando._data; for (int i = 0; i < data.Class.Keys.Length; i++) { if (data[i] != Uninitialized) { array[arrayIndex++] = data[i]; } } } } public int Count { get { CheckVersion(); return _expandoCount; } } public bool IsReadOnly { get { return true; } } public bool Remove(object item) { throw Error.CollectionReadOnly(); } #endregion #region IEnumerable<string> Members public IEnumerator<object> GetEnumerator() { ExpandoData data = _expando._data; for (int i = 0; i < data.Class.Keys.Length; i++) { CheckVersion(); // Capture the value into a temp so we don't inadvertently // return Uninitialized. object temp = data[i]; if (temp != Uninitialized) { yield return temp; } } } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion } #endregion #region IDictionary<string, object> Members ICollection<string> IDictionary<string, object>.Keys { get { return new KeyCollection(this); } } ICollection<object> IDictionary<string, object>.Values { get { return new ValueCollection(this); } } object IDictionary<string, object>.this[string key] { get { object value; if (!TryGetValueForKey(key, out value)) { throw Error.KeyDoesNotExistInExpando(key); } return value; } set { ContractUtils.RequiresNotNull(key, nameof(key)); // Pass null to the class, which forces lookup. TrySetValue(null, -1, value, key, false, false); } } void IDictionary<string, object>.Add(string key, object value) { this.TryAddMember(key, value); } bool IDictionary<string, object>.ContainsKey(string key) { ContractUtils.RequiresNotNull(key, nameof(key)); ExpandoData data = _data; int index = data.Class.GetValueIndexCaseSensitive(key); return index >= 0 && data[index] != Uninitialized; } bool IDictionary<string, object>.Remove(string key) { ContractUtils.RequiresNotNull(key, nameof(key)); // Pass null to the class, which forces lookup. return TryDeleteValue(null, -1, key, false, Uninitialized); } bool IDictionary<string, object>.TryGetValue(string key, out object value) { return TryGetValueForKey(key, out value); } #endregion #region ICollection<KeyValuePair<string, object>> Members int ICollection<KeyValuePair<string, object>>.Count { get { return _count; } } bool ICollection<KeyValuePair<string, object>>.IsReadOnly { get { return false; } } void ICollection<KeyValuePair<string, object>>.Add(KeyValuePair<string, object> item) { TryAddMember(item.Key, item.Value); } void ICollection<KeyValuePair<string, object>>.Clear() { // We remove both class and data! ExpandoData data; lock (LockObject) { data = _data; _data = ExpandoData.Empty; _count = 0; } // Notify property changed for all properties. var propertyChanged = _propertyChanged; if (propertyChanged != null) { for (int i = 0, n = data.Class.Keys.Length; i < n; i++) { if (data[i] != Uninitialized) { propertyChanged(this, new PropertyChangedEventArgs(data.Class.Keys[i])); } } } } bool ICollection<KeyValuePair<string, object>>.Contains(KeyValuePair<string, object> item) { object value; if (!TryGetValueForKey(item.Key, out value)) { return false; } return object.Equals(value, item.Value); } void ICollection<KeyValuePair<string, object>>.CopyTo(KeyValuePair<string, object>[] array, int arrayIndex) { ContractUtils.RequiresNotNull(array, nameof(array)); ContractUtils.RequiresArrayRange(array, arrayIndex, _count, nameof(arrayIndex), nameof(ICollection<KeyValuePair<string, object>>.Count)); // We want this to be atomic and not throw lock (LockObject) { foreach (KeyValuePair<string, object> item in this) { array[arrayIndex++] = item; } } } bool ICollection<KeyValuePair<string, object>>.Remove(KeyValuePair<string, object> item) { return TryDeleteValue(null, -1, item.Key, false, item.Value); } #endregion #region IEnumerable<KeyValuePair<string, object>> Member IEnumerator<KeyValuePair<string, object>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator() { ExpandoData data = _data; return GetExpandoEnumerator(data, data.Version); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { ExpandoData data = _data; return GetExpandoEnumerator(data, data.Version); } // Note: takes the data and version as parameters so they will be // captured before the first call to MoveNext(). private IEnumerator<KeyValuePair<string, object>> GetExpandoEnumerator(ExpandoData data, int version) { for (int i = 0; i < data.Class.Keys.Length; i++) { if (_data.Version != version || data != _data) { // The underlying expando object has changed: // 1) the version of the expando data changed // 2) the data object is changed throw Error.CollectionModifiedWhileEnumerating(); } // Capture the value into a temp so we don't inadvertently // return Uninitialized. object temp = data[i]; if (temp != Uninitialized) { yield return new KeyValuePair<string, object>(data.Class.Keys[i], temp); } } } #endregion #region MetaExpando private class MetaExpando : DynamicMetaObject { public MetaExpando(Expression expression, ExpandoObject value) : base(expression, BindingRestrictions.Empty, value) { } private DynamicMetaObject BindGetOrInvokeMember(DynamicMetaObjectBinder binder, string name, bool ignoreCase, DynamicMetaObject fallback, Func<DynamicMetaObject, DynamicMetaObject> fallbackInvoke) { ExpandoClass klass = Value.Class; //try to find the member, including the deleted members int index = klass.GetValueIndex(name, ignoreCase, Value); ParameterExpression value = Expression.Parameter(typeof(object), "value"); Expression tryGetValue = Expression.Call( typeof(RuntimeOps).GetMethod("ExpandoTryGetValue"), GetLimitedSelf(), Expression.Constant(klass, typeof(object)), Expression.Constant(index), Expression.Constant(name), Expression.Constant(ignoreCase), value ); var result = new DynamicMetaObject(value, BindingRestrictions.Empty); if (fallbackInvoke != null) { result = fallbackInvoke(result); } result = new DynamicMetaObject( Expression.Block( new[] { value }, Expression.Condition( tryGetValue, result.Expression, fallback.Expression, typeof(object) ) ), result.Restrictions.Merge(fallback.Restrictions) ); return AddDynamicTestAndDefer(binder, Value.Class, null, result); } public override DynamicMetaObject BindGetMember(GetMemberBinder binder) { ContractUtils.RequiresNotNull(binder, nameof(binder)); return BindGetOrInvokeMember( binder, binder.Name, binder.IgnoreCase, binder.FallbackGetMember(this), null ); } public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) { ContractUtils.RequiresNotNull(binder, nameof(binder)); return BindGetOrInvokeMember( binder, binder.Name, binder.IgnoreCase, binder.FallbackInvokeMember(this, args), value => binder.FallbackInvoke(value, args, null) ); } public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value) { ContractUtils.RequiresNotNull(binder, nameof(binder)); ContractUtils.RequiresNotNull(value, nameof(value)); ExpandoClass klass; int index; ExpandoClass originalClass = GetClassEnsureIndex(binder.Name, binder.IgnoreCase, Value, out klass, out index); return AddDynamicTestAndDefer( binder, klass, originalClass, new DynamicMetaObject( Expression.Call( typeof(RuntimeOps).GetMethod("ExpandoTrySetValue"), GetLimitedSelf(), Expression.Constant(klass, typeof(object)), Expression.Constant(index), Expression.Convert(value.Expression, typeof(object)), Expression.Constant(binder.Name), Expression.Constant(binder.IgnoreCase) ), BindingRestrictions.Empty ) ); } public override DynamicMetaObject BindDeleteMember(DeleteMemberBinder binder) { ContractUtils.RequiresNotNull(binder, nameof(binder)); int index = Value.Class.GetValueIndex(binder.Name, binder.IgnoreCase, Value); Expression tryDelete = Expression.Call( typeof(RuntimeOps).GetMethod("ExpandoTryDeleteValue"), GetLimitedSelf(), Expression.Constant(Value.Class, typeof(object)), Expression.Constant(index), Expression.Constant(binder.Name), Expression.Constant(binder.IgnoreCase) ); DynamicMetaObject fallback = binder.FallbackDeleteMember(this); DynamicMetaObject target = new DynamicMetaObject( Expression.IfThen(Expression.Not(tryDelete), fallback.Expression), fallback.Restrictions ); return AddDynamicTestAndDefer(binder, Value.Class, null, target); } public override IEnumerable<string> GetDynamicMemberNames() { var expandoData = Value._data; var klass = expandoData.Class; for (int i = 0; i < klass.Keys.Length; i++) { object val = expandoData[i]; if (val != ExpandoObject.Uninitialized) { yield return klass.Keys[i]; } } } /// <summary> /// Adds a dynamic test which checks if the version has changed. The test is only necessary for /// performance as the methods will do the correct thing if called with an incorrect version. /// </summary> private DynamicMetaObject AddDynamicTestAndDefer(DynamicMetaObjectBinder binder, ExpandoClass klass, ExpandoClass originalClass, DynamicMetaObject succeeds) { Expression ifTestSucceeds = succeeds.Expression; if (originalClass != null) { // we are accessing a member which has not yet been defined on this class. // We force a class promotion after the type check. If the class changes the // promotion will fail and the set/delete will do a full lookup using the new // class to discover the name. Debug.Assert(originalClass != klass); ifTestSucceeds = Expression.Block( Expression.Call( null, typeof(RuntimeOps).GetMethod("ExpandoPromoteClass"), GetLimitedSelf(), Expression.Constant(originalClass, typeof(object)), Expression.Constant(klass, typeof(object)) ), succeeds.Expression ); } return new DynamicMetaObject( Expression.Condition( Expression.Call( null, typeof(RuntimeOps).GetMethod("ExpandoCheckVersion"), GetLimitedSelf(), Expression.Constant(originalClass ?? klass, typeof(object)) ), ifTestSucceeds, binder.GetUpdateExpression(ifTestSucceeds.Type) ), GetRestrictions().Merge(succeeds.Restrictions) ); } /// <summary> /// Gets the class and the index associated with the given name. Does not update the expando object. Instead /// this returns both the original and desired new class. A rule is created which includes the test for the /// original class, the promotion to the new class, and the set/delete based on the class post-promotion. /// </summary> private ExpandoClass GetClassEnsureIndex(string name, bool caseInsensitive, ExpandoObject obj, out ExpandoClass klass, out int index) { ExpandoClass originalClass = Value.Class; index = originalClass.GetValueIndex(name, caseInsensitive, obj); if (index == ExpandoObject.AmbiguousMatchFound) { klass = originalClass; return null; } if (index == ExpandoObject.NoMatch) { // go ahead and find a new class now... ExpandoClass newClass = originalClass.FindNewClass(name); klass = newClass; index = newClass.GetValueIndexCaseSensitive(name); Debug.Assert(index != ExpandoObject.NoMatch); return originalClass; } else { klass = originalClass; return null; } } /// <summary> /// Returns our Expression converted to our known LimitType /// </summary> private Expression GetLimitedSelf() { if (TypeUtils.AreEquivalent(Expression.Type, LimitType)) { return Expression; } return Expression.Convert(Expression, LimitType); } /// <summary> /// Returns a Restrictions object which includes our current restrictions merged /// with a restriction limiting our type /// </summary> private BindingRestrictions GetRestrictions() { Debug.Assert(Restrictions == BindingRestrictions.Empty, "We don't merge, restrictions are always empty"); return BindingRestrictions.GetTypeRestriction(this); } public new ExpandoObject Value { get { return (ExpandoObject)base.Value; } } } #endregion #region ExpandoData /// <summary> /// Stores the class and the data associated with the class as one atomic /// pair. This enables us to do a class check in a thread safe manner w/o /// requiring locks. /// </summary> private class ExpandoData { internal static ExpandoData Empty = new ExpandoData(); /// <summary> /// the dynamically assigned class associated with the Expando object /// </summary> internal readonly ExpandoClass Class; /// <summary> /// data stored in the expando object, key names are stored in the class. /// /// Expando._data must be locked when mutating the value. Otherwise a copy of it /// could be made and lose values. /// </summary> private readonly object[] _dataArray; /// <summary> /// Indexer for getting/setting the data /// </summary> internal object this[int index] { get { return _dataArray[index]; } set { //when the array is updated, version increases, even the new value is the same //as previous. Dictionary type has the same behavior. _version++; _dataArray[index] = value; } } internal int Version { get { return _version; } } internal int Length { get { return _dataArray.Length; } } /// <summary> /// Constructs an empty ExpandoData object with the empty class and no data. /// </summary> private ExpandoData() { Class = ExpandoClass.Empty; _dataArray = Array.Empty<object>(); } /// <summary> /// the version of the ExpandoObject that tracks set and delete operations /// </summary> private int _version; /// <summary> /// Constructs a new ExpandoData object with the specified class and data. /// </summary> internal ExpandoData(ExpandoClass klass, object[] data, int version) { Class = klass; _dataArray = data; _version = version; } /// <summary> /// Update the associated class and increases the storage for the data array if needed. /// </summary> /// <returns></returns> internal ExpandoData UpdateClass(ExpandoClass newClass) { if (_dataArray.Length >= newClass.Keys.Length) { // we have extra space in our buffer, just initialize it to Uninitialized. this[newClass.Keys.Length - 1] = ExpandoObject.Uninitialized; return new ExpandoData(newClass, _dataArray, _version); } else { // we've grown too much - we need a new object array int oldLength = _dataArray.Length; object[] arr = new object[GetAlignedSize(newClass.Keys.Length)]; Array.Copy(_dataArray, 0, arr, 0, _dataArray.Length); ExpandoData newData = new ExpandoData(newClass, arr, _version); newData[oldLength] = ExpandoObject.Uninitialized; return newData; } } private static int GetAlignedSize(int len) { // the alignment of the array for storage of values (must be a power of two) const int DataArrayAlignment = 8; // round up and then mask off lower bits return (len + (DataArrayAlignment - 1)) & (~(DataArrayAlignment - 1)); } } #endregion #region INotifyPropertyChanged event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged { add { _propertyChanged += value; } remove { _propertyChanged -= value; } } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Monitor.Fluent { using Microsoft.Azure.Management.Monitor.Fluent.Models; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; /// <summary> /// Implementation for ActivityLogs. /// </summary> ///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50Lm1vbml0b3IuaW1wbGVtZW50YXRpb24uQWN0aXZpdHlMb2dzSW1wbA== internal partial class ActivityLogsImpl : IActivityLogs, IActivityLogsQueryDefinition { private bool filterForTenant; private string filterString; private MonitorManager myManager; private DateTime queryEndTime; private DateTime queryStartTime; private HashSet<string> responsePropertySelector; ///GENMHASH:657DEC775ABB08A370F0E7B424DF2C55:2F1B9317851B2A1DD48CC2ED2AA07143 internal ActivityLogsImpl(MonitorManager monitorManager) { this.myManager = monitorManager; this.responsePropertySelector = new HashSet<string>(); this.filterString = ""; this.filterForTenant = false; } ///GENMHASH:024411138CED6DE639DA12D726BD0621:834C35BC52D5E712B2EE3999934B62E5 private string CreatePropertyFilter() { var propertyFilter = string.Join(",", this.responsePropertySelector.OrderBy(o => o)); if (string.IsNullOrWhiteSpace(propertyFilter)) { propertyFilter = null; } return propertyFilter; } ///GENMHASH:6F01E78E35D7E5AB58994AE36EDFAB4A:B883F859C5ECB2870CD846D5172095F9 private string GetOdataFilterString() { return string.Format("eventTimestamp ge '{0}' and eventTimestamp le '{1}'", this.queryStartTime.ToString("o"), this.queryEndTime.ToString("o")); } ///GENMHASH:66A358446BB2F4C0D4EA5FC8537BD415:7FDA4951E189B2016B3D2310EE5F3420 private IEnumerable<IEventData> ListEventData(string filter) { return Extensions.Synchronize(() => this.Inner.ListAsync(filter, CreatePropertyFilter())) .AsContinuousCollection(link => Extensions.Synchronize(() => this.Inner.ListNextAsync(link))) .Select(inner => new EventDataImpl(inner)); } ///GENMHASH:917C4A9B611CD52A7033C2682FC82B65:822E0FD9095BE313AADE1B493098C7C0 private async Task<IPagedCollection<IEventData>> ListEventDataAsync(string filter, CancellationToken cancellationToken = default(CancellationToken)) { return await PagedCollection<IEventData, EventDataInner>.LoadPage( async (cancellation) => await Inner.ListAsync(filter, CreatePropertyFilter(), cancellation), async (nextLink, cancellation) => await Inner.ListNextAsync(nextLink, cancellation), (inner) => new EventDataImpl(inner), true, cancellationToken); } ///GENMHASH:EA6A4C027BF47CC52B95F02B557B4A40:DC8B9F137B1D502452AF2DD36012BA63 private IEnumerable<IEventData> ListEventDataForTenant(string filter) { return Extensions.Synchronize(() => this.Manager().Inner.TenantActivityLogs.ListAsync(filter, CreatePropertyFilter())) .AsContinuousCollection(link => Extensions.Synchronize(() => this.Manager().Inner.TenantActivityLogs.ListNextAsync(link))) .Select(inner => new EventDataImpl(inner)); } ///GENMHASH:8FC9B471C1A78BF1D3EBC410128DE0FA:A581C3311414879F15C3BB031BF1F5A5 private async Task<IPagedCollection<IEventData>> ListEventDataForTenantAsync(string filter, CancellationToken cancellationToken = default(CancellationToken)) { return await PagedCollection<IEventData, EventDataInner>.LoadPage( async (cancellation) => await this.Manager().Inner.TenantActivityLogs.ListAsync(filter, CreatePropertyFilter(), cancellationToken), async (nextLink, cancellation) => await this.Manager().Inner.TenantActivityLogs.ListNextAsync(nextLink, cancellation), (inner) => new EventDataImpl(inner), true, cancellationToken); } ///GENMHASH:914F5848297276F1D8C78263F5BE935D:295B4DBA4EF3CDAC9D498BAF8DAB131F public IWithEventDataStartTimeFilter DefineQuery() { this.responsePropertySelector.Clear(); this.filterString = ""; this.filterForTenant = false; return this; } ///GENMHASH:8E798D06F036643A781434270F4F347E:6ED95D1C0D7030224A0A5556D72F0018 public ActivityLogsImpl EndsBefore(DateTime endTime) { this.queryEndTime = endTime; return this; } ///GENMHASH:6E40675090A7C5A5E2DC401C96A422D5:D9CC57125A6433E06763A35AA50F44DF public IEnumerable<Models.IEventData> Execute() { if (this.filterForTenant) { return ListEventDataForTenant(GetOdataFilterString() + this.filterString + " eventChannels eq 'Admin, Operation'"); } return ListEventData(GetOdataFilterString() + this.filterString); } ///GENMHASH:28267C95BE469468FC3C62D4CF4CCA7C:F7D4D3D83965F2CAF36159C081016C40 public async Task<IPagedCollection<IEventData>> ExecuteAsync(CancellationToken cancellationToken) { if (this.filterForTenant) { return await ListEventDataForTenantAsync(GetOdataFilterString() + this.filterString + " eventChannels eq 'Admin, Operation'"); } return await ListEventDataAsync(GetOdataFilterString() + this.filterString, cancellationToken); } ///GENMHASH:F9AA0F78087650E68B1DEE08F26A8EC9:51829AEAB69FA856409258ADAF5B2B08 public ActivityLogsImpl FilterAtTenantLevel() { this.filterForTenant = true; return this; } ///GENMHASH:6C04BF10CFC9018CA61EC48D69CCFFC4:D91695419640E79A341E8B6E40B9C518 public ActivityLogsImpl FilterByCorrelationId(string correlationId) { this.filterString = string.Format(" and correlationId eq '{0}'", correlationId); return this; } ///GENMHASH:F53D539E431A5CEE4CC1B076D4C77610:BFADD6FEAFCB5CD377ED3E9C10E4C678 public ActivityLogsImpl FilterByResource(string resourceId) { this.filterString = String.Format(" and resourceUri eq '{0}'", resourceId); return this; } ///GENMHASH:CF28D7A5A1EBEBDAA73B8839CA5F9631:30133FA4E893BDEF196AC52E4D00AD6F public ActivityLogsImpl FilterByResourceGroup(string resourceGroupName) { this.filterString = string.Format(" and resourceGroupName eq '{0}'", resourceGroupName); return this; } ///GENMHASH:4E25211860404EE8E2BAF86972E02D5D:151A4F9B8C46D2B66AE4C6FF9A546B84 public ActivityLogsImpl FilterByResourceProvider(string resourceProviderName) { this.filterString = string.Format(" and resourceProvider eq '{0}'", resourceProviderName); return this; } ///GENMHASH:C852FF1A7022E39B3C33C4B996B5E6D6:E24F3ED3849126FC0026B1F5D9B9CE70 public IActivityLogsOperations Inner { get { return this.myManager.Inner.ActivityLogs; } } ///GENMHASH:BECC31966AF171B5D462326D3806A2C9:2DF33786C02E42C345D1AB03B3DE2FD6 public IReadOnlyList<Models.ILocalizableString> ListEventCategories() { return Extensions.Synchronize(() => ListEventCategoriesAsync()); } ///GENMHASH:FDF86E3C0954DF96F806851F8D0E9022:63C88E9F65C9F2F07A5D1B56DC85A9E3 public async Task<IReadOnlyList<Models.ILocalizableString>> ListEventCategoriesAsync(CancellationToken cancellationToken = default(CancellationToken)) { return (await this.Manager().Inner.EventCategories.ListAsync(cancellationToken)) .Select(i => new LocalizableStringImpl(i)) .ToList(); } ///GENMHASH:B6961E0C7CB3A9659DE0E1489F44A936:363E4D62FCA795A36F9CB60513C86AFA public MonitorManager Manager() { return this.myManager; } ///GENMHASH:466C9D6BF16AFC7E5643C50D8BF6E937:38A64203651F9C55FF10205837F6BF41 public ActivityLogsImpl StartingFrom(DateTime startTime) { this.queryStartTime = startTime; return this; } ///GENMHASH:5377F347172D86792C2D0F8ADCF6A22B:68C9E86F48D7C68955A6BCE451CAB7A5 public ActivityLogsImpl WithAllPropertiesInResponse() { this.responsePropertySelector.Clear(); return this; } ///GENMHASH:32EF35107E348211C3A6304CFDDF64B8:16484880324A3F804530C40A3A4891BC public ActivityLogsImpl WithResponseProperties(params EventDataPropertyName[] responseProperties) { this.responsePropertySelector.Clear(); foreach (var EventDataPropertyName in responseProperties) { this.responsePropertySelector.Add(EventDataPropertyName.Value); } return this; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Xml; namespace V1TaskManager { public class Config { private const string ConfigFilePath = "config.xml"; private IList<String> _recentItems; private IList<String> _recentMessages; private IList<String> _recentSearches; public string ApplicationPath { get { return Read<string>("ApplicationPath"); } set { Set("ApplicationPath", value); } } public bool UseWindowsIntegrated { get { return Convert.ToBoolean(Read<string>("UseWindowsIntegrated")); } set { Set("UseWindowsIntegrated", value); } } public string Username { get { return Read<string>("Username"); } set { Set("Username", value); } } public string Password { get { return Read<string>("Password"); } set { Set("Password", value); } } public IList<String> RecentMessages { get { return _recentMessages ?? (_recentMessages = ReadStringCollection("RecentMessages")); } } public IList<String> RecentItems { get { return _recentItems ?? (_recentItems = ReadStringCollection("RecentItems")); } } public IList<String> RecentSearches { get { return _recentSearches ?? (_recentSearches = ReadStringCollection("RecentSearches")); } } public bool IsValid { get { return ApplicationPath != null && Username != null && Password != null; } } public event EventHandler OnChanged; public static void UpdateRecentList(IList<string> messages, string content, int maxitems) { if (messages.Contains(content)) messages.Remove(content); messages.Insert(0, content); while (messages.Count > maxitems) messages.RemoveAt(messages.Count - 1); } #region Config Reading private XmlDocument _doc; private XmlDocument Doc { get { if (_doc == null) { _doc = new XmlDocument(); if (File.Exists(ConfigFilePath)) _doc.Load(ConfigFilePath); if (_doc.DocumentElement == null) _doc.AppendChild(_doc.CreateElement("Configuration")); } return _doc; } } private XmlNode EnsureNode(string name) { return Doc.DocumentElement.SelectSingleNode(name) ?? Doc.DocumentElement.AppendChild(Doc.CreateElement(name)); } private T Read<T>(string name) { return Read(name, default(T)); } private T Read<T>(string name, T def) { string text = EnsureNode(name).InnerText; if (string.IsNullOrEmpty(text)) return def; return (T) Convert.ChangeType(text, typeof (T)); } private void Set<T>(string name, T value) { Set(name, value, true); } private void Set<T>(string name, T value, bool announce) { EnsureNode(name).InnerText = (string) Convert.ChangeType(value, typeof (string)); Save(); if (announce && OnChanged != null) OnChanged(this, EventArgs.Empty); } private void Save() { Doc.Save(ConfigFilePath); } private IList<string> ReadStringCollection(string name) { return new XmlStringCollection(EnsureNode(name), this); } private class XmlStringCollection : IList<string> { private readonly Config _config; private readonly XmlNode _node; private readonly IList<string> _values = new List<string>(); public XmlStringCollection(XmlNode node, Config config) { _node = node; _config = config; ParseNode(); } #region IList<string> Members public void Add(string item) { _values.Add(item); SaveNode(); } public void Clear() { _values.Clear(); SaveNode(); } public bool Contains(string item) { return _values.Contains(item); } public void CopyTo(string[] array, int arrayIndex) { _values.CopyTo(array, arrayIndex); } public bool Remove(string item) { bool b = _values.Remove(item); SaveNode(); return b; } public int Count { get { return _values.Count; } } public bool IsReadOnly { get { return false; } } IEnumerator<string> IEnumerable<string>.GetEnumerator() { return _values.GetEnumerator(); } public IEnumerator GetEnumerator() { return ((IEnumerable<string>) this).GetEnumerator(); } public int IndexOf(string item) { return _values.IndexOf(item); } public void Insert(int index, string item) { _values.Insert(index, item); SaveNode(); } public void RemoveAt(int index) { _values.RemoveAt(index); SaveNode(); } public string this[int index] { get { return _values[index]; } set { _values[index] = value; SaveNode(); } } #endregion private static XmlAttribute EnsureAttribute(XmlNode node, string name) { return node.Attributes[name] ?? node.Attributes.Append(node.OwnerDocument.CreateAttribute(name)); } private static XmlNode EnsureElement(XmlNode parent, string name) { return parent.SelectSingleNode(name) ?? parent.AppendChild(parent.OwnerDocument.CreateElement(name)); } private static XmlNode EnsureCData(XmlNode parent) { if (parent.ChildNodes.Count == 0) return parent.AppendChild(parent.OwnerDocument.CreateCDataSection(string.Empty)); return parent.ChildNodes[0]; } private void ParseNode() { XmlAttribute attrib = EnsureAttribute(_node, "Count"); int count = 0; string text = attrib.InnerText; if (!string.IsNullOrEmpty(text)) count = int.Parse(text); for (int i = 0; i < count; i++) { XmlNode subNode = _node.SelectSingleNode("Node" + i); if (subNode != null) { XmlNode cDataNode = subNode.ChildNodes[0]; if (cDataNode != null && cDataNode.NodeType == XmlNodeType.CDATA) _values.Add(cDataNode.InnerText); } } } private void SaveNode() { _node.RemoveAll(); EnsureAttribute(_node, "Count").InnerText = _values.Count.ToString(CultureInfo.InvariantCulture); for (int i = 0; i < _values.Count; i++) { XmlNode subNode = EnsureElement(_node, "Node" + i); XmlNode cDataNode = EnsureCData(subNode); cDataNode.InnerText = _values[i]; } _config.Save(); } } #endregion } }
//------------------------------------------------------------------------------ // <copyright file="EntityFunctions.cs company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <auto-generated> // This code was generated by a tool. // Generation date and time : 5/13/2011 12:53:13.2245698 // // Changes to this file will be lost if the code is regenerated. // </auto-generated> // @owner [....] // @backupOwner [....] //------------------------------------------------------------------------------ using System.Collections.Generic; using System.Data.Objects; using System.Data.Objects.DataClasses; using System.Linq; using System.Linq.Expressions; using System.Reflection; namespace System.Data.Objects { /// <summary> /// Contains function stubs that expose Edm methods in Linq to Entities. /// </summary> public static partial class EntityFunctions { /// <summary> /// Proxy for the function Edm.StDev /// </summary> [EdmFunction("Edm", "StDev")] public static System.Double? StandardDeviation(IEnumerable<System.Decimal> collection) { ObjectQuery<System.Decimal> objectQuerySource = collection as ObjectQuery<System.Decimal>; if (objectQuerySource != null) { return ((IQueryable)objectQuerySource).Provider.Execute<System.Double?>(Expression.Call((MethodInfo)MethodInfo.GetCurrentMethod(),Expression.Constant(collection))); } throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.StDev /// </summary> [EdmFunction("Edm", "StDev")] public static System.Double? StandardDeviation(IEnumerable<System.Decimal?> collection) { ObjectQuery<System.Decimal?> objectQuerySource = collection as ObjectQuery<System.Decimal?>; if (objectQuerySource != null) { return ((IQueryable)objectQuerySource).Provider.Execute<System.Double?>(Expression.Call((MethodInfo)MethodInfo.GetCurrentMethod(),Expression.Constant(collection))); } throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.StDev /// </summary> [EdmFunction("Edm", "StDev")] public static System.Double? StandardDeviation(IEnumerable<System.Double> collection) { ObjectQuery<System.Double> objectQuerySource = collection as ObjectQuery<System.Double>; if (objectQuerySource != null) { return ((IQueryable)objectQuerySource).Provider.Execute<System.Double?>(Expression.Call((MethodInfo)MethodInfo.GetCurrentMethod(),Expression.Constant(collection))); } throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.StDev /// </summary> [EdmFunction("Edm", "StDev")] public static System.Double? StandardDeviation(IEnumerable<System.Double?> collection) { ObjectQuery<System.Double?> objectQuerySource = collection as ObjectQuery<System.Double?>; if (objectQuerySource != null) { return ((IQueryable)objectQuerySource).Provider.Execute<System.Double?>(Expression.Call((MethodInfo)MethodInfo.GetCurrentMethod(),Expression.Constant(collection))); } throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.StDev /// </summary> [EdmFunction("Edm", "StDev")] public static System.Double? StandardDeviation(IEnumerable<System.Int32> collection) { ObjectQuery<System.Int32> objectQuerySource = collection as ObjectQuery<System.Int32>; if (objectQuerySource != null) { return ((IQueryable)objectQuerySource).Provider.Execute<System.Double?>(Expression.Call((MethodInfo)MethodInfo.GetCurrentMethod(),Expression.Constant(collection))); } throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.StDev /// </summary> [EdmFunction("Edm", "StDev")] public static System.Double? StandardDeviation(IEnumerable<System.Int32?> collection) { ObjectQuery<System.Int32?> objectQuerySource = collection as ObjectQuery<System.Int32?>; if (objectQuerySource != null) { return ((IQueryable)objectQuerySource).Provider.Execute<System.Double?>(Expression.Call((MethodInfo)MethodInfo.GetCurrentMethod(),Expression.Constant(collection))); } throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.StDev /// </summary> [EdmFunction("Edm", "StDev")] public static System.Double? StandardDeviation(IEnumerable<System.Int64> collection) { ObjectQuery<System.Int64> objectQuerySource = collection as ObjectQuery<System.Int64>; if (objectQuerySource != null) { return ((IQueryable)objectQuerySource).Provider.Execute<System.Double?>(Expression.Call((MethodInfo)MethodInfo.GetCurrentMethod(),Expression.Constant(collection))); } throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.StDev /// </summary> [EdmFunction("Edm", "StDev")] public static System.Double? StandardDeviation(IEnumerable<System.Int64?> collection) { ObjectQuery<System.Int64?> objectQuerySource = collection as ObjectQuery<System.Int64?>; if (objectQuerySource != null) { return ((IQueryable)objectQuerySource).Provider.Execute<System.Double?>(Expression.Call((MethodInfo)MethodInfo.GetCurrentMethod(),Expression.Constant(collection))); } throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.StDevP /// </summary> [EdmFunction("Edm", "StDevP")] public static System.Double? StandardDeviationP(IEnumerable<System.Decimal> collection) { ObjectQuery<System.Decimal> objectQuerySource = collection as ObjectQuery<System.Decimal>; if (objectQuerySource != null) { return ((IQueryable)objectQuerySource).Provider.Execute<System.Double?>(Expression.Call((MethodInfo)MethodInfo.GetCurrentMethod(),Expression.Constant(collection))); } throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.StDevP /// </summary> [EdmFunction("Edm", "StDevP")] public static System.Double? StandardDeviationP(IEnumerable<System.Decimal?> collection) { ObjectQuery<System.Decimal?> objectQuerySource = collection as ObjectQuery<System.Decimal?>; if (objectQuerySource != null) { return ((IQueryable)objectQuerySource).Provider.Execute<System.Double?>(Expression.Call((MethodInfo)MethodInfo.GetCurrentMethod(),Expression.Constant(collection))); } throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.StDevP /// </summary> [EdmFunction("Edm", "StDevP")] public static System.Double? StandardDeviationP(IEnumerable<System.Double> collection) { ObjectQuery<System.Double> objectQuerySource = collection as ObjectQuery<System.Double>; if (objectQuerySource != null) { return ((IQueryable)objectQuerySource).Provider.Execute<System.Double?>(Expression.Call((MethodInfo)MethodInfo.GetCurrentMethod(),Expression.Constant(collection))); } throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.StDevP /// </summary> [EdmFunction("Edm", "StDevP")] public static System.Double? StandardDeviationP(IEnumerable<System.Double?> collection) { ObjectQuery<System.Double?> objectQuerySource = collection as ObjectQuery<System.Double?>; if (objectQuerySource != null) { return ((IQueryable)objectQuerySource).Provider.Execute<System.Double?>(Expression.Call((MethodInfo)MethodInfo.GetCurrentMethod(),Expression.Constant(collection))); } throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.StDevP /// </summary> [EdmFunction("Edm", "StDevP")] public static System.Double? StandardDeviationP(IEnumerable<System.Int32> collection) { ObjectQuery<System.Int32> objectQuerySource = collection as ObjectQuery<System.Int32>; if (objectQuerySource != null) { return ((IQueryable)objectQuerySource).Provider.Execute<System.Double?>(Expression.Call((MethodInfo)MethodInfo.GetCurrentMethod(),Expression.Constant(collection))); } throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.StDevP /// </summary> [EdmFunction("Edm", "StDevP")] public static System.Double? StandardDeviationP(IEnumerable<System.Int32?> collection) { ObjectQuery<System.Int32?> objectQuerySource = collection as ObjectQuery<System.Int32?>; if (objectQuerySource != null) { return ((IQueryable)objectQuerySource).Provider.Execute<System.Double?>(Expression.Call((MethodInfo)MethodInfo.GetCurrentMethod(),Expression.Constant(collection))); } throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.StDevP /// </summary> [EdmFunction("Edm", "StDevP")] public static System.Double? StandardDeviationP(IEnumerable<System.Int64> collection) { ObjectQuery<System.Int64> objectQuerySource = collection as ObjectQuery<System.Int64>; if (objectQuerySource != null) { return ((IQueryable)objectQuerySource).Provider.Execute<System.Double?>(Expression.Call((MethodInfo)MethodInfo.GetCurrentMethod(),Expression.Constant(collection))); } throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.StDevP /// </summary> [EdmFunction("Edm", "StDevP")] public static System.Double? StandardDeviationP(IEnumerable<System.Int64?> collection) { ObjectQuery<System.Int64?> objectQuerySource = collection as ObjectQuery<System.Int64?>; if (objectQuerySource != null) { return ((IQueryable)objectQuerySource).Provider.Execute<System.Double?>(Expression.Call((MethodInfo)MethodInfo.GetCurrentMethod(),Expression.Constant(collection))); } throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.Var /// </summary> [EdmFunction("Edm", "Var")] public static System.Double? Var(IEnumerable<System.Decimal> collection) { ObjectQuery<System.Decimal> objectQuerySource = collection as ObjectQuery<System.Decimal>; if (objectQuerySource != null) { return ((IQueryable)objectQuerySource).Provider.Execute<System.Double?>(Expression.Call((MethodInfo)MethodInfo.GetCurrentMethod(),Expression.Constant(collection))); } throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.Var /// </summary> [EdmFunction("Edm", "Var")] public static System.Double? Var(IEnumerable<System.Decimal?> collection) { ObjectQuery<System.Decimal?> objectQuerySource = collection as ObjectQuery<System.Decimal?>; if (objectQuerySource != null) { return ((IQueryable)objectQuerySource).Provider.Execute<System.Double?>(Expression.Call((MethodInfo)MethodInfo.GetCurrentMethod(),Expression.Constant(collection))); } throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.Var /// </summary> [EdmFunction("Edm", "Var")] public static System.Double? Var(IEnumerable<System.Double> collection) { ObjectQuery<System.Double> objectQuerySource = collection as ObjectQuery<System.Double>; if (objectQuerySource != null) { return ((IQueryable)objectQuerySource).Provider.Execute<System.Double?>(Expression.Call((MethodInfo)MethodInfo.GetCurrentMethod(),Expression.Constant(collection))); } throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.Var /// </summary> [EdmFunction("Edm", "Var")] public static System.Double? Var(IEnumerable<System.Double?> collection) { ObjectQuery<System.Double?> objectQuerySource = collection as ObjectQuery<System.Double?>; if (objectQuerySource != null) { return ((IQueryable)objectQuerySource).Provider.Execute<System.Double?>(Expression.Call((MethodInfo)MethodInfo.GetCurrentMethod(),Expression.Constant(collection))); } throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.Var /// </summary> [EdmFunction("Edm", "Var")] public static System.Double? Var(IEnumerable<System.Int32> collection) { ObjectQuery<System.Int32> objectQuerySource = collection as ObjectQuery<System.Int32>; if (objectQuerySource != null) { return ((IQueryable)objectQuerySource).Provider.Execute<System.Double?>(Expression.Call((MethodInfo)MethodInfo.GetCurrentMethod(),Expression.Constant(collection))); } throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.Var /// </summary> [EdmFunction("Edm", "Var")] public static System.Double? Var(IEnumerable<System.Int32?> collection) { ObjectQuery<System.Int32?> objectQuerySource = collection as ObjectQuery<System.Int32?>; if (objectQuerySource != null) { return ((IQueryable)objectQuerySource).Provider.Execute<System.Double?>(Expression.Call((MethodInfo)MethodInfo.GetCurrentMethod(),Expression.Constant(collection))); } throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.Var /// </summary> [EdmFunction("Edm", "Var")] public static System.Double? Var(IEnumerable<System.Int64> collection) { ObjectQuery<System.Int64> objectQuerySource = collection as ObjectQuery<System.Int64>; if (objectQuerySource != null) { return ((IQueryable)objectQuerySource).Provider.Execute<System.Double?>(Expression.Call((MethodInfo)MethodInfo.GetCurrentMethod(),Expression.Constant(collection))); } throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.Var /// </summary> [EdmFunction("Edm", "Var")] public static System.Double? Var(IEnumerable<System.Int64?> collection) { ObjectQuery<System.Int64?> objectQuerySource = collection as ObjectQuery<System.Int64?>; if (objectQuerySource != null) { return ((IQueryable)objectQuerySource).Provider.Execute<System.Double?>(Expression.Call((MethodInfo)MethodInfo.GetCurrentMethod(),Expression.Constant(collection))); } throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.VarP /// </summary> [EdmFunction("Edm", "VarP")] public static System.Double? VarP(IEnumerable<System.Decimal> collection) { ObjectQuery<System.Decimal> objectQuerySource = collection as ObjectQuery<System.Decimal>; if (objectQuerySource != null) { return ((IQueryable)objectQuerySource).Provider.Execute<System.Double?>(Expression.Call((MethodInfo)MethodInfo.GetCurrentMethod(),Expression.Constant(collection))); } throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.VarP /// </summary> [EdmFunction("Edm", "VarP")] public static System.Double? VarP(IEnumerable<System.Decimal?> collection) { ObjectQuery<System.Decimal?> objectQuerySource = collection as ObjectQuery<System.Decimal?>; if (objectQuerySource != null) { return ((IQueryable)objectQuerySource).Provider.Execute<System.Double?>(Expression.Call((MethodInfo)MethodInfo.GetCurrentMethod(),Expression.Constant(collection))); } throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.VarP /// </summary> [EdmFunction("Edm", "VarP")] public static System.Double? VarP(IEnumerable<System.Double> collection) { ObjectQuery<System.Double> objectQuerySource = collection as ObjectQuery<System.Double>; if (objectQuerySource != null) { return ((IQueryable)objectQuerySource).Provider.Execute<System.Double?>(Expression.Call((MethodInfo)MethodInfo.GetCurrentMethod(),Expression.Constant(collection))); } throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.VarP /// </summary> [EdmFunction("Edm", "VarP")] public static System.Double? VarP(IEnumerable<System.Double?> collection) { ObjectQuery<System.Double?> objectQuerySource = collection as ObjectQuery<System.Double?>; if (objectQuerySource != null) { return ((IQueryable)objectQuerySource).Provider.Execute<System.Double?>(Expression.Call((MethodInfo)MethodInfo.GetCurrentMethod(),Expression.Constant(collection))); } throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.VarP /// </summary> [EdmFunction("Edm", "VarP")] public static System.Double? VarP(IEnumerable<System.Int32> collection) { ObjectQuery<System.Int32> objectQuerySource = collection as ObjectQuery<System.Int32>; if (objectQuerySource != null) { return ((IQueryable)objectQuerySource).Provider.Execute<System.Double?>(Expression.Call((MethodInfo)MethodInfo.GetCurrentMethod(),Expression.Constant(collection))); } throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.VarP /// </summary> [EdmFunction("Edm", "VarP")] public static System.Double? VarP(IEnumerable<System.Int32?> collection) { ObjectQuery<System.Int32?> objectQuerySource = collection as ObjectQuery<System.Int32?>; if (objectQuerySource != null) { return ((IQueryable)objectQuerySource).Provider.Execute<System.Double?>(Expression.Call((MethodInfo)MethodInfo.GetCurrentMethod(),Expression.Constant(collection))); } throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.VarP /// </summary> [EdmFunction("Edm", "VarP")] public static System.Double? VarP(IEnumerable<System.Int64> collection) { ObjectQuery<System.Int64> objectQuerySource = collection as ObjectQuery<System.Int64>; if (objectQuerySource != null) { return ((IQueryable)objectQuerySource).Provider.Execute<System.Double?>(Expression.Call((MethodInfo)MethodInfo.GetCurrentMethod(),Expression.Constant(collection))); } throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.VarP /// </summary> [EdmFunction("Edm", "VarP")] public static System.Double? VarP(IEnumerable<System.Int64?> collection) { ObjectQuery<System.Int64?> objectQuerySource = collection as ObjectQuery<System.Int64?>; if (objectQuerySource != null) { return ((IQueryable)objectQuerySource).Provider.Execute<System.Double?>(Expression.Call((MethodInfo)MethodInfo.GetCurrentMethod(),Expression.Constant(collection))); } throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.Left /// </summary> [EdmFunction("Edm", "Left")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "string")] public static System.String Left(System.String stringArgument, System.Int64? length) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.Right /// </summary> [EdmFunction("Edm", "Right")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "string")] public static System.String Right(System.String stringArgument, System.Int64? length) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.Reverse /// </summary> [EdmFunction("Edm", "Reverse")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "string")] public static System.String Reverse(System.String stringArgument) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.GetTotalOffsetMinutes /// </summary> [EdmFunction("Edm", "GetTotalOffsetMinutes")] public static System.Int32? GetTotalOffsetMinutes(System.DateTimeOffset? dateTimeOffsetArgument) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.TruncateTime /// </summary> [EdmFunction("Edm", "TruncateTime")] public static System.DateTimeOffset? TruncateTime(System.DateTimeOffset? dateValue) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.TruncateTime /// </summary> [EdmFunction("Edm", "TruncateTime")] public static System.DateTime? TruncateTime(System.DateTime? dateValue) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.CreateDateTime /// </summary> [EdmFunction("Edm", "CreateDateTime")] public static System.DateTime? CreateDateTime(System.Int32? year, System.Int32? month, System.Int32? day, System.Int32? hour, System.Int32? minute, System.Double? second) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.CreateDateTimeOffset /// </summary> [EdmFunction("Edm", "CreateDateTimeOffset")] public static System.DateTimeOffset? CreateDateTimeOffset(System.Int32? year, System.Int32? month, System.Int32? day, System.Int32? hour, System.Int32? minute, System.Double? second, System.Int32? timeZoneOffset) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.CreateTime /// </summary> [EdmFunction("Edm", "CreateTime")] public static System.TimeSpan? CreateTime(System.Int32? hour, System.Int32? minute, System.Double? second) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.AddYears /// </summary> [EdmFunction("Edm", "AddYears")] public static System.DateTimeOffset? AddYears(System.DateTimeOffset? dateValue, System.Int32? addValue) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.AddYears /// </summary> [EdmFunction("Edm", "AddYears")] public static System.DateTime? AddYears(System.DateTime? dateValue, System.Int32? addValue) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.AddMonths /// </summary> [EdmFunction("Edm", "AddMonths")] public static System.DateTimeOffset? AddMonths(System.DateTimeOffset? dateValue, System.Int32? addValue) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.AddMonths /// </summary> [EdmFunction("Edm", "AddMonths")] public static System.DateTime? AddMonths(System.DateTime? dateValue, System.Int32? addValue) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.AddDays /// </summary> [EdmFunction("Edm", "AddDays")] public static System.DateTimeOffset? AddDays(System.DateTimeOffset? dateValue, System.Int32? addValue) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.AddDays /// </summary> [EdmFunction("Edm", "AddDays")] public static System.DateTime? AddDays(System.DateTime? dateValue, System.Int32? addValue) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.AddHours /// </summary> [EdmFunction("Edm", "AddHours")] public static System.DateTimeOffset? AddHours(System.DateTimeOffset? timeValue, System.Int32? addValue) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.AddHours /// </summary> [EdmFunction("Edm", "AddHours")] public static System.DateTime? AddHours(System.DateTime? timeValue, System.Int32? addValue) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.AddHours /// </summary> [EdmFunction("Edm", "AddHours")] public static System.TimeSpan? AddHours(System.TimeSpan? timeValue, System.Int32? addValue) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.AddMinutes /// </summary> [EdmFunction("Edm", "AddMinutes")] public static System.DateTimeOffset? AddMinutes(System.DateTimeOffset? timeValue, System.Int32? addValue) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.AddMinutes /// </summary> [EdmFunction("Edm", "AddMinutes")] public static System.DateTime? AddMinutes(System.DateTime? timeValue, System.Int32? addValue) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.AddMinutes /// </summary> [EdmFunction("Edm", "AddMinutes")] public static System.TimeSpan? AddMinutes(System.TimeSpan? timeValue, System.Int32? addValue) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.AddSeconds /// </summary> [EdmFunction("Edm", "AddSeconds")] public static System.DateTimeOffset? AddSeconds(System.DateTimeOffset? timeValue, System.Int32? addValue) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.AddSeconds /// </summary> [EdmFunction("Edm", "AddSeconds")] public static System.DateTime? AddSeconds(System.DateTime? timeValue, System.Int32? addValue) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.AddSeconds /// </summary> [EdmFunction("Edm", "AddSeconds")] public static System.TimeSpan? AddSeconds(System.TimeSpan? timeValue, System.Int32? addValue) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.AddMilliseconds /// </summary> [EdmFunction("Edm", "AddMilliseconds")] public static System.DateTimeOffset? AddMilliseconds(System.DateTimeOffset? timeValue, System.Int32? addValue) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.AddMilliseconds /// </summary> [EdmFunction("Edm", "AddMilliseconds")] public static System.DateTime? AddMilliseconds(System.DateTime? timeValue, System.Int32? addValue) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.AddMilliseconds /// </summary> [EdmFunction("Edm", "AddMilliseconds")] public static System.TimeSpan? AddMilliseconds(System.TimeSpan? timeValue, System.Int32? addValue) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.AddMicroseconds /// </summary> [EdmFunction("Edm", "AddMicroseconds")] public static System.DateTimeOffset? AddMicroseconds(System.DateTimeOffset? timeValue, System.Int32? addValue) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.AddMicroseconds /// </summary> [EdmFunction("Edm", "AddMicroseconds")] public static System.DateTime? AddMicroseconds(System.DateTime? timeValue, System.Int32? addValue) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.AddMicroseconds /// </summary> [EdmFunction("Edm", "AddMicroseconds")] public static System.TimeSpan? AddMicroseconds(System.TimeSpan? timeValue, System.Int32? addValue) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.AddNanoseconds /// </summary> [EdmFunction("Edm", "AddNanoseconds")] public static System.DateTimeOffset? AddNanoseconds(System.DateTimeOffset? timeValue, System.Int32? addValue) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.AddNanoseconds /// </summary> [EdmFunction("Edm", "AddNanoseconds")] public static System.DateTime? AddNanoseconds(System.DateTime? timeValue, System.Int32? addValue) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.AddNanoseconds /// </summary> [EdmFunction("Edm", "AddNanoseconds")] public static System.TimeSpan? AddNanoseconds(System.TimeSpan? timeValue, System.Int32? addValue) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.DiffYears /// </summary> [EdmFunction("Edm", "DiffYears")] public static System.Int32? DiffYears(System.DateTimeOffset? dateValue1, System.DateTimeOffset? dateValue2) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.DiffYears /// </summary> [EdmFunction("Edm", "DiffYears")] public static System.Int32? DiffYears(System.DateTime? dateValue1, System.DateTime? dateValue2) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.DiffMonths /// </summary> [EdmFunction("Edm", "DiffMonths")] public static System.Int32? DiffMonths(System.DateTimeOffset? dateValue1, System.DateTimeOffset? dateValue2) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.DiffMonths /// </summary> [EdmFunction("Edm", "DiffMonths")] public static System.Int32? DiffMonths(System.DateTime? dateValue1, System.DateTime? dateValue2) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.DiffDays /// </summary> [EdmFunction("Edm", "DiffDays")] public static System.Int32? DiffDays(System.DateTimeOffset? dateValue1, System.DateTimeOffset? dateValue2) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.DiffDays /// </summary> [EdmFunction("Edm", "DiffDays")] public static System.Int32? DiffDays(System.DateTime? dateValue1, System.DateTime? dateValue2) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.DiffHours /// </summary> [EdmFunction("Edm", "DiffHours")] public static System.Int32? DiffHours(System.DateTimeOffset? timeValue1, System.DateTimeOffset? timeValue2) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.DiffHours /// </summary> [EdmFunction("Edm", "DiffHours")] public static System.Int32? DiffHours(System.DateTime? timeValue1, System.DateTime? timeValue2) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.DiffHours /// </summary> [EdmFunction("Edm", "DiffHours")] public static System.Int32? DiffHours(System.TimeSpan? timeValue1, System.TimeSpan? timeValue2) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.DiffMinutes /// </summary> [EdmFunction("Edm", "DiffMinutes")] public static System.Int32? DiffMinutes(System.DateTimeOffset? timeValue1, System.DateTimeOffset? timeValue2) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.DiffMinutes /// </summary> [EdmFunction("Edm", "DiffMinutes")] public static System.Int32? DiffMinutes(System.DateTime? timeValue1, System.DateTime? timeValue2) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.DiffMinutes /// </summary> [EdmFunction("Edm", "DiffMinutes")] public static System.Int32? DiffMinutes(System.TimeSpan? timeValue1, System.TimeSpan? timeValue2) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.DiffSeconds /// </summary> [EdmFunction("Edm", "DiffSeconds")] public static System.Int32? DiffSeconds(System.DateTimeOffset? timeValue1, System.DateTimeOffset? timeValue2) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.DiffSeconds /// </summary> [EdmFunction("Edm", "DiffSeconds")] public static System.Int32? DiffSeconds(System.DateTime? timeValue1, System.DateTime? timeValue2) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.DiffSeconds /// </summary> [EdmFunction("Edm", "DiffSeconds")] public static System.Int32? DiffSeconds(System.TimeSpan? timeValue1, System.TimeSpan? timeValue2) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.DiffMilliseconds /// </summary> [EdmFunction("Edm", "DiffMilliseconds")] public static System.Int32? DiffMilliseconds(System.DateTimeOffset? timeValue1, System.DateTimeOffset? timeValue2) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.DiffMilliseconds /// </summary> [EdmFunction("Edm", "DiffMilliseconds")] public static System.Int32? DiffMilliseconds(System.DateTime? timeValue1, System.DateTime? timeValue2) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.DiffMilliseconds /// </summary> [EdmFunction("Edm", "DiffMilliseconds")] public static System.Int32? DiffMilliseconds(System.TimeSpan? timeValue1, System.TimeSpan? timeValue2) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.DiffMicroseconds /// </summary> [EdmFunction("Edm", "DiffMicroseconds")] public static System.Int32? DiffMicroseconds(System.DateTimeOffset? timeValue1, System.DateTimeOffset? timeValue2) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.DiffMicroseconds /// </summary> [EdmFunction("Edm", "DiffMicroseconds")] public static System.Int32? DiffMicroseconds(System.DateTime? timeValue1, System.DateTime? timeValue2) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.DiffMicroseconds /// </summary> [EdmFunction("Edm", "DiffMicroseconds")] public static System.Int32? DiffMicroseconds(System.TimeSpan? timeValue1, System.TimeSpan? timeValue2) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.DiffNanoseconds /// </summary> [EdmFunction("Edm", "DiffNanoseconds")] public static System.Int32? DiffNanoseconds(System.DateTimeOffset? timeValue1, System.DateTimeOffset? timeValue2) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.DiffNanoseconds /// </summary> [EdmFunction("Edm", "DiffNanoseconds")] public static System.Int32? DiffNanoseconds(System.DateTime? timeValue1, System.DateTime? timeValue2) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.DiffNanoseconds /// </summary> [EdmFunction("Edm", "DiffNanoseconds")] public static System.Int32? DiffNanoseconds(System.TimeSpan? timeValue1, System.TimeSpan? timeValue2) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.Truncate /// </summary> [EdmFunction("Edm", "Truncate")] public static System.Double? Truncate(System.Double? value, System.Int32? digits) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } /// <summary> /// Proxy for the function Edm.Truncate /// </summary> [EdmFunction("Edm", "Truncate")] public static System.Decimal? Truncate(System.Decimal? value, System.Int32? digits) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_EdmFunctionDirectCall); } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlTypes; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Reflection; using BLToolkit.Common; using BLToolkit.ComponentModel; using BLToolkit.EditableObjects; using BLToolkit.Mapping; using BLToolkit.TypeBuilder; using BLToolkit.TypeBuilder.Builders; using JNotNull = JetBrains.Annotations.NotNullAttribute; namespace BLToolkit.Reflection { public delegate object NullValueProvider(Type type); public delegate bool IsNullHandler (object obj); [DebuggerDisplay("Type = {Type}, OriginalType = {OriginalType}")] public abstract class TypeAccessor : ICollection, ITypeDescriptionProvider, IEnumerable<MemberAccessor> { #region Protected Emit Helpers protected MemberInfo GetMember(int memberType, string memberName) { const BindingFlags allInstaceMembers = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; MemberInfo mi; switch (memberType) { case 1: mi = Type.GetField (memberName, allInstaceMembers); break; case 2: mi = Type. GetProperty(memberName, allInstaceMembers) ?? OriginalType.GetProperty(memberName, allInstaceMembers); break; default: throw new InvalidOperationException(); } return mi; } protected void AddMember(MemberAccessor member) { if (member == null) throw new ArgumentNullException("member"); _members.Add(member); _memberNames.Add(member.MemberInfo.Name, member); } #endregion #region CreateInstance [DebuggerStepThrough] public virtual object CreateInstance() { throw new TypeBuilderException(string.Format( "The '{0}' type must have public default or init constructor.", OriginalType.Name)); } [DebuggerStepThrough] public virtual object CreateInstance(InitContext context) { return CreateInstance(); } [DebuggerStepThrough] public object CreateInstanceEx() { return _objectFactory != null? _objectFactory.CreateInstance(this, null): CreateInstance((InitContext)null); } [DebuggerStepThrough] public object CreateInstanceEx(InitContext context) { return _objectFactory != null? _objectFactory.CreateInstance(this, context): CreateInstance(context); } #endregion #region ObjectFactory private IObjectFactory _objectFactory; public IObjectFactory ObjectFactory { get { return _objectFactory; } set { _objectFactory = value; } } #endregion #region Copy & AreEqual internal static object CopyInternal(object source, object dest, TypeAccessor ta) { bool isDirty = false; IMemberwiseEditable sourceEditable = source as IMemberwiseEditable; IMemberwiseEditable destEditable = dest as IMemberwiseEditable; if (sourceEditable != null && destEditable != null) { foreach (MemberAccessor ma in ta) { // BVChanges: XmlIgnoreAttribute && RelationAttribute if (ma.GetAttribute<System.Xml.Serialization.XmlIgnoreAttribute>() == null) { ma.CloneValue(source, dest); if (sourceEditable.IsDirtyMember(null, ma.MemberInfo.Name, ref isDirty) && !isDirty) destEditable.AcceptMemberChanges(null, ma.MemberInfo.Name); } } } else { foreach (MemberAccessor ma in ta) ma.CloneValue(source, dest); } return dest; } public static object Copy(object source, object dest) { if (source == null) throw new ArgumentNullException("source"); if (dest == null) throw new ArgumentNullException("dest"); TypeAccessor ta; Type sType = source.GetType(); Type dType = dest. GetType(); if (TypeHelper.IsSameOrParent(sType, dType)) ta = GetAccessor(sType); else if (TypeHelper.IsSameOrParent(dType, sType)) ta = GetAccessor(dType); else throw new ArgumentException(); return CopyInternal(source, dest, ta); } public static object Copy(object source) { if (source == null) throw new ArgumentNullException("source"); TypeAccessor ta = GetAccessor(source.GetType()); return CopyInternal(source, ta.CreateInstanceEx(), ta); } public static bool AreEqual(object obj1, object obj2) { if (ReferenceEquals(obj1, obj2)) return true; if (obj1 == null || obj2 == null) return false; TypeAccessor ta; Type sType = obj1.GetType(); Type dType = obj2.GetType(); if (TypeHelper.IsSameOrParent(sType, dType)) ta = GetAccessor(sType); else if (TypeHelper.IsSameOrParent(dType, sType)) ta = GetAccessor(dType); else return false; foreach (MemberAccessor ma in ta) if ((!Equals(ma.GetValue(obj1), ma.GetValue(obj2)))) return false; return true; } public static int GetHashCode(object obj) { if (obj == null) throw new ArgumentNullException("obj"); int hash = 0; object value; foreach (MemberAccessor ma in GetAccessor(obj.GetType())) { value = ma.GetValue(obj); hash = ((hash << 5) + hash) ^ (value == null ? 0 : value.GetHashCode()); } return hash; } #endregion #region Abstract Members public abstract Type Type { get; } public abstract Type OriginalType { get; } #endregion #region Items private readonly ArrayList _members = new ArrayList(); private readonly Hashtable _memberNames = new Hashtable(); public MemberAccessor this[string memberName] { get { return (MemberAccessor)_memberNames[memberName]; } } public MemberAccessor this[int index] { get { return (MemberAccessor)_members[index]; } } public MemberAccessor this[NameOrIndexParameter nameOrIndex] { get { return (MemberAccessor) (nameOrIndex.ByName ? _memberNames[nameOrIndex.Name] : _members[nameOrIndex.Index]); } } #endregion #region Static Members [Obsolete("Use TypeFactory.LoadTypes instead")] public static bool LoadTypes { get { return TypeFactory.LoadTypes; } set { TypeFactory.LoadTypes = value; } } private static readonly Hashtable _accessors = new Hashtable(10); public static TypeAccessor GetAccessor(Type originalType) { if (originalType == null) throw new ArgumentNullException("originalType"); TypeAccessor accessor = (TypeAccessor)_accessors[originalType]; if (accessor == null) { lock (_accessors.SyncRoot) { accessor = (TypeAccessor)_accessors[originalType]; if (accessor == null) { if (IsAssociatedType(originalType)) return (TypeAccessor)_accessors[originalType]; Type instanceType = IsClassBulderNeeded(originalType)? null: originalType; if (instanceType == null) instanceType = TypeFactory.GetType(originalType); Type accessorType = TypeFactory.GetType(originalType, originalType, new TypeAccessorBuilder(instanceType, originalType)); accessor = (TypeAccessor)Activator.CreateInstance(accessorType); _accessors[originalType] = accessor; if (originalType != instanceType) _accessors[instanceType] = accessor; } } } return accessor; } public static TypeAccessor GetAccessor([JNotNull] object obj) { if (obj == null) throw new ArgumentNullException("obj"); return GetAccessor(obj.GetType()); } public static TypeAccessor GetAccessor<T>() { return TypeAccessor<T>.Instance; } private static bool IsClassBulderNeeded(Type type) { if (type.IsAbstract && !type.IsSealed) { if (!type.IsInterface) { if (TypeHelper.GetDefaultConstructor(type) != null) return true; if (TypeHelper.GetConstructor(type, typeof(InitContext)) != null) return true; } else { object[] attrs = TypeHelper.GetAttributes(type, typeof(AutoImplementInterfaceAttribute)); if (attrs != null && attrs.Length > 0) return true; } } return false; } internal static bool IsInstanceBuildable(Type type) { if (!type.IsInterface) return true; lock (_accessors.SyncRoot) { if (_accessors[type] != null) return true; if (IsAssociatedType(type)) return true; } object[] attrs = TypeHelper.GetAttributes(type, typeof(AutoImplementInterfaceAttribute)); return attrs != null && attrs.Length > 0; } private static bool IsAssociatedType(Type type) { if (AssociatedTypeHandler != null) { Type child = AssociatedTypeHandler(type); if (child != null) { AssociateType(type, child); return true; } } return false; } public static object CreateInstance(Type type) { return GetAccessor(type).CreateInstance(); } public static object CreateInstance(Type type, InitContext context) { return GetAccessor(type).CreateInstance(context); } public static object CreateInstanceEx(Type type) { return GetAccessor(type).CreateInstanceEx(); } public static object CreateInstanceEx(Type type, InitContext context) { return GetAccessor(type).CreateInstance(context); } public static T CreateInstance<T>() { return TypeAccessor<T>.CreateInstance(); } public static T CreateInstance<T>(InitContext context) { return TypeAccessor<T>.CreateInstance(context); } public static T CreateInstanceEx<T>() { return TypeAccessor<T>.CreateInstanceEx(); } public static T CreateInstanceEx<T>(InitContext context) { return TypeAccessor<T>.CreateInstance(context); } public static TypeAccessor AssociateType(Type parent, Type child) { if (!TypeHelper.IsSameOrParent(parent, child)) throw new ArgumentException( string.Format("'{0}' must be a base type of '{1}'", parent, child), "child"); TypeAccessor accessor = GetAccessor(child); accessor = (TypeAccessor)Activator.CreateInstance(accessor.GetType()); lock (_accessors.SyncRoot) _accessors[parent] = accessor; return accessor; } public delegate Type GetAssociatedType(Type parent); public static event GetAssociatedType AssociatedTypeHandler; #endregion #region GetNullValue private static NullValueProvider _getNullValue = GetNullInternal; public static NullValueProvider GetNullValue { get { return _getNullValue ?? (_getNullValue = GetNullInternal);} set { _getNullValue = value; } } private static object GetNullInternal(Type type) { if (type == null) throw new ArgumentNullException("type"); if (type.IsValueType) { if (type.IsEnum) return GetEnumNullValue(type); if (type.IsPrimitive) { if (type == typeof(Int32)) return Common.Configuration.NullableValues.Int32; if (type == typeof(Double)) return Common.Configuration.NullableValues.Double; if (type == typeof(Int16)) return Common.Configuration.NullableValues.Int16; if (type == typeof(Boolean)) return Common.Configuration.NullableValues.Boolean; if (type == typeof(SByte)) return Common.Configuration.NullableValues.SByte; if (type == typeof(Int64)) return Common.Configuration.NullableValues.Int64; if (type == typeof(Byte)) return Common.Configuration.NullableValues.Byte; if (type == typeof(UInt16)) return Common.Configuration.NullableValues.UInt16; if (type == typeof(UInt32)) return Common.Configuration.NullableValues.UInt32; if (type == typeof(UInt64)) return Common.Configuration.NullableValues.UInt64; if (type == typeof(Single)) return Common.Configuration.NullableValues.Single; if (type == typeof(Char)) return Common.Configuration.NullableValues.Char; } else { if (type == typeof(DateTime)) return Common.Configuration.NullableValues.DateTime; #if FW3 if (type == typeof(DateTimeOffset)) return Common.Configuration.NullableValues.DateTimeOffset; #endif if (type == typeof(Decimal)) return Common.Configuration.NullableValues.Decimal; if (type == typeof(Guid)) return Common.Configuration.NullableValues.Guid; if (type == typeof(SqlInt32)) return SqlInt32. Null; if (type == typeof(SqlString)) return SqlString. Null; if (type == typeof(SqlBoolean)) return SqlBoolean. Null; if (type == typeof(SqlByte)) return SqlByte. Null; if (type == typeof(SqlDateTime)) return SqlDateTime.Null; if (type == typeof(SqlDecimal)) return SqlDecimal. Null; if (type == typeof(SqlDouble)) return SqlDouble. Null; if (type == typeof(SqlGuid)) return SqlGuid. Null; if (type == typeof(SqlInt16)) return SqlInt16. Null; if (type == typeof(SqlInt64)) return SqlInt64. Null; if (type == typeof(SqlMoney)) return SqlMoney. Null; if (type == typeof(SqlSingle)) return SqlSingle. Null; if (type == typeof(SqlBinary)) return SqlBinary. Null; } } else { if (type == typeof(String)) return Common.Configuration.NullableValues.String; if (type == typeof(DBNull)) return DBNull.Value; if (type == typeof(Stream)) return Stream.Null; if (type == typeof(SqlXml)) return SqlXml.Null; } return null; } const FieldAttributes EnumField = FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.Literal; private static readonly Hashtable _nullValues = new Hashtable(); private static object GetEnumNullValue(Type type) { object nullValue = _nullValues[type]; if (nullValue != null || _nullValues.Contains(type)) return nullValue; FieldInfo[] fields = type.GetFields(); foreach (FieldInfo fi in fields) { if ((fi.Attributes & EnumField) == EnumField) { Attribute[] attrs = Attribute.GetCustomAttributes(fi, typeof(NullValueAttribute)); if (attrs.Length > 0) { nullValue = Enum.Parse(type, fi.Name); break; } } } _nullValues[type] = nullValue; return nullValue; } private static IsNullHandler _isNull = IsNullInternal; public static IsNullHandler IsNull { get { return _isNull ?? (_isNull = IsNullInternal); } set { _isNull = value; } } private static bool IsNullInternal(object value) { if (value == null) return true; object nullValue = GetNullValue(value.GetType()); return nullValue != null && value.Equals(nullValue); } #endregion #region ICollection Members public void CopyTo(Array array, int index) { _members.CopyTo(array, index); } public int Count { get { return _members.Count; } } public bool IsSynchronized { get { return _members.IsSynchronized; } } public object SyncRoot { get { return _members.SyncRoot; } } public int IndexOf(MemberAccessor ma) { return _members.IndexOf(ma); } #endregion #region IEnumerable Members public IEnumerator GetEnumerator() { return _members.GetEnumerator(); } #endregion #region Write Object Info public static void WriteDebug(object o) { #if DEBUG Write(o, DebugWriteLine); #endif } private static void DebugWriteLine(string text) { Debug.WriteLine(text); } public static void WriteConsole(object o) { Write(o, Console.WriteLine); } [SuppressMessage("Microsoft.Performance", "CA1818:DoNotConcatenateStringsInsideLoops")] private static string MapTypeName(Type type) { if (type.IsGenericType) { if (type.GetGenericTypeDefinition() == typeof(Nullable<>)) return string.Format("{0}?", MapTypeName(Nullable.GetUnderlyingType(type))); string name = type.Name; int idx = name.IndexOf('`'); if (idx >= 0) name = name.Substring(0, idx); name += "<"; foreach (Type t in type.GetGenericArguments()) name += MapTypeName(t) + ','; if (name[name.Length - 1] == ',') name = name.Substring(0, name.Length - 1); name += ">"; return name; } if (type.IsPrimitive || type == typeof(string) || type == typeof(object) || type == typeof(decimal)) { if (type == typeof(int)) return "int"; if (type == typeof(bool)) return "bool"; if (type == typeof(short)) return "short"; if (type == typeof(long)) return "long"; if (type == typeof(ushort)) return "ushort"; if (type == typeof(uint)) return "uint"; if (type == typeof(ulong)) return "ulong"; if (type == typeof(float)) return "float"; return type.Name.ToLower(); } return type.Name; } public delegate void WriteLine(string text); [SuppressMessage("Microsoft.Usage", "CA2241:ProvideCorrectArgumentsToFormattingMethods")] public static void Write(object o, WriteLine writeLine) { if (o == null) { writeLine("*** (null) ***"); return; } TypeAccessor ta = GetAccessor(o.GetType()); MemberAccessor ma; int nameLen = 0; int typeLen = 0; foreach (DictionaryEntry de in ta._memberNames) { if (nameLen < de.Key.ToString().Length) nameLen = de.Key.ToString().Length; ma = (MemberAccessor)de.Value; if (typeLen < MapTypeName(ma.Type).Length) typeLen = MapTypeName(ma.Type).Length; } string text = "*** " + o.GetType().FullName + ": ***"; writeLine(text); string format = string.Format("{{0,-{0}}} {{1,-{1}}} : {{2}}", typeLen, nameLen); foreach (DictionaryEntry de in ta._memberNames) { ma = (MemberAccessor)de.Value; object value = ma.GetValue(o); if (value == null) value = "(null)"; else if (value is ICollection) value = string.Format("(Count = {0})", ((ICollection)value).Count); text = string.Format(format, MapTypeName(ma.Type), de.Key, value); writeLine(text); } writeLine("***"); } #endregion #region CustomTypeDescriptor private static readonly Hashtable _descriptors = new Hashtable(); public static ICustomTypeDescriptor GetCustomTypeDescriptor(Type type) { ICustomTypeDescriptor descriptor = (ICustomTypeDescriptor)_descriptors[type]; if (descriptor == null) { lock (_descriptors.SyncRoot) { descriptor = (ICustomTypeDescriptor)_descriptors[type]; if (descriptor == null) { descriptor = new CustomTypeDescriptorImpl(type); _descriptors.Add(type, descriptor); } } } return descriptor; } private ICustomTypeDescriptor _customTypeDescriptor; public ICustomTypeDescriptor CustomTypeDescriptor { get { if (_customTypeDescriptor == null) _customTypeDescriptor = GetCustomTypeDescriptor(OriginalType); return _customTypeDescriptor; } } #endregion #region Property Descriptors private PropertyDescriptorCollection _propertyDescriptors; public PropertyDescriptorCollection PropertyDescriptors { get { if (_propertyDescriptors == null) { if (TypeHelper.IsSameOrParent(typeof(ICustomTypeDescriptor), OriginalType)) { ICustomTypeDescriptor descriptor = CreateInstance() as ICustomTypeDescriptor; if (descriptor != null) _propertyDescriptors = descriptor.GetProperties(); } if (_propertyDescriptors == null) _propertyDescriptors = CreatePropertyDescriptors(); } return _propertyDescriptors; } } public PropertyDescriptorCollection CreatePropertyDescriptors() { Debug.WriteLineIf(BLToolkit.Data.DbManager.TraceSwitch.TraceInfo, OriginalType.FullName, "CreatePropertyDescriptors"); PropertyDescriptor[] pd = new PropertyDescriptor[Count]; int i = 0; foreach (MemberAccessor ma in _members) pd[i++] = ma.PropertyDescriptor; return new PropertyDescriptorCollection(pd); } public PropertyDescriptorCollection CreateExtendedPropertyDescriptors( Type objectViewType, IsNullHandler isNull) { // This is definitely wrong. // //if (isNull == null) // isNull = _isNull; PropertyDescriptorCollection pdc; pdc = CreatePropertyDescriptors(); if (objectViewType != null) { TypeAccessor viewAccessor = GetAccessor(objectViewType); IObjectView objectView = (IObjectView)viewAccessor.CreateInstanceEx(); List<PropertyDescriptor> list = new List<PropertyDescriptor>(); PropertyDescriptorCollection viewpdc = viewAccessor.PropertyDescriptors; foreach (PropertyDescriptor pd in viewpdc) list.Add(new ObjectViewPropertyDescriptor(pd, objectView)); foreach (PropertyDescriptor pd in pdc) if (viewpdc.Find(pd.Name, false) == null) list.Add(pd); pdc = new PropertyDescriptorCollection(list.ToArray()); } pdc = pdc.Sort(new PropertyDescriptorComparer()); pdc = GetExtendedProperties(pdc, OriginalType, String.Empty, Type.EmptyTypes, new PropertyDescriptor[0], isNull); return pdc; } private static PropertyDescriptorCollection GetExtendedProperties( PropertyDescriptorCollection pdc, Type itemType, string propertyPrefix, Type[] parentTypes, PropertyDescriptor[] parentAccessors, IsNullHandler isNull) { ArrayList list = new ArrayList(pdc.Count); ArrayList objects = new ArrayList(); bool isDataRow = itemType.IsSubclassOf(typeof(DataRow)); foreach (PropertyDescriptor p in pdc) { Type propertyType = p.PropertyType; if (p.Attributes.Matches(BindableAttribute.No) || //propertyType == typeof(Type) || isDataRow && p.Name == "ItemArray") continue; bool isList = false; bool explicitlyBound = p.Attributes.Contains(BindableAttribute.Yes); PropertyDescriptor pd = p; if (propertyType.GetInterface("IList") != null) { //if (!explicitlyBound) // continue; isList = true; pd = new ListPropertyDescriptor(pd); } if (!isList && !propertyType.IsValueType && !propertyType.IsArray && (!propertyType.FullName.StartsWith("System.") || explicitlyBound || propertyType.IsGenericType) && propertyType != typeof(Type) && propertyType != typeof(string) && propertyType != typeof(object) && Array.IndexOf(parentTypes, propertyType) == -1) { Type[] childParentTypes = new Type[parentTypes.Length + 1]; parentTypes.CopyTo(childParentTypes, 0); childParentTypes[parentTypes.Length] = itemType; PropertyDescriptor[] childParentAccessors = new PropertyDescriptor[parentAccessors.Length + 1]; parentAccessors.CopyTo(childParentAccessors, 0); childParentAccessors[parentAccessors.Length] = pd; PropertyDescriptorCollection pdch = GetAccessor(propertyType).PropertyDescriptors; pdch = pdch.Sort(new PropertyDescriptorComparer()); pdch = GetExtendedProperties( pdch, propertyType, propertyPrefix + pd.Name + "+", childParentTypes, childParentAccessors, isNull); objects.AddRange(pdch); } else { if (propertyPrefix.Length != 0 || isNull != null) pd = new StandardPropertyDescriptor(pd, propertyPrefix, parentAccessors, isNull); list.Add(pd); } } list.AddRange(objects); return new PropertyDescriptorCollection( (PropertyDescriptor[])list.ToArray(typeof(PropertyDescriptor))); } #region PropertyDescriptorComparer class PropertyDescriptorComparer : IComparer { public int Compare(object x, object y) { return String.Compare(((PropertyDescriptor)x).Name, ((PropertyDescriptor)y).Name); } } #endregion #region ListPropertyDescriptor class ListPropertyDescriptor : PropertyDescriptorWrapper { public ListPropertyDescriptor(PropertyDescriptor descriptor) : base(descriptor) { } public override object GetValue(object component) { object value = base.GetValue(component); if (value == null) return value; if (value is IBindingList && value is ITypedList) return value; return EditableArrayList.Adapter((IList)value); } } #endregion #region StandardPropertyDescriptor class StandardPropertyDescriptor : PropertyDescriptorWrapper { protected readonly PropertyDescriptor _descriptor = null; protected readonly IsNullHandler _isNull; protected readonly string _prefixedName; protected readonly PropertyDescriptor[] _chainAccessors; public StandardPropertyDescriptor( PropertyDescriptor pd, string namePrefix, PropertyDescriptor[] chainAccessors, IsNullHandler isNull) : base(pd) { _descriptor = pd; _isNull = isNull; _prefixedName = namePrefix + pd.Name; _chainAccessors = chainAccessors; } protected object GetNestedComponent(object component) { for (int i = 0; i < _chainAccessors.Length && component != null && !(component is DBNull); i++) { component = _chainAccessors[i].GetValue(component); } return component; } public override void SetValue(object component, object value) { component = GetNestedComponent(component); if (component != null && !(component is DBNull)) _descriptor.SetValue(component, value); } public override object GetValue(object component) { component = GetNestedComponent(component); return CheckNull( component != null && !(component is DBNull)? _descriptor.GetValue(component): null); } public override string Name { get { return _prefixedName; } } protected object CheckNull(object value) { if (_isNull != null && _isNull(value)) { switch (Common.Configuration.CheckNullReturnIfNull) { case Common.Configuration.NullEquivalent.DBNull: return DBNull.Value; case Common.Configuration.NullEquivalent.Null: return null; case Common.Configuration.NullEquivalent.Value: return value; } return DBNull.Value; } return value; } } #endregion #region objectViewPropertyDescriptor class ObjectViewPropertyDescriptor : PropertyDescriptorWrapper { public ObjectViewPropertyDescriptor(PropertyDescriptor pd, IObjectView objectView) : base(pd) { _objectView = objectView; } private readonly IObjectView _objectView; public override object GetValue(object component) { _objectView.Object = component; return base.GetValue(_objectView); } public override void SetValue(object component, object value) { _objectView.Object = component; base.SetValue(_objectView, value); } } #endregion #endregion #region ITypeDescriptionProvider Members string ITypeDescriptionProvider.ClassName { get { return OriginalType.Name; } } string ITypeDescriptionProvider.ComponentName { get { return OriginalType.Name; } } EventDescriptor ITypeDescriptionProvider.GetEvent(string name) { return new CustomEventDescriptor(OriginalType.GetEvent(name)); } PropertyDescriptor ITypeDescriptionProvider.GetProperty(string name) { MemberAccessor ma = this[name]; return ma != null ? ma.PropertyDescriptor : null; } AttributeCollection ITypeDescriptionProvider.GetAttributes() { return new AttributeCollection((Attribute[])new TypeHelper(OriginalType).GetAttributes()); } EventDescriptorCollection ITypeDescriptionProvider.GetEvents() { EventInfo[] ei = OriginalType.GetEvents(); EventDescriptor[] ed = new EventDescriptor[ei.Length]; for (int i = 0; i < ei.Length; i++) ed[i] = new CustomEventDescriptor(ei[i]); return new EventDescriptorCollection(ed); } PropertyDescriptorCollection ITypeDescriptionProvider.GetProperties() { return CreatePropertyDescriptors(); } #region CustomEventDescriptor class CustomEventDescriptor : EventDescriptor { public CustomEventDescriptor(EventInfo eventInfo) : base(eventInfo.Name, null) { _eventInfo = eventInfo; } private readonly EventInfo _eventInfo; public override void AddEventHandler(object component, Delegate value) { _eventInfo.AddEventHandler(component, value); } public override void RemoveEventHandler(object component, Delegate value) { _eventInfo.RemoveEventHandler(component, value); } public override Type ComponentType { get { return _eventInfo.DeclaringType; } } public override Type EventType { get { return _eventInfo.EventHandlerType; } } public override bool IsMulticast { get { return _eventInfo.IsMulticast; } } } #endregion #endregion #region IEnumerable<MemberAccessor> Members IEnumerator<MemberAccessor> IEnumerable<MemberAccessor>.GetEnumerator() { foreach (MemberAccessor member in _members) yield return member; } #endregion } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Reflection.Emit.ModuleBuilder.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Reflection.Emit { public partial class ModuleBuilder : System.Reflection.Module, System.Runtime.InteropServices._ModuleBuilder { #region Methods and constructors public void CreateGlobalFunctions() { } public System.Diagnostics.SymbolStore.ISymbolDocumentWriter DefineDocument(string url, Guid language, Guid languageVendor, Guid documentType) { return default(System.Diagnostics.SymbolStore.ISymbolDocumentWriter); } public EnumBuilder DefineEnum(string name, System.Reflection.TypeAttributes visibility, Type underlyingType) { Contract.Ensures(Contract.Result<System.Reflection.Emit.EnumBuilder>() != null); return default(EnumBuilder); } public MethodBuilder DefineGlobalMethod(string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers) { Contract.Ensures(Contract.Result<System.Reflection.Emit.MethodBuilder>() != null); return default(MethodBuilder); } public MethodBuilder DefineGlobalMethod(string name, System.Reflection.MethodAttributes attributes, Type returnType, Type[] parameterTypes) { Contract.Ensures(Contract.Result<System.Reflection.Emit.MethodBuilder>() != null); return default(MethodBuilder); } public MethodBuilder DefineGlobalMethod(string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type returnType, Type[] parameterTypes) { Contract.Ensures(Contract.Result<System.Reflection.Emit.MethodBuilder>() != null); return default(MethodBuilder); } public FieldBuilder DefineInitializedData(string name, byte[] data, System.Reflection.FieldAttributes attributes) { Contract.Ensures(Contract.Result<System.Reflection.Emit.FieldBuilder>() != null); return default(FieldBuilder); } public void DefineManifestResource(string name, Stream stream, System.Reflection.ResourceAttributes attribute) { } public MethodBuilder DefinePInvokeMethod(string name, string dllName, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type returnType, Type[] parameterTypes, System.Runtime.InteropServices.CallingConvention nativeCallConv, System.Runtime.InteropServices.CharSet nativeCharSet) { Contract.Ensures(Contract.Result<System.Reflection.Emit.MethodBuilder>() != null); return default(MethodBuilder); } public MethodBuilder DefinePInvokeMethod(string name, string dllName, string entryName, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type returnType, Type[] parameterTypes, System.Runtime.InteropServices.CallingConvention nativeCallConv, System.Runtime.InteropServices.CharSet nativeCharSet) { Contract.Ensures(Contract.Result<System.Reflection.Emit.MethodBuilder>() != null); return default(MethodBuilder); } public System.Resources.IResourceWriter DefineResource(string name, string description) { Contract.Ensures(Contract.Result<System.Resources.IResourceWriter>() != null); return default(System.Resources.IResourceWriter); } public System.Resources.IResourceWriter DefineResource(string name, string description, System.Reflection.ResourceAttributes attribute) { Contract.Ensures(Contract.Result<System.Resources.IResourceWriter>() != null); return default(System.Resources.IResourceWriter); } public TypeBuilder DefineType(string name, System.Reflection.TypeAttributes attr, Type parent, PackingSize packingSize, int typesize) { Contract.Ensures(0 <= name.Length); Contract.Ensures(Contract.Result<System.Reflection.Emit.TypeBuilder>() != null); Contract.Ensures(name.Length <= 1023); return default(TypeBuilder); } public TypeBuilder DefineType(string name) { Contract.Ensures(0 <= name.Length); Contract.Ensures(Contract.Result<System.Reflection.Emit.TypeBuilder>() != null); Contract.Ensures(name.Length <= 1023); return default(TypeBuilder); } public TypeBuilder DefineType(string name, System.Reflection.TypeAttributes attr, Type parent, int typesize) { Contract.Ensures(0 <= name.Length); Contract.Ensures(Contract.Result<System.Reflection.Emit.TypeBuilder>() != null); Contract.Ensures(name.Length <= 1023); return default(TypeBuilder); } public TypeBuilder DefineType(string name, System.Reflection.TypeAttributes attr) { Contract.Ensures(0 <= name.Length); Contract.Ensures(Contract.Result<System.Reflection.Emit.TypeBuilder>() != null); Contract.Ensures(name.Length <= 1023); return default(TypeBuilder); } public TypeBuilder DefineType(string name, System.Reflection.TypeAttributes attr, Type parent) { Contract.Ensures(0 <= name.Length); Contract.Ensures(Contract.Result<System.Reflection.Emit.TypeBuilder>() != null); Contract.Ensures(name.Length <= 1023); return default(TypeBuilder); } public TypeBuilder DefineType(string name, System.Reflection.TypeAttributes attr, Type parent, Type[] interfaces) { Contract.Ensures(0 <= name.Length); Contract.Ensures(Contract.Result<System.Reflection.Emit.TypeBuilder>() != null); Contract.Ensures(name.Length <= 1023); return default(TypeBuilder); } public TypeBuilder DefineType(string name, System.Reflection.TypeAttributes attr, Type parent, PackingSize packsize) { Contract.Ensures(0 <= name.Length); Contract.Ensures(Contract.Result<System.Reflection.Emit.TypeBuilder>() != null); Contract.Ensures(name.Length <= 1023); return default(TypeBuilder); } public FieldBuilder DefineUninitializedData(string name, int size, System.Reflection.FieldAttributes attributes) { Contract.Ensures(Contract.Result<System.Reflection.Emit.FieldBuilder>() != null); return default(FieldBuilder); } public void DefineUnmanagedResource(string resourceFileName) { } public void DefineUnmanagedResource(byte[] resource) { } public override bool Equals(Object obj) { return default(bool); } public System.Reflection.MethodInfo GetArrayMethod(Type arrayClass, string methodName, System.Reflection.CallingConventions callingConvention, Type returnType, Type[] parameterTypes) { Contract.Ensures(Contract.Result<System.Reflection.MethodInfo>() != null); return default(System.Reflection.MethodInfo); } public MethodToken GetArrayMethodToken(Type arrayClass, string methodName, System.Reflection.CallingConventions callingConvention, Type returnType, Type[] parameterTypes) { return default(MethodToken); } public MethodToken GetConstructorToken(System.Reflection.ConstructorInfo con) { return default(MethodToken); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { return default(Object[]); } public override Object[] GetCustomAttributes(bool inherit) { return default(Object[]); } public override IList<System.Reflection.CustomAttributeData> GetCustomAttributesData() { return default(IList<System.Reflection.CustomAttributeData>); } public override System.Reflection.FieldInfo GetField(string name, System.Reflection.BindingFlags bindingAttr) { return default(System.Reflection.FieldInfo); } public override System.Reflection.FieldInfo[] GetFields(System.Reflection.BindingFlags bindingFlags) { return default(System.Reflection.FieldInfo[]); } public FieldToken GetFieldToken(System.Reflection.FieldInfo field) { return default(FieldToken); } public override int GetHashCode() { return default(int); } protected override System.Reflection.MethodInfo GetMethodImpl(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, Type[] types, System.Reflection.ParameterModifier[] modifiers) { return default(System.Reflection.MethodInfo); } public override System.Reflection.MethodInfo[] GetMethods(System.Reflection.BindingFlags bindingFlags) { return default(System.Reflection.MethodInfo[]); } public MethodToken GetMethodToken(System.Reflection.MethodInfo method) { return default(MethodToken); } public override void GetPEKind(out System.Reflection.PortableExecutableKinds peKind, out System.Reflection.ImageFileMachine machine) { peKind = default(System.Reflection.PortableExecutableKinds); machine = default(System.Reflection.ImageFileMachine); } public SignatureToken GetSignatureToken(byte[] sigBytes, int sigLength) { return default(SignatureToken); } public SignatureToken GetSignatureToken(SignatureHelper sigHelper) { return default(SignatureToken); } public override System.Security.Cryptography.X509Certificates.X509Certificate GetSignerCertificate() { return default(System.Security.Cryptography.X509Certificates.X509Certificate); } public StringToken GetStringConstant(string str) { return default(StringToken); } public System.Diagnostics.SymbolStore.ISymbolWriter GetSymWriter() { return default(System.Diagnostics.SymbolStore.ISymbolWriter); } public override Type GetType(string className) { return default(Type); } public override Type GetType(string className, bool ignoreCase) { return default(Type); } public override Type GetType(string className, bool throwOnError, bool ignoreCase) { return default(Type); } public override Type[] GetTypes() { return default(Type[]); } public TypeToken GetTypeToken(Type type) { return default(TypeToken); } public TypeToken GetTypeToken(string name) { return default(TypeToken); } public override bool IsDefined(Type attributeType, bool inherit) { return default(bool); } public override bool IsResource() { return default(bool); } public bool IsTransient() { return default(bool); } internal ModuleBuilder() { } public override System.Reflection.FieldInfo ResolveField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { return default(System.Reflection.FieldInfo); } public override System.Reflection.MemberInfo ResolveMember(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { return default(System.Reflection.MemberInfo); } public override System.Reflection.MethodBase ResolveMethod(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { return default(System.Reflection.MethodBase); } public override byte[] ResolveSignature(int metadataToken) { return default(byte[]); } public override string ResolveString(int metadataToken) { return default(string); } public override Type ResolveType(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { return default(Type); } public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { } public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { } public void SetSymCustomAttribute(string name, byte[] data) { } public void SetUserEntryPoint(System.Reflection.MethodInfo entryPoint) { } void System.Runtime.InteropServices._ModuleBuilder.GetIDsOfNames(ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) { } void System.Runtime.InteropServices._ModuleBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) { } void System.Runtime.InteropServices._ModuleBuilder.GetTypeInfoCount(out uint pcTInfo) { pcTInfo = default(uint); } void System.Runtime.InteropServices._ModuleBuilder.Invoke(uint dispIdMember, ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) { } #endregion #region Properties and indexers public override System.Reflection.Assembly Assembly { get { return default(System.Reflection.Assembly); } } public override string FullyQualifiedName { get { return default(string); } } public override int MDStreamVersion { get { return default(int); } } public override int MetadataToken { get { return default(int); } } public override Guid ModuleVersionId { get { return default(Guid); } } public override string Name { get { return default(string); } } public override string ScopeName { get { return default(string); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // WARNING: This file is generated and should not be modified directly. // Instead, modify HtmlRawTextWriterGenerator.ttinclude using System; using System.IO; using System.Text; using System.Xml; using System.Xml.Schema; using System.Diagnostics; using MS.Internal.Xml; namespace System.Xml { internal class HtmlEncodedRawTextWriter : XmlEncodedRawTextWriter { protected ByteStack elementScope; protected ElementProperties currentElementProperties; private AttributeProperties _currentAttributeProperties; private bool _endsWithAmpersand; private byte[] _uriEscapingBuffer; private string _mediaType; private bool _doNotEscapeUriAttributes; protected static TernaryTreeReadOnly elementPropertySearch; protected static TernaryTreeReadOnly attributePropertySearch; private const int StackIncrement = 10; public HtmlEncodedRawTextWriter(TextWriter writer, XmlWriterSettings settings) : base(writer, settings) { Init(settings); } public HtmlEncodedRawTextWriter(Stream stream, XmlWriterSettings settings) : base(stream, settings) { Init(settings); } internal override void WriteXmlDeclaration(XmlStandalone standalone) { // Ignore xml declaration } internal override void WriteXmlDeclaration(string xmldecl) { // Ignore xml declaration } /// Html rules allow public ID without system ID and always output "html" public override void WriteDocType(string name, string pubid, string sysid, string subset) { Debug.Assert(name != null && name.Length > 0); if (trackTextContent && inTextContent != false) { ChangeTextContentMark(false); } RawText("<!DOCTYPE "); // Bug: Always output "html" or "HTML" in doc-type, even if "name" is something else if (name == "HTML") RawText("HTML"); else RawText("html"); if (pubid != null) { RawText(" PUBLIC \""); RawText(pubid); if (sysid != null) { RawText("\" \""); RawText(sysid); } bufChars[bufPos++] = (char)'"'; } else if (sysid != null) { RawText(" SYSTEM \""); RawText(sysid); bufChars[bufPos++] = (char)'"'; } else { bufChars[bufPos++] = (char)' '; } if (subset != null) { bufChars[bufPos++] = (char)'['; RawText(subset); bufChars[bufPos++] = (char)']'; } bufChars[bufPos++] = (char)'>'; } // For the HTML element, it should call this method with ns and prefix as String.Empty public override void WriteStartElement(string prefix, string localName, string ns) { Debug.Assert(localName != null && localName.Length != 0 && prefix != null && ns != null); elementScope.Push((byte)currentElementProperties); if (ns.Length == 0) { Debug.Assert(prefix.Length == 0); if (trackTextContent && inTextContent != false) { ChangeTextContentMark(false); } currentElementProperties = (ElementProperties)elementPropertySearch.FindCaseInsensitiveString(localName); base.bufChars[bufPos++] = (char)'<'; base.RawText(localName); base.attrEndPos = bufPos; } else { // Since the HAS_NS has no impact to the ElementTextBlock behavior, // we don't need to push it into the stack. currentElementProperties = ElementProperties.HAS_NS; base.WriteStartElement(prefix, localName, ns); } } // Output >. For HTML needs to output META info internal override void StartElementContent() { base.bufChars[base.bufPos++] = (char)'>'; // Detect whether content is output contentPos = bufPos; if ((currentElementProperties & ElementProperties.HEAD) != 0) { WriteMetaElement(); } } // end element with /> // for HTML(ns.Length == 0) // not an empty tag <h1></h1> // empty tag <basefont> internal override void WriteEndElement(string prefix, string localName, string ns) { if (ns.Length == 0) { Debug.Assert(prefix.Length == 0); if (trackTextContent && inTextContent != false) { ChangeTextContentMark(false); } if ((currentElementProperties & ElementProperties.EMPTY) == 0) { bufChars[base.bufPos++] = (char)'<'; bufChars[base.bufPos++] = (char)'/'; base.RawText(localName); bufChars[base.bufPos++] = (char)'>'; } } else { //xml content base.WriteEndElement(prefix, localName, ns); } currentElementProperties = (ElementProperties)elementScope.Pop(); } internal override void WriteFullEndElement(string prefix, string localName, string ns) { if (ns.Length == 0) { Debug.Assert(prefix.Length == 0); if (trackTextContent && inTextContent != false) { ChangeTextContentMark(false); } if ((currentElementProperties & ElementProperties.EMPTY) == 0) { bufChars[base.bufPos++] = (char)'<'; bufChars[base.bufPos++] = (char)'/'; base.RawText(localName); bufChars[base.bufPos++] = (char)'>'; } } else { //xml content base.WriteFullEndElement(prefix, localName, ns); } currentElementProperties = (ElementProperties)elementScope.Pop(); } // 1. How the outputBooleanAttribute(fBOOL) and outputHtmlUriText(fURI) being set? // When SA is called. // // BOOL_PARENT URI_PARENT Others // fURI // URI att false true false // // fBOOL // BOOL att true false false // // How they change the attribute output behaviors? // // 1) fURI=true fURI=false // SA a=" a=" // AT HtmlURIText HtmlText // EA " " // // 2) fBOOL=true fBOOL=false // SA a a=" // AT HtmlText output nothing // EA output nothing " // // When they get reset? // At the end of attribute. // 2. How the outputXmlTextElementScoped(fENs) and outputXmlTextattributeScoped(fANs) are set? // fANs is in the scope of the fENs. // // SE(localName) SE(ns, pre, localName) SA(localName) SA(ns, pre, localName) // fENs false(default) true(action) // fANs false(default) false(default) false(default) true(action) // how they get reset? // // EE(localName) EE(ns, pre, localName) EENC(ns, pre, localName) EA(localName) EA(ns, pre, localName) // fENs false(action) // fANs false(action) // How they change the TextOutput? // // fENs | fANs Else // AT XmlText HtmlText // // // 3. Flags for processing &{ split situations // // When the flag is set? // // AT src[lastchar]='&' flag&{ = true; // // when it get result? // // AT method. // // How it changes the behaviors? // // flag&{=true // // AT if (src[0] == '{') { // output "&{" // } // else { // output &amp; // } // // EA output amp; // // SA if (flagBOOL == false) { output =";} // // AT if (flagBOOL) { return}; // if (flagNS) {XmlText;} { // } // else if (flagURI) { // HtmlURIText; // } // else { // HtmlText; // } // // AT if (flagNS) {XmlText;} { // } // else if (flagURI) { // HtmlURIText; // } // else if (!flagBOOL) { // HtmlText; //flag&{ handling // } // // // EA if (flagBOOL == false) { output " // } // else if (flag&{) { // output amp; // } // public override void WriteStartAttribute(string prefix, string localName, string ns) { Debug.Assert(localName != null && localName.Length != 0 && prefix != null && ns != null); if (ns.Length == 0) { Debug.Assert(prefix.Length == 0); if (trackTextContent && inTextContent != false) { ChangeTextContentMark(false); } if (base.attrEndPos == bufPos) { base.bufChars[bufPos++] = (char)' '; } base.RawText(localName); if ((currentElementProperties & (ElementProperties.BOOL_PARENT | ElementProperties.URI_PARENT | ElementProperties.NAME_PARENT)) != 0) { _currentAttributeProperties = (AttributeProperties)attributePropertySearch.FindCaseInsensitiveString(localName) & (AttributeProperties)currentElementProperties; if ((_currentAttributeProperties & AttributeProperties.BOOLEAN) != 0) { base.inAttributeValue = true; return; } } else { _currentAttributeProperties = AttributeProperties.DEFAULT; } base.bufChars[bufPos++] = (char)'='; base.bufChars[bufPos++] = (char)'"'; } else { base.WriteStartAttribute(prefix, localName, ns); _currentAttributeProperties = AttributeProperties.DEFAULT; } base.inAttributeValue = true; } // Output the amp; at end of EndAttribute public override void WriteEndAttribute() { if ((_currentAttributeProperties & AttributeProperties.BOOLEAN) != 0) { base.attrEndPos = bufPos; } else { if (_endsWithAmpersand) { OutputRestAmps(); _endsWithAmpersand = false; } if (trackTextContent && inTextContent != false) { ChangeTextContentMark(false); } base.bufChars[bufPos++] = (char)'"'; } base.inAttributeValue = false; base.attrEndPos = bufPos; } // HTML PI's use ">" to terminate rather than "?>". public override void WriteProcessingInstruction(string target, string text) { Debug.Assert(target != null && target.Length != 0 && text != null); if (trackTextContent && inTextContent != false) { ChangeTextContentMark(false); } bufChars[base.bufPos++] = (char)'<'; bufChars[base.bufPos++] = (char)'?'; base.RawText(target); bufChars[base.bufPos++] = (char)' '; base.WriteCommentOrPi(text, '?'); base.bufChars[base.bufPos++] = (char)'>'; if (base.bufPos > base.bufLen) { FlushBuffer(); } } // Serialize either attribute or element text using HTML rules. public override unsafe void WriteString(string text) { Debug.Assert(text != null); if (trackTextContent && inTextContent != true) { ChangeTextContentMark(true); } fixed (char* pSrc = text) { char* pSrcEnd = pSrc + text.Length; if (base.inAttributeValue) { WriteHtmlAttributeTextBlock(pSrc, pSrcEnd); } else { WriteHtmlElementTextBlock(pSrc, pSrcEnd); } } } public override void WriteEntityRef(string name) { throw new InvalidOperationException(SR.Xml_InvalidOperation); } public override void WriteCharEntity(char ch) { throw new InvalidOperationException(SR.Xml_InvalidOperation); } public override void WriteSurrogateCharEntity(char lowChar, char highChar) { throw new InvalidOperationException(SR.Xml_InvalidOperation); } public override unsafe void WriteChars(char[] buffer, int index, int count) { Debug.Assert(buffer != null); Debug.Assert(index >= 0); Debug.Assert(count >= 0 && index + count <= buffer.Length); if (trackTextContent && inTextContent != true) { ChangeTextContentMark(true); } fixed (char* pSrcBegin = &buffer[index]) { if (inAttributeValue) { WriteAttributeTextBlock(pSrcBegin, pSrcBegin + count); } else { WriteElementTextBlock(pSrcBegin, pSrcBegin + count); } } } // // Private methods // private void Init(XmlWriterSettings settings) { Debug.Assert((int)ElementProperties.URI_PARENT == (int)AttributeProperties.URI); Debug.Assert((int)ElementProperties.BOOL_PARENT == (int)AttributeProperties.BOOLEAN); Debug.Assert((int)ElementProperties.NAME_PARENT == (int)AttributeProperties.NAME); if (elementPropertySearch == null) { //elementPropertySearch should be init last for the mutli thread safe situation. attributePropertySearch = new TernaryTreeReadOnly(HtmlTernaryTree.htmlAttributes); elementPropertySearch = new TernaryTreeReadOnly(HtmlTernaryTree.htmlElements); } elementScope = new ByteStack(StackIncrement); _uriEscapingBuffer = new byte[5]; currentElementProperties = ElementProperties.DEFAULT; _mediaType = settings.MediaType; _doNotEscapeUriAttributes = settings.DoNotEscapeUriAttributes; } protected void WriteMetaElement() { base.RawText("<META http-equiv=\"Content-Type\""); if (_mediaType == null) { _mediaType = "text/html"; } base.RawText(" content=\""); base.RawText(_mediaType); base.RawText("; charset="); base.RawText(base.encoding.WebName); base.RawText("\">"); } // Justify the stack usage: // // Nested elements has following possible position combinations // 1. <E1>Content1<E2>Content2</E2></E1> // 2. <E1><E2>Content2</E2>Content1</E1> // 3. <E1>Content<E2>Cotent2</E2>Content1</E1> // // In the situation 2 and 3, the stored currentElementProrperties will be E2's, // only the top of the stack is the real E1 element properties. protected unsafe void WriteHtmlElementTextBlock(char* pSrc, char* pSrcEnd) { if ((currentElementProperties & ElementProperties.NO_ENTITIES) != 0) { base.RawText(pSrc, pSrcEnd); } else { base.WriteElementTextBlock(pSrc, pSrcEnd); } } protected unsafe void WriteHtmlAttributeTextBlock(char* pSrc, char* pSrcEnd) { if ((_currentAttributeProperties & (AttributeProperties.BOOLEAN | AttributeProperties.URI | AttributeProperties.NAME)) != 0) { if ((_currentAttributeProperties & AttributeProperties.BOOLEAN) != 0) { //if output boolean attribute, ignore this call. return; } if ((_currentAttributeProperties & (AttributeProperties.URI | AttributeProperties.NAME)) != 0 && !_doNotEscapeUriAttributes) { WriteUriAttributeText(pSrc, pSrcEnd); } else { WriteHtmlAttributeText(pSrc, pSrcEnd); } } else if ((currentElementProperties & ElementProperties.HAS_NS) != 0) { base.WriteAttributeTextBlock(pSrc, pSrcEnd); } else { WriteHtmlAttributeText(pSrc, pSrcEnd); } } // // &{ split cases // 1). HtmlAttributeText("a&"); // HtmlAttributeText("{b}"); // // 2). HtmlAttributeText("a&"); // EndAttribute(); // 3).split with Flush by the user // HtmlAttributeText("a&"); // FlushBuffer(); // HtmlAttributeText("{b}"); // // Solutions: // case 1)hold the &amp; output as & // if the next income character is {, output { // else output amp; // private unsafe void WriteHtmlAttributeText(char* pSrc, char* pSrcEnd) { if (_endsWithAmpersand) { if (pSrcEnd - pSrc > 0 && pSrc[0] != '{') { OutputRestAmps(); } _endsWithAmpersand = false; } fixed (char* pDstBegin = bufChars) { char* pDst = pDstBegin + bufPos; char ch = (char)0; while (true) { char* pDstEnd = pDst + (pSrcEnd - pSrc); if (pDstEnd > pDstBegin + bufLen) { pDstEnd = pDstBegin + bufLen; } while (pDst < pDstEnd && xmlCharType.IsAttributeValueChar((char)(ch = *pSrc))) { *pDst++ = (char)ch; pSrc++; } Debug.Assert(pSrc <= pSrcEnd); // end of value if (pSrc >= pSrcEnd) { break; } // end of buffer if (pDst >= pDstEnd) { bufPos = (int)(pDst - pDstBegin); FlushBuffer(); pDst = pDstBegin + 1; continue; } // some character needs to be escaped switch (ch) { case '&': if (pSrc + 1 == pSrcEnd) { _endsWithAmpersand = true; } else if (pSrc[1] != '{') { pDst = AmpEntity(pDst); break; } *pDst++ = (char)ch; break; case '"': pDst = QuoteEntity(pDst); break; case '<': case '>': case '\'': case (char)0x9: *pDst++ = (char)ch; break; case (char)0xD: // do not normalize new lines in attributes - just escape them pDst = CarriageReturnEntity(pDst); break; case (char)0xA: // do not normalize new lines in attributes - just escape them pDst = LineFeedEntity(pDst); break; default: EncodeChar(ref pSrc, pSrcEnd, ref pDst); continue; } pSrc++; } bufPos = (int)(pDst - pDstBegin); } } private unsafe void WriteUriAttributeText(char* pSrc, char* pSrcEnd) { if (_endsWithAmpersand) { if (pSrcEnd - pSrc > 0 && pSrc[0] != '{') { OutputRestAmps(); } _endsWithAmpersand = false; } fixed (char* pDstBegin = bufChars) { char* pDst = pDstBegin + bufPos; char ch = (char)0; while (true) { char* pDstEnd = pDst + (pSrcEnd - pSrc); if (pDstEnd > pDstBegin + bufLen) { pDstEnd = pDstBegin + bufLen; } while (pDst < pDstEnd && (xmlCharType.IsAttributeValueChar((char)(ch = *pSrc)) && ch < 0x80)) { *pDst++ = (char)ch; pSrc++; } Debug.Assert(pSrc <= pSrcEnd); // end of value if (pSrc >= pSrcEnd) { break; } // end of buffer if (pDst >= pDstEnd) { bufPos = (int)(pDst - pDstBegin); FlushBuffer(); pDst = pDstBegin + 1; continue; } // some character needs to be escaped switch (ch) { case '&': if (pSrc + 1 == pSrcEnd) { _endsWithAmpersand = true; } else if (pSrc[1] != '{') { pDst = AmpEntity(pDst); break; } *pDst++ = (char)ch; break; case '"': pDst = QuoteEntity(pDst); break; case '<': case '>': case '\'': case (char)0x9: *pDst++ = (char)ch; break; case (char)0xD: // do not normalize new lines in attributes - just escape them pDst = CarriageReturnEntity(pDst); break; case (char)0xA: // do not normalize new lines in attributes - just escape them pDst = LineFeedEntity(pDst); break; default: const string hexDigits = "0123456789ABCDEF"; Debug.Assert(_uriEscapingBuffer?.Length > 0); fixed (byte* pUriEscapingBuffer = _uriEscapingBuffer) { byte* pByte = pUriEscapingBuffer; byte* pEnd = pByte; XmlUtf8RawTextWriter.CharToUTF8(ref pSrc, pSrcEnd, ref pEnd); while (pByte < pEnd) { *pDst++ = (char)'%'; *pDst++ = (char)hexDigits[*pByte >> 4]; *pDst++ = (char)hexDigits[*pByte & 0xF]; pByte++; } } continue; } pSrc++; } bufPos = (int)(pDst - pDstBegin); } } // For handling &{ in Html text field. If & is not followed by {, it still needs to be escaped. private void OutputRestAmps() { base.bufChars[bufPos++] = (char)'a'; base.bufChars[bufPos++] = (char)'m'; base.bufChars[bufPos++] = (char)'p'; base.bufChars[bufPos++] = (char)';'; } } // // Indentation HtmlWriter only indent <BLOCK><BLOCK> situations // // Here are all the cases: // ELEMENT1 actions ELEMENT2 actions SC EE // 1). SE SC store SE blockPro SE a). check ELEMENT1 blockPro <A> </A> // EE if SE, EE are blocks b). true: check ELEMENT2 blockPro <B> <B> // c). detect ELEMENT is SE, SC // d). increase the indexlevel // // 2). SE SC, Store EE blockPro EE a). check stored blockPro <A></A> </A> // EE if SE, EE are blocks b). true: indexLevel same </B> // // // This is an alternative way to make the output looks better // // Indentation HtmlWriter only indent <BLOCK><BLOCK> situations // // Here are all the cases: // ELEMENT1 actions ELEMENT2 actions Samples // 1). SE SC store SE blockPro SE a). check ELEMENT1 blockPro <A>(blockPos) // b). true: check ELEMENT2 blockPro <B> // c). detect ELEMENT is SE, SC // d). increase the indentLevel // // 2). EE Store EE blockPro SE a). check stored blockPro </A> // b). true: indentLevel same <B> // c). output block2 // // 3). EE same as above EE a). check stored blockPro </A> // b). true: --indentLevel </B> // c). output block2 // // 4). SE SC same as above EE a). check stored blockPro <A></A> // b). true: indentLevel no change internal class HtmlEncodedRawTextWriterIndent : HtmlEncodedRawTextWriter { // // Fields // private int _indentLevel; // for detecting SE SC sitution private int _endBlockPos; // settings private string _indentChars; private bool _newLineOnAttributes; // // Constructors // public HtmlEncodedRawTextWriterIndent(TextWriter writer, XmlWriterSettings settings) : base(writer, settings) { Init(settings); } public HtmlEncodedRawTextWriterIndent(Stream stream, XmlWriterSettings settings) : base(stream, settings) { Init(settings); } // // XmlRawWriter overrides // /// <summary> /// Serialize the document type declaration. /// </summary> public override void WriteDocType(string name, string pubid, string sysid, string subset) { base.WriteDocType(name, pubid, sysid, subset); // Allow indentation after DocTypeDecl _endBlockPos = base.bufPos; } public override void WriteStartElement(string prefix, string localName, string ns) { Debug.Assert(localName != null && localName.Length != 0 && prefix != null && ns != null); if (trackTextContent && inTextContent != false) { ChangeTextContentMark(false); } base.elementScope.Push((byte)base.currentElementProperties); if (ns.Length == 0) { Debug.Assert(prefix.Length == 0); base.currentElementProperties = (ElementProperties)elementPropertySearch.FindCaseInsensitiveString(localName); if (_endBlockPos == base.bufPos && (base.currentElementProperties & ElementProperties.BLOCK_WS) != 0) { WriteIndent(); } _indentLevel++; base.bufChars[bufPos++] = (char)'<'; } else { base.currentElementProperties = ElementProperties.HAS_NS | ElementProperties.BLOCK_WS; if (_endBlockPos == base.bufPos) { WriteIndent(); } _indentLevel++; base.bufChars[base.bufPos++] = (char)'<'; if (prefix.Length != 0) { base.RawText(prefix); base.bufChars[base.bufPos++] = (char)':'; } } base.RawText(localName); base.attrEndPos = bufPos; } internal override void StartElementContent() { base.bufChars[base.bufPos++] = (char)'>'; // Detect whether content is output base.contentPos = base.bufPos; if ((currentElementProperties & ElementProperties.HEAD) != 0) { WriteIndent(); WriteMetaElement(); _endBlockPos = base.bufPos; } else if ((base.currentElementProperties & ElementProperties.BLOCK_WS) != 0) { // store the element block position _endBlockPos = base.bufPos; } } internal override void WriteEndElement(string prefix, string localName, string ns) { bool isBlockWs; Debug.Assert(localName != null && localName.Length != 0 && prefix != null && ns != null); _indentLevel--; // If this element has block whitespace properties, isBlockWs = (base.currentElementProperties & ElementProperties.BLOCK_WS) != 0; if (isBlockWs) { // And if the last node to be output had block whitespace properties, // And if content was output within this element, if (_endBlockPos == base.bufPos && base.contentPos != base.bufPos) { // Then indent WriteIndent(); } } base.WriteEndElement(prefix, localName, ns); // Reset contentPos in case of empty elements base.contentPos = 0; // Mark end of element in buffer for element's with block whitespace properties if (isBlockWs) { _endBlockPos = base.bufPos; } } public override void WriteStartAttribute(string prefix, string localName, string ns) { if (_newLineOnAttributes) { RawText(base.newLineChars); _indentLevel++; WriteIndent(); _indentLevel--; } base.WriteStartAttribute(prefix, localName, ns); } protected override void FlushBuffer() { // Make sure the buffer will reset the block position _endBlockPos = (_endBlockPos == base.bufPos) ? 1 : 0; base.FlushBuffer(); } // // Private methods // private void Init(XmlWriterSettings settings) { _indentLevel = 0; _indentChars = settings.IndentChars; _newLineOnAttributes = settings.NewLineOnAttributes; } private void WriteIndent() { // <block><inline> -- suppress ws betw <block> and <inline> // <block><block> -- don't suppress ws betw <block> and <block> // <block>text -- suppress ws betw <block> and text (handled by wcharText method) // <block><?PI?> -- suppress ws betw <block> and PI // <block><!-- --> -- suppress ws betw <block> and comment // <inline><block> -- suppress ws betw <inline> and <block> // <inline><inline> -- suppress ws betw <inline> and <inline> // <inline>text -- suppress ws betw <inline> and text (handled by wcharText method) // <inline><?PI?> -- suppress ws betw <inline> and PI // <inline><!-- --> -- suppress ws betw <inline> and comment RawText(base.newLineChars); for (int i = _indentLevel; i > 0; i--) { RawText(_indentChars); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace AwesomeNamespace { using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; /// <summary> /// The Storage Management Client. /// </summary> public partial class StorageManagementClient : ServiceClient<StorageManagementClient>, IStorageManagementClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets subscription credentials which uniquely identify Microsoft Azure /// subscription. The subscription ID forms part of the URI for every service /// call. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// Client Api Version. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IStorageAccountsOperations. /// </summary> public virtual IStorageAccountsOperations StorageAccounts { get; private set; } /// <summary> /// Gets the IUsageOperations. /// </summary> public virtual IUsageOperations Usage { get; private set; } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected StorageManagementClient(params DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected StorageManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected StorageManagementClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected StorageManagementClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public StorageManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public StorageManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public StorageManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public StorageManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { StorageAccounts = new StorageAccountsOperations(this); Usage = new UsageOperations(this); BaseUri = new System.Uri("https://management.azure.com"); ApiVersion = "2015-06-15"; AcceptLanguage = "en-US"; LongRunningOperationRetryTimeout = 30; GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
//------------------------------------------------------------------------------ // <copyright file="MultiDirectionTestBase.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation // </copyright> //------------------------------------------------------------------------------ namespace DMLibTest { using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Threading.Tasks; using DMLibTestCodeGen; using Microsoft.VisualStudio.TestTools.UnitTesting; using MS.Test.Common.MsTestLib; public enum StopDMLibType { None, Kill, TestHookCtrlC, BreakNetwork } public enum SourceOrDest { Source, Dest, } public abstract class MultiDirectionTestBase<TDataInfo, TDataType> where TDataInfo : IDataInfo where TDataType : struct { public const string SourceRoot = "sourceroot"; public const string DestRoot = "destroot"; public const string SourceFolder = "sourcefolder"; public const string DestFolder = "destfolder"; protected static Random random = new Random(); private static Dictionary<string, DataAdaptor<TDataInfo>> sourceAdaptors = new Dictionary<string, DataAdaptor<TDataInfo>>(); private static Dictionary<string, DataAdaptor<TDataInfo>> destAdaptors = new Dictionary<string, DataAdaptor<TDataInfo>>(); private TestContext testContextInstance; /// <summary> ///Gets or sets the test context which provides ///information about and functionality for the current test run. ///</summary> public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } public static string NetworkShare { get; set; } public static bool CleanupSource { get; set; } public static bool CleanupDestination { get; set; } public static DataAdaptor<TDataInfo> SourceAdaptor { get { return GetSourceAdaptor(MultiDirectionTestContext<TDataType>.SourceType); } } public static DataAdaptor<TDataInfo> DestAdaptor { get { return GetDestAdaptor(MultiDirectionTestContext<TDataType>.DestType); } } public static void BaseClassInitialize(TestContext testContext) { Test.Info("ClassInitialize"); #if !DNXCORE50 Test.FullClassName = testContext.FullyQualifiedTestClassName; #endif MultiDirectionTestBase<TDataInfo, TDataType>.CleanupSource = true; MultiDirectionTestBase<TDataInfo, TDataType>.CleanupDestination = true; NetworkShare = Test.Data.Get("NetworkFolder"); } public static void BaseClassCleanup() { Test.Info("ClassCleanup"); //DeleteAllLocations(sourceAdaptors); //DeleteAllLocations(destAdaptors); Test.Info("ClassCleanup done."); } private static void DeleteAllLocations(Dictionary<string, DataAdaptor<TDataInfo>> adaptorDic) { Parallel.ForEach(adaptorDic, pair => { try { pair.Value.DeleteLocation(); } catch { Test.Warn("Fail to delete location for data adaptor: {0}", pair.Key); } }); } public virtual void BaseTestInitialize() { #if !DNXCORE50 Test.Start(TestContext.FullyQualifiedTestClassName, TestContext.TestName); #endif Test.Info("TestInitialize"); MultiDirectionTestInfo.Cleanup(); } public virtual void BaseTestCleanup() { if (Test.ErrorCount > 0) { MultiDirectionTestInfo.Print(); } Test.Info("TestCleanup"); #if !DNXCORE50 Test.End(TestContext.FullyQualifiedTestClassName, TestContext.TestName); #endif try { this.CleanupData(); MultiDirectionTestBase<TDataInfo, TDataType>.SourceAdaptor.Reset(); MultiDirectionTestBase<TDataInfo, TDataType>.DestAdaptor.Reset(); } catch { // ignore exception } } public virtual void CleanupData() { this.CleanupData( MultiDirectionTestBase<TDataInfo, TDataType>.CleanupSource, MultiDirectionTestBase<TDataInfo, TDataType>.CleanupDestination); } protected void CleanupData(bool cleanupSource, bool cleanupDestination) { if (cleanupSource) { MultiDirectionTestBase<TDataInfo, TDataType>.SourceAdaptor.Cleanup(); } if (cleanupDestination) { MultiDirectionTestBase<TDataInfo, TDataType>.DestAdaptor.Cleanup(); } } protected static string GetLocationKey(TDataType dataType) { return dataType.ToString(); } public static DataAdaptor<TDataInfo> GetSourceAdaptor(TDataType dataType) { string key = MultiDirectionTestBase<TDataInfo, TDataType>.GetLocationKey(dataType); if (!sourceAdaptors.ContainsKey(key)) { throw new KeyNotFoundException( string.Format("Can't find key of source data adaptor. DataType:{0}.", dataType.ToString())); } return sourceAdaptors[key]; } public static DataAdaptor<TDataInfo> GetDestAdaptor(TDataType dataType) { string key = MultiDirectionTestBase<TDataInfo, TDataType>.GetLocationKey(dataType); if (!destAdaptors.ContainsKey(key)) { throw new KeyNotFoundException( string.Format("Can't find key of destination data adaptor. DataType:{0}.", dataType.ToString())); } return destAdaptors[key]; } protected static void SetSourceAdaptor(TDataType dataType, DataAdaptor<TDataInfo> adaptor) { string key = MultiDirectionTestBase<TDataInfo, TDataType>.GetLocationKey(dataType); sourceAdaptors[key] = adaptor; } protected static void SetDestAdaptor(TDataType dataType, DataAdaptor<TDataInfo> adaptor) { string key = MultiDirectionTestBase<TDataInfo, TDataType>.GetLocationKey(dataType); destAdaptors[key] = adaptor; } public abstract bool IsCloudService(TDataType dataType); public static CredentialType GetRandomCredentialType() { int credentialCount = Enum.GetNames(typeof(CredentialType)).Length; int randomNum = MultiDirectionTestBase<TDataInfo, TDataType>.random.Next(0, credentialCount); CredentialType result; switch (randomNum) { case 0: result = CredentialType.None; break; case 1: result = CredentialType.Public; break; case 2: result = CredentialType.Key; break; case 3: result = CredentialType.SAS; break; default: result = CredentialType.EmbeddedSAS; break; } Test.Info("Random credential type: {0}", result.ToString()); return result; } protected static string GetRelativePath(string basePath, string fullPath) { string normalizedBasePath = MultiDirectionTestBase<TDataInfo, TDataType>.NormalizePath(basePath); string normalizedFullPath = MultiDirectionTestBase<TDataInfo, TDataType>.NormalizePath(fullPath); int index = normalizedFullPath.IndexOf(normalizedBasePath); if (index < 0) { return null; } return normalizedFullPath.Substring(index + normalizedBasePath.Length); } protected static string NormalizePath(string path) { if (path.StartsWith("\"") && path.EndsWith("\"")) { path = path.Substring(1, path.Length - 2); } try { var uri = new Uri(path); return uri.GetComponents(UriComponents.Path, UriFormat.Unescaped); } catch (UriFormatException) { return path; } } } public enum CredentialType { None = 0, Public, Key, SAS, EmbeddedSAS, } }
using System.Collections.Generic; using System.Linq; using UnityEngine; namespace Oxide.Plugins { [Info("Hooks Test", "Oxide Team", 0.1)] public class HooksTest : RustPlugin { int hookCount = 0; int hooksVerified; Dictionary<string, bool> hooksRemaining = new Dictionary<string, bool>(); public void HookCalled(string name) { if (!hooksRemaining.ContainsKey(name)) return; hookCount--; hooksVerified++; PrintWarning("{0} is working. {1} hooks verified!", name, hooksVerified); hooksRemaining.Remove(name); if (hookCount == 0) PrintWarning("All hooks verified!"); else PrintWarning("{0} hooks remaining: " + string.Join(", ", hooksRemaining.Keys.ToArray()), hookCount); } #region Plugin Hooks private void Init() { hookCount = hooks.Count; hooksRemaining = hooks.Keys.ToDictionary(k => k, k => true); PrintWarning("{0} hook to test!", hookCount); HookCalled("Init"); } public void Loaded() { HookCalled("Loaded"); } protected override void LoadDefaultConfig() { HookCalled("LoadDefaultConfig"); } private void Unloaded() { HookCalled("Unloaded"); // TODO: Unload plugin and store state in config } #endregion #region Server Hooks private void BuildServerTags(IList<string> tags) { HookCalled("BuildServerTags"); // TODO: Print new tags } private void OnFrame() { HookCalled("OnFrame"); } private void OnTick() { HookCalled("OnTick"); } private void OnTerrainInitialized() { HookCalled("OnTerrainInitialized"); } private void OnServerInitialized() { HookCalled("OnServerInitialized"); } private void OnServerSave() { HookCalled("OnServerSave"); } private void OnServerShutdown() { HookCalled("OnServerShutdown"); } private void OnRunCommand(ConsoleSystem.Arg arg) { HookCalled("OnRunCommand"); // TODO: Run test command // TODO: Print command messages } #endregion #region Player Hooks private void OnUserApprove(Network.Connection connection) { HookCalled("OnUserApprove"); } private void CanClientLogin(Network.Connection connection) { HookCalled("CanClientLogin"); } private void OnPlayerConnected(Network.Message packet) { HookCalled("OnPlayerConnected"); // TODO: Print player connected } private void OnPlayerDisconnected(BasePlayer player, string reason) { HookCalled("OnPlayerDisconnected"); // TODO: Print player disconnected } private void OnPlayerInit(BasePlayer player) { HookCalled("OnPlayerInit"); // TODO: Force admin to spawn/wakeup } private void OnFindSpawnPoint() { HookCalled("OnFindSpawnPoint"); // TODO: Print spawn point } private void OnPlayerRespawned(BasePlayer player) { HookCalled("OnPlayerRespawned"); // TODO: Print respawn location // TODO: Print start metabolism values // TODO: Give admin items for testing } private void OnPlayerChat(ConsoleSystem.Arg arg) { HookCalled("OnPlayerChat"); } private void OnPlayerLoot(PlayerLoot lootInventory, BaseEntity targetEntity) //private void OnPlayerLoot(PlayerLoot lootInventory, BasePlayer targetPlayer) //private void OnPlayerLoot(PlayerLoot lootInventory, Item targetItem) { HookCalled("OnPlayerLoot"); } private void OnPlayerInput(BasePlayer player, InputState input) { HookCalled("OnPlayerInput"); } private void OnRunPlayerMetabolism(PlayerMetabolism metabolism) { HookCalled("OnRunPlayerMetabolism"); // TODO: Print new metabolism values } #endregion #region Entity Hooks private void OnEntityTakeDamage(MonoBehaviour entity, HitInfo hitInfo) { HookCalled("OnEntityTakeDamage"); } private void OnEntityBuilt(Planner planner, GameObject gameObject) { HookCalled("OnEntityBuilt"); } private void OnEntityDeath(MonoBehaviour entity, HitInfo hitInfo) { HookCalled("OnEntityDeath"); // TODO: Print player died // TODO: Automatically respawn admin after X time } private void OnEntityEnter(TriggerBase triggerBase, BaseEntity entity) { HookCalled("OnEntityEnter"); } private void OnEntityLeave(TriggerBase triggerBase, BaseEntity entity) { HookCalled("OnEntityLeave"); } private void OnEntitySpawned(MonoBehaviour entity) { HookCalled("OnEntitySpawned"); } #endregion #region Item Hooks private void OnItemCraft(ItemCraftTask item) { HookCalled("OnItemCraft"); // TODO: Print item crafting } private void OnItemDeployed(Deployer deployer, BaseEntity deployedEntity) { HookCalled("OnItemDeployed"); // TODO: Print item deployed } private void OnItemPickup(BasePlayer player, Item item) { HookCalled("OnItemPickup"); } private void OnItemAddedToContainer(ItemContainer container, Item item) { HookCalled("OnItemAddedToContainer"); // TODO: Print item added } private void OnItemRemovedFromContainer(ItemContainer container, Item item) { HookCalled("OnItemRemovedToContainer"); // TODO: Print item removed } private void OnConsumableUse(Item item) { HookCalled("OnConsumableUse"); // TODO: Print consumable item used } private void OnConsumeFuel(BaseOven oven, Item fuel, ItemModBurnable burnable) { HookCalled("OnConsumeFuel"); // TODO: Print fuel consumed } private void OnDispenserGather(ResourceDispenser dispenser, BaseEntity entity, Item item) { HookCalled("OnDispenserGather"); // TODO: Print item to be gathered } private void OnPlantGather(PlantEntity plant, Item item, BasePlayer player) { HookCalled("OnPlantGather"); // TODO: Print item to be gathered } private void OnSurveyGather(SurveyCharge surveyCharge, Item item) { HookCalled("OnSurveyGather"); } private void OnQuarryGather(MiningQuarry miningQuarry, Item item) { HookCalled("OnQuarryGather"); } private void OnQuarryEnabled() { HookCalled("OnQuarryEnabled"); } private void OnTrapArm(BearTrap trap) { HookCalled("OnTrapArm"); } private void OnTrapSnapped(BaseTrapTrigger trap, GameObject go) { HookCalled("OnTrapSnapped"); } private void OnTrapTrigger(BaseTrap trap, GameObject go) { HookCalled("OnTrapTrigger"); } #endregion #region Structure Hooks private void CanUseDoor(BasePlayer player, BaseLock door) //private void CanUseDoor(BasePlayer player, CodeLock doorCode) //private void CanUseDoor(BasePlayer player, KeyLock doorKey) { HookCalled("CanUseDoor"); } private void OnStructureDemolish(BuildingBlock block, BasePlayer player) { HookCalled("OnStructureDemolish"); } private void OnStructureRepair(BuildingBlock block, BasePlayer player) { HookCalled("OnStructureRepair"); } private void OnStructureRotate(BuildingBlock block, BasePlayer player) { HookCalled("OnStructureRotate"); } private void OnStructureUpgrade(BuildingBlock block, BasePlayer player, BuildingGrade.Enum grade) { HookCalled("OnStructureUpgrade"); } private void OnHammerHit(BasePlayer player, HitInfo info) { HookCalled("OnHammerHit"); } #endregion private void OnAirdrop(CargoPlane plane, Vector3 dropLocation) { HookCalled("OnAirdrop"); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: user-management/user_management_service.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace KillrVideo.UserManagement { /// <summary>Holder for reflection information generated from user-management/user_management_service.proto</summary> public static partial class UserManagementServiceReflection { #region Descriptor /// <summary>File descriptor for user-management/user_management_service.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static UserManagementServiceReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Ci11c2VyLW1hbmFnZW1lbnQvdXNlcl9tYW5hZ2VtZW50X3NlcnZpY2UucHJv", "dG8SGmtpbGxydmlkZW8udXNlcl9tYW5hZ2VtZW50Ghljb21tb24vY29tbW9u", "X3R5cGVzLnByb3RvIoUBChFDcmVhdGVVc2VyUmVxdWVzdBIoCgd1c2VyX2lk", "GAEgASgLMhcua2lsbHJ2aWRlby5jb21tb24uVXVpZBISCgpmaXJzdF9uYW1l", "GAIgASgJEhEKCWxhc3RfbmFtZRgDIAEoCRINCgVlbWFpbBgEIAEoCRIQCghw", "YXNzd29yZBgFIAEoCSIUChJDcmVhdGVVc2VyUmVzcG9uc2UiOwoYVmVyaWZ5", "Q3JlZGVudGlhbHNSZXF1ZXN0Eg0KBWVtYWlsGAEgASgJEhAKCHBhc3N3b3Jk", "GAIgASgJIkUKGVZlcmlmeUNyZWRlbnRpYWxzUmVzcG9uc2USKAoHdXNlcl9p", "ZBgBIAEoCzIXLmtpbGxydmlkZW8uY29tbW9uLlV1aWQiQgoVR2V0VXNlclBy", "b2ZpbGVSZXF1ZXN0EikKCHVzZXJfaWRzGAEgAygLMhcua2lsbHJ2aWRlby5j", "b21tb24uVXVpZCJTChZHZXRVc2VyUHJvZmlsZVJlc3BvbnNlEjkKCHByb2Zp", "bGVzGAEgAygLMicua2lsbHJ2aWRlby51c2VyX21hbmFnZW1lbnQuVXNlclBy", "b2ZpbGUibQoLVXNlclByb2ZpbGUSKAoHdXNlcl9pZBgBIAEoCzIXLmtpbGxy", "dmlkZW8uY29tbW9uLlV1aWQSEgoKZmlyc3RfbmFtZRgCIAEoCRIRCglsYXN0", "X25hbWUYAyABKAkSDQoFZW1haWwYBCABKAkygAMKFVVzZXJNYW5hZ2VtZW50", "U2VydmljZRJrCgpDcmVhdGVVc2VyEi0ua2lsbHJ2aWRlby51c2VyX21hbmFn", "ZW1lbnQuQ3JlYXRlVXNlclJlcXVlc3QaLi5raWxscnZpZGVvLnVzZXJfbWFu", "YWdlbWVudC5DcmVhdGVVc2VyUmVzcG9uc2USgAEKEVZlcmlmeUNyZWRlbnRp", "YWxzEjQua2lsbHJ2aWRlby51c2VyX21hbmFnZW1lbnQuVmVyaWZ5Q3JlZGVu", "dGlhbHNSZXF1ZXN0GjUua2lsbHJ2aWRlby51c2VyX21hbmFnZW1lbnQuVmVy", "aWZ5Q3JlZGVudGlhbHNSZXNwb25zZRJ3Cg5HZXRVc2VyUHJvZmlsZRIxLmtp", "bGxydmlkZW8udXNlcl9tYW5hZ2VtZW50LkdldFVzZXJQcm9maWxlUmVxdWVz", "dBoyLmtpbGxydmlkZW8udXNlcl9tYW5hZ2VtZW50LkdldFVzZXJQcm9maWxl", "UmVzcG9uc2VCHKoCGUtpbGxyVmlkZW8uVXNlck1hbmFnZW1lbnRiBnByb3Rv", "Mw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::KillrVideo.Protobuf.CommonTypesReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::KillrVideo.UserManagement.CreateUserRequest), global::KillrVideo.UserManagement.CreateUserRequest.Parser, new[]{ "UserId", "FirstName", "LastName", "Email", "Password" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::KillrVideo.UserManagement.CreateUserResponse), global::KillrVideo.UserManagement.CreateUserResponse.Parser, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::KillrVideo.UserManagement.VerifyCredentialsRequest), global::KillrVideo.UserManagement.VerifyCredentialsRequest.Parser, new[]{ "Email", "Password" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::KillrVideo.UserManagement.VerifyCredentialsResponse), global::KillrVideo.UserManagement.VerifyCredentialsResponse.Parser, new[]{ "UserId" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::KillrVideo.UserManagement.GetUserProfileRequest), global::KillrVideo.UserManagement.GetUserProfileRequest.Parser, new[]{ "UserIds" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::KillrVideo.UserManagement.GetUserProfileResponse), global::KillrVideo.UserManagement.GetUserProfileResponse.Parser, new[]{ "Profiles" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::KillrVideo.UserManagement.UserProfile), global::KillrVideo.UserManagement.UserProfile.Parser, new[]{ "UserId", "FirstName", "LastName", "Email" }, null, null, null) })); } #endregion } #region Messages /// <summary> /// Request to create a new user /// </summary> public sealed partial class CreateUserRequest : pb::IMessage<CreateUserRequest> { private static readonly pb::MessageParser<CreateUserRequest> _parser = new pb::MessageParser<CreateUserRequest>(() => new CreateUserRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<CreateUserRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::KillrVideo.UserManagement.UserManagementServiceReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CreateUserRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CreateUserRequest(CreateUserRequest other) : this() { UserId = other.userId_ != null ? other.UserId.Clone() : null; firstName_ = other.firstName_; lastName_ = other.lastName_; email_ = other.email_; password_ = other.password_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CreateUserRequest Clone() { return new CreateUserRequest(this); } /// <summary>Field number for the "user_id" field.</summary> public const int UserIdFieldNumber = 1; private global::KillrVideo.Protobuf.Uuid userId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::KillrVideo.Protobuf.Uuid UserId { get { return userId_; } set { userId_ = value; } } /// <summary>Field number for the "first_name" field.</summary> public const int FirstNameFieldNumber = 2; private string firstName_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string FirstName { get { return firstName_; } set { firstName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "last_name" field.</summary> public const int LastNameFieldNumber = 3; private string lastName_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string LastName { get { return lastName_; } set { lastName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "email" field.</summary> public const int EmailFieldNumber = 4; private string email_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Email { get { return email_; } set { email_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "password" field.</summary> public const int PasswordFieldNumber = 5; private string password_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Password { get { return password_; } set { password_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as CreateUserRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(CreateUserRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(UserId, other.UserId)) return false; if (FirstName != other.FirstName) return false; if (LastName != other.LastName) return false; if (Email != other.Email) return false; if (Password != other.Password) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (userId_ != null) hash ^= UserId.GetHashCode(); if (FirstName.Length != 0) hash ^= FirstName.GetHashCode(); if (LastName.Length != 0) hash ^= LastName.GetHashCode(); if (Email.Length != 0) hash ^= Email.GetHashCode(); if (Password.Length != 0) hash ^= Password.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (userId_ != null) { output.WriteRawTag(10); output.WriteMessage(UserId); } if (FirstName.Length != 0) { output.WriteRawTag(18); output.WriteString(FirstName); } if (LastName.Length != 0) { output.WriteRawTag(26); output.WriteString(LastName); } if (Email.Length != 0) { output.WriteRawTag(34); output.WriteString(Email); } if (Password.Length != 0) { output.WriteRawTag(42); output.WriteString(Password); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (userId_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(UserId); } if (FirstName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(FirstName); } if (LastName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(LastName); } if (Email.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Email); } if (Password.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Password); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(CreateUserRequest other) { if (other == null) { return; } if (other.userId_ != null) { if (userId_ == null) { userId_ = new global::KillrVideo.Protobuf.Uuid(); } UserId.MergeFrom(other.UserId); } if (other.FirstName.Length != 0) { FirstName = other.FirstName; } if (other.LastName.Length != 0) { LastName = other.LastName; } if (other.Email.Length != 0) { Email = other.Email; } if (other.Password.Length != 0) { Password = other.Password; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (userId_ == null) { userId_ = new global::KillrVideo.Protobuf.Uuid(); } input.ReadMessage(userId_); break; } case 18: { FirstName = input.ReadString(); break; } case 26: { LastName = input.ReadString(); break; } case 34: { Email = input.ReadString(); break; } case 42: { Password = input.ReadString(); break; } } } } } /// <summary> /// Response when creating a new user /// </summary> public sealed partial class CreateUserResponse : pb::IMessage<CreateUserResponse> { private static readonly pb::MessageParser<CreateUserResponse> _parser = new pb::MessageParser<CreateUserResponse>(() => new CreateUserResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<CreateUserResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::KillrVideo.UserManagement.UserManagementServiceReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CreateUserResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CreateUserResponse(CreateUserResponse other) : this() { } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CreateUserResponse Clone() { return new CreateUserResponse(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as CreateUserResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(CreateUserResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(CreateUserResponse other) { if (other == null) { return; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; } } } } /// <summary> /// Request to verify a user's credentials (i.e. for logging them in) /// </summary> public sealed partial class VerifyCredentialsRequest : pb::IMessage<VerifyCredentialsRequest> { private static readonly pb::MessageParser<VerifyCredentialsRequest> _parser = new pb::MessageParser<VerifyCredentialsRequest>(() => new VerifyCredentialsRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<VerifyCredentialsRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::KillrVideo.UserManagement.UserManagementServiceReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public VerifyCredentialsRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public VerifyCredentialsRequest(VerifyCredentialsRequest other) : this() { email_ = other.email_; password_ = other.password_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public VerifyCredentialsRequest Clone() { return new VerifyCredentialsRequest(this); } /// <summary>Field number for the "email" field.</summary> public const int EmailFieldNumber = 1; private string email_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Email { get { return email_; } set { email_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "password" field.</summary> public const int PasswordFieldNumber = 2; private string password_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Password { get { return password_; } set { password_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as VerifyCredentialsRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(VerifyCredentialsRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Email != other.Email) return false; if (Password != other.Password) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Email.Length != 0) hash ^= Email.GetHashCode(); if (Password.Length != 0) hash ^= Password.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Email.Length != 0) { output.WriteRawTag(10); output.WriteString(Email); } if (Password.Length != 0) { output.WriteRawTag(18); output.WriteString(Password); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Email.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Email); } if (Password.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Password); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(VerifyCredentialsRequest other) { if (other == null) { return; } if (other.Email.Length != 0) { Email = other.Email; } if (other.Password.Length != 0) { Password = other.Password; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Email = input.ReadString(); break; } case 18: { Password = input.ReadString(); break; } } } } } /// <summary> /// Response that indicates the user's id if the credentials were correct /// </summary> public sealed partial class VerifyCredentialsResponse : pb::IMessage<VerifyCredentialsResponse> { private static readonly pb::MessageParser<VerifyCredentialsResponse> _parser = new pb::MessageParser<VerifyCredentialsResponse>(() => new VerifyCredentialsResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<VerifyCredentialsResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::KillrVideo.UserManagement.UserManagementServiceReflection.Descriptor.MessageTypes[3]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public VerifyCredentialsResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public VerifyCredentialsResponse(VerifyCredentialsResponse other) : this() { UserId = other.userId_ != null ? other.UserId.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public VerifyCredentialsResponse Clone() { return new VerifyCredentialsResponse(this); } /// <summary>Field number for the "user_id" field.</summary> public const int UserIdFieldNumber = 1; private global::KillrVideo.Protobuf.Uuid userId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::KillrVideo.Protobuf.Uuid UserId { get { return userId_; } set { userId_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as VerifyCredentialsResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(VerifyCredentialsResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(UserId, other.UserId)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (userId_ != null) hash ^= UserId.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (userId_ != null) { output.WriteRawTag(10); output.WriteMessage(UserId); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (userId_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(UserId); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(VerifyCredentialsResponse other) { if (other == null) { return; } if (other.userId_ != null) { if (userId_ == null) { userId_ = new global::KillrVideo.Protobuf.Uuid(); } UserId.MergeFrom(other.UserId); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (userId_ == null) { userId_ = new global::KillrVideo.Protobuf.Uuid(); } input.ReadMessage(userId_); break; } } } } } /// <summary> /// Request to get a user or multiple users profiles /// </summary> public sealed partial class GetUserProfileRequest : pb::IMessage<GetUserProfileRequest> { private static readonly pb::MessageParser<GetUserProfileRequest> _parser = new pb::MessageParser<GetUserProfileRequest>(() => new GetUserProfileRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<GetUserProfileRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::KillrVideo.UserManagement.UserManagementServiceReflection.Descriptor.MessageTypes[4]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetUserProfileRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetUserProfileRequest(GetUserProfileRequest other) : this() { userIds_ = other.userIds_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetUserProfileRequest Clone() { return new GetUserProfileRequest(this); } /// <summary>Field number for the "user_ids" field.</summary> public const int UserIdsFieldNumber = 1; private static readonly pb::FieldCodec<global::KillrVideo.Protobuf.Uuid> _repeated_userIds_codec = pb::FieldCodec.ForMessage(10, global::KillrVideo.Protobuf.Uuid.Parser); private readonly pbc::RepeatedField<global::KillrVideo.Protobuf.Uuid> userIds_ = new pbc::RepeatedField<global::KillrVideo.Protobuf.Uuid>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::KillrVideo.Protobuf.Uuid> UserIds { get { return userIds_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as GetUserProfileRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(GetUserProfileRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!userIds_.Equals(other.userIds_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= userIds_.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { userIds_.WriteTo(output, _repeated_userIds_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += userIds_.CalculateSize(_repeated_userIds_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(GetUserProfileRequest other) { if (other == null) { return; } userIds_.Add(other.userIds_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { userIds_.AddEntriesFrom(input, _repeated_userIds_codec); break; } } } } } /// <summary> /// Response with user profiles /// </summary> public sealed partial class GetUserProfileResponse : pb::IMessage<GetUserProfileResponse> { private static readonly pb::MessageParser<GetUserProfileResponse> _parser = new pb::MessageParser<GetUserProfileResponse>(() => new GetUserProfileResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<GetUserProfileResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::KillrVideo.UserManagement.UserManagementServiceReflection.Descriptor.MessageTypes[5]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetUserProfileResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetUserProfileResponse(GetUserProfileResponse other) : this() { profiles_ = other.profiles_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetUserProfileResponse Clone() { return new GetUserProfileResponse(this); } /// <summary>Field number for the "profiles" field.</summary> public const int ProfilesFieldNumber = 1; private static readonly pb::FieldCodec<global::KillrVideo.UserManagement.UserProfile> _repeated_profiles_codec = pb::FieldCodec.ForMessage(10, global::KillrVideo.UserManagement.UserProfile.Parser); private readonly pbc::RepeatedField<global::KillrVideo.UserManagement.UserProfile> profiles_ = new pbc::RepeatedField<global::KillrVideo.UserManagement.UserProfile>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::KillrVideo.UserManagement.UserProfile> Profiles { get { return profiles_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as GetUserProfileResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(GetUserProfileResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!profiles_.Equals(other.profiles_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= profiles_.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { profiles_.WriteTo(output, _repeated_profiles_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += profiles_.CalculateSize(_repeated_profiles_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(GetUserProfileResponse other) { if (other == null) { return; } profiles_.Add(other.profiles_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { profiles_.AddEntriesFrom(input, _repeated_profiles_codec); break; } } } } } /// <summary> /// A user's profile information /// </summary> public sealed partial class UserProfile : pb::IMessage<UserProfile> { private static readonly pb::MessageParser<UserProfile> _parser = new pb::MessageParser<UserProfile>(() => new UserProfile()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<UserProfile> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::KillrVideo.UserManagement.UserManagementServiceReflection.Descriptor.MessageTypes[6]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UserProfile() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UserProfile(UserProfile other) : this() { UserId = other.userId_ != null ? other.UserId.Clone() : null; firstName_ = other.firstName_; lastName_ = other.lastName_; email_ = other.email_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UserProfile Clone() { return new UserProfile(this); } /// <summary>Field number for the "user_id" field.</summary> public const int UserIdFieldNumber = 1; private global::KillrVideo.Protobuf.Uuid userId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::KillrVideo.Protobuf.Uuid UserId { get { return userId_; } set { userId_ = value; } } /// <summary>Field number for the "first_name" field.</summary> public const int FirstNameFieldNumber = 2; private string firstName_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string FirstName { get { return firstName_; } set { firstName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "last_name" field.</summary> public const int LastNameFieldNumber = 3; private string lastName_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string LastName { get { return lastName_; } set { lastName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "email" field.</summary> public const int EmailFieldNumber = 4; private string email_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Email { get { return email_; } set { email_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as UserProfile); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(UserProfile other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(UserId, other.UserId)) return false; if (FirstName != other.FirstName) return false; if (LastName != other.LastName) return false; if (Email != other.Email) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (userId_ != null) hash ^= UserId.GetHashCode(); if (FirstName.Length != 0) hash ^= FirstName.GetHashCode(); if (LastName.Length != 0) hash ^= LastName.GetHashCode(); if (Email.Length != 0) hash ^= Email.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (userId_ != null) { output.WriteRawTag(10); output.WriteMessage(UserId); } if (FirstName.Length != 0) { output.WriteRawTag(18); output.WriteString(FirstName); } if (LastName.Length != 0) { output.WriteRawTag(26); output.WriteString(LastName); } if (Email.Length != 0) { output.WriteRawTag(34); output.WriteString(Email); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (userId_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(UserId); } if (FirstName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(FirstName); } if (LastName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(LastName); } if (Email.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Email); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(UserProfile other) { if (other == null) { return; } if (other.userId_ != null) { if (userId_ == null) { userId_ = new global::KillrVideo.Protobuf.Uuid(); } UserId.MergeFrom(other.UserId); } if (other.FirstName.Length != 0) { FirstName = other.FirstName; } if (other.LastName.Length != 0) { LastName = other.LastName; } if (other.Email.Length != 0) { Email = other.Email; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (userId_ == null) { userId_ = new global::KillrVideo.Protobuf.Uuid(); } input.ReadMessage(userId_); break; } case 18: { FirstName = input.ReadString(); break; } case 26: { LastName = input.ReadString(); break; } case 34: { Email = input.ReadString(); break; } } } } } #endregion } #endregion Designer generated code
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System.Collections.Generic; using System.Reflection; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications.Limit; using OpenSim.Framework.Statistics; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.CoreModules.Agent.TextureDownload { /// <summary> /// This module sets up texture senders in response to client texture requests, and places them on a /// processing queue once those senders have the appropriate data (i.e. a texture retrieved from the /// asset cache). /// </summary> public class UserTextureDownloadService { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// True if the service has been closed, probably because a user with texture requests still queued /// logged out. /// </summary> private bool closed; /// <summary> /// We will allow the client to request the same texture n times before dropping further requests /// /// This number includes repeated requests for the same texture at different resolutions (which we don't /// currently handle properly as far as I know). However, this situation should be handled in a more /// sophisticated way. /// </summary> private static readonly int MAX_ALLOWED_TEXTURE_REQUESTS = 5; /// <summary> /// XXX Also going to limit requests for found textures. /// </summary> private readonly IRequestLimitStrategy<UUID> foundTextureLimitStrategy = new RepeatLimitStrategy<UUID>(MAX_ALLOWED_TEXTURE_REQUESTS); private readonly IClientAPI m_client; private readonly Scene m_scene; /// <summary> /// Texture Senders are placed in this queue once they have received their texture from the asset /// cache. Another module actually invokes the send. /// </summary> private readonly OpenSim.Framework.BlockingQueue<ITextureSender> m_sharedSendersQueue; /// <summary> /// Holds texture senders before they have received the appropriate texture from the asset cache. /// </summary> private readonly Dictionary<UUID, TextureSender.TextureSender> m_textureSenders = new Dictionary<UUID, TextureSender.TextureSender>(); /// <summary> /// We're going to limit requests for the same missing texture. /// XXX This is really a temporary solution to deal with the situation where a client continually requests /// the same missing textures /// </summary> private readonly IRequestLimitStrategy<UUID> missingTextureLimitStrategy = new RepeatLimitStrategy<UUID>(MAX_ALLOWED_TEXTURE_REQUESTS); public UserTextureDownloadService( IClientAPI client, Scene scene, OpenSim.Framework.BlockingQueue<ITextureSender> sharedQueue) { m_client = client; m_scene = scene; m_sharedSendersQueue = sharedQueue; } /// <summary> /// Handle a texture request. This involves creating a texture sender and placing it on the /// previously passed in shared queue. /// </summary> /// <param name="e"></param> public void HandleTextureRequest(TextureRequestArgs e) { TextureSender.TextureSender textureSender; //TODO: should be working out the data size/ number of packets to be sent for each discard level if ((e.DiscardLevel >= 0) || (e.Priority != 0)) { lock (m_textureSenders) { if (m_textureSenders.TryGetValue(e.RequestedAssetID, out textureSender)) { // If we've received new non UUID information for this request and it hasn't dispatched // yet, then update the request accordingly. textureSender.UpdateRequest(e.DiscardLevel, e.PacketNumber); } else { // m_log.DebugFormat("[TEXTURE]: Received a request for texture {0}", e.RequestedAssetID); if (!foundTextureLimitStrategy.AllowRequest(e.RequestedAssetID)) { // m_log.DebugFormat( // "[TEXTURE]: Refusing request for {0} from client {1}", // e.RequestedAssetID, m_client.AgentId); return; } else if (!missingTextureLimitStrategy.AllowRequest(e.RequestedAssetID)) { if (missingTextureLimitStrategy.IsFirstRefusal(e.RequestedAssetID)) { if (StatsManager.SimExtraStats != null) StatsManager.SimExtraStats.AddBlockedMissingTextureRequest(); // Commenting out this message for now as it causes too much noise with other // debug messages. // m_log.DebugFormat( // "[TEXTURE]: Dropping requests for notified missing texture {0} for client {1} since we have received more than {2} requests", // e.RequestedAssetID, m_client.AgentId, MAX_ALLOWED_TEXTURE_REQUESTS); } return; } m_scene.StatsReporter.AddPendingDownloads(1); TextureSender.TextureSender requestHandler = new TextureSender.TextureSender(m_client, e.DiscardLevel, e.PacketNumber); m_textureSenders.Add(e.RequestedAssetID, requestHandler); m_scene.CommsManager.AssetCache.GetAsset(e.RequestedAssetID, TextureCallback, AssetRequestInfo.GenericNetRequest()); } } } else { lock (m_textureSenders) { if (m_textureSenders.TryGetValue(e.RequestedAssetID, out textureSender)) { textureSender.Cancel = true; } } } } /// <summary> /// The callback for the asset cache when a texture has been retrieved. This method queues the /// texture sender for processing. /// </summary> /// <param name="textureID"></param> /// <param name="texture"></param> public void TextureCallback(UUID textureID, AssetBase texture) { //m_log.DebugFormat("[USER TEXTURE DOWNLOAD SERVICE]: Calling TextureCallback with {0}, texture == null is {1}", textureID, (texture == null ? true : false)); // There may still be texture requests pending for a logged out client if (closed) return; lock (m_textureSenders) { TextureSender.TextureSender textureSender; if (m_textureSenders.TryGetValue(textureID, out textureSender)) { // XXX It may be perfectly valid for a texture to have no data... but if we pass // this on to the TextureSender it will blow up, so just discard for now. // Needs investigation. if (texture == null || texture.Data == null) { if (!missingTextureLimitStrategy.IsMonitoringRequests(textureID)) { missingTextureLimitStrategy.MonitorRequests(textureID); // m_log.DebugFormat( // "[TEXTURE]: Queueing first TextureNotFoundSender for {0}, client {1}", // textureID, m_client.AgentId); } ITextureSender textureNotFoundSender = new TextureNotFoundSender(m_client, textureID); EnqueueTextureSender(textureNotFoundSender); } else { if (!textureSender.ImageLoaded) { textureSender.TextureReceived(texture); EnqueueTextureSender(textureSender); foundTextureLimitStrategy.MonitorRequests(textureID); } } //m_log.InfoFormat("[TEXTURE] Removing texture sender with uuid {0}", textureID); m_textureSenders.Remove(textureID); //m_log.InfoFormat("[TEXTURE] Current texture senders in dictionary: {0}", m_textureSenders.Count); } else { m_log.WarnFormat( "[TEXTURE]: Got a texture uuid {0} with no sender object to handle it, this shouldn't happen", textureID); } } } /// <summary> /// Place a ready texture sender on the processing queue. /// </summary> /// <param name="textureSender"></param> private void EnqueueTextureSender(ITextureSender textureSender) { textureSender.Cancel = false; textureSender.Sending = true; if (!m_sharedSendersQueue.Contains(textureSender)) { m_sharedSendersQueue.Enqueue(textureSender); } } /// <summary> /// Close this module. /// </summary> internal void Close() { closed = true; lock (m_textureSenders) { foreach (TextureSender.TextureSender textureSender in m_textureSenders.Values) { textureSender.Cancel = true; } m_textureSenders.Clear(); } // XXX: It might be possible to also remove pending texture requests from the asset cache queues, // though this might also be more trouble than it's worth. } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Test.Utilities.Parallel; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { [ParallelFixture] public class ShortKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AtRoot_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterClass_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterGlobalStatement_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterGlobalVariableDeclaration_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotInUsingAlias() { VerifyAbsence( @"using Foo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterStackAlloc() { VerifyKeyword( @"class C { int* foo = stackalloc $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InFixedStatement() { VerifyKeyword( @"fixed ($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InDelegateReturnType() { VerifyKeyword( @"public delegate $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InCastType() { VerifyKeyword(AddInsideMethod( @"var str = (($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InCastType2() { VerifyKeyword(AddInsideMethod( @"var str = (($$)items) as string;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterOuterConst() { VerifyKeyword( @"class C { const $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterInnerConst() { VerifyKeyword(AddInsideMethod( @"const $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InEmptyStatement() { VerifyKeyword(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void EnumBaseTypes() { VerifyKeyword( @"enum E : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InGenericType1() { VerifyKeyword(AddInsideMethod( @"IList<$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InGenericType2() { VerifyKeyword(AddInsideMethod( @"IList<int,$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InGenericType3() { VerifyKeyword(AddInsideMethod( @"IList<int[],$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InGenericType4() { VerifyKeyword(AddInsideMethod( @"IList<IFoo<int?,byte*>,$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotInBaseList() { VerifyAbsence( @"class C : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InGenericType_InBaseList() { VerifyKeyword( @"class C : IList<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterIs() { VerifyKeyword(AddInsideMethod( @"var v = foo is $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterAs() { VerifyKeyword(AddInsideMethod( @"var v = foo as $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterMethod() { VerifyKeyword( @"class C { void Foo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterField() { VerifyKeyword( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterProperty() { VerifyKeyword( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedAttribute() { VerifyKeyword( @"class C { [foo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InsideStruct() { VerifyKeyword( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InsideInterface() { VerifyKeyword( @"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InsideClass() { VerifyKeyword( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterPartial() { VerifyAbsence(@"partial $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterNestedPartial() { VerifyAbsence( @"class C { partial $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedAbstract() { VerifyKeyword( @"class C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedInternal() { VerifyKeyword( @"class C { internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedStaticPublic() { VerifyKeyword( @"class C { static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedPublicStatic() { VerifyKeyword( @"class C { public static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterVirtualPublic() { VerifyKeyword( @"class C { virtual public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedPublic() { VerifyKeyword( @"class C { public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedPrivate() { VerifyKeyword( @"class C { private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedProtected() { VerifyKeyword( @"class C { protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedSealed() { VerifyKeyword( @"class C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedStatic() { VerifyKeyword( @"class C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InLocalVariableDeclaration() { VerifyKeyword(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InForVariableDeclaration() { VerifyKeyword(AddInsideMethod( @"for ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InForeachVariableDeclaration() { VerifyKeyword(AddInsideMethod( @"foreach ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InUsingVariableDeclaration() { VerifyKeyword(AddInsideMethod( @"using ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InFromVariableDeclaration() { VerifyKeyword(AddInsideMethod( @"var q = from $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InJoinVariableDeclaration() { VerifyKeyword(AddInsideMethod( @"var q = from a in b join $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterMethodOpenParen() { VerifyKeyword( @"class C { void Foo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterMethodComma() { VerifyKeyword( @"class C { void Foo(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterMethodAttribute() { VerifyKeyword( @"class C { void Foo(int i, [Foo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterConstructorOpenParen() { VerifyKeyword( @"class C { public C($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterConstructorComma() { VerifyKeyword( @"class C { public C(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterConstructorAttribute() { VerifyKeyword( @"class C { public C(int i, [Foo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterDelegateOpenParen() { VerifyKeyword( @"delegate void D($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterDelegateComma() { VerifyKeyword( @"delegate void D(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterDelegateAttribute() { VerifyKeyword( @"delegate void D(int i, [Foo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterThis() { VerifyKeyword( @"static class C { public static void Foo(this $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterRef() { VerifyKeyword( @"class C { void Foo(ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterOut() { VerifyKeyword( @"class C { void Foo(out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterLambdaRef() { VerifyKeyword( @"class C { void Foo() { System.Func<int, int> f = (ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterLambdaOut() { VerifyKeyword( @"class C { void Foo() { System.Func<int, int> f = (out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterParams() { VerifyKeyword( @"class C { void Foo(params $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InImplicitOperator() { VerifyKeyword( @"class C { public static implicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InExplicitOperator() { VerifyKeyword( @"class C { public static explicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterIndexerBracket() { VerifyKeyword( @"class C { int this[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterIndexerBracketComma() { VerifyKeyword( @"class C { int this[int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNewInExpression() { VerifyKeyword(AddInsideMethod( @"new $$")); } [WorkItem(538804)] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InTypeOf() { VerifyKeyword(AddInsideMethod( @"typeof($$")); } [WorkItem(538804)] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InDefault() { VerifyKeyword(AddInsideMethod( @"default($$")); } [WorkItem(538804)] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InSizeOf() { VerifyKeyword(AddInsideMethod( @"sizeof($$")); } [WorkItem(544219)] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotInObjectInitializerMemberContext() { VerifyAbsence(@" class C { public int x, y; void M() { var c = new C { x = 2, y = 3, $$"); } [WorkItem(546938)] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InCrefContext() { VerifyKeyword(@" class Program { /// <see cref=""$$""> static void Main(string[] args) { } }"); } [WorkItem(546955)] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InCrefContextNotAfterDot() { VerifyAbsence(@" /// <see cref=""System.$$"" /> class C { } "); } [WorkItem(18374)] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterAsyncAsType() { VerifyAbsence(@"class c { async async $$ }"); } [WorkItem(1468, "https://github.com/dotnet/roslyn/issues/1468")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotInCrefTypeParameter() { VerifyAbsence(@" using System; /// <see cref=""List{$$}"" /> class C { } "); } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editing; namespace OmniSharp.Intellisense { public static class ISymbolExtensions { /// <summary> /// Checks if 'symbol' is accessible from within 'within'. /// </summary> public static bool IsAccessibleWithin( this ISymbol symbol, ISymbol within, ITypeSymbol throughTypeOpt = null) { if (within is IAssemblySymbol) { return symbol.IsAccessibleWithin((IAssemblySymbol)within, throughTypeOpt); } else if (within is INamedTypeSymbol) { return symbol.IsAccessibleWithin((INamedTypeSymbol)within, throughTypeOpt); } else { throw new ArgumentException(); } } /// <summary> /// Checks if 'symbol' is accessible from within assembly 'within'. /// </summary> public static bool IsAccessibleWithin( this ISymbol symbol, IAssemblySymbol within, ITypeSymbol throughTypeOpt = null) { bool failedThroughTypeCheck; return IsSymbolAccessibleCore(symbol, within, throughTypeOpt, out failedThroughTypeCheck); } /// <summary> /// Checks if 'symbol' is accessible from within name type 'within', with an optional /// qualifier of type "throughTypeOpt". /// </summary> public static bool IsAccessibleWithin( this ISymbol symbol, INamedTypeSymbol within, ITypeSymbol throughTypeOpt = null) { bool failedThroughTypeCheck; return IsSymbolAccessible(symbol, within, throughTypeOpt, out failedThroughTypeCheck); } /// <summary> /// Checks if 'symbol' is accessible from within assembly 'within', with an qualifier of /// type "throughTypeOpt". Sets "failedThroughTypeCheck" to true if it failed the "through /// type" check. /// </summary> private static bool IsSymbolAccessible( ISymbol symbol, INamedTypeSymbol within, ITypeSymbol throughTypeOpt, out bool failedThroughTypeCheck) { return IsSymbolAccessibleCore(symbol, within, throughTypeOpt, out failedThroughTypeCheck); } /// <summary> /// Checks if 'symbol' is accessible from within 'within', which must be a INamedTypeSymbol /// or an IAssemblySymbol. If 'symbol' is accessed off of an expression then /// 'throughTypeOpt' is the type of that expression. This is needed to properly do protected /// access checks. Sets "failedThroughTypeCheck" to true if this protected check failed. /// </summary> //// NOTE(cyrusn): I expect this function to be called a lot. As such, I do not do any memory //// allocations in the function itself (including not making any iterators). This does mean //// that certain helper functions that we'd like to call are inlined in this method to //// prevent the overhead of returning collections or enumerators. private static bool IsSymbolAccessibleCore( ISymbol symbol, ISymbol within, // must be assembly or named type symbol ITypeSymbol throughTypeOpt, out bool failedThroughTypeCheck) { // Contract.ThrowIfNull(symbol); // Contract.ThrowIfNull(within); // Contract.Requires(within is INamedTypeSymbol || within is IAssemblySymbol); failedThroughTypeCheck = false; // var withinAssembly = (within as IAssemblySymbol) ?? ((INamedTypeSymbol)within).ContainingAssembly; switch (symbol.Kind) { case SymbolKind.Alias: return IsSymbolAccessibleCore(((IAliasSymbol)symbol).Target, within, throughTypeOpt, out failedThroughTypeCheck); case SymbolKind.ArrayType: return IsSymbolAccessibleCore(((IArrayTypeSymbol)symbol).ElementType, within, null, out failedThroughTypeCheck); case SymbolKind.PointerType: return IsSymbolAccessibleCore(((IPointerTypeSymbol)symbol).PointedAtType, within, null, out failedThroughTypeCheck); case SymbolKind.NamedType: return IsNamedTypeAccessible((INamedTypeSymbol)symbol, within); case SymbolKind.ErrorType: return true; case SymbolKind.TypeParameter: case SymbolKind.Parameter: case SymbolKind.Local: case SymbolKind.Label: case SymbolKind.Namespace: case SymbolKind.DynamicType: case SymbolKind.Assembly: case SymbolKind.NetModule: case SymbolKind.RangeVariable: // These types of symbols are always accessible (if visible). return true; case SymbolKind.Method: case SymbolKind.Property: case SymbolKind.Field: case SymbolKind.Event: if (symbol.IsStatic) { // static members aren't accessed "through" an "instance" of any type. So we // null out the "through" instance here. This ensures that we'll understand // accessing protected statics properly. throughTypeOpt = null; } // If this is a synthesized operator of dynamic, it's always accessible. if (symbol.IsKind(SymbolKind.Method) && ((IMethodSymbol)symbol).MethodKind == MethodKind.BuiltinOperator && symbol.ContainingSymbol.IsKind(SymbolKind.DynamicType)) { return true; } // If it's a synthesized operator on a pointer, use the pointer's PointedAtType. if (symbol.IsKind(SymbolKind.Method) && ((IMethodSymbol)symbol).MethodKind == MethodKind.BuiltinOperator && symbol.ContainingSymbol.IsKind(SymbolKind.PointerType)) { return IsSymbolAccessibleCore(((IPointerTypeSymbol)symbol.ContainingSymbol).PointedAtType, within, null, out failedThroughTypeCheck); } return IsMemberAccessible(symbol.ContainingType, symbol.DeclaredAccessibility, within, throughTypeOpt, out failedThroughTypeCheck); default: throw new Exception("unreachable"); } } // Is the named type "type" accessible from within "within", which must be a named type or // an assembly. private static bool IsNamedTypeAccessible(INamedTypeSymbol type, ISymbol within) { // Contract.Requires(within is INamedTypeSymbol || within is IAssemblySymbol); // Contract.ThrowIfNull(type); if (type.IsErrorType()) { // Always assume that error types are accessible. return true; } bool unused; if (!type.IsDefinition) { // All type argument must be accessible. foreach (var typeArg in type.TypeArguments) { // type parameters are always accessible, so don't check those (so common it's // worth optimizing this). if (typeArg.Kind != SymbolKind.TypeParameter && typeArg.TypeKind != TypeKind.Error && !IsSymbolAccessibleCore(typeArg, within, null, out unused)) { return false; } } } var containingType = type.ContainingType; return containingType == null ? IsNonNestedTypeAccessible(type.ContainingAssembly, type.DeclaredAccessibility, within) : IsMemberAccessible(type.ContainingType, type.DeclaredAccessibility, within, null, out unused); } // Is a top-level type with accessibility "declaredAccessibility" inside assembly "assembly" // accessible from "within", which must be a named type of an assembly. private static bool IsNonNestedTypeAccessible( IAssemblySymbol assembly, Accessibility declaredAccessibility, ISymbol within) { // Contract.Requires(within is INamedTypeSymbol || within is IAssemblySymbol); // Contract.ThrowIfNull(assembly); var withinAssembly = (within as IAssemblySymbol) ?? ((INamedTypeSymbol)within).ContainingAssembly; switch (declaredAccessibility) { case Accessibility.NotApplicable: case Accessibility.Public: // Public symbols are always accessible from any context return true; case Accessibility.Private: case Accessibility.Protected: case Accessibility.ProtectedAndInternal: // Shouldn't happen except in error cases. return false; case Accessibility.Internal: case Accessibility.ProtectedOrInternal: // An internal type is accessible if we're in the same assembly or we have // friend access to the assembly it was defined in. return withinAssembly.IsSameAssemblyOrHasFriendAccessTo(assembly); default: throw new Exception("unreachable"); } } // Is a member with declared accessibility "declaredAccessiblity" accessible from within // "within", which must be a named type or an assembly. private static bool IsMemberAccessible( INamedTypeSymbol containingType, Accessibility declaredAccessibility, ISymbol within, ITypeSymbol throughTypeOpt, out bool failedThroughTypeCheck) { // Contract.Requires(within is INamedTypeSymbol || within is IAssemblySymbol); // Contract.ThrowIfNull(containingType); failedThroughTypeCheck = false; var originalContainingType = containingType.OriginalDefinition; var withinNamedType = within as INamedTypeSymbol; var withinAssembly = (within as IAssemblySymbol) ?? ((INamedTypeSymbol)within).ContainingAssembly; // A nested symbol is only accessible to us if its container is accessible as well. if (!IsNamedTypeAccessible(containingType, within)) { return false; } switch (declaredAccessibility) { case Accessibility.NotApplicable: // TODO(cyrusn): Is this the right thing to do here? Should the caller ever be // asking about the accessibility of a symbol that has "NotApplicable" as its // value? For now, I'm preserving the behavior of the existing code. But perhaps // we should fail here and require the caller to not do this? return true; case Accessibility.Public: // Public symbols are always accessible from any context return true; case Accessibility.Private: // All expressions in the current submission (top-level or nested in a method or // type) can access previous submission's private top-level members. Previous // submissions are treated like outer classes for the current submission - the // inner class can access private members of the outer class. if (withinAssembly.IsInteractive && containingType.IsScriptClass) { return true; } // private members never accessible from outside a type. return withinNamedType != null && IsPrivateSymbolAccessible(withinNamedType, originalContainingType); case Accessibility.Internal: // An internal type is accessible if we're in the same assembly or we have // friend access to the assembly it was defined in. return withinAssembly.IsSameAssemblyOrHasFriendAccessTo(containingType.ContainingAssembly); case Accessibility.ProtectedAndInternal: if (!withinAssembly.IsSameAssemblyOrHasFriendAccessTo(containingType.ContainingAssembly)) { // We require internal access. If we don't have it, then this symbol is // definitely not accessible to us. return false; } // We had internal access. Also have to make sure we have protected access. return IsProtectedSymbolAccessible(withinNamedType, withinAssembly, throughTypeOpt, originalContainingType, out failedThroughTypeCheck); case Accessibility.ProtectedOrInternal: if (withinAssembly.IsSameAssemblyOrHasFriendAccessTo(containingType.ContainingAssembly)) { // If we have internal access to this symbol, then that's sufficient. no // need to do the complicated protected case. return true; } // We don't have internal access. But if we have protected access then that's // sufficient. return IsProtectedSymbolAccessible(withinNamedType, withinAssembly, throughTypeOpt, originalContainingType, out failedThroughTypeCheck); case Accessibility.Protected: return IsProtectedSymbolAccessible(withinNamedType, withinAssembly, throughTypeOpt, originalContainingType, out failedThroughTypeCheck); default: throw new Exception("unreachable"); } } // Is a protected symbol inside "originalContainingType" accessible from within "within", // which much be a named type or an assembly. private static bool IsProtectedSymbolAccessible( INamedTypeSymbol withinType, IAssemblySymbol withinAssembly, ITypeSymbol throughTypeOpt, INamedTypeSymbol originalContainingType, out bool failedThroughTypeCheck) { failedThroughTypeCheck = false; // It is not an error to define protected member in a sealed Script class, // it's just a warning. The member behaves like a private one - it is visible // in all subsequent submissions. if (withinAssembly.IsInteractive && originalContainingType.IsScriptClass) { return true; } if (withinType == null) { // If we're not within a type, we can't access a protected symbol return false; } // A protected symbol is accessible if we're (optionally nested) inside the type that it // was defined in. // NOTE(ericli): It is helpful to consider 'protected' as *increasing* the // accessibility domain of a private member, rather than *decreasing* that of a public // member. Members are naturally private; the protected, internal and public access // modifiers all increase the accessibility domain. Since private members are accessible // to nested types, so are protected members. // NOTE(cyrusn): We do this check up front as it is very fast and easy to do. if (IsNestedWithinOriginalContainingType(withinType, originalContainingType)) { return true; } // Protected is really confusing. Check out 3.5.3 of the language spec "protected access // for instance members" to see how it works. I actually got the code for this from // LangCompiler::CheckAccessCore { var current = withinType.OriginalDefinition; var originalThroughTypeOpt = throughTypeOpt == null ? null : throughTypeOpt.OriginalDefinition; while (current != null) { // Contract.Requires(current.IsDefinition); if (current.InheritsFromOrEqualsIgnoringConstruction(originalContainingType)) { // NOTE(cyrusn): We're continually walking up the 'throughType's inheritance // chain. We could compute it up front and cache it in a set. However, i // don't want to allocate memory in this function. Also, in practice // inheritance chains should be very short. As such, it might actually be // slower to create and check inside the set versus just walking the // inheritance chain. if (originalThroughTypeOpt == null || originalThroughTypeOpt.InheritsFromOrEqualsIgnoringConstruction(current)) { return true; } else { failedThroughTypeCheck = true; } } // NOTE(cyrusn): The container of an original type is always original. current = current.ContainingType; } } return false; } // Is a private symbol access private static bool IsPrivateSymbolAccessible( ISymbol within, INamedTypeSymbol originalContainingType) { //Contract.Requires(within is INamedTypeSymbol || within is IAssemblySymbol); var withinType = within as INamedTypeSymbol; if (withinType == null) { // If we're not within a type, we can't access a private symbol return false; } // A private symbol is accessible if we're (optionally nested) inside the type that it // was defined in. return IsNestedWithinOriginalContainingType(withinType, originalContainingType); } // Is the type "withinType" nested within the original type "originalContainingType". private static bool IsNestedWithinOriginalContainingType( INamedTypeSymbol withinType, INamedTypeSymbol originalContainingType) { // Contract.ThrowIfNull(withinType); // Contract.ThrowIfNull(originalContainingType); // Walk up my parent chain and see if I eventually hit the owner. If so then I'm a // nested type of that owner and I'm allowed access to everything inside of it. var current = withinType.OriginalDefinition; while (current != null) { //Contract.Requires(current.IsDefinition); if (current.Equals(originalContainingType)) { return true; } // NOTE(cyrusn): The container of an 'original' type is always original. current = current.ContainingType; } return false; } public static bool IsDefinedInMetadata(this ISymbol symbol) { return symbol.Locations.Any(loc => loc.IsInMetadata); } public static bool IsDefinedInSource(this ISymbol symbol) { return symbol.Locations.All(loc => loc.IsInSource); } public static DeclarationModifiers GetSymbolModifiers(this ISymbol symbol) { // ported from roslyn source - why they didn't use DeclarationModifiers.From (symbol) ? return DeclarationModifiers.None .WithIsStatic(symbol.IsStatic) .WithIsAbstract(symbol.IsAbstract) .WithIsUnsafe(symbol.IsUnsafe()) .WithIsVirtual(symbol.IsVirtual) .WithIsOverride(symbol.IsOverride) .WithIsSealed(symbol.IsSealed); } public static IEnumerable<SyntaxReference> GetDeclarations(this ISymbol symbol) { return symbol != null ? symbol.DeclaringSyntaxReferences.AsEnumerable() : SpecializedCollections.EmptyEnumerable<SyntaxReference>(); } } }
//----------------------------------------------------------------------- // <copyright file="FileSinkSpec.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Akka.Actor; using Akka.IO; using Akka.Streams.Dsl; using Akka.Streams.Implementation; using Akka.Streams.IO; using Akka.Streams.TestKit.Tests; using Akka.Util.Internal; using FluentAssertions; using Xunit; using Xunit.Abstractions; namespace Akka.Streams.Tests.IO { public class FileSinkSpec : AkkaSpec { private readonly ActorMaterializer _materializer; private readonly List<string> _testLines = new List<string>(); private readonly List<ByteString> _testByteStrings; public FileSinkSpec(ITestOutputHelper helper) : base(Utils.UnboundedMailboxConfig, helper) { Sys.Settings.InjectTopLevelFallback(ActorMaterializer.DefaultConfig()); var settings = ActorMaterializerSettings.Create(Sys).WithDispatcher("akka.actor.default-dispatcher"); _materializer = Sys.Materializer(settings); foreach (var character in new[] { "a", "b", "c", "d", "e", "f" }) { var line = ""; for (var i = 0; i < 1000; i++) line += character; // don't use Environment.NewLine - it can contain more than one byte length marker, // causing tests to fail due to incorrect number of bytes in input string line += "\n"; _testLines.Add(line); } _testByteStrings = _testLines.Select(ByteString.FromString).ToList(); } [Fact] public void SynchronousFileSink_should_write_lines_to_a_file() { this.AssertAllStagesStopped(() => { TargetFile(f => { var completion = Source.From(_testByteStrings).RunWith(FileIO.ToFile(f), _materializer); completion.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); var result = completion.Result; result.Count.Should().Be(6006); CheckFileContent(f, _testLines.Aggregate((s, s1) => s + s1)); }); }, _materializer); } [Fact] public void SynchronousFileSink_should_create_new_file_if_not_exists() { this.AssertAllStagesStopped(() => { TargetFile(f => { var completion = Source.From(_testByteStrings).RunWith(FileIO.ToFile(f), _materializer); completion.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); var result = completion.Result; result.Count.Should().Be(6006); CheckFileContent(f, _testLines.Aggregate((s, s1) => s + s1)); }, false); }, _materializer); } [Fact] public void SynchronousFileSink_should_by_default_write_into_existing_file() { this.AssertAllStagesStopped(() => { TargetFile(f => { Func<IEnumerable<string>, Task<IOResult>> write = lines => Source.From(lines) .Select(ByteString.FromString) .RunWith(FileIO.ToFile(f), _materializer); var completion1 = write(_testLines); completion1.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); var lastWrite = new string[100]; for (var i = 0; i < 100; i++) lastWrite[i] = "x"; var completion2 = write(lastWrite); completion2.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); var result = completion2.Result; var lastWriteString = new string(lastWrite.SelectMany(x => x).ToArray()); result.Count.Should().Be(lastWriteString.Length); var testLinesString = new string(_testLines.SelectMany(x => x).ToArray()); CheckFileContent(f, lastWriteString + testLinesString.Substring(100)); }); }, _materializer); } [Fact] public void SynchronousFileSink_should_allow_appending_to_file() { this.AssertAllStagesStopped(() => { TargetFile(f => { Func<List<string>, Task<IOResult>> write = lines => Source.From(lines) .Select(ByteString.FromString) .RunWith(FileIO.ToFile(f, fileMode: FileMode.Append), _materializer); var completion1 = write(_testLines); completion1.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); var result1 = completion1.Result; var lastWrite = new List<string>(); for (var i = 0; i < 100; i++) lastWrite.Add("x"); var completion2 = write(lastWrite); completion2.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); var result2 = completion2.Result; var lastWriteString = new string(lastWrite.SelectMany(x => x).ToArray()); var testLinesString = new string(_testLines.SelectMany(x => x).ToArray()); f.Length.Should().Be(result1.Count + result2.Count); //NOTE: no new line at the end of the file - does JVM/linux appends new line at the end of the file in append mode? CheckFileContent(f, testLinesString + lastWriteString); }); }, _materializer); } [Fact] public void SynchronousFileSink_should_use_dedicated_blocking_io_dispatcher_by_default() { this.AssertAllStagesStopped(() => { TargetFile(f => { var sys = ActorSystem.Create("dispatcher-testing", Utils.UnboundedMailboxConfig); var materializer = ActorMaterializer.Create(sys); try { //hack for Iterator.continually Source.FromEnumerator(() => Enumerable.Repeat(_testByteStrings.Head(), Int32.MaxValue).GetEnumerator()) .RunWith(FileIO.ToFile(f), materializer); ((ActorMaterializerImpl)materializer).Supervisor.Tell(StreamSupervisor.GetChildren.Instance, TestActor); var refs = ExpectMsg<StreamSupervisor.Children>().Refs; //NOTE: Akka uses "fileSource" as name for DefaultAttributes.FileSink - I think it's mistake on the JVM implementation side var actorRef = refs.First(@ref => @ref.Path.ToString().Contains("fileSink")); Utils.AssertDispatcher(actorRef, "akka.stream.default-blocking-io-dispatcher"); } finally { Shutdown(sys); } }); }, _materializer); } // FIXME: overriding dispatcher should be made available with dispatcher alias support in materializer (#17929) [Fact(Skip = "overriding dispatcher should be made available with dispatcher alias support in materializer")] public void SynchronousFileSink_should_allow_overriding_the_dispatcher_using_Attributes() { this.AssertAllStagesStopped(() => { TargetFile(f => { var sys = ActorSystem.Create("dispatcher_testing", Utils.UnboundedMailboxConfig); var materializer = ActorMaterializer.Create(sys); try { //hack for Iterator.continually Source.FromEnumerator(() => Enumerable.Repeat(_testByteStrings.Head(), Int32.MaxValue).GetEnumerator()) .To(FileIO.ToFile(f)) .WithAttributes(ActorAttributes.CreateDispatcher("akka.actor.default-dispatcher")); //.Run(materializer); ((ActorMaterializerImpl)materializer).Supervisor.Tell(StreamSupervisor.GetChildren.Instance, TestActor); var actorRef = ExpectMsg<StreamSupervisor.Children>().Refs.First(@ref => @ref.Path.ToString().Contains("File")); Utils.AssertDispatcher(actorRef, "akka.actor.default-dispatcher"); } finally { Shutdown(sys); } }); }, _materializer); } private static void TargetFile(Action<FileInfo> block, bool create = true) { var targetFile = new FileInfo(Path.Combine(Path.GetTempPath(), "synchronous-file-sink.tmp")); if (!create) targetFile.Delete(); else targetFile.Create().Close(); try { block(targetFile); } finally { //give the system enough time to shutdown and release the file handle Thread.Sleep(500); targetFile.Delete(); } } private static void CheckFileContent(FileInfo f, string contents) { var s = f.OpenText(); var cont = s.ReadToEnd(); s.Close(); cont.Should().Be(contents); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void CompareScalarOrderedDouble() { var test = new SimpleBinaryOpTest__CompareScalarOrderedDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareScalarOrderedDouble { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Double> _fld1; public Vector128<Double> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__CompareScalarOrderedDouble testClass) { var result = Sse2.CompareScalarOrdered(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareScalarOrderedDouble testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse2.CompareScalarOrdered( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Vector128<Double> _clsVar1; private static Vector128<Double> _clsVar2; private Vector128<Double> _fld1; private Vector128<Double> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__CompareScalarOrderedDouble() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); } public SimpleBinaryOpTest__CompareScalarOrderedDouble() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.CompareScalarOrdered( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.CompareScalarOrdered( Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.CompareScalarOrdered( Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareScalarOrdered), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareScalarOrdered), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareScalarOrdered), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.CompareScalarOrdered( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Double>* pClsVar1 = &_clsVar1) fixed (Vector128<Double>* pClsVar2 = &_clsVar2) { var result = Sse2.CompareScalarOrdered( Sse2.LoadVector128((Double*)(pClsVar1)), Sse2.LoadVector128((Double*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr); var result = Sse2.CompareScalarOrdered(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.CompareScalarOrdered(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.CompareScalarOrdered(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__CompareScalarOrderedDouble(); var result = Sse2.CompareScalarOrdered(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__CompareScalarOrderedDouble(); fixed (Vector128<Double>* pFld1 = &test._fld1) fixed (Vector128<Double>* pFld2 = &test._fld2) { var result = Sse2.CompareScalarOrdered( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.CompareScalarOrdered(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse2.CompareScalarOrdered( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.CompareScalarOrdered(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse2.CompareScalarOrdered( Sse2.LoadVector128((Double*)(&test._fld1)), Sse2.LoadVector128((Double*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Double> op1, Vector128<Double> op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.DoubleToInt64Bits(result[0]) != ((!double.IsNaN(left[0]) && !double.IsNaN(right[0])) ? -1 : 0)) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(left[i]) != BitConverter.DoubleToInt64Bits(result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.CompareScalarOrdered)}<Double>(Vector128<Double>, Vector128<Double>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.IO; using System.Text; using NUnit.Framework; using Raksha.Crypto; using Raksha.Crypto.IO; using Raksha.Crypto.Parameters; using Raksha.Security; using Raksha.Utilities.Encoders; using Raksha.Tests.Utilities; namespace Raksha.Tests.Misc { /// <remarks>Check that cipher input/output streams are working correctly</remarks> [TestFixture] public class CipherStreamTest : SimpleTest { private static readonly byte[] RK = Hex.Decode("0123456789ABCDEF"); private static readonly byte[] RIN = Hex.Decode("4e6f772069732074"); private static readonly byte[] ROUT = Hex.Decode("3afbb5c77938280d"); private static byte[] SIN = Hex.Decode( "00000000000000000000000000000000" + "00000000000000000000000000000000" + "00000000000000000000000000000000" + "00000000000000000000000000000000"); private static readonly byte[] SK = Hex.Decode("80000000000000000000000000000000"); private static readonly byte[] SIV = Hex.Decode("0000000000000000"); private static readonly byte[] SOUT = Hex.Decode( "4DFA5E481DA23EA09A31022050859936" + "DA52FCEE218005164F267CB65F5CFD7F" + "2B4F97E0FF16924A52DF269515110A07" + "F9E460BC65EF95DA58F740B7D1DBB0AA"); private static readonly byte[] HCIN = new byte[64]; private static readonly byte[] HCIV = new byte[32]; private static readonly byte[] HCK256A = new byte[32]; private static readonly byte[] HC256A = Hex.Decode( "5B078985D8F6F30D42C5C02FA6B67951" + "53F06534801F89F24E74248B720B4818" + "CD9227ECEBCF4DBF8DBF6977E4AE14FA" + "E8504C7BC8A9F3EA6C0106F5327E6981"); private static readonly byte[] HCK128A = new byte[16]; private static readonly byte[] HC128A = Hex.Decode( "82001573A003FD3B7FD72FFB0EAF63AA" + "C62F12DEB629DCA72785A66268EC758B" + "1EDB36900560898178E0AD009ABF1F49" + "1330DC1C246E3D6CB264F6900271D59C"); private void doRunTest( string name, int ivLength) { string lCode = "ABCDEFGHIJKLMNOPQRSTUVWXY0123456789"; string baseName = name; if (name.IndexOf('/') >= 0) { baseName = name.Substring(0, name.IndexOf('/')); } CipherKeyGenerator kGen = GeneratorUtilities.GetKeyGenerator(baseName); IBufferedCipher inCipher = CipherUtilities.GetCipher(name); IBufferedCipher outCipher = CipherUtilities.GetCipher(name); KeyParameter key = ParameterUtilities.CreateKeyParameter(baseName, kGen.GenerateKey()); MemoryStream bIn = new MemoryStream(Encoding.ASCII.GetBytes(lCode), false); MemoryStream bOut = new MemoryStream(); // In the Java build, this IV would be implicitly created and then retrieved with getIV() ICipherParameters cipherParams = key; if (ivLength > 0) { cipherParams = new ParametersWithIV(cipherParams, new byte[ivLength]); } inCipher.Init(true, cipherParams); // TODO Should we provide GetIV() method on IBufferedCipher? //if (inCipher.getIV() != null) //{ // outCipher.Init(false, new ParametersWithIV(key, inCipher.getIV())); //} //else //{ // outCipher.Init(false, key); //} outCipher.Init(false, cipherParams); CipherStream cIn = new CipherStream(bIn, inCipher, null); CipherStream cOut = new CipherStream(bOut, null, outCipher); int c; while ((c = cIn.ReadByte()) >= 0) { cOut.WriteByte((byte)c); } cIn.Close(); cOut.Flush(); cOut.Close(); byte[] bs = bOut.ToArray(); string res = Encoding.ASCII.GetString(bs, 0, bs.Length); if (!res.Equals(lCode)) { Fail("Failed - decrypted data doesn't match."); } } private void doTestAlgorithm( string name, byte[] keyBytes, byte[] iv, byte[] plainText, byte[] cipherText) { KeyParameter key = ParameterUtilities.CreateKeyParameter(name, keyBytes); IBufferedCipher inCipher = CipherUtilities.GetCipher(name); IBufferedCipher outCipher = CipherUtilities.GetCipher(name); if (iv != null) { inCipher.Init(true, new ParametersWithIV(key, iv)); outCipher.Init(false, new ParametersWithIV(key, iv)); } else { inCipher.Init(true, key); outCipher.Init(false, key); } byte[] enc = inCipher.DoFinal(plainText); if (!AreEqual(enc, cipherText)) { Fail(name + ": cipher text doesn't match"); } byte[] dec = outCipher.DoFinal(enc); if (!AreEqual(dec, plainText)) { Fail(name + ": plain text doesn't match"); } } private void doTestException( string name, int ivLength) { try { byte[] key128 = { (byte)128, (byte)131, (byte)133, (byte)134, (byte)137, (byte)138, (byte)140, (byte)143, (byte)128, (byte)131, (byte)133, (byte)134, (byte)137, (byte)138, (byte)140, (byte)143 }; byte[] key256 = { (byte)128, (byte)131, (byte)133, (byte)134, (byte)137, (byte)138, (byte)140, (byte)143, (byte)128, (byte)131, (byte)133, (byte)134, (byte)137, (byte)138, (byte)140, (byte)143, (byte)128, (byte)131, (byte)133, (byte)134, (byte)137, (byte)138, (byte)140, (byte)143, (byte)128, (byte)131, (byte)133, (byte)134, (byte)137, (byte)138, (byte)140, (byte)143 }; byte[] keyBytes; if (name.Equals("HC256")) { keyBytes = key256; } else { keyBytes = key128; } KeyParameter cipherKey = ParameterUtilities.CreateKeyParameter(name, keyBytes); ICipherParameters cipherParams = cipherKey; if (ivLength > 0) { cipherParams = new ParametersWithIV(cipherParams, new byte[ivLength]); } IBufferedCipher ecipher = CipherUtilities.GetCipher(name); ecipher.Init(true, cipherParams); byte[] cipherText = new byte[0]; try { // According specification Method engineUpdate(byte[] input, // int inputOffset, int inputLen, byte[] output, int // outputOffset) // throws ShortBufferException - if the given output buffer is // too // small to hold the result ecipher.ProcessBytes(new byte[20], 0, 20, cipherText, 0); // Fail("failed exception test - no ShortBufferException thrown"); Fail("failed exception test - no DataLengthException thrown"); } // catch (ShortBufferException e) catch (DataLengthException) { // ignore } // NB: The lightweight engine doesn't take public/private keys // try // { // IBufferedCipher c = CipherUtilities.GetCipher(name); // // // Key k = new PublicKey() // // { // // // // public string getAlgorithm() // // { // // return "STUB"; // // } // // // // public string getFormat() // // { // // return null; // // } // // // // public byte[] getEncoded() // // { // // return null; // // } // // // // }; // AsymmetricKeyParameter k = new AsymmetricKeyParameter(false); // c.Init(true, k); // // Fail("failed exception test - no InvalidKeyException thrown for public key"); // } // catch (InvalidKeyException) // { // // okay // } // // try // { // IBufferedCipher c = CipherUtilities.GetCipher(name); // // // Key k = new PrivateKey() // // { // // // // public string getAlgorithm() // // { // // return "STUB"; // // } // // // // public string getFormat() // // { // // return null; // // } // // // // public byte[] getEncoded() // // { // // return null; // // } // // // // }; // // AsymmetricKeyParameter k = new AsymmetricKeyParameter(true); // c.Init(false, k); // // Fail("failed exception test - no InvalidKeyException thrown for private key"); // } // catch (InvalidKeyException) // { // // okay // } } catch (Exception e) { Fail("unexpected exception.", e); } } [Test] public void TestRC4() { doRunTest("RC4", 0); } [Test] public void TestRC4Exception() { doTestException("RC4", 0); } [Test] public void TestRC4Algorithm() { doTestAlgorithm("RC4", RK, null, RIN, ROUT); } [Test] public void TestSalsa20() { doRunTest("Salsa20", 8); } [Test] public void TestSalsa20Exception() { doTestException("Salsa20", 8); } [Test] public void TestSalsa20Algorithm() { doTestAlgorithm("Salsa20", SK, SIV, SIN, SOUT); } [Test] public void TestHC128() { doRunTest("HC128", 16); } [Test] public void TestHC128Exception() { doTestException("HC128", 16); } [Test] public void TestHC128Algorithm() { doTestAlgorithm("HC128", HCK128A, HCIV, HCIN, HC128A); } [Test] public void TestHC256() { doRunTest("HC256", 32); } [Test] public void TestHC256Exception() { doTestException("HC256", 32); } [Test] public void TestHC256Algorithm() { doTestAlgorithm("HC256", HCK256A, HCIV, HCIN, HC256A); } [Test] public void TestVmpc() { doRunTest("VMPC", 16); } [Test] public void TestVmpcException() { doTestException("VMPC", 16); } // [Test] // public void TestVmpcAlgorithm() // { // doTestAlgorithm("VMPC", a, iv, in, a); // } [Test] public void TestVmpcKsa3() { doRunTest("VMPC-KSA3", 16); } [Test] public void TestVmpcKsa3Exception() { doTestException("VMPC-KSA3", 16); } // [Test] // public void TestVmpcKsa3Algorithm() // { // doTestAlgorithm("VMPC-KSA3", a, iv, in, a); // } [Test] public void TestDesEcbPkcs7() { doRunTest("DES/ECB/PKCS7Padding", 0); } [Test] public void TestDesCfbNoPadding() { doRunTest("DES/CFB8/NoPadding", 0); } public override void PerformTest() { TestRC4(); TestRC4Exception(); TestRC4Algorithm(); TestSalsa20(); TestSalsa20Exception(); TestSalsa20Algorithm(); TestHC128(); TestHC128Exception(); TestHC128Algorithm(); TestHC256(); TestHC256Exception(); TestHC256Algorithm(); TestVmpc(); TestVmpcException(); // TestVmpcAlgorithm(); TestVmpcKsa3(); TestVmpcKsa3Exception(); // TestVmpcKsa3Algorithm(); TestDesEcbPkcs7(); TestDesCfbNoPadding(); } public override string Name { get { return "CipherStreamTest"; } } public static void Main( string[] args) { RunTest(new CipherStreamTest()); } } }
// Copyright (c) Geta Digital. All rights reserved. // Licensed under Apache-2.0. See the LICENSE file in the project root for more information // What's wrong with Request.Headers["Accept-Encoding"].Contains("gzip")? // http://www.singular.co.nz/2008/07/finding-preferred-accept-encoding-header-in-csharp/ // Original code by Dave Transom namespace Geta.SEO.Sitemaps { using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; /// <summary> /// Represents a weighted value (or quality value) from an http header e.g. gzip=0.9; deflate; x-gzip=0.5; /// </summary> /// <remarks> /// accept-encoding spec: /// http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html /// </remarks> /// <example> /// Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5 /// Accept-Encoding: gzip,deflate /// Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 /// Accept-Language: en-us,en;q=0.5 /// </example> [DebuggerDisplay("QValue[{Name}, {Weight}]")] public struct QValue : IComparable<QValue> { static char[] delimiters = { ';', '=' }; const float defaultWeight = 1; string _name; float _weight; int _ordinal; /// <summary> /// Creates a new QValue by parsing the given value /// for name and weight (qvalue) /// </summary> /// <param name="value">The value to be parsed e.g. gzip=0.3</param> public QValue(string value) : this(value, 0) { } /// <summary> /// Creates a new QValue by parsing the given value /// for name and weight (qvalue) and assigns the given /// ordinal /// </summary> /// <param name="value">The value to be parsed e.g. gzip=0.3</param> /// <param name="ordinal">The ordinal/index where the item /// was found in the original list.</param> public QValue(string value, int ordinal) { _name = null; _weight = 0; _ordinal = ordinal; ParseInternal(ref this, value); } /// <summary> /// The name of the value part /// </summary> public string Name { get { return _name; } } /// <summary> /// The weighting (or qvalue, quality value) of the encoding /// </summary> public float Weight { get { return _weight; } } /// <summary> /// Whether the value can be accepted /// i.e. it's weight is greater than zero /// </summary> public bool CanAccept { get { return _weight > 0; } } /// <summary> /// Whether the value is empty (i.e. has no name) /// </summary> public bool IsEmpty { get { return string.IsNullOrEmpty(_name); } } /// <summary> /// Parses the given string for name and /// weigth (qvalue) /// </summary> /// <param name="value">The string to parse</param> public static QValue Parse(string value) { QValue item = new QValue(); ParseInternal(ref item, value); return item; } /// <summary> /// Parses the given string for name and /// weigth (qvalue) /// </summary> /// <param name="value">The string to parse</param> /// <param name="ordinal">The order of item in sequence</param> /// <returns></returns> public static QValue Parse(string value, int ordinal) { QValue item = Parse(value); item._ordinal = ordinal; return item; } /// <summary> /// Parses the given string for name and /// weigth (qvalue) /// </summary> /// <param name="value">The string to parse</param> static void ParseInternal(ref QValue target, string value) { string[] parts = value.Split(delimiters, 3); if (parts.Length > 0) { target._name = parts[0].Trim(); target._weight = defaultWeight; } if (parts.Length == 3) { float.TryParse(parts[2],NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture.NumberFormat, out target._weight); } } /// <summary> /// Compares this instance to another QValue by /// comparing first weights, then ordinals. /// </summary> /// <param name="other">The QValue to compare</param> /// <returns></returns> public int CompareTo(QValue other) { int value = _weight.CompareTo(other._weight); if (value == 0) { int ord = -_ordinal; value = ord.CompareTo(-other._ordinal); } return value; } /// <summary> /// Compares two QValues in ascending order. /// </summary> /// <param name="x">The first QValue</param> /// <param name="y">The second QValue</param> /// <returns></returns> public static int CompareByWeightAsc(QValue x, QValue y) { return x.CompareTo(y); } /// <summary> /// Compares two QValues in descending order. /// </summary> /// <param name="x">The first QValue</param> /// <param name="y">The second QValue</param> /// <returns></returns> public static int CompareByWeightDesc(QValue x, QValue y) { return -x.CompareTo(y); } } /// <summary> /// Provides a collection for working with qvalue http headers /// </summary> /// <remarks> /// accept-encoding spec: /// http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html /// </remarks> [DebuggerDisplay("QValue[{Count}, {AcceptWildcard}]")] public sealed class QValueList : List<QValue> { static char[] delimiters = { ',' }; bool _acceptWildcard; bool _autoSort; /// <summary> /// Creates a new instance of an QValueList list from /// the given string of comma delimited values /// </summary> /// <param name="values">The raw string of qvalues to load</param> public QValueList(string values) : this(null == values ? new string[0] : values.Split(delimiters, StringSplitOptions.RemoveEmptyEntries)) { } /// <summary> /// Creates a new instance of an QValueList from /// the given string array of qvalues /// </summary> /// <param name="values">The array of qvalue strings /// i.e. name(;q=[0-9\.]+)?</param> /// <remarks> /// Should AcceptWildcard include */* as well? /// What about other wildcard forms? /// </remarks> public QValueList(string[] values) { int ordinal = -1; foreach (string value in values) { QValue qvalue = QValue.Parse(value.Trim(), ++ordinal); if (qvalue.Name.Equals("*")) // wildcard _acceptWildcard = qvalue.CanAccept; Add(qvalue); } /// this list should be sorted by weight for /// methods like FindPreferred to work correctly DefaultSort(); _autoSort = true; } /// <summary> /// Whether or not the wildcarded encoding is available and allowed /// </summary> public bool AcceptWildcard { get { return _acceptWildcard; } } /// <summary> /// Whether, after an add operation, the list should be resorted /// </summary> public bool AutoSort { get { return _autoSort; } set { _autoSort = value; } } /// <summary> /// Synonym for FindPreferred /// </summary> /// <param name="candidates">The preferred order in which to return an encoding</param> /// <returns>An QValue based on weight, or null</returns> public QValue this[params string[] candidates] { get { return FindPreferred(candidates); } } /// <summary> /// Adds an item to the list, then applies sorting /// if AutoSort is enabled. /// </summary> /// <param name="item">The item to add</param> public new void Add(QValue item) { base.Add(item); applyAutoSort(); } /// <summary> /// Adds a range of items to the list, then applies sorting /// if AutoSort is enabled. /// </summary> /// <param name="collection">The items to add</param> public new void AddRange(IEnumerable<QValue> collection) { bool state = _autoSort; _autoSort = false; base.AddRange(collection); _autoSort = state; applyAutoSort(); } /// <summary> /// Finds the first QValue with the given name (case-insensitive) /// </summary> /// <param name="name">The name of the QValue to search for</param> /// <returns></returns> public QValue Find(string name) { Predicate<QValue> criteria = delegate(QValue item) { return item.Name.Equals(name, StringComparison.OrdinalIgnoreCase); }; return Find(criteria); } /// <summary> /// Returns the first match found from the given candidates /// </summary> /// <param name="candidates">The list of QValue names to find</param> /// <returns>The first QValue match to be found</returns> /// <remarks>Loops from the first item in the list to the last and finds /// the first candidate - the list must be sorted for weight prior to /// calling this method.</remarks> public QValue FindHighestWeight(params string[] candidates) { Predicate<QValue> criteria = delegate(QValue item) { return isCandidate(item.Name, candidates); }; return Find(criteria); } /// <summary> /// Returns the first match found from the given candidates that is accepted /// </summary> /// <param name="candidates">The list of names to find</param> /// <returns>The first QValue match to be found</returns> /// <remarks>Loops from the first item in the list to the last and finds the /// first candidate that can be accepted - the list must be sorted for weight /// prior to calling this method.</remarks> public QValue FindPreferred(params string[] candidates) { Predicate<QValue> criteria = delegate(QValue item) { return isCandidate(item.Name, candidates) && item.CanAccept; }; return Find(criteria); } /// <summary> /// Sorts the list comparing by weight in /// descending order /// </summary> public void DefaultSort() { Sort(QValue.CompareByWeightDesc); } /// <summary> /// Applies the default sorting method if /// the autosort field is currently enabled /// </summary> void applyAutoSort() { if (_autoSort) DefaultSort(); } /// <summary> /// Determines if the given item contained within the applied array /// (case-insensitive) /// </summary> /// <param name="item">The string to search for</param> /// <param name="candidates">The array to search in</param> /// <returns></returns> static bool isCandidate(string item, params string[] candidates) { foreach (string candidate in candidates) { if (candidate.Equals(item, StringComparison.OrdinalIgnoreCase)) return true; } return false; } } }
//--------------------------------------------------------------------------- // // <copyright file="MediaPermission.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // Description: // The MediaPermission controls the ability to create rich Media in Avalon. // // // History: // 06/07/05: marka Created. //--------------------------------------------------------------------------- using System; using System.Security; using System.Security.Permissions; using System.IO; using System.Runtime.Serialization; using System.Collections; using System.Globalization; using System.Diagnostics.CodeAnalysis; using System.Windows; using MS.Internal.WindowsBase; namespace System.Security.Permissions { ///<summary> /// Enum of audio permission levels. ///</summary> public enum MediaPermissionAudio { /// <summary> /// NoAudio - no sound allowed to play. /// </summary> NoAudio, /// <summary> /// SiteOfOriginAudio - only allow audio from site of origin. /// </summary> SiteOfOriginAudio, /// <summary> /// SafeAudio - allowed to play audio with some restrictions. /// </summary> SafeAudio, /// <summary> /// Allowed to play audio with no restrictions /// </summary> AllAudio } ///<summary> /// Enum of video permission levels. ///</summary> public enum MediaPermissionVideo { /// <summary> /// NoVideo - no video allowed to play. /// </summary> NoVideo, /// <summary> /// SiteOfOriginVideo - only allow video from site of origin. /// </summary> SiteOfOriginVideo, /// <summary> /// SafeVideo - allowed to play video with some restrictions. /// </summary> SafeVideo, /// <summary> /// allowed to play video with no restrictions /// </summary> AllVideo, } ///<summary> /// Enum of image permission levels. ///</summary> public enum MediaPermissionImage { /// <summary> /// NoImage - no images allowed to display /// </summary> NoImage, /// <summary> /// SiteOfOriginImage -only allow image from site of origin. /// </summary> SiteOfOriginImage, /// <summary> /// SafeImage - allowed to display images with some restrictions. /// Only certified codecs allowed. /// </summary> SafeImage, /// <summary> /// Allowed to display images with no restrictions. /// </summary> AllImage, } ///<summary> /// The MediaPermission controls the ability for richMedia to work in partial trust. /// /// There are 3 enum values that control the type of media that can work. /// /// MediaPermissionAudio - controls the level of audio support. /// MediaPermissionVideo - controls the level of video supported. /// MeidaPermissionImage - controls the level of image display supported. ///</summary> [Serializable()] sealed public class MediaPermission : CodeAccessPermission, IUnrestrictedPermission { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ #region Constructors ///<summary> /// MediaPermission ctor. ///</summary> public MediaPermission() { InitDefaults(); } ///<summary> /// MediaPermission ctor. ///</summary> public MediaPermission(PermissionState state) { if (state == PermissionState.Unrestricted) { _mediaPermissionAudio = MediaPermissionAudio.AllAudio; _mediaPermissionVideo = MediaPermissionVideo.AllVideo; _mediaPermissionImage = MediaPermissionImage.AllImage; } else if (state == PermissionState.None) { _mediaPermissionAudio = MediaPermissionAudio.NoAudio; _mediaPermissionVideo = MediaPermissionVideo.NoVideo; _mediaPermissionImage = MediaPermissionImage.NoImage; } else { throw new ArgumentException( SR.Get(SRID.InvalidPermissionState) ); } } ///<summary> /// MediaPermission ctor. ///</summary> public MediaPermission(MediaPermissionAudio permissionAudio ) { VerifyMediaPermissionAudio( permissionAudio ) ; InitDefaults(); _mediaPermissionAudio = permissionAudio ; } ///<summary> /// MediaPermission ctor. ///</summary> public MediaPermission(MediaPermissionVideo permissionVideo ) { VerifyMediaPermissionVideo( permissionVideo ) ; InitDefaults(); _mediaPermissionVideo = permissionVideo ; } ///<summary> /// MediaPermission ctor. ///</summary> public MediaPermission(MediaPermissionImage permissionImage ) { VerifyMediaPermissionImage( permissionImage ); InitDefaults(); _mediaPermissionImage = permissionImage ; } ///<summary> /// MediaPermission ctor. ///</summary> public MediaPermission(MediaPermissionAudio permissionAudio, MediaPermissionVideo permissionVideo, MediaPermissionImage permissionImage ) { VerifyMediaPermissionAudio( permissionAudio ); VerifyMediaPermissionVideo( permissionVideo ); VerifyMediaPermissionImage( permissionImage ); _mediaPermissionAudio = permissionAudio ; _mediaPermissionVideo = permissionVideo ; _mediaPermissionImage = permissionImage ; } #endregion Constructors //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods // // IUnrestrictedPermission implementation // ///<summary> /// Is this an unrestricted permisison ? ///</summary> public bool IsUnrestricted() { return EqualsLevel( MediaPermissionAudio.AllAudio , MediaPermissionVideo.AllVideo, MediaPermissionImage.AllImage ) ; } // // CodeAccessPermission implementation // ///<summary> /// Is this a subsetOf the target ? ///</summary> public override bool IsSubsetOf(IPermission target) { if (target == null) { return EqualsLevel( MediaPermissionAudio.NoAudio, MediaPermissionVideo.NoVideo, MediaPermissionImage.NoImage ) ; } MediaPermission operand = target as MediaPermission ; if ( operand != null ) { return ( ( this._mediaPermissionAudio <= operand._mediaPermissionAudio) && ( this._mediaPermissionVideo <= operand._mediaPermissionVideo ) && ( this._mediaPermissionImage <= operand._mediaPermissionImage ) ) ; } else { throw new ArgumentException(SR.Get(SRID.TargetNotMediaPermissionLevel)); } } ///<summary> /// Return the intersection with the target ///</summary> public override IPermission Intersect(IPermission target) { if (target == null) { return null; } MediaPermission operand = target as MediaPermission ; if ( operand != null ) { // // Construct a permission that is the aggregate of the // least priveleged level of the 3 enums. // MediaPermissionAudio audioIntersectLevel = _mediaPermissionAudio < operand._mediaPermissionAudio ? _mediaPermissionAudio : operand._mediaPermissionAudio; MediaPermissionVideo videoIntersectLevel = _mediaPermissionVideo < operand._mediaPermissionVideo ? _mediaPermissionVideo : operand._mediaPermissionVideo; MediaPermissionImage imageIntersectLevel = _mediaPermissionImage < operand._mediaPermissionImage ? _mediaPermissionImage : operand._mediaPermissionImage ; if ( ( audioIntersectLevel == MediaPermissionAudio.NoAudio ) && ( videoIntersectLevel == MediaPermissionVideo.NoVideo ) && ( imageIntersectLevel == MediaPermissionImage.NoImage ) ) { return null; } else { return new MediaPermission( audioIntersectLevel, videoIntersectLevel, imageIntersectLevel ) ; } } else { throw new ArgumentException(SR.Get(SRID.TargetNotMediaPermissionLevel)); } } ///<summary> /// Return the Union with the target ///</summary> public override IPermission Union(IPermission target) { if (target == null) { return this.Copy(); } MediaPermission operand = target as MediaPermission ; if ( operand != null ) { // // Construct a permission that is the aggregate of the // most priveleged level of the 3 enums. // MediaPermissionAudio audioUnionLevel = _mediaPermissionAudio > operand._mediaPermissionAudio ? _mediaPermissionAudio : operand._mediaPermissionAudio; MediaPermissionVideo videoUnionLevel = _mediaPermissionVideo > operand._mediaPermissionVideo ? _mediaPermissionVideo : operand._mediaPermissionVideo; MediaPermissionImage imageUnionLevel = _mediaPermissionImage > operand._mediaPermissionImage ? _mediaPermissionImage : operand._mediaPermissionImage ; if ( ( audioUnionLevel == MediaPermissionAudio.NoAudio ) && ( videoUnionLevel == MediaPermissionVideo.NoVideo ) && ( imageUnionLevel == MediaPermissionImage.NoImage ) ) { return null; } else { return new MediaPermission( audioUnionLevel, videoUnionLevel, imageUnionLevel ) ; } } else { throw new ArgumentException(SR.Get(SRID.TargetNotMediaPermissionLevel)); } } ///<summary> /// Copy this permission. ///</summary> public override IPermission Copy() { return new MediaPermission( this._mediaPermissionAudio, this._mediaPermissionVideo, this._mediaPermissionImage ); } ///<summary> /// Return an XML instantiation of this permisson. ///</summary> public override SecurityElement ToXml() { SecurityElement securityElement = new SecurityElement("IPermission"); securityElement.AddAttribute("class", this.GetType().AssemblyQualifiedName); securityElement.AddAttribute("version", "1"); if (IsUnrestricted()) { securityElement.AddAttribute("Unrestricted", Boolean.TrueString); } else { securityElement.AddAttribute("Audio", _mediaPermissionAudio.ToString()); securityElement.AddAttribute("Video", _mediaPermissionVideo.ToString()); securityElement.AddAttribute("Image", _mediaPermissionImage.ToString()); } return securityElement; } ///<summary> /// Create a permission from XML ///</summary> public override void FromXml(SecurityElement securityElement) { if (securityElement == null) { throw new ArgumentNullException("securityElement"); } String className = securityElement.Attribute("class"); if (className == null || className.IndexOf(this.GetType().FullName, StringComparison.Ordinal) == -1) { throw new ArgumentNullException("securityElement"); } String unrestricted = securityElement.Attribute("Unrestricted"); if (unrestricted != null && Boolean.Parse(unrestricted)) { _mediaPermissionAudio = MediaPermissionAudio.AllAudio ; _mediaPermissionVideo = MediaPermissionVideo.AllVideo ; _mediaPermissionImage = MediaPermissionImage.AllImage; return; } InitDefaults(); String audio = securityElement.Attribute("Audio"); if (audio != null) { _mediaPermissionAudio = (MediaPermissionAudio)Enum.Parse(typeof(MediaPermissionAudio), audio ); } else { throw new ArgumentException(SR.Get(SRID.BadXml,"audio")); // bad XML } String video = securityElement.Attribute("Video"); if (video != null) { _mediaPermissionVideo = (MediaPermissionVideo)Enum.Parse(typeof(MediaPermissionVideo), video ); } else { throw new ArgumentException(SR.Get(SRID.BadXml,"video")); // bad XML } String image = securityElement.Attribute("Image"); if (image != null) { _mediaPermissionImage = (MediaPermissionImage)Enum.Parse(typeof(MediaPermissionImage), image ); } else { throw new ArgumentException(SR.Get(SRID.BadXml,"image")); // bad XML } } #endregion Public Methods //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ #region Public Properties ///<summary> /// Current value of allowed audio permission level ///</summary> public MediaPermissionAudio Audio { get { return _mediaPermissionAudio ; } } ///<summary> /// Current value of allowed video permission level ///</summary> public MediaPermissionVideo Video { get { return _mediaPermissionVideo ; } } ///<summary> /// Current value of allowed image permission level ///</summary> public MediaPermissionImage Image { get { return _mediaPermissionImage ; } } #endregion Public Properties //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods internal static void VerifyMediaPermissionAudio(MediaPermissionAudio level) { if (level < MediaPermissionAudio.NoAudio || level > MediaPermissionAudio.AllAudio ) { throw new ArgumentException(SR.Get(SRID.InvalidPermissionLevel)); } } internal static void VerifyMediaPermissionVideo(MediaPermissionVideo level) { if (level < MediaPermissionVideo.NoVideo || level > MediaPermissionVideo.AllVideo ) { throw new ArgumentException(SR.Get(SRID.InvalidPermissionLevel)); } } internal static void VerifyMediaPermissionImage(MediaPermissionImage level) { if (level < MediaPermissionImage.NoImage || level > MediaPermissionImage.AllImage ) { throw new ArgumentException(SR.Get(SRID.InvalidPermissionLevel)); } } #endregion Internal Methods //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ #region Private Methods private void InitDefaults() { _mediaPermissionAudio = MediaPermissionAudio.SafeAudio; _mediaPermissionVideo = MediaPermissionVideo.SafeVideo; _mediaPermissionImage = MediaPermissionImage.SafeImage; } ///<summary> /// Private helper to compare the level of the 3 enum fields. ///</summary> private bool EqualsLevel( MediaPermissionAudio audioLevel, MediaPermissionVideo videoLevel, MediaPermissionImage imageLevel ) { return ( ( _mediaPermissionAudio == audioLevel ) && ( _mediaPermissionVideo == videoLevel ) && ( _mediaPermissionImage == imageLevel ) ) ; } #endregion Private Methods // // Private fields: // private MediaPermissionAudio _mediaPermissionAudio ; private MediaPermissionVideo _mediaPermissionVideo ; private MediaPermissionImage _mediaPermissionImage ; } ///<summary> /// Imperative attribute to create a MediaPermission. ///</summary> [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )] sealed public class MediaPermissionAttribute : CodeAccessSecurityAttribute { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ #region Constructors ///<summary> /// Imperative attribute to create a MediaPermission. ///</summary> public MediaPermissionAttribute(SecurityAction action) : base(action) { } #endregion Constructors //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods ///<summary> /// Create a MediaPermisison. ///</summary> public override IPermission CreatePermission() { if (Unrestricted) { return new MediaPermission(PermissionState.Unrestricted); } else { return new MediaPermission( _mediaPermissionAudio, _mediaPermissionVideo, _mediaPermissionImage ); } } #endregion Public Methods //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ #region Public Properties ///<summary> /// Current audio level. ///</summary> public MediaPermissionAudio Audio { get { return _mediaPermissionAudio ; } set { MediaPermission.VerifyMediaPermissionAudio(value); _mediaPermissionAudio = value; } } ///<summary> /// Current Video level. ///</summary> public MediaPermissionVideo Video { get { return _mediaPermissionVideo ; } set { MediaPermission.VerifyMediaPermissionVideo(value); _mediaPermissionVideo = value; } } ///<summary> /// Current Image level. ///</summary> public MediaPermissionImage Image { get { return _mediaPermissionImage ; } set { MediaPermission.VerifyMediaPermissionImage(value); _mediaPermissionImage = value; } } #endregion Public Properties // // Private fields: // private MediaPermissionAudio _mediaPermissionAudio ; private MediaPermissionVideo _mediaPermissionVideo ; private MediaPermissionImage _mediaPermissionImage ; } }
/*++ File: FixedSOMPageConstructor.cs Copyright (C) 2005 Microsoft Corporation. All rights reserved. Description: This class is responsible for algorithmically reconstructing a semantic object model (SOM) for each page on the document History: 05/17/2005: agurcan - Created --*/ namespace System.Windows.Documents { using System.Collections; using System.Collections.Generic; using System.Windows.Shapes; using System.Windows.Controls; using System.Diagnostics; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Globalization; #region GeometryAnalyzer /// <summary> /// Walk a StreamGeometry to find line shapes for table recognition, without expensive conversion to PathGeometry /// For filling, check bounding box of each figure, abort on curves /// For stroking, check straight lines, ignore curves /// /// Calling sequence from PathGeometry.ParsePathGeometryData /// SetFigureCount /// BeginFigure /// SetSegmentCount /// LineTo | BezierTo | ... /// </summary> internal sealed class GeometryWalker : CapacityStreamGeometryContext { private FixedSOMPageConstructor _pageConstructor; private Matrix _transform; // Transformation from page root private bool _stroke; // Path has stroke brush private bool _fill; // Path has fill brush private Point _startPoint; // Start point for current figure private Point _lastPoint; // Current end point for current figure private bool _isClosed; // Is current figure closed? private bool _isFilled; // Is current figure filled? private double _xMin, _xMax, _yMin, _yMax; // Bounding box for current figure, only needed when (_fill && _isFilled) private bool _needClose; // Need to check for closing current/last figure public GeometryWalker(FixedSOMPageConstructor pageConstructor) { _pageConstructor = pageConstructor; } public void FindLines(StreamGeometry geometry, bool stroke, bool fill, Matrix trans) { Debug.Assert(stroke || fill, "should not be a nop"); _transform = trans; _fill = fill; _stroke = stroke; PathGeometry.ParsePathGeometryData(geometry.GetPathGeometryData(), this); CheckCloseFigure(); } private void CheckCloseFigure() { if (_needClose) { if (_stroke && _isClosed) { _pageConstructor._AddLine(_startPoint, _lastPoint, _transform); } if (_fill && _isFilled) { _pageConstructor._ProcessFilledRect(_transform, new Rect(_xMin, _yMin, _xMax - _xMin, _yMax - _yMin)); } _needClose = false; } } private void GatherBounds(Point p) { if (p.X < _xMin) { _xMin = p.X; } else if (p.X > _xMax) { _xMax = p.X; } if (p.Y < _yMin) { _yMin = p.Y; } else if (p.Y > _yMax) { _yMax = p.Y; } } // CapacityStreamGeometryContext Members public override void BeginFigure(Point startPoint, bool isFilled, bool isClosed) { CheckCloseFigure(); _startPoint = startPoint; _lastPoint = startPoint; _isClosed = isClosed; _isFilled = isFilled; if (_isFilled && _fill) { _xMin = _xMax = startPoint.X; _yMin = _yMax = startPoint.Y; } } public override void LineTo(Point point, bool isStroked, bool isSmoothJoin) { if (isStroked && _stroke) { _pageConstructor._AddLine(_lastPoint, point, _transform); } if (_isFilled && _fill) { GatherBounds(point); } _lastPoint = point; } public override void QuadraticBezierTo(Point point1, Point point2, bool isStroked, bool isSmoothJoin) { _lastPoint = point2; _fill = false; } public override void BezierTo(Point point1, Point point2, Point point3, bool isStroked, bool isSmoothJoin) { _lastPoint = point3; _fill = false; } public override void PolyLineTo(IList<Point> points, bool isStroked, bool isSmoothJoin) { if (isStroked && _stroke) { for (int i = 0; i <points.Count; i ++) { _pageConstructor._AddLine(_lastPoint, points[i], _transform); _lastPoint = points[i]; } } else { _lastPoint = points[points.Count - 1]; } if (_isFilled && _fill) { for (int i = 0; i < points.Count; i++) { GatherBounds(points[i]); } } } public override void PolyQuadraticBezierTo(IList<Point> points, bool isStroked, bool isSmoothJoin) { _lastPoint = points[points.Count - 1]; _fill = false; } public override void PolyBezierTo(IList<Point> points, bool isStroked, bool isSmoothJoin) { _lastPoint = points[points.Count - 1]; _fill = false; } public override void ArcTo(Point point, Size size, double rotationAngle, bool isLargeArc, SweepDirection sweepDirection, bool isStroked, bool isSmoothJoin) { _lastPoint = point; _fill = false; } internal override void SetClosedState(bool closed) { Debug.Assert(false, "It should not be called"); } internal override void SetFigureCount(int figureCount) { } internal override void SetSegmentCount(int segmentCount) { if (segmentCount != 0) { _needClose = true; } } } #endregion internal sealed class FixedSOMPageConstructor { //-------------------------------------------------------------------- // // Constructors // //--------------------------------------------------------------------- #region Constructors public FixedSOMPageConstructor(FixedPage fixedPage, int pageIndex) { Debug.Assert(fixedPage != null); _fixedPage = fixedPage; _pageIndex = pageIndex; _fixedSOMPage = new FixedSOMPage(); _fixedSOMPage.CultureInfo = _fixedPage.Language.GetCompatibleCulture(); _fixedNodes = new List<FixedNode>(); _lines = new FixedSOMLineCollection(); } #endregion Constructors #region Public methods public FixedSOMPage ConstructPageStructure(List<FixedNode> fixedNodes) { Debug.Assert(_fixedPage != null); foreach (FixedNode node in fixedNodes) { DependencyObject obj = _fixedPage.GetElement(node); Debug.Assert(obj != null); if (obj is Glyphs) { _ProcessGlyphsElement(obj as Glyphs, node); } else if (obj is Image || obj is Path && ((obj as Path).Fill is ImageBrush)) { _ProcessImage(obj, node); } } //Inner sorting of all page elements foreach (FixedSOMSemanticBox box in _fixedSOMPage.SemanticBoxes) { FixedSOMContainer container = box as FixedSOMContainer; container.SemanticBoxes.Sort(); } _DetectTables(); _CombinePass(); _CreateGroups(_fixedSOMPage); _fixedSOMPage.SemanticBoxes.Sort(); return _fixedSOMPage; } public void ProcessPath(Path path, Matrix transform) { if (path == null) { throw new ArgumentNullException("path"); } Geometry geom = path.Data; bool fill = path.Fill != null; bool stroke = path.Stroke != null; if ((geom == null) || (! fill && ! stroke)) { return; } Transform transPath = path.RenderTransform; if (transPath != null) { transform *= transPath.Value; } // When filling, we may be able to determine from bounding box only if (fill && _ProcessFilledRect(transform, geom.Bounds)) { fill = false; if (! stroke) { return; } } StreamGeometry sgeo = geom as StreamGeometry; // Avoiding convert to PathGeometry if it's StreamGeometry, which can be walked if (sgeo != null) { if (_geometryWalker == null) { _geometryWalker = new GeometryWalker(this); } _geometryWalker.FindLines(sgeo, stroke, fill, transform); } else { PathGeometry pathGeom = PathGeometry.CreateFromGeometry(geom); if (pathGeom != null) { if (fill) { _ProcessSolidPath(transform, pathGeom); } if (stroke) { _ProcessOutlinePath(transform, pathGeom); } } } } #endregion Public methods //-------------------------------------------------------------------- // // Internal Properties // //--------------------------------------------------------------------- #region Public Properties public FixedSOMPage FixedSOMPage { get { return _fixedSOMPage; } } #endregion Public Properties //-------------------------------------------------------------------- // // Private Methods // //--------------------------------------------------------------------- #region Private methods private void _ProcessImage(DependencyObject obj, FixedNode fixedNode) { Debug.Assert(obj is Image || obj is Path); FixedSOMImage somImage = null; while (true) { Image image = obj as Image; if (image != null) { somImage = FixedSOMImage.Create(_fixedPage, image, fixedNode); break; } Path path = obj as Path; if (path != null) { somImage = FixedSOMImage.Create(_fixedPage, path, fixedNode); break; } } //Create a wrapper FixedBlock: FixedSOMFixedBlock fixedBlock = new FixedSOMFixedBlock(_fixedSOMPage); fixedBlock.AddImage(somImage); _fixedSOMPage.AddFixedBlock(fixedBlock); _currentFixedBlock = fixedBlock; } //Processes the Glyphs element, create one or more text runs out of it, add to containing text line and text box private void _ProcessGlyphsElement(Glyphs glyphs, FixedNode node) { Debug.Assert(glyphs != null); string s = glyphs.UnicodeString; if (s.Length == 0 || glyphs.FontRenderingEmSize <= 0) { return; } //Multiple table cells separated by wide spaces should be identified GlyphRun glyphRun = glyphs.ToGlyphRun(); if (glyphRun == null) { //Could not create a GlyphRun out of this Glyphs element //Some key properties might be missing/invalid return; } Rect alignmentBox = glyphRun.ComputeAlignmentBox(); alignmentBox.Offset(glyphs.OriginX, glyphs.OriginY); GlyphTypeface typeFace = glyphRun.GlyphTypeface; GeneralTransform trans = glyphs.TransformToAncestor(_fixedPage); int charIndex= -1; double advWidth = 0; double cumulativeAdvWidth = 0; int lastAdvWidthIndex = 0; int textRunStartIndex = 0; double lastX = alignmentBox.Left; int glyphIndex = charIndex; do { charIndex = s.IndexOf(" ", charIndex+1, s.Length - charIndex -1, StringComparison.Ordinal); if (charIndex >=0 ) { if (glyphRun.ClusterMap != null && glyphRun.ClusterMap.Count > 0) { glyphIndex = glyphRun.ClusterMap[charIndex]; } else { glyphIndex = charIndex; } //Advance width of the space character in the font double advFont = typeFace.AdvanceWidths[glyphRun.GlyphIndices[glyphIndex]] * glyphRun.FontRenderingEmSize; double advSpecified = glyphRun.AdvanceWidths[glyphIndex]; if ((advSpecified / advFont) > 2) { //Are these seperated by a vertical line? advWidth = 0; for (int i=lastAdvWidthIndex; i<glyphIndex; i++) { advWidth += glyphRun.AdvanceWidths[i]; } cumulativeAdvWidth += advWidth; lastAdvWidthIndex = glyphIndex + 1; if (_lines.IsVerticallySeparated(glyphRun.BaselineOrigin.X + cumulativeAdvWidth, alignmentBox.Top, glyphRun.BaselineOrigin.X + cumulativeAdvWidth + advSpecified, alignmentBox.Bottom)) { //Create a new FixedTextRun Rect boundingRect = new Rect(lastX, alignmentBox.Top, advWidth + advFont, alignmentBox.Height); int endIndex = charIndex; if ((charIndex == 0 || s[charIndex-1] == ' ') && (charIndex != s.Length - 1)) { endIndex = charIndex + 1; } _CreateTextRun(boundingRect, trans, glyphs, node, textRunStartIndex, endIndex); lastX = lastX + advWidth + advSpecified; textRunStartIndex = charIndex+1; } cumulativeAdvWidth += advSpecified; } } } while (charIndex >= 0 && charIndex < s.Length-1); if (textRunStartIndex < s.Length) { //Last text run //For non-partitioned elements this will be the whole Glyphs element Rect boundingRect = new Rect(lastX, alignmentBox.Top, alignmentBox.Right-lastX, alignmentBox.Height); _CreateTextRun( boundingRect, trans, glyphs, node, textRunStartIndex, s.Length); } } //Creates a FixedSOMTextRun, and updates containing structures private void _CreateTextRun(Rect boundingRect, GeneralTransform trans, Glyphs glyphs, FixedNode node, int startIndex, int endIndex) { if (startIndex < endIndex) { FixedSOMTextRun textRun = FixedSOMTextRun.Create(boundingRect, trans, glyphs, node, startIndex, endIndex, true); FixedSOMFixedBlock fixedBlock = _GetContainingFixedBlock(textRun); if (fixedBlock == null) { fixedBlock= new FixedSOMFixedBlock(_fixedSOMPage); fixedBlock.AddTextRun(textRun); _fixedSOMPage.AddFixedBlock(fixedBlock); } else { fixedBlock.AddTextRun(textRun); } _currentFixedBlock = fixedBlock; } } //Find and return a FixedBlock that would contain this TextRun private FixedSOMFixedBlock _GetContainingFixedBlock(FixedSOMTextRun textRun) { FixedSOMFixedBlock fixedBlock = null; if (_currentFixedBlock == null) { return null; } if (_currentFixedBlock != null && _IsCombinable(_currentFixedBlock, textRun)) { fixedBlock = _currentFixedBlock; } else { //If this is aligned with the previous block, simply create a new block Rect textRunRect = textRun.BoundingRect; Rect fixedBlockRect = _currentFixedBlock.BoundingRect; if (Math.Abs(textRunRect.Left - fixedBlockRect.Left) <= textRun.DefaultCharWidth || Math.Abs(textRunRect.Right - fixedBlockRect.Right) <= textRun.DefaultCharWidth) { return null; } foreach (FixedSOMSemanticBox box in _fixedSOMPage.SemanticBoxes) { if ((box is FixedSOMFixedBlock) && _IsCombinable(box as FixedSOMFixedBlock, textRun)) { fixedBlock = box as FixedSOMFixedBlock; } } } return fixedBlock; } private bool _IsCombinable(FixedSOMFixedBlock fixedBlock, FixedSOMTextRun textRun) { Debug.Assert (fixedBlock.SemanticBoxes.Count > 0); if (fixedBlock.SemanticBoxes.Count == 0) { return false; } //Currently we do not support inline images if (fixedBlock.IsFloatingImage) { return false; } Rect textRunRect = textRun.BoundingRect; Rect fixedBlockRect = fixedBlock.BoundingRect; FixedSOMTextRun compareLine = null; FixedSOMTextRun lastLine = fixedBlock.SemanticBoxes[fixedBlock.SemanticBoxes.Count - 1] as FixedSOMTextRun; if (lastLine != null && textRunRect.Bottom <= lastLine.BoundingRect.Top) { //This run is above the last run of the fixed block. Can't be the same paragraph return false; } bool fixedBlockBelow = false; bool textRunBelow = false; //Allow 20% overlap double verticalOverlap = textRunRect.Height * 0.2; if (textRunRect.Bottom - verticalOverlap < fixedBlockRect.Top) { fixedBlockBelow = true; compareLine = fixedBlock.SemanticBoxes[0] as FixedSOMTextRun; } else if (textRunRect.Top + verticalOverlap > fixedBlockRect.Bottom) { textRunBelow = true; compareLine = fixedBlock.SemanticBoxes[fixedBlock.SemanticBoxes.Count-1] as FixedSOMTextRun; } if ( (fixedBlock.IsWhiteSpace || textRun.IsWhiteSpace) && (fixedBlock != _currentFixedBlock || compareLine != null || !_IsSpatiallyCombinable(fixedBlockRect, textRunRect, textRun.DefaultCharWidth * 3, 0)) ) { //When combining with white spaces, they need to be consecutive in markup and need to be on the same line. return false; } if (fixedBlock.Matrix.M11 != textRun.Matrix.M11 || fixedBlock.Matrix.M12 != textRun.Matrix.M12 || fixedBlock.Matrix.M21 != textRun.Matrix.M21 || fixedBlock.Matrix.M22 != textRun.Matrix.M22) { //We don't allow combining TextRuns with different scale/rotation properties return false; } Debug.Assert(textRunRect.Height != 0 && fixedBlock.LineHeight != 0); //Rect textRunRect = textRun.BoundingRect; if (compareLine != null) //Most probably different lines { double ratio = fixedBlock.LineHeight / textRunRect.Height; if (ratio<1.0) { ratio = 1.0 / ratio; } //Allow 10% height difference if ((ratio > 1.1) && !(FixedTextBuilder.IsSameLine(compareLine.BoundingRect.Top - textRunRect.Top, textRunRect.Height, compareLine.BoundingRect.Height))) { return false; } } double width = textRun.DefaultCharWidth; if (width < 1.0) { width = 1.0; } double dHorInflate = 0; double heightRatio = fixedBlock.LineHeight / textRunRect.Height; if (heightRatio < 1.0) { heightRatio = 1.0 / heightRatio; } //If consecutive in markup and seem to be on the same line, almost discard horizontal distance if (fixedBlock == _currentFixedBlock && compareLine == null && heightRatio < 1.5 ) { dHorInflate = 200; } else { dHorInflate = width*1.5; } if (!_IsSpatiallyCombinable(fixedBlockRect, textRunRect, dHorInflate, textRunRect.Height*0.7)) { return false; } //If these two have originated from the same Glyphs element, this means we intentionally separated them (separated by vertical lines). //Don't combine in this case. FixedSOMElement element = fixedBlock.SemanticBoxes[fixedBlock.SemanticBoxes.Count - 1] as FixedSOMElement; if (element!=null && element.FixedNode.CompareTo(textRun.FixedNode) == 0) { return false; } //Are these seperated by a line? Check only if they are not considered overlapping if (fixedBlockBelow || textRunBelow) { double bottom = 0.0; double top = 0.0; double margin = textRunRect.Height * 0.2; if (textRunBelow) { top = fixedBlockRect.Bottom - margin; bottom = textRunRect.Top + margin; } else { top = textRunRect.Bottom - margin ; bottom = fixedBlockRect.Top + margin; } double left = (fixedBlockRect.Left > textRunRect.Left) ? fixedBlockRect.Left : textRunRect.Left; double right = (fixedBlockRect.Right < textRunRect.Right) ? fixedBlockRect.Right: textRunRect.Right; return (!_lines.IsHorizontallySeparated(left, top, right, bottom)); } else { //These two overlap vertically. Let's check whether there is a vertical separator in between double left = (fixedBlockRect.Right < textRunRect.Right) ? fixedBlockRect.Right: textRunRect.Right; double right =(fixedBlockRect.Left > textRunRect.Left) ? fixedBlockRect.Left: textRunRect.Left; if (left > right) { double temp = left; left = right; right = temp; } return (!_lines.IsVerticallySeparated(left, textRunRect.Top, right, textRunRect.Bottom)); } } private bool _IsSpatiallyCombinable(FixedSOMSemanticBox box1, FixedSOMSemanticBox box2, double inflateH, double inflateV) { return _IsSpatiallyCombinable(box1.BoundingRect, box2.BoundingRect, inflateH, inflateV); } private bool _IsSpatiallyCombinable(Rect rect1, Rect rect2, double inflateH, double inflateV) { //Do these rects intersect? If so, we can combine if (rect1.IntersectsWith(rect2)) { return true; } //Try inflating rect1.Inflate(inflateH, inflateV); if (rect1.IntersectsWith(rect2)) { return true; } return false; } private void _DetectTables() { double minLineSeparation = FixedSOMLineRanges.MinLineSeparation; List<FixedSOMLineRanges> horizontal = _lines.HorizontalLines; List<FixedSOMLineRanges> vertical = _lines.VerticalLines; if (horizontal.Count < 2 || vertical.Count < 2) return; List<FixedSOMTableRow> tableRows = new List<FixedSOMTableRow>(); FixedSOMTableRow currentRow = null; //iterate through for (int h = 0; h < horizontal.Count; h++) { int v = 0; int h2 = -1; int hSeg2 = -1; int hLastCellBottom = -1; int vLastCellRight = -1; double dropLine = horizontal[h].Line + minLineSeparation; //loop through each line segment on this Y value for (int hSeg = 0; hSeg < horizontal[h].Count; hSeg++) { // X range for this segment -- allow some margin for error double hStart = horizontal[h].Start[hSeg] - minLineSeparation; double hEnd = horizontal[h].End[hSeg] + minLineSeparation; // no cell has been started int vCellStart = -1; while (v < vertical.Count && vertical[v].Line < hStart) { v++; } for (; v < vertical.Count && vertical[v].Line < hEnd; v++) { int vSeg = vertical[v].GetLineAt(dropLine); if (vSeg != -1) { double vBottom = vertical[v].End[vSeg]; if (vCellStart != -1 && horizontal[h2].Line < vBottom + minLineSeparation && horizontal[h2].End[hSeg2] + minLineSeparation > vertical[v].Line) { // should also check if any other lines cut through rectangle? double top = horizontal[h].Line; double bottom = horizontal[h2].Line; double left = vertical[vCellStart].Line; double right = vertical[v].Line; // Create Table Cell FixedSOMTableCell cell = new FixedSOMTableCell(left, top, right, bottom); //_fixedSOMPage.Add(cell); // for now just doing cells // Check if in same row if (vCellStart == vLastCellRight && h2 == hLastCellBottom) { // same row! // Assert(currentRow != null); } else { currentRow = new FixedSOMTableRow(); tableRows.Add(currentRow); } currentRow.AddCell(cell); vLastCellRight = v; hLastCellBottom = h2; } vCellStart = -1; // any previously started cell is not valid // look for cell bottom for (h2 = h + 1; h2 < horizontal.Count && horizontal[h2].Line < vBottom + minLineSeparation; h2++) { hSeg2 = horizontal[h2].GetLineAt(vertical[v].Line + minLineSeparation); if (hSeg2 != -1) { // start of new cell! (maybe...) vCellStart = v; break; } } } } } } _FillTables(tableRows); } public void _AddLine(Point startP, Point endP, Matrix transform) { startP = transform.Transform(startP); endP = transform.Transform(endP); if (startP.X == endP.X) { _lines.AddVertical(startP, endP); } else if (startP.Y == endP.Y) { _lines.AddHorizontal(startP, endP); } } private void _CombinePass() { if (_fixedSOMPage.SemanticBoxes.Count < 2) { //Nothing to do return; } int prevBoxCount; do { prevBoxCount = _fixedSOMPage.SemanticBoxes.Count; List<FixedSOMSemanticBox> boxes = _fixedSOMPage.SemanticBoxes; for (int i = 0; i < boxes.Count; i++) { FixedSOMTable table1 = boxes[i] as FixedSOMTable; if (table1 != null) { //Check for nested tables for (int j = i + 1; j < boxes.Count; j++) { FixedSOMTable table2 = boxes[j] as FixedSOMTable; if (table2 != null && table1.AddContainer(table2)) { boxes.Remove(table2); } } continue; } FixedSOMFixedBlock box1 = boxes[i] as FixedSOMFixedBlock; if (box1 == null || box1.IsFloatingImage) { continue; } for (int j = i + 1; j < boxes.Count; j++) { FixedSOMFixedBlock box2 = boxes[j] as FixedSOMFixedBlock; if (box2 != null && !box2.IsFloatingImage && box2.Matrix.Equals(box1.Matrix) && (_IsSpatiallyCombinable(box1, box2, 0, 0))) { { box1.CombineWith(box2); boxes.Remove(box2); } } } } } while (_fixedSOMPage.SemanticBoxes.Count > 1 && _fixedSOMPage.SemanticBoxes.Count != prevBoxCount); } // Check if a Geometry bound has a line shape internal bool _ProcessFilledRect(Matrix transform, Rect bounds) { const double maxLineWidth = 10; const double minLineRatio = 5; if (bounds.Height > bounds.Width && bounds.Width < maxLineWidth && bounds.Height > bounds.Width * minLineRatio) { double center = bounds.Left + .5 * bounds.Width; _AddLine(new Point(center, bounds.Top), new Point(center, bounds.Bottom), transform); return true; } else if (bounds.Height < maxLineWidth && bounds.Width > bounds.Height * minLineRatio) { double center = bounds.Top + .5 * bounds.Height; _AddLine(new Point(bounds.Left, center), new Point(bounds.Right, center), transform); return true; } return false; } // Check if each PathFigure within a PathGeometry has a line shape private void _ProcessSolidPath(Matrix transform, PathGeometry pathGeom) { PathFigureCollection pathFigures = pathGeom.Figures; // Single figure should already covered by bounding box check if ((pathFigures != null) && (pathFigures.Count > 1)) { foreach (PathFigure pathFigure in pathFigures) { PathGeometry pg = new PathGeometry(); pg.Figures.Add(pathFigure); _ProcessFilledRect(transform, pg.Bounds); } } } // Find all straight lines within a PathGeometry private void _ProcessOutlinePath(Matrix transform, PathGeometry pathGeom) { PathFigureCollection pathFigures = pathGeom.Figures; foreach (PathFigure pathFigure in pathFigures) { PathSegmentCollection pathSegments = pathFigure.Segments; Point startPoint = pathFigure.StartPoint; Point lastPoint = startPoint; foreach (PathSegment pathSegment in pathSegments) { if (pathSegment is ArcSegment) { lastPoint = (pathSegment as ArcSegment).Point; } else if (pathSegment is BezierSegment) { lastPoint = (pathSegment as BezierSegment).Point3; } else if (pathSegment is LineSegment) { Point endPoint = (pathSegment as LineSegment).Point; _AddLine(lastPoint, endPoint, transform); lastPoint = endPoint; } else if (pathSegment is PolyBezierSegment) { PointCollection points = (pathSegment as PolyBezierSegment).Points; lastPoint = points[points.Count - 1]; } else if (pathSegment is PolyLineSegment) { PointCollection points = (pathSegment as PolyLineSegment).Points; foreach (Point point in points) { _AddLine(lastPoint, point, transform); lastPoint = point; } } else if (pathSegment is PolyQuadraticBezierSegment) { PointCollection points = (pathSegment as PolyQuadraticBezierSegment).Points; lastPoint = points[points.Count - 1]; } else if (pathSegment is QuadraticBezierSegment) { lastPoint = (pathSegment as QuadraticBezierSegment).Point2; } else { Debug.Assert(false); } } if (pathFigure.IsClosed) { _AddLine(lastPoint, startPoint, transform); } } } private void _FillTables(List<FixedSOMTableRow> tableRows) { List<FixedSOMTable> tables = new List<FixedSOMTable>(); foreach (FixedSOMTableRow row in tableRows) { FixedSOMTable table = null; double fudge = 0.01; foreach (FixedSOMTable t in tables) { if (Math.Abs(t.BoundingRect.Left - row.BoundingRect.Left) < fudge && Math.Abs(t.BoundingRect.Right - row.BoundingRect.Right) < fudge && Math.Abs(t.BoundingRect.Bottom - row.BoundingRect.Top) < fudge) { table = t; break; } } if (table == null) { table = new FixedSOMTable(_fixedSOMPage); tables.Add(table); } table.AddRow(row); } //Check for nested tables first for (int i=0; i<tables.Count-1; i++) { for (int j=i+1; j<tables.Count; j++) { if (tables[i].BoundingRect.Contains(tables[j].BoundingRect) && tables[i].AddContainer(tables[j])) { tables.RemoveAt(j--); } else if (tables[j].BoundingRect.Contains(tables[i].BoundingRect) && tables[j].AddContainer(tables[i])) { tables.RemoveAt(i--); if (i < 0) { break; } } } } foreach (FixedSOMTable table in tables) { if (table.IsSingleCelled) { continue; } bool containsAnything = false; for (int i = 0; i < _fixedSOMPage.SemanticBoxes.Count;) { //Only FixedBlocks are added to tables at this stage if (_fixedSOMPage.SemanticBoxes[i] is FixedSOMFixedBlock && table.AddContainer(_fixedSOMPage.SemanticBoxes[i] as FixedSOMContainer)) { _fixedSOMPage.SemanticBoxes.RemoveAt(i); containsAnything = true; } else { i++; } } if (containsAnything) { table.DeleteEmptyRows(); table.DeleteEmptyColumns(); //Remove any internal empty tables //Do grouping and sorting inside cells foreach (FixedSOMTableRow row in table.SemanticBoxes) { foreach (FixedSOMTableCell cell in row.SemanticBoxes) { for (int i=0; i<cell.SemanticBoxes.Count;) { FixedSOMTable innerTable = cell.SemanticBoxes[i] as FixedSOMTable; if (innerTable != null && innerTable.IsEmpty) { cell.SemanticBoxes.Remove(innerTable); } else { i++; } } _CreateGroups(cell); cell.SemanticBoxes.Sort(); } } _fixedSOMPage.AddTable(table); } } } //Creates a set of groups inside this container based on heuristics. //This will ensure that elements consecutive in markup that also seem to be //spatially consecutive don't get separated private void _CreateGroups(FixedSOMContainer container) { if (container.SemanticBoxes.Count > 0) { List<FixedSOMSemanticBox> groups = new List<FixedSOMSemanticBox>(); FixedSOMGroup currentGroup = new FixedSOMGroup(_fixedSOMPage); FixedSOMPageElement currentPageElement = container.SemanticBoxes[0] as FixedSOMPageElement; Debug.Assert(currentPageElement != null); FixedSOMPageElement nextPageElement = null; currentGroup.AddContainer(currentPageElement); groups.Add(currentGroup); for (int i=1; i<container.SemanticBoxes.Count; i++) { nextPageElement = container.SemanticBoxes[i] as FixedSOMPageElement; Debug.Assert(nextPageElement != null); if (!( _IsSpatiallyCombinable(currentPageElement, nextPageElement, 0, 30) && nextPageElement.BoundingRect.Top >= currentPageElement.BoundingRect.Top)) { currentGroup = new FixedSOMGroup(_fixedSOMPage); groups.Add(currentGroup); } currentGroup.AddContainer(nextPageElement); currentPageElement = nextPageElement; } container.SemanticBoxes = groups; } } #endregion Private methods //-------------------------------------------------------------------- // // Private Fields // //--------------------------------------------------------------------- #region Private Fields private FixedSOMFixedBlock _currentFixedBlock; private int _pageIndex; private FixedPage _fixedPage; private FixedSOMPage _fixedSOMPage; private List<FixedNode> _fixedNodes; private FixedSOMLineCollection _lines; private GeometryWalker _geometryWalker; #endregion Private Fields } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.CommandLine; using Microsoft.Extensions.Configuration.EnvironmentVariables; using Newtonsoft.Json.Linq; using OrchardCore.Environment.Shell.Configuration; using OrchardCore.Environment.Shell.Models; namespace OrchardCore.Environment.Shell { public class ShellSettingsManager : IShellSettingsManager { private readonly IConfiguration _applicationConfiguration; private readonly IShellsConfigurationSources _tenantsConfigSources; private readonly IShellConfigurationSources _tenantConfigSources; private readonly IShellsSettingsSources _settingsSources; private IConfiguration _configuration; private IEnumerable<string> _configuredTenants; private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1); private Func<string, Task<IConfigurationBuilder>> _tenantConfigBuilderFactory; private readonly SemaphoreSlim _tenantConfigSemaphore = new SemaphoreSlim(1); public ShellSettingsManager( IConfiguration applicationConfiguration, IShellsConfigurationSources tenantsConfigSources, IShellConfigurationSources tenantConfigSources, IShellsSettingsSources settingsSources) { _applicationConfiguration = applicationConfiguration; _tenantsConfigSources = tenantsConfigSources; _tenantConfigSources = tenantConfigSources; _settingsSources = settingsSources; } public ShellSettings CreateDefaultSettings() { return new ShellSettings ( new ShellConfiguration(_configuration), new ShellConfiguration(_configuration) ); } public async Task<IEnumerable<ShellSettings>> LoadSettingsAsync() { await _semaphore.WaitAsync(); try { await EnsureConfigurationAsync(); var tenantsSettings = (await new ConfigurationBuilder() .AddSourcesAsync(_settingsSources)) .Build(); var tenants = tenantsSettings.GetChildren().Select(section => section.Key); var allTenants = _configuredTenants.Concat(tenants).Distinct().ToArray(); var allSettings = new List<ShellSettings>(); foreach (var tenant in allTenants) { var tenantSettings = new ConfigurationBuilder() .AddConfiguration(_configuration) .AddConfiguration(_configuration.GetSection(tenant)) .AddConfiguration(tenantsSettings.GetSection(tenant)) .Build(); var settings = new ShellConfiguration(tenantSettings); var configuration = new ShellConfiguration(tenant, _tenantConfigBuilderFactory); var shellSettings = new ShellSettings(settings, configuration) { Name = tenant, }; allSettings.Add(shellSettings); }; return allSettings; } finally { _semaphore.Release(); } } public async Task<ShellSettings> LoadSettingsAsync(string tenant) { await _semaphore.WaitAsync(); try { await EnsureConfigurationAsync(); var tenantsSettings = (await new ConfigurationBuilder() .AddSourcesAsync(_settingsSources)) .Build(); var tenantSettings = new ConfigurationBuilder() .AddConfiguration(_configuration) .AddConfiguration(_configuration.GetSection(tenant)) .AddConfiguration(tenantsSettings.GetSection(tenant)) .Build(); var settings = new ShellConfiguration(tenantSettings); var configuration = new ShellConfiguration(tenant, _tenantConfigBuilderFactory); return new ShellSettings(settings, configuration) { Name = tenant, }; } finally { _semaphore.Release(); } } public async Task SaveSettingsAsync(ShellSettings settings) { await _semaphore.WaitAsync(); try { await EnsureConfigurationAsync(); if (settings == null) { throw new ArgumentNullException(nameof(settings)); } var configuration = new ConfigurationBuilder() .AddConfiguration(_configuration) .AddConfiguration(_configuration.GetSection(settings.Name)) .Build(); var shellSettings = new ShellSettings() { Name = settings.Name }; configuration.Bind(shellSettings); var configSettings = JObject.FromObject(shellSettings); var tenantSettings = JObject.FromObject(settings); foreach (var property in configSettings) { var tenantValue = tenantSettings.Value<string>(property.Key); var configValue = configSettings.Value<string>(property.Key); if (tenantValue != configValue) { tenantSettings[property.Key] = tenantValue; } else { tenantSettings[property.Key] = null; } } tenantSettings.Remove("Name"); await _settingsSources.SaveAsync(settings.Name, tenantSettings.ToObject<Dictionary<string, string>>()); var tenantConfig = new JObject(); var sections = settings.ShellConfiguration.GetChildren() .Where(s => !s.GetChildren().Any()) .ToArray(); foreach (var section in sections) { if (settings[section.Key] != configuration[section.Key]) { tenantConfig[section.Key] = settings[section.Key]; } else { tenantConfig[section.Key] = null; } } tenantConfig.Remove("Name"); await _tenantConfigSemaphore.WaitAsync(); try { await _tenantConfigSources.SaveAsync(settings.Name, tenantConfig.ToObject<Dictionary<string, string>>()); } finally { _tenantConfigSemaphore.Release(); } } finally { _semaphore.Release(); } } private async Task EnsureConfigurationAsync() { if (_configuration != null) { return; } var lastProviders = (_applicationConfiguration as IConfigurationRoot)?.Providers .Where(p => p is EnvironmentVariablesConfigurationProvider || p is CommandLineConfigurationProvider) .ToArray(); var configurationBuilder = await new ConfigurationBuilder() .AddConfiguration(_applicationConfiguration) .AddSourcesAsync(_tenantsConfigSources); if (lastProviders.Count() > 0) { configurationBuilder.AddConfiguration(new ConfigurationRoot(lastProviders)); } var configuration = configurationBuilder.Build().GetSection("OrchardCore"); _configuredTenants = configuration.GetChildren() .Where(section => Enum.TryParse<TenantState>(section["State"], ignoreCase: true, out var result)) .Select(section => section.Key) .Distinct() .ToArray(); _tenantConfigBuilderFactory = async (tenant) => { await _tenantConfigSemaphore.WaitAsync(); try { var builder = new ConfigurationBuilder().AddConfiguration(_configuration); builder.AddConfiguration(configuration.GetSection(tenant)); return await builder.AddSourcesAsync(tenant, _tenantConfigSources); } finally { _tenantConfigSemaphore.Release(); } }; _configuration = configuration; } } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // namespace DiscUtils.Iso9660 { using System; using System.Collections.Generic; using System.Globalization; using System.Text; /// <summary> /// Represents a directory that will be built into the ISO image. /// </summary> public sealed class BuildDirectoryInfo : BuildDirectoryMember { internal static readonly Comparer<BuildDirectoryInfo> PathTableSortComparison = new PathTableComparison(); private BuildDirectoryInfo _parent; private Dictionary<string, BuildDirectoryMember> _members; private int _hierarchyDepth; private List<BuildDirectoryMember> _sortedMembers; internal BuildDirectoryInfo(string name, BuildDirectoryInfo parent) : base(name, MakeShortDirName(name, parent)) { _parent = (parent == null) ? this : parent; _hierarchyDepth = (parent == null) ? 0 : parent._hierarchyDepth + 1; _members = new Dictionary<string, BuildDirectoryMember>(); } /// <summary> /// The parent directory, or <c>null</c> if none. /// </summary> public override BuildDirectoryInfo Parent { get { return _parent; } } internal int HierarchyDepth { get { return _hierarchyDepth; } } /// <summary> /// Gets the specified child directory or file. /// </summary> /// <param name="name">The name of the file or directory to get.</param> /// <param name="member">The member found (or <c>null</c>).</param> /// <returns><c>true</c> if the specified member was found.</returns> internal bool TryGetMember(string name, out BuildDirectoryMember member) { return _members.TryGetValue(name, out member); } internal void Add(BuildDirectoryMember member) { _members.Add(member.Name, member); _sortedMembers = null; } internal override long GetDataSize(Encoding enc) { List<BuildDirectoryMember> sorted = GetSortedMembers(); long total = 34 * 2; // Two pseudo entries (self & parent) foreach (BuildDirectoryMember m in sorted) { uint recordSize = m.GetDirectoryRecordSize(enc); // If this record would span a sector boundary, then the current sector is // zero-padded, and the record goes at the start of the next sector. if ((total % IsoUtilities.SectorSize) + recordSize > IsoUtilities.SectorSize) { long padLength = IsoUtilities.SectorSize - (total % IsoUtilities.SectorSize); total += padLength; } total += recordSize; } return Utilities.RoundUp(total, IsoUtilities.SectorSize); } internal uint GetPathTableEntrySize(Encoding enc) { int nameBytes = enc.GetByteCount(PickName(null, enc)); return (uint)(8 + nameBytes + (((nameBytes & 0x1) == 1) ? 1 : 0)); } internal int Write(byte[] buffer, int offset, Dictionary<BuildDirectoryMember, uint> locationTable, Encoding enc) { int pos = 0; List<BuildDirectoryMember> sorted = GetSortedMembers(); // Two pseudo entries, effectively '.' and '..' pos += WriteMember(this, "\0", Encoding.ASCII, buffer, offset + pos, locationTable, enc); pos += WriteMember(_parent, "\x01", Encoding.ASCII, buffer, offset + pos, locationTable, enc); foreach (BuildDirectoryMember m in sorted) { uint recordSize = m.GetDirectoryRecordSize(enc); if ((pos % IsoUtilities.SectorSize) + recordSize > IsoUtilities.SectorSize) { int padLength = IsoUtilities.SectorSize - (pos % IsoUtilities.SectorSize); Array.Clear(buffer, offset + pos, padLength); pos += padLength; } pos += WriteMember(m, null, enc, buffer, offset + pos, locationTable, enc); } // Ensure final padding data is zero'd int finalPadLength = Utilities.RoundUp(pos, IsoUtilities.SectorSize) - pos; Array.Clear(buffer, offset + pos, finalPadLength); return pos + finalPadLength; } private static int WriteMember(BuildDirectoryMember m, string nameOverride, Encoding nameEnc, byte[] buffer, int offset, Dictionary<BuildDirectoryMember, uint> locationTable, Encoding dataEnc) { DirectoryRecord dr = new DirectoryRecord(); dr.FileIdentifier = m.PickName(nameOverride, nameEnc); dr.LocationOfExtent = locationTable[m]; dr.DataLength = (uint)m.GetDataSize(dataEnc); dr.RecordingDateAndTime = m.CreationTime; dr.Flags = (m is BuildDirectoryInfo) ? FileFlags.Directory : FileFlags.None; return dr.WriteTo(buffer, offset, nameEnc); } private static string MakeShortDirName(string longName, BuildDirectoryInfo dir) { if (IsoUtilities.IsValidDirectoryName(longName)) { return longName; } char[] shortNameChars = longName.ToUpper(CultureInfo.InvariantCulture).ToCharArray(); for (int i = 0; i < shortNameChars.Length; ++i) { if (!IsoUtilities.IsValidDChar(shortNameChars[i]) && shortNameChars[i] != '.' && shortNameChars[i] != ';') { shortNameChars[i] = '_'; } } return new string(shortNameChars); } private List<BuildDirectoryMember> GetSortedMembers() { if (_sortedMembers == null) { List<BuildDirectoryMember> sorted = new List<BuildDirectoryMember>(_members.Values); sorted.Sort(BuildDirectoryMember.SortedComparison); _sortedMembers = sorted; } return _sortedMembers; } private class PathTableComparison : Comparer<BuildDirectoryInfo> { public override int Compare(BuildDirectoryInfo x, BuildDirectoryInfo y) { if (x.HierarchyDepth != y.HierarchyDepth) { return x.HierarchyDepth - y.HierarchyDepth; } if (x.Parent != y.Parent) { return Compare(x.Parent, y.Parent); } return CompareNames(x.Name, y.Name, ' '); } private static int CompareNames(string x, string y, char padChar) { int max = Math.Max(x.Length, y.Length); for (int i = 0; i < max; ++i) { char xChar = (i < x.Length) ? x[i] : padChar; char yChar = (i < y.Length) ? y[i] : padChar; if (xChar != yChar) { return xChar - yChar; } } return 0; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Diagnostics; using System.IO; using System.Threading; using System.Speech.Recognition; using eDocumentReader.Hubs.structure; namespace eDocumentReader.Hubs { public enum Mode{ RECORD, REPLAY, REALTIME, TTS, UNKNOWN } public class StoryManager { private readonly string navigationCommandFileName = "command.grxml"; private string storyDirectory; private Story currentStory; private string tests; List<Story> stories = new List<Story>(); private TextProcessor textProcessor; private LogPlayer audioProcessor; //used to replay recorded speech private StoryLoggingDevice storyLogger; private Mode storyMode = Mode.UNKNOWN; public StoryManager() { textProcessor = new TextProcessor(); audioProcessor = new LogPlayer(); storyLogger = new StoryLoggingDevice(); } public void init(string storyDirectory) { //initialize story foreach (string d in Directory.GetDirectories(storyDirectory)) { foreach (string xmlMainFileName in Directory.GetFiles(d, "*.xml")) { Story story = new Story(xmlMainFileName); Debug.WriteLine(story.ToString()); stories.Add(story); } } this.storyDirectory = storyDirectory; textProcessor.SetStoryDirectory(storyDirectory); } public void stop() { audioProcessor.stop(); audioProcessor = new LogPlayer(); } public void pause() { audioProcessor.pause(); } public void resume() { audioProcessor.resume(); } public string[] getStoryNames() { string[] ret = new string[stories.Count]; for (int i = 0; i < stories.Count; i++) { ret[i] = stories.ElementAt(i).GetStoryName(); } return ret; } public void SetStory(string storyName) { foreach (Story s in stories) { if (s.GetStoryName().CompareTo(storyName) == 0) { currentStory = s; break; } } generateSpeechSynthesisData(); } public string getCurrentStoryPath() { if(currentStory != null){ return currentStory.getFullPath(); } return null; } private void generateSpeechSynthesisData() { EBookSpeechSynthesizer.getInstance().generateSynthesisData(currentStory); } public List<string> getCommandGrammars() { List<string> grammarList = new List<string>(); foreach (string grxmlFile in Directory.GetFiles(storyDirectory, navigationCommandFileName)) { grammarList.Add(grxmlFile); } return grammarList; } public void changeStoryMode(Mode storyMode) { this.storyMode = storyMode; } public void startReplay(string path) { audioProcessor.processAudioFiles(path); textProcessor.process(currentStory.GetFirstPage(), storyMode); } public void start() { textProcessor.process(currentStory.GetFirstPage(), storyMode); } public void finishReplayAudio(int audioIndex) { audioProcessor.finishReplayAudio(audioIndex); } public void confirmHighlight() { textProcessor.confirmHighlight(); } /* * USE IN RECORD MODE * The user click reject to clear out the unconfirm recordings */ public void rollBackHighlight() { textProcessor.rollBackHighlight(); } /* * update the recognized text */ public void updateRecognizedText(float confidence, string textResult, bool isHypothesis, KeyValuePair<string, SemanticValue>[] semantics, string grammarName, string ruleName, double audioDuration, string wavPath) { textProcessor.processRecognitionResult(confidence, textResult, isHypothesis, semantics, grammarName, ruleName, audioDuration, wavPath); } /* * update the speech state. */ public void updateSpeechState(SpeechState state) { textProcessor.setSpeechState(state); } public void updateAcousticHypothesis(int audioState, double startTime) { textProcessor.processAcousticHypothesisHighlight(audioState, startTime); } /** * remove the last highlight if the SR reject the intermidiate result at the final stage */ public void removeLastHighlight() { textProcessor.rollBackText(); } public Mode getStoryMode() { return storyMode; } /* * Change page in the story. */ public void changePage(PageAction pa, int pageNum) { if (pa == PageAction.NEXT) { Page page = currentStory.GetNextPage(); if (page != null) { textProcessor.process(page, storyMode); } } else if (pa == PageAction.PREVIOUS) { Page page = currentStory.GetPreviousPage(); if (page != null) { textProcessor.process(page, storyMode); } } else if (pa == PageAction.GO_PAGE_X) { Page page = currentStory.GetPage(pageNum); if (page != null) { textProcessor.process(page, storyMode); } } } } }
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using Ctrip.Layout; using Ctrip.Core; using Ctrip.DateFormatter; using Ctrip.Layout.Pattern; using Ctrip.Util; namespace Ctrip.Util { /// <summary> /// Most of the work of the <see cref="PatternLayout"/> class /// is delegated to the PatternParser class. /// </summary> /// <remarks> /// <para> /// The <c>PatternParser</c> processes a pattern string and /// returns a chain of <see cref="PatternConverter"/> objects. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public sealed class PatternParser { #region Public Instance Constructors /// <summary> /// Constructor /// </summary> /// <param name="pattern">The pattern to parse.</param> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="PatternParser" /> class /// with the specified pattern string. /// </para> /// </remarks> public PatternParser(string pattern) { m_pattern = pattern; } #endregion Public Instance Constructors #region Public Instance Methods /// <summary> /// Parses the pattern into a chain of pattern converters. /// </summary> /// <returns>The head of a chain of pattern converters.</returns> /// <remarks> /// <para> /// Parses the pattern into a chain of pattern converters. /// </para> /// </remarks> public PatternConverter Parse() { string[] converterNamesCache = BuildCache(); ParseInternal(m_pattern, converterNamesCache); return m_head; } #endregion Public Instance Methods #region Public Instance Properties /// <summary> /// Get the converter registry used by this parser /// </summary> /// <value> /// The converter registry used by this parser /// </value> /// <remarks> /// <para> /// Get the converter registry used by this parser /// </para> /// </remarks> public Hashtable PatternConverters { get { return m_patternConverters; } } #endregion Public Instance Properties #region Private Instance Methods /// <summary> /// Build the unified cache of converters from the static and instance maps /// </summary> /// <returns>the list of all the converter names</returns> /// <remarks> /// <para> /// Build the unified cache of converters from the static and instance maps /// </para> /// </remarks> private string[] BuildCache() { string[] converterNamesCache = new string[m_patternConverters.Keys.Count]; m_patternConverters.Keys.CopyTo(converterNamesCache, 0); // sort array so that longer strings come first Array.Sort(converterNamesCache, 0, converterNamesCache.Length, StringLengthComparer.Instance); return converterNamesCache; } #region StringLengthComparer /// <summary> /// Sort strings by length /// </summary> /// <remarks> /// <para> /// <see cref="IComparer" /> that orders strings by string length. /// The longest strings are placed first /// </para> /// </remarks> private sealed class StringLengthComparer : IComparer { public static readonly StringLengthComparer Instance = new StringLengthComparer(); private StringLengthComparer() { } #region Implementation of IComparer public int Compare(object x, object y) { string s1 = x as string; string s2 = y as string; if (s1 == null && s2 == null) { return 0; } if (s1 == null) { return 1; } if (s2 == null) { return -1; } return s2.Length.CompareTo(s1.Length); } #endregion } #endregion // StringLengthComparer /// <summary> /// Internal method to parse the specified pattern to find specified matches /// </summary> /// <param name="pattern">the pattern to parse</param> /// <param name="matches">the converter names to match in the pattern</param> /// <remarks> /// <para> /// The matches param must be sorted such that longer strings come before shorter ones. /// </para> /// </remarks> private void ParseInternal(string pattern, string[] matches) { int offset = 0; while(offset < pattern.Length) { int i = pattern.IndexOf('%', offset); if (i < 0 || i == pattern.Length - 1) { ProcessLiteral(pattern.Substring(offset)); offset = pattern.Length; } else { if (pattern[i+1] == '%') { // Escaped ProcessLiteral(pattern.Substring(offset, i - offset + 1)); offset = i + 2; } else { ProcessLiteral(pattern.Substring(offset, i - offset)); offset = i + 1; FormattingInfo formattingInfo = new FormattingInfo(); // Process formatting options // Look for the align flag if (offset < pattern.Length) { if (pattern[offset] == '-') { // Seen align flag formattingInfo.LeftAlign = true; offset++; } } // Look for the minimum length while (offset < pattern.Length && char.IsDigit(pattern[offset])) { // Seen digit if (formattingInfo.Min < 0) { formattingInfo.Min = 0; } formattingInfo.Min = (formattingInfo.Min * 10) + int.Parse(pattern[offset].ToString(CultureInfo.InvariantCulture), System.Globalization.NumberFormatInfo.InvariantInfo); offset++; } // Look for the separator between min and max if (offset < pattern.Length) { if (pattern[offset] == '.') { // Seen separator offset++; } } // Look for the maximum length while (offset < pattern.Length && char.IsDigit(pattern[offset])) { // Seen digit if (formattingInfo.Max == int.MaxValue) { formattingInfo.Max = 0; } formattingInfo.Max = (formattingInfo.Max * 10) + int.Parse(pattern[offset].ToString(CultureInfo.InvariantCulture), System.Globalization.NumberFormatInfo.InvariantInfo); offset++; } int remainingStringLength = pattern.Length - offset; // Look for pattern for(int m=0; m<matches.Length; m++) { if (matches[m].Length <= remainingStringLength) { if (String.Compare(pattern, offset, matches[m], 0, matches[m].Length, false, System.Globalization.CultureInfo.InvariantCulture) == 0) { // Found match offset = offset + matches[m].Length; string option = null; // Look for option if (offset < pattern.Length) { if (pattern[offset] == '{') { // Seen option start offset++; int optEnd = pattern.IndexOf('}', offset); if (optEnd < 0) { // error } else { option = pattern.Substring(offset, optEnd - offset); offset = optEnd + 1; } } } ProcessConverter(matches[m], option, formattingInfo); break; } } } } } } } /// <summary> /// Process a parsed literal /// </summary> /// <param name="text">the literal text</param> private void ProcessLiteral(string text) { if (text.Length > 0) { // Convert into a pattern ProcessConverter("literal", text, new FormattingInfo()); } } /// <summary> /// Process a parsed converter pattern /// </summary> /// <param name="converterName">the name of the converter</param> /// <param name="option">the optional option for the converter</param> /// <param name="formattingInfo">the formatting info for the converter</param> private void ProcessConverter(string converterName, string option, FormattingInfo formattingInfo) { LogLog.Debug(declaringType, "Converter ["+converterName+"] Option ["+option+"] Format [min="+formattingInfo.Min+",max="+formattingInfo.Max+",leftAlign="+formattingInfo.LeftAlign+"]"); // Lookup the converter type ConverterInfo converterInfo = (ConverterInfo)m_patternConverters[converterName]; if (converterInfo == null) { LogLog.Error(declaringType, "Unknown converter name ["+converterName+"] in conversion pattern."); } else { // Create the pattern converter PatternConverter pc = null; try { pc = (PatternConverter)Activator.CreateInstance(converterInfo.Type); } catch(Exception createInstanceEx) { LogLog.Error(declaringType, "Failed to create instance of Type [" + converterInfo.Type.FullName + "] using default constructor. Exception: " + createInstanceEx.ToString()); } // formattingInfo variable is an instance variable, occasionally reset // and used over and over again pc.FormattingInfo = formattingInfo; pc.Option = option; pc.Properties = converterInfo.Properties; IOptionHandler optionHandler = pc as IOptionHandler; if (optionHandler != null) { optionHandler.ActivateOptions(); } AddConverter(pc); } } /// <summary> /// Resets the internal state of the parser and adds the specified pattern converter /// to the chain. /// </summary> /// <param name="pc">The pattern converter to add.</param> private void AddConverter(PatternConverter pc) { // Add the pattern converter to the list. if (m_head == null) { m_head = m_tail = pc; } else { // Set the next converter on the tail // Update the tail reference // note that a converter may combine the 'next' into itself // and therefore the tail would not change! m_tail = m_tail.SetNext(pc); } } #endregion Protected Instance Methods #region Private Constants private const char ESCAPE_CHAR = '%'; #endregion Private Constants #region Private Instance Fields /// <summary> /// The first pattern converter in the chain /// </summary> private PatternConverter m_head; /// <summary> /// the last pattern converter in the chain /// </summary> private PatternConverter m_tail; /// <summary> /// The pattern /// </summary> private string m_pattern; /// <summary> /// Internal map of converter identifiers to converter types /// </summary> /// <remarks> /// <para> /// This map overrides the static s_globalRulesRegistry map. /// </para> /// </remarks> private Hashtable m_patternConverters = new Hashtable(); #endregion Private Instance Fields #region Private Static Fields /// <summary> /// The fully qualified type of the PatternParser class. /// </summary> /// <remarks> /// Used by the internal logger to record the Type of the /// log message. /// </remarks> private readonly static Type declaringType = typeof(PatternParser); #endregion Private Static Fields } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using UnityEngine; namespace HoloToolkit.Unity { /// <summary> /// Currently active AudioEvents along with their AudioSource components for instance limiting events /// </summary> public class ActiveEvent : IDisposable { private AudioSource primarySource = null; public AudioSource PrimarySource { get { return primarySource; } private set { primarySource = value; if (primarySource != null) { primarySource.enabled = true; } } } private AudioSource secondarySource = null; public AudioSource SecondarySource { get { return secondarySource; } private set { secondarySource = value; if (secondarySource != null) { secondarySource.enabled = true; } } } public bool IsPlaying { get { return (primarySource != null && primarySource.isPlaying) || (secondarySource != null && secondarySource.isPlaying); } } public GameObject AudioEmitter { get; private set; } public string MessageOnAudioEnd { get; private set; } public AudioEvent AudioEvent = null; public bool IsStoppable = true; public float VolDest = 1; public float AltVolDest = 1; public float CurrentFade = 0; public bool PlayingAlt = false; public bool IsActiveTimeComplete = false; public float ActiveTime = 0; public bool CancelEvent = false; public ActiveEvent(AudioEvent audioEvent, GameObject emitter, AudioSource primarySource, AudioSource secondarySource, string messageOnAudioEnd = null) { this.AudioEvent = audioEvent; AudioEmitter = emitter; PrimarySource = primarySource; SecondarySource = secondarySource; MessageOnAudioEnd = messageOnAudioEnd; SetSourceProperties(); } public static AnimationCurve SpatialRolloff; /// <summary> /// Set the volume, spatialization, etc., on our AudioSources to match the settings on the event to play. /// </summary> private void SetSourceProperties() { Action<Action<AudioSource>> forEachSource = (action) => { action(PrimarySource); if (SecondarySource != null) { action(SecondarySource); } }; AudioEvent audioEvent = this.AudioEvent; switch (audioEvent.Spatialization) { case SpatialPositioningType.TwoD: forEachSource((source) => { source.spatialBlend = 0f; source.spatialize = false; }); break; case SpatialPositioningType.ThreeD: forEachSource((source) => { source.spatialBlend = 1f; source.spatialize = false; }); break; case SpatialPositioningType.SpatialSound: forEachSource((source) => { source.spatialBlend = 1f; source.spatialize = true; }); break; default: Debug.LogErrorFormat("Unexpected spatialization type: {0}", audioEvent.Spatialization.ToString()); break; } if (audioEvent.Spatialization == SpatialPositioningType.SpatialSound) { forEachSource((source) => { SpatialSoundSettings.SetRoomSize(source, audioEvent.RoomSize); source.rolloffMode = AudioRolloffMode.Custom; source.maxDistance = audioEvent.MaxDistanceAttenuation3D; source.SetCustomCurve(AudioSourceCurveType.CustomRolloff, audioEvent.AttenuationCurve); }); } else { forEachSource((source) => { if (audioEvent.Spatialization == SpatialPositioningType.ThreeD) { source.rolloffMode = AudioRolloffMode.Custom; source.maxDistance = audioEvent.MaxDistanceAttenuation3D; source.SetCustomCurve(AudioSourceCurveType.CustomRolloff, audioEvent.AttenuationCurve); source.SetCustomCurve(AudioSourceCurveType.SpatialBlend, audioEvent.SpatialCurve); source.SetCustomCurve(AudioSourceCurveType.Spread, audioEvent.SpreadCurve); source.SetCustomCurve(AudioSourceCurveType.ReverbZoneMix, audioEvent.ReverbCurve); } else { source.rolloffMode = AudioRolloffMode.Logarithmic; } }); } if (audioEvent.AudioBus != null) { forEachSource((source) => source.outputAudioMixerGroup = audioEvent.AudioBus); } float pitch = 1f; if (audioEvent.PitchRandomization != 0) { pitch = UnityEngine.Random.Range(audioEvent.PitchCenter - audioEvent.PitchRandomization, audioEvent.PitchCenter + audioEvent.PitchRandomization); } else { pitch = audioEvent.PitchCenter; } forEachSource((source) => source.pitch = pitch); float vol = 1f; if (audioEvent.FadeInTime > 0) { forEachSource((source) => source.volume = 0f); this.CurrentFade = audioEvent.FadeInTime; if (audioEvent.VolumeRandomization != 0) { vol = UnityEngine.Random.Range(audioEvent.VolumeCenter - audioEvent.VolumeRandomization, audioEvent.VolumeCenter + audioEvent.VolumeRandomization); } else { vol = audioEvent.VolumeCenter; } this.VolDest = vol; } else { if (audioEvent.VolumeRandomization != 0) { vol = UnityEngine.Random.Range(audioEvent.VolumeCenter - audioEvent.VolumeRandomization, audioEvent.VolumeCenter + audioEvent.VolumeRandomization); } else { vol = audioEvent.VolumeCenter; } forEachSource((source) => source.volume = vol); } float pan = audioEvent.PanCenter; if (audioEvent.PanRandomization != 0) { pan = UnityEngine.Random.Range(audioEvent.PanCenter - audioEvent.PanRandomization, audioEvent.PanCenter + audioEvent.PanRandomization); } forEachSource((source) => source.panStereo = pan); } /// <summary> /// Sets the pitch value for the primary source. /// </summary> /// <param name="newPitch">The value to set the pitch, between 0 (exclusive) and 3 (inclusive).</param> public void SetPitch(float newPitch) { if (newPitch <= 0 || newPitch > 3) { Debug.LogErrorFormat("Invalid pitch {0} set for event", newPitch); return; } this.PrimarySource.pitch = newPitch; } public void Dispose() { if (this.primarySource != null) { this.primarySource.enabled = false; this.primarySource = null; } if (this.secondarySource != null) { this.secondarySource.enabled = false; this.secondarySource = null; } } /// <summary> /// Creates a flat animation curve to negate Unity's distance attenuation when using Spatial Sound /// </summary> public static void CreateFlatSpatialRolloffCurve() { if (SpatialRolloff != null) { return; } SpatialRolloff = new AnimationCurve(); SpatialRolloff.AddKey(0, 1); SpatialRolloff.AddKey(1, 1); } } }
// // BEncodedNumber.cs // // Authors: // Alan McGovern [email protected] // // Copyright (C) 2006 Alan McGovern // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Text; using System.Collections.Generic; namespace TorrentHardLinkHelper.BEncoding { /// <summary> /// Class representing a BEncoded number /// </summary> public class BEncodedNumber : BEncodedValue, IComparable<BEncodedNumber> { #region Member Variables /// <summary> /// The value of the BEncodedNumber /// </summary> public long Number { get { return number; } set { number = value; } } internal long number; #endregion #region Constructors public BEncodedNumber() : this(0) { } /// <summary> /// Create a new BEncoded number with the given value /// </summary> /// <param name="initialValue">The inital value of the BEncodedNumber</param> public BEncodedNumber(long value) { this.number = value; } public static implicit operator BEncodedNumber(long value) { return new BEncodedNumber(value); } #endregion #region Encode/Decode Methods /// <summary> /// Encodes this number to the supplied byte[] starting at the supplied offset /// </summary> /// <param name="buffer">The buffer to write the data to</param> /// <param name="offset">The offset to start writing the data at</param> /// <returns></returns> public override int Encode(byte[] buffer, int offset) { long number = this.number; int written = offset; buffer[written++] = (byte)'i'; if (number < 0) { buffer[written++] = (byte)'-'; number = -number; } // Reverse the number '12345' to get '54321' long reversed = 0; for (long i = number; i != 0; i /= 10) reversed = reversed * 10 + i % 10; // Write each digit of the reversed number to the array. We write '1' // first, then '2', etc for (long i = reversed; i != 0; i /= 10) buffer[written++] = (byte)(i % 10 + '0'); if (number == 0) buffer[written++] = (byte)'0'; // If the original number ends in one or more zeros, they are lost // when we reverse the number. We add them back in here. for (long i = number; i % 10 == 0 && number != 0; i /= 10) buffer[written++] = (byte)'0'; buffer[written++] = (byte)'e'; return written - offset; } /// <summary> /// Decodes a BEncoded number from the supplied RawReader /// </summary> /// <param name="reader">RawReader containing a BEncoded Number</param> internal override void DecodeInternal(RawReader reader) { int sign = 1; if (reader == null) throw new ArgumentNullException("reader"); if (reader.ReadByte() != 'i') // remove the leading 'i' throw new BEncodingException("Invalid data found. Aborting."); if (reader.PeekByte() == '-') { sign = -1; reader.ReadByte (); } int letter; while (((letter = reader.PeekByte()) != -1) && letter != 'e') { if(letter < '0' || letter > '9') throw new BEncodingException("Invalid number found."); number = number * 10 + (letter - '0'); reader.ReadByte (); } if (reader.ReadByte() != 'e') //remove the trailing 'e' throw new BEncodingException("Invalid data found. Aborting."); number *= sign; } #endregion #region Helper Methods /// <summary> /// Returns the length of the encoded string in bytes /// </summary> /// <returns></returns> public override int LengthInBytes() { long number = this.number; int count = 2; // account for the 'i' and 'e' if (number == 0) return count + 1; if (number < 0) { number = -number; count++; } for (long i = number; i != 0; i /= 10) count++; return count; } public int CompareTo(object other) { if (other is BEncodedNumber || other is long || other is int) return CompareTo((BEncodedNumber)other); return -1; } public int CompareTo(BEncodedNumber other) { if (other == null) throw new ArgumentNullException("other"); return this.number.CompareTo(other.number); } public int CompareTo(long other) { return this.number.CompareTo(other); } #endregion #region Overridden Methods /// <summary> /// /// </summary> /// <param name="obj"></param> /// <returns></returns> public override bool Equals(object obj) { BEncodedNumber obj2 = obj as BEncodedNumber; if (obj2 == null) return false; return (this.number == obj2.number); } /// <summary> /// /// </summary> /// <returns></returns> public override int GetHashCode() { return this.number.GetHashCode(); } /// <summary> /// /// </summary> /// <returns></returns> public override string ToString() { return (this.number.ToString()); } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using NUnit.Framework; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes; using OpenSim.Tests.Common; using log4net; namespace OpenSim.Region.Framework.Scenes.Tests { [TestFixture] public class SceneObjectLinkingTests : OpenSimTestCase { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Links to self should be ignored. /// </summary> [Test] public void TestLinkToSelf() { TestHelpers.InMethod(); UUID ownerId = TestHelpers.ParseTail(0x1); int nParts = 3; TestScene scene = new SceneHelpers().SetupScene(); SceneObjectGroup sog1 = SceneHelpers.CreateSceneObject(nParts, ownerId, "TestLinkToSelf_", 0x10); scene.AddSceneObject(sog1); scene.LinkObjects(ownerId, sog1.LocalId, new List<uint>() { sog1.Parts[1].LocalId }); // sog1.LinkToGroup(sog1); Assert.That(sog1.Parts.Length, Is.EqualTo(nParts)); } [Test] public void TestLinkDelink2SceneObjects() { TestHelpers.InMethod(); bool debugtest = false; Scene scene = new SceneHelpers().SetupScene(); SceneObjectGroup grp1 = SceneHelpers.AddSceneObject(scene); SceneObjectPart part1 = grp1.RootPart; SceneObjectGroup grp2 = SceneHelpers.AddSceneObject(scene); SceneObjectPart part2 = grp2.RootPart; grp1.AbsolutePosition = new Vector3(10, 10, 10); grp2.AbsolutePosition = Vector3.Zero; // <90,0,0> // grp1.UpdateGroupRotationR(Quaternion.CreateFromEulers(90 * Utils.DEG_TO_RAD, 0, 0)); // <180,0,0> grp2.UpdateGroupRotationR(Quaternion.CreateFromEulers(180 * Utils.DEG_TO_RAD, 0, 0)); // Required for linking grp1.RootPart.ClearUpdateSchedule(); grp2.RootPart.ClearUpdateSchedule(); // Link grp2 to grp1. part2 becomes child prim to grp1. grp2 is eliminated. Assert.IsFalse(grp1.GroupContainsForeignPrims); grp1.LinkToGroup(grp2); Assert.IsTrue(grp1.GroupContainsForeignPrims); scene.Backup(true); Assert.IsFalse(grp1.GroupContainsForeignPrims); // FIXME: Can't do this test yet since group 2 still has its root part! We can't yet null this since // it might cause SOG.ProcessBackup() to fail due to the race condition. This really needs to be fixed. Assert.That(grp2.IsDeleted, "SOG 2 was not registered as deleted after link."); Assert.That(grp2.Parts.Length, Is.EqualTo(0), "Group 2 still contained children after delink."); Assert.That(grp1.Parts.Length == 2); if (debugtest) { m_log.Debug("parts: " + grp1.Parts.Length); m_log.Debug("Group1: Pos:"+grp1.AbsolutePosition+", Rot:"+grp1.GroupRotation); m_log.Debug("Group1: Prim1: OffsetPosition:"+ part1.OffsetPosition+", OffsetRotation:"+part1.RotationOffset); m_log.Debug("Group1: Prim2: OffsetPosition:"+part2.OffsetPosition+", OffsetRotation:"+part2.RotationOffset); } // root part should have no offset position or rotation Assert.That(part1.OffsetPosition == Vector3.Zero && part1.RotationOffset == Quaternion.Identity, "root part should have no offset position or rotation"); // offset position should be root part position - part2.absolute position. Assert.That(part2.OffsetPosition == new Vector3(-10, -10, -10), "offset position should be root part position - part2.absolute position."); float roll = 0; float pitch = 0; float yaw = 0; // There's a euler anomoly at 180, 0, 0 so expect 180 to turn into -180. part1.RotationOffset.GetEulerAngles(out roll, out pitch, out yaw); Vector3 rotEuler1 = new Vector3(roll * Utils.RAD_TO_DEG, pitch * Utils.RAD_TO_DEG, yaw * Utils.RAD_TO_DEG); if (debugtest) m_log.Debug(rotEuler1); part2.RotationOffset.GetEulerAngles(out roll, out pitch, out yaw); Vector3 rotEuler2 = new Vector3(roll * Utils.RAD_TO_DEG, pitch * Utils.RAD_TO_DEG, yaw * Utils.RAD_TO_DEG); if (debugtest) m_log.Debug(rotEuler2); Assert.That(rotEuler2.ApproxEquals(new Vector3(-180, 0, 0), 0.001f) || rotEuler2.ApproxEquals(new Vector3(180, 0, 0), 0.001f), "Not exactly sure what this is asserting..."); // Delink part 2 SceneObjectGroup grp3 = grp1.DelinkFromGroup(part2.LocalId); if (debugtest) m_log.Debug("Group2: Prim2: OffsetPosition:" + part2.AbsolutePosition + ", OffsetRotation:" + part2.RotationOffset); Assert.That(grp1.Parts.Length, Is.EqualTo(1), "Group 1 still contained part2 after delink."); Assert.That(part2.AbsolutePosition == Vector3.Zero, "The absolute position should be zero"); Assert.NotNull(grp3); } [Test] public void TestLinkDelink2groups4SceneObjects() { TestHelpers.InMethod(); bool debugtest = false; Scene scene = new SceneHelpers().SetupScene(); SceneObjectGroup grp1 = SceneHelpers.AddSceneObject(scene); SceneObjectPart part1 = grp1.RootPart; SceneObjectGroup grp2 = SceneHelpers.AddSceneObject(scene); SceneObjectPart part2 = grp2.RootPart; SceneObjectGroup grp3 = SceneHelpers.AddSceneObject(scene); SceneObjectPart part3 = grp3.RootPart; SceneObjectGroup grp4 = SceneHelpers.AddSceneObject(scene); SceneObjectPart part4 = grp4.RootPart; grp1.AbsolutePosition = new Vector3(10, 10, 10); grp2.AbsolutePosition = Vector3.Zero; grp3.AbsolutePosition = new Vector3(20, 20, 20); grp4.AbsolutePosition = new Vector3(40, 40, 40); // <90,0,0> // grp1.UpdateGroupRotationR(Quaternion.CreateFromEulers(90 * Utils.DEG_TO_RAD, 0, 0)); // <180,0,0> grp2.UpdateGroupRotationR(Quaternion.CreateFromEulers(180 * Utils.DEG_TO_RAD, 0, 0)); // <270,0,0> // grp3.UpdateGroupRotationR(Quaternion.CreateFromEulers(270 * Utils.DEG_TO_RAD, 0, 0)); // <0,90,0> grp4.UpdateGroupRotationR(Quaternion.CreateFromEulers(0, 90 * Utils.DEG_TO_RAD, 0)); // Required for linking grp1.RootPart.ClearUpdateSchedule(); grp2.RootPart.ClearUpdateSchedule(); grp3.RootPart.ClearUpdateSchedule(); grp4.RootPart.ClearUpdateSchedule(); // Link grp2 to grp1. part2 becomes child prim to grp1. grp2 is eliminated. grp1.LinkToGroup(grp2); // Link grp4 to grp3. grp3.LinkToGroup(grp4); // At this point we should have 4 parts total in two groups. Assert.That(grp1.Parts.Length == 2, "Group1 children count should be 2"); Assert.That(grp2.IsDeleted, "Group 2 was not registered as deleted after link."); Assert.That(grp2.Parts.Length, Is.EqualTo(0), "Group 2 still contained parts after delink."); Assert.That(grp3.Parts.Length == 2, "Group3 children count should be 2"); Assert.That(grp4.IsDeleted, "Group 4 was not registered as deleted after link."); Assert.That(grp4.Parts.Length, Is.EqualTo(0), "Group 4 still contained parts after delink."); if (debugtest) { m_log.Debug("--------After Link-------"); m_log.Debug("Group1: parts:" + grp1.Parts.Length); m_log.Debug("Group1: Pos:"+grp1.AbsolutePosition+", Rot:"+grp1.GroupRotation); m_log.Debug("Group1: Prim1: OffsetPosition:" + part1.OffsetPosition + ", OffsetRotation:" + part1.RotationOffset); m_log.Debug("Group1: Prim2: OffsetPosition:"+part2.OffsetPosition+", OffsetRotation:"+ part2.RotationOffset); m_log.Debug("Group3: parts:" + grp3.Parts.Length); m_log.Debug("Group3: Pos:"+grp3.AbsolutePosition+", Rot:"+grp3.GroupRotation); m_log.Debug("Group3: Prim1: OffsetPosition:"+part3.OffsetPosition+", OffsetRotation:"+part3.RotationOffset); m_log.Debug("Group3: Prim2: OffsetPosition:"+part4.OffsetPosition+", OffsetRotation:"+part4.RotationOffset); } // Required for linking grp1.RootPart.ClearUpdateSchedule(); grp3.RootPart.ClearUpdateSchedule(); // root part should have no offset position or rotation Assert.That(part1.OffsetPosition == Vector3.Zero && part1.RotationOffset == Quaternion.Identity, "root part should have no offset position or rotation (again)"); // offset position should be root part position - part2.absolute position. Assert.That(part2.OffsetPosition == new Vector3(-10, -10, -10), "offset position should be root part position - part2.absolute position (again)"); float roll = 0; float pitch = 0; float yaw = 0; // There's a euler anomoly at 180, 0, 0 so expect 180 to turn into -180. part1.RotationOffset.GetEulerAngles(out roll, out pitch, out yaw); Vector3 rotEuler1 = new Vector3(roll * Utils.RAD_TO_DEG, pitch * Utils.RAD_TO_DEG, yaw * Utils.RAD_TO_DEG); if (debugtest) m_log.Debug(rotEuler1); part2.RotationOffset.GetEulerAngles(out roll, out pitch, out yaw); Vector3 rotEuler2 = new Vector3(roll * Utils.RAD_TO_DEG, pitch * Utils.RAD_TO_DEG, yaw * Utils.RAD_TO_DEG); if (debugtest) m_log.Debug(rotEuler2); Assert.That(rotEuler2.ApproxEquals(new Vector3(-180, 0, 0), 0.001f) || rotEuler2.ApproxEquals(new Vector3(180, 0, 0), 0.001f), "Not sure what this assertion is all about..."); // Now we're linking the first group to the third group. This will make the first group child parts of the third one. grp3.LinkToGroup(grp1); // Delink parts 2 and 3 grp3.DelinkFromGroup(part2.LocalId); grp3.DelinkFromGroup(part3.LocalId); if (debugtest) { m_log.Debug("--------After De-Link-------"); m_log.Debug("Group1: parts:" + grp1.Parts.Length); m_log.Debug("Group1: Pos:" + grp1.AbsolutePosition + ", Rot:" + grp1.GroupRotation); m_log.Debug("Group1: Prim1: OffsetPosition:" + part1.OffsetPosition + ", OffsetRotation:" + part1.RotationOffset); m_log.Debug("Group1: Prim2: OffsetPosition:" + part2.OffsetPosition + ", OffsetRotation:" + part2.RotationOffset); m_log.Debug("Group3: parts:" + grp3.Parts.Length); m_log.Debug("Group3: Pos:" + grp3.AbsolutePosition + ", Rot:" + grp3.GroupRotation); m_log.Debug("Group3: Prim1: OffsetPosition:" + part3.OffsetPosition + ", OffsetRotation:" + part3.RotationOffset); m_log.Debug("Group3: Prim2: OffsetPosition:" + part4.OffsetPosition + ", OffsetRotation:" + part4.RotationOffset); } Assert.That(part2.AbsolutePosition == Vector3.Zero, "Badness 1"); Assert.That(part4.OffsetPosition == new Vector3(20, 20, 20), "Badness 2"); Quaternion compareQuaternion = new Quaternion(0, 0.7071068f, 0, 0.7071068f); Assert.That((part4.RotationOffset.X - compareQuaternion.X < 0.00003) && (part4.RotationOffset.Y - compareQuaternion.Y < 0.00003) && (part4.RotationOffset.Z - compareQuaternion.Z < 0.00003) && (part4.RotationOffset.W - compareQuaternion.W < 0.00003), "Badness 3"); } /// <summary> /// Test that a new scene object which is already linked is correctly persisted to the persistence layer. /// </summary> [Test] public void TestNewSceneObjectLinkPersistence() { TestHelpers.InMethod(); //log4net.Config.XmlConfigurator.Configure(); TestScene scene = new SceneHelpers().SetupScene(); string rootPartName = "rootpart"; UUID rootPartUuid = new UUID("00000000-0000-0000-0000-000000000001"); string linkPartName = "linkpart"; UUID linkPartUuid = new UUID("00000000-0000-0000-0001-000000000000"); SceneObjectPart rootPart = new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero) { Name = rootPartName, UUID = rootPartUuid }; SceneObjectPart linkPart = new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero) { Name = linkPartName, UUID = linkPartUuid }; SceneObjectGroup sog = new SceneObjectGroup(rootPart); sog.AddPart(linkPart); scene.AddNewSceneObject(sog, true); // In a test, we have to crank the backup handle manually. Normally this would be done by the timer invoked // scene backup thread. scene.Backup(true); List<SceneObjectGroup> storedObjects = scene.SimulationDataService.LoadObjects(scene.RegionInfo.RegionID); Assert.That(storedObjects.Count, Is.EqualTo(1)); Assert.That(storedObjects[0].Parts.Length, Is.EqualTo(2)); Assert.That(storedObjects[0].ContainsPart(rootPartUuid)); Assert.That(storedObjects[0].ContainsPart(linkPartUuid)); } /// <summary> /// Test that a delink of a previously linked object is correctly persisted to the database /// </summary> [Test] public void TestDelinkPersistence() { TestHelpers.InMethod(); //log4net.Config.XmlConfigurator.Configure(); TestScene scene = new SceneHelpers().SetupScene(); string rootPartName = "rootpart"; UUID rootPartUuid = new UUID("00000000-0000-0000-0000-000000000001"); string linkPartName = "linkpart"; UUID linkPartUuid = new UUID("00000000-0000-0000-0001-000000000000"); SceneObjectPart rootPart = new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero) { Name = rootPartName, UUID = rootPartUuid }; SceneObjectPart linkPart = new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero) { Name = linkPartName, UUID = linkPartUuid }; SceneObjectGroup linkGroup = new SceneObjectGroup(linkPart); scene.AddNewSceneObject(linkGroup, true); SceneObjectGroup sog = new SceneObjectGroup(rootPart); scene.AddNewSceneObject(sog, true); Assert.IsFalse(sog.GroupContainsForeignPrims); sog.LinkToGroup(linkGroup); Assert.IsTrue(sog.GroupContainsForeignPrims); scene.Backup(true); Assert.AreEqual(1, scene.SimulationDataService.LoadObjects(scene.RegionInfo.RegionID).Count); // These changes should occur immediately without waiting for a backup pass SceneObjectGroup groupToDelete = sog.DelinkFromGroup(linkPart, false); Assert.IsFalse(groupToDelete.GroupContainsForeignPrims); scene.DeleteSceneObject(groupToDelete, false); List<SceneObjectGroup> storedObjects = scene.SimulationDataService.LoadObjects(scene.RegionInfo.RegionID); Assert.AreEqual(1, storedObjects.Count); Assert.AreEqual(1, storedObjects[0].Parts.Length); Assert.IsTrue(storedObjects[0].ContainsPart(rootPartUuid)); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Diagnostics; //for [DebuggerNonUserCode] using System.Runtime.Remoting.Lifetime; using System.Threading; using System.Reflection; using System.Collections; using System.Collections.Generic; using OpenSim.Region.ScriptEngine.Interfaces; using OpenSim.Region.ScriptEngine.Shared.Api.Interfaces; using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat; using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger; using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list; using LSL_Rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion; using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; using LSL_Vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3; namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase { public partial class ScriptBaseClass : MarshalByRefObject { public ILSL_Api m_LSL_Functions; public void ApiTypeLSL(IScriptApi api) { if (!(api is ILSL_Api)) return; m_LSL_Functions = (ILSL_Api)api; } public void state(string newState) { m_LSL_Functions.state(newState); } // // Script functions // public LSL_Integer llAbs(int i) { return m_LSL_Functions.llAbs(i); } public LSL_Float llAcos(double val) { return m_LSL_Functions.llAcos(val); } public void llAddToLandBanList(string avatar, double hours) { m_LSL_Functions.llAddToLandBanList(avatar, hours); } public void llAddToLandPassList(string avatar, double hours) { m_LSL_Functions.llAddToLandPassList(avatar, hours); } public void llAdjustSoundVolume(double volume) { m_LSL_Functions.llAdjustSoundVolume(volume); } public void llAllowInventoryDrop(int add) { m_LSL_Functions.llAllowInventoryDrop(add); } public LSL_Float llAngleBetween(LSL_Rotation a, LSL_Rotation b) { return m_LSL_Functions.llAngleBetween(a, b); } public void llApplyImpulse(LSL_Vector force, int local) { m_LSL_Functions.llApplyImpulse(force, local); } public void llApplyRotationalImpulse(LSL_Vector force, int local) { m_LSL_Functions.llApplyRotationalImpulse(force, local); } public LSL_Float llAsin(double val) { return m_LSL_Functions.llAsin(val); } public LSL_Float llAtan2(double x, double y) { return m_LSL_Functions.llAtan2(x, y); } public void llAttachToAvatar(int attachment) { m_LSL_Functions.llAttachToAvatar(attachment); } public LSL_Key llAvatarOnSitTarget() { return m_LSL_Functions.llAvatarOnSitTarget(); } public LSL_Key llAvatarOnLinkSitTarget(int linknum) { return m_LSL_Functions.llAvatarOnLinkSitTarget(linknum); } public LSL_Rotation llAxes2Rot(LSL_Vector fwd, LSL_Vector left, LSL_Vector up) { return m_LSL_Functions.llAxes2Rot(fwd, left, up); } public LSL_Rotation llAxisAngle2Rot(LSL_Vector axis, double angle) { return m_LSL_Functions.llAxisAngle2Rot(axis, angle); } public LSL_Integer llBase64ToInteger(string str) { return m_LSL_Functions.llBase64ToInteger(str); } public LSL_String llBase64ToString(string str) { return m_LSL_Functions.llBase64ToString(str); } public void llBreakAllLinks() { m_LSL_Functions.llBreakAllLinks(); } public void llBreakLink(int linknum) { m_LSL_Functions.llBreakLink(linknum); } public LSL_Integer llCeil(double f) { return m_LSL_Functions.llCeil(f); } public void llClearCameraParams() { m_LSL_Functions.llClearCameraParams(); } public void llCloseRemoteDataChannel(string channel) { m_LSL_Functions.llCloseRemoteDataChannel(channel); } public LSL_Float llCloud(LSL_Vector offset) { return m_LSL_Functions.llCloud(offset); } public void llCollisionFilter(string name, string id, int accept) { m_LSL_Functions.llCollisionFilter(name, id, accept); } public void llCollisionSound(string impact_sound, double impact_volume) { m_LSL_Functions.llCollisionSound(impact_sound, impact_volume); } public void llCollisionSprite(string impact_sprite) { m_LSL_Functions.llCollisionSprite(impact_sprite); } public LSL_Float llCos(double f) { return m_LSL_Functions.llCos(f); } public void llCreateLink(string target, int parent) { m_LSL_Functions.llCreateLink(target, parent); } public LSL_List llCSV2List(string src) { return m_LSL_Functions.llCSV2List(src); } public LSL_List llDeleteSubList(LSL_List src, int start, int end) { return m_LSL_Functions.llDeleteSubList(src, start, end); } public LSL_String llDeleteSubString(string src, int start, int end) { return m_LSL_Functions.llDeleteSubString(src, start, end); } public void llDetachFromAvatar() { m_LSL_Functions.llDetachFromAvatar(); } public LSL_Vector llDetectedGrab(int number) { return m_LSL_Functions.llDetectedGrab(number); } public LSL_Integer llDetectedGroup(int number) { return m_LSL_Functions.llDetectedGroup(number); } public LSL_Key llDetectedKey(int number) { return m_LSL_Functions.llDetectedKey(number); } public LSL_Integer llDetectedLinkNumber(int number) { return m_LSL_Functions.llDetectedLinkNumber(number); } public LSL_String llDetectedName(int number) { return m_LSL_Functions.llDetectedName(number); } public LSL_Key llDetectedOwner(int number) { return m_LSL_Functions.llDetectedOwner(number); } public LSL_Vector llDetectedPos(int number) { return m_LSL_Functions.llDetectedPos(number); } public LSL_Rotation llDetectedRot(int number) { return m_LSL_Functions.llDetectedRot(number); } public LSL_Integer llDetectedType(int number) { return m_LSL_Functions.llDetectedType(number); } public LSL_Vector llDetectedTouchBinormal(int index) { return m_LSL_Functions.llDetectedTouchBinormal(index); } public LSL_Integer llDetectedTouchFace(int index) { return m_LSL_Functions.llDetectedTouchFace(index); } public LSL_Vector llDetectedTouchNormal(int index) { return m_LSL_Functions.llDetectedTouchNormal(index); } public LSL_Vector llDetectedTouchPos(int index) { return m_LSL_Functions.llDetectedTouchPos(index); } public LSL_Vector llDetectedTouchST(int index) { return m_LSL_Functions.llDetectedTouchST(index); } public LSL_Vector llDetectedTouchUV(int index) { return m_LSL_Functions.llDetectedTouchUV(index); } public LSL_Vector llDetectedVel(int number) { return m_LSL_Functions.llDetectedVel(number); } public void llDialog(string avatar, string message, LSL_List buttons, int chat_channel) { m_LSL_Functions.llDialog(avatar, message, buttons, chat_channel); } [DebuggerNonUserCode] public void llDie() { m_LSL_Functions.llDie(); } public LSL_String llDumpList2String(LSL_List src, string seperator) { return m_LSL_Functions.llDumpList2String(src, seperator); } public LSL_Integer llEdgeOfWorld(LSL_Vector pos, LSL_Vector dir) { return m_LSL_Functions.llEdgeOfWorld(pos, dir); } public void llEjectFromLand(string pest) { m_LSL_Functions.llEjectFromLand(pest); } public void llEmail(string address, string subject, string message) { m_LSL_Functions.llEmail(address, subject, message); } public LSL_String llEscapeURL(string url) { return m_LSL_Functions.llEscapeURL(url); } public LSL_Rotation llEuler2Rot(LSL_Vector v) { return m_LSL_Functions.llEuler2Rot(v); } public LSL_Float llFabs(double f) { return m_LSL_Functions.llFabs(f); } public LSL_Integer llFloor(double f) { return m_LSL_Functions.llFloor(f); } public void llForceMouselook(int mouselook) { m_LSL_Functions.llForceMouselook(mouselook); } public LSL_Float llFrand(double mag) { return m_LSL_Functions.llFrand(mag); } public LSL_Key llGenerateKey() { return m_LSL_Functions.llGenerateKey(); } public LSL_Vector llGetAccel() { return m_LSL_Functions.llGetAccel(); } public LSL_Integer llGetAgentInfo(string id) { return m_LSL_Functions.llGetAgentInfo(id); } public LSL_String llGetAgentLanguage(string id) { return m_LSL_Functions.llGetAgentLanguage(id); } public LSL_List llGetAgentList(LSL_Integer scope, LSL_List options) { return m_LSL_Functions.llGetAgentList(scope, options); } public LSL_Vector llGetAgentSize(string id) { return m_LSL_Functions.llGetAgentSize(id); } public LSL_Float llGetAlpha(int face) { return m_LSL_Functions.llGetAlpha(face); } public LSL_Float llGetAndResetTime() { return m_LSL_Functions.llGetAndResetTime(); } public LSL_String llGetAnimation(string id) { return m_LSL_Functions.llGetAnimation(id); } public LSL_List llGetAnimationList(string id) { return m_LSL_Functions.llGetAnimationList(id); } public LSL_Integer llGetAttached() { return m_LSL_Functions.llGetAttached(); } public LSL_List llGetAttachedList(string id) { return m_LSL_Functions.llGetAttachedList(id); } public LSL_List llGetBoundingBox(string obj) { return m_LSL_Functions.llGetBoundingBox(obj); } public LSL_Vector llGetCameraPos() { return m_LSL_Functions.llGetCameraPos(); } public LSL_Rotation llGetCameraRot() { return m_LSL_Functions.llGetCameraRot(); } public LSL_Vector llGetCenterOfMass() { return m_LSL_Functions.llGetCenterOfMass(); } public LSL_Vector llGetColor(int face) { return m_LSL_Functions.llGetColor(face); } public LSL_String llGetCreator() { return m_LSL_Functions.llGetCreator(); } public LSL_String llGetDate() { return m_LSL_Functions.llGetDate(); } public LSL_Float llGetEnergy() { return m_LSL_Functions.llGetEnergy(); } public LSL_String llGetEnv(LSL_String name) { return m_LSL_Functions.llGetEnv(name); } public LSL_Vector llGetForce() { return m_LSL_Functions.llGetForce(); } public LSL_Integer llGetFreeMemory() { return m_LSL_Functions.llGetFreeMemory(); } public LSL_Integer llGetUsedMemory() { return m_LSL_Functions.llGetUsedMemory(); } public LSL_Integer llGetFreeURLs() { return m_LSL_Functions.llGetFreeURLs(); } public LSL_Vector llGetGeometricCenter() { return m_LSL_Functions.llGetGeometricCenter(); } public LSL_Float llGetGMTclock() { return m_LSL_Functions.llGetGMTclock(); } public LSL_String llGetHTTPHeader(LSL_Key request_id, string header) { return m_LSL_Functions.llGetHTTPHeader(request_id, header); } public LSL_Key llGetInventoryCreator(string item) { return m_LSL_Functions.llGetInventoryCreator(item); } public LSL_Key llGetInventoryKey(string name) { return m_LSL_Functions.llGetInventoryKey(name); } public LSL_String llGetInventoryName(int type, int number) { return m_LSL_Functions.llGetInventoryName(type, number); } public LSL_Integer llGetInventoryNumber(int type) { return m_LSL_Functions.llGetInventoryNumber(type); } public LSL_Integer llGetInventoryPermMask(string item, int mask) { return m_LSL_Functions.llGetInventoryPermMask(item, mask); } public LSL_Integer llGetInventoryType(string name) { return m_LSL_Functions.llGetInventoryType(name); } public LSL_Key llGetKey() { return m_LSL_Functions.llGetKey(); } public LSL_Key llGetLandOwnerAt(LSL_Vector pos) { return m_LSL_Functions.llGetLandOwnerAt(pos); } public LSL_Key llGetLinkKey(int linknum) { return m_LSL_Functions.llGetLinkKey(linknum); } public LSL_String llGetLinkName(int linknum) { return m_LSL_Functions.llGetLinkName(linknum); } public LSL_Integer llGetLinkNumber() { return m_LSL_Functions.llGetLinkNumber(); } public LSL_Integer llGetLinkNumberOfSides(int link) { return m_LSL_Functions.llGetLinkNumberOfSides(link); } public LSL_Integer llGetListEntryType(LSL_List src, int index) { return m_LSL_Functions.llGetListEntryType(src, index); } public LSL_Integer llGetListLength(LSL_List src) { return m_LSL_Functions.llGetListLength(src); } public LSL_Vector llGetLocalPos() { return m_LSL_Functions.llGetLocalPos(); } public LSL_Rotation llGetLocalRot() { return m_LSL_Functions.llGetLocalRot(); } public LSL_Float llGetMass() { return m_LSL_Functions.llGetMass(); } public LSL_Float llGetMassMKS() { return m_LSL_Functions.llGetMassMKS(); } public LSL_Integer llGetMemoryLimit() { return m_LSL_Functions.llGetMemoryLimit(); } public void llGetNextEmail(string address, string subject) { m_LSL_Functions.llGetNextEmail(address, subject); } public LSL_String llGetNotecardLine(string name, int line) { return m_LSL_Functions.llGetNotecardLine(name, line); } public LSL_Key llGetNumberOfNotecardLines(string name) { return m_LSL_Functions.llGetNumberOfNotecardLines(name); } public LSL_Integer llGetNumberOfPrims() { return m_LSL_Functions.llGetNumberOfPrims(); } public LSL_Integer llGetNumberOfSides() { return m_LSL_Functions.llGetNumberOfSides(); } public LSL_String llGetObjectDesc() { return m_LSL_Functions.llGetObjectDesc(); } public LSL_List llGetObjectDetails(string id, LSL_List args) { return m_LSL_Functions.llGetObjectDetails(id, args); } public LSL_Float llGetObjectMass(string id) { return m_LSL_Functions.llGetObjectMass(id); } public LSL_String llGetObjectName() { return m_LSL_Functions.llGetObjectName(); } public LSL_Integer llGetObjectPermMask(int mask) { return m_LSL_Functions.llGetObjectPermMask(mask); } public LSL_Integer llGetObjectPrimCount(string object_id) { return m_LSL_Functions.llGetObjectPrimCount(object_id); } public LSL_Vector llGetOmega() { return m_LSL_Functions.llGetOmega(); } public LSL_Key llGetOwner() { return m_LSL_Functions.llGetOwner(); } public LSL_Key llGetOwnerKey(string id) { return m_LSL_Functions.llGetOwnerKey(id); } public LSL_List llGetParcelDetails(LSL_Vector pos, LSL_List param) { return m_LSL_Functions.llGetParcelDetails(pos, param); } public LSL_Integer llGetParcelFlags(LSL_Vector pos) { return m_LSL_Functions.llGetParcelFlags(pos); } public LSL_Integer llGetParcelMaxPrims(LSL_Vector pos, int sim_wide) { return m_LSL_Functions.llGetParcelMaxPrims(pos, sim_wide); } public LSL_String llGetParcelMusicURL() { return m_LSL_Functions.llGetParcelMusicURL(); } public LSL_Integer llGetParcelPrimCount(LSL_Vector pos, int category, int sim_wide) { return m_LSL_Functions.llGetParcelPrimCount(pos, category, sim_wide); } public LSL_List llGetParcelPrimOwners(LSL_Vector pos) { return m_LSL_Functions.llGetParcelPrimOwners(pos); } public LSL_Integer llGetPermissions() { return m_LSL_Functions.llGetPermissions(); } public LSL_Key llGetPermissionsKey() { return m_LSL_Functions.llGetPermissionsKey(); } public LSL_Vector llGetPos() { return m_LSL_Functions.llGetPos(); } public LSL_List llGetPrimitiveParams(LSL_List rules) { return m_LSL_Functions.llGetPrimitiveParams(rules); } public LSL_List llGetLinkPrimitiveParams(int linknum, LSL_List rules) { return m_LSL_Functions.llGetLinkPrimitiveParams(linknum, rules); } public LSL_Integer llGetRegionAgentCount() { return m_LSL_Functions.llGetRegionAgentCount(); } public LSL_Vector llGetRegionCorner() { return m_LSL_Functions.llGetRegionCorner(); } public LSL_Integer llGetRegionFlags() { return m_LSL_Functions.llGetRegionFlags(); } public LSL_Float llGetRegionFPS() { return m_LSL_Functions.llGetRegionFPS(); } public LSL_String llGetRegionName() { return m_LSL_Functions.llGetRegionName(); } public LSL_Float llGetRegionTimeDilation() { return m_LSL_Functions.llGetRegionTimeDilation(); } public LSL_Vector llGetRootPosition() { return m_LSL_Functions.llGetRootPosition(); } public LSL_Rotation llGetRootRotation() { return m_LSL_Functions.llGetRootRotation(); } public LSL_Rotation llGetRot() { return m_LSL_Functions.llGetRot(); } public LSL_Vector llGetScale() { return m_LSL_Functions.llGetScale(); } public LSL_String llGetScriptName() { return m_LSL_Functions.llGetScriptName(); } public LSL_Integer llGetScriptState(string name) { return m_LSL_Functions.llGetScriptState(name); } public LSL_String llGetSimulatorHostname() { return m_LSL_Functions.llGetSimulatorHostname(); } public LSL_Integer llGetSPMaxMemory() { return m_LSL_Functions.llGetSPMaxMemory(); } public LSL_Integer llGetStartParameter() { return m_LSL_Functions.llGetStartParameter(); } public LSL_Integer llGetStatus(int status) { return m_LSL_Functions.llGetStatus(status); } public LSL_String llGetSubString(string src, int start, int end) { return m_LSL_Functions.llGetSubString(src, start, end); } public LSL_Vector llGetSunDirection() { return m_LSL_Functions.llGetSunDirection(); } public LSL_String llGetTexture(int face) { return m_LSL_Functions.llGetTexture(face); } public LSL_Vector llGetTextureOffset(int face) { return m_LSL_Functions.llGetTextureOffset(face); } public LSL_Float llGetTextureRot(int side) { return m_LSL_Functions.llGetTextureRot(side); } public LSL_Vector llGetTextureScale(int side) { return m_LSL_Functions.llGetTextureScale(side); } public LSL_Float llGetTime() { return m_LSL_Functions.llGetTime(); } public LSL_Float llGetTimeOfDay() { return m_LSL_Functions.llGetTimeOfDay(); } public LSL_String llGetTimestamp() { return m_LSL_Functions.llGetTimestamp(); } public LSL_Vector llGetTorque() { return m_LSL_Functions.llGetTorque(); } public LSL_Integer llGetUnixTime() { return m_LSL_Functions.llGetUnixTime(); } public LSL_Vector llGetVel() { return m_LSL_Functions.llGetVel(); } public LSL_Float llGetWallclock() { return m_LSL_Functions.llGetWallclock(); } public void llGiveInventory(string destination, string inventory) { m_LSL_Functions.llGiveInventory(destination, inventory); } public void llGiveInventoryList(string destination, string category, LSL_List inventory) { m_LSL_Functions.llGiveInventoryList(destination, category, inventory); } public LSL_Integer llGiveMoney(string destination, int amount) { return m_LSL_Functions.llGiveMoney(destination, amount); } public LSL_String llTransferLindenDollars(string destination, int amount) { return m_LSL_Functions.llTransferLindenDollars(destination, amount); } public void llGodLikeRezObject(string inventory, LSL_Vector pos) { m_LSL_Functions.llGodLikeRezObject(inventory, pos); } public LSL_Float llGround(LSL_Vector offset) { return m_LSL_Functions.llGround(offset); } public LSL_Vector llGroundContour(LSL_Vector offset) { return m_LSL_Functions.llGroundContour(offset); } public LSL_Vector llGroundNormal(LSL_Vector offset) { return m_LSL_Functions.llGroundNormal(offset); } public void llGroundRepel(double height, int water, double tau) { m_LSL_Functions.llGroundRepel(height, water, tau); } public LSL_Vector llGroundSlope(LSL_Vector offset) { return m_LSL_Functions.llGroundSlope(offset); } public LSL_String llHTTPRequest(string url, LSL_List parameters, string body) { return m_LSL_Functions.llHTTPRequest(url, parameters, body); } public void llHTTPResponse(LSL_Key id, int status, string body) { m_LSL_Functions.llHTTPResponse(id, status, body); } public LSL_String llInsertString(string dst, int position, string src) { return m_LSL_Functions.llInsertString(dst, position, src); } public void llInstantMessage(string user, string message) { m_LSL_Functions.llInstantMessage(user, message); } public LSL_String llIntegerToBase64(int number) { return m_LSL_Functions.llIntegerToBase64(number); } public LSL_String llKey2Name(string id) { return m_LSL_Functions.llKey2Name(id); } public LSL_String llGetUsername(string id) { return m_LSL_Functions.llGetUsername(id); } public LSL_String llRequestUsername(string id) { return m_LSL_Functions.llRequestUsername(id); } public LSL_String llGetDisplayName(string id) { return m_LSL_Functions.llGetDisplayName(id); } public LSL_String llRequestDisplayName(string id) { return m_LSL_Functions.llRequestDisplayName(id); } public LSL_List llCastRay(LSL_Vector start, LSL_Vector end, LSL_List options) { return m_LSL_Functions.llCastRay(start, end, options); } public void llLinkParticleSystem(int linknum, LSL_List rules) { m_LSL_Functions.llLinkParticleSystem(linknum, rules); } public LSL_String llList2CSV(LSL_List src) { return m_LSL_Functions.llList2CSV(src); } public LSL_Float llList2Float(LSL_List src, int index) { return m_LSL_Functions.llList2Float(src, index); } public LSL_Integer llList2Integer(LSL_List src, int index) { return m_LSL_Functions.llList2Integer(src, index); } public LSL_Key llList2Key(LSL_List src, int index) { return m_LSL_Functions.llList2Key(src, index); } public LSL_List llList2List(LSL_List src, int start, int end) { return m_LSL_Functions.llList2List(src, start, end); } public LSL_List llList2ListStrided(LSL_List src, int start, int end, int stride) { return m_LSL_Functions.llList2ListStrided(src, start, end, stride); } public LSL_Rotation llList2Rot(LSL_List src, int index) { return m_LSL_Functions.llList2Rot(src, index); } public LSL_String llList2String(LSL_List src, int index) { return m_LSL_Functions.llList2String(src, index); } public LSL_Vector llList2Vector(LSL_List src, int index) { return m_LSL_Functions.llList2Vector(src, index); } public LSL_Integer llListen(int channelID, string name, string ID, string msg) { return m_LSL_Functions.llListen(channelID, name, ID, msg); } public void llListenControl(int number, int active) { m_LSL_Functions.llListenControl(number, active); } public void llListenRemove(int number) { m_LSL_Functions.llListenRemove(number); } public LSL_Integer llListFindList(LSL_List src, LSL_List test) { return m_LSL_Functions.llListFindList(src, test); } public LSL_List llListInsertList(LSL_List dest, LSL_List src, int start) { return m_LSL_Functions.llListInsertList(dest, src, start); } public LSL_List llListRandomize(LSL_List src, int stride) { return m_LSL_Functions.llListRandomize(src, stride); } public LSL_List llListReplaceList(LSL_List dest, LSL_List src, int start, int end) { return m_LSL_Functions.llListReplaceList(dest, src, start, end); } public LSL_List llListSort(LSL_List src, int stride, int ascending) { return m_LSL_Functions.llListSort(src, stride, ascending); } public LSL_Float llListStatistics(int operation, LSL_List src) { return m_LSL_Functions.llListStatistics(operation, src); } public void llLoadURL(string avatar_id, string message, string url) { m_LSL_Functions.llLoadURL(avatar_id, message, url); } public LSL_Float llLog(double val) { return m_LSL_Functions.llLog(val); } public LSL_Float llLog10(double val) { return m_LSL_Functions.llLog10(val); } public void llLookAt(LSL_Vector target, double strength, double damping) { m_LSL_Functions.llLookAt(target, strength, damping); } public void llLoopSound(string sound, double volume) { m_LSL_Functions.llLoopSound(sound, volume); } public void llLoopSoundMaster(string sound, double volume) { m_LSL_Functions.llLoopSoundMaster(sound, volume); } public void llLoopSoundSlave(string sound, double volume) { m_LSL_Functions.llLoopSoundSlave(sound, volume); } public LSL_Integer llManageEstateAccess(int action, string avatar) { return m_LSL_Functions.llManageEstateAccess(action, avatar); } public void llMakeExplosion(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset) { m_LSL_Functions.llMakeExplosion(particles, scale, vel, lifetime, arc, texture, offset); } public void llMakeFire(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset) { m_LSL_Functions.llMakeFire(particles, scale, vel, lifetime, arc, texture, offset); } public void llMakeFountain(int particles, double scale, double vel, double lifetime, double arc, int bounce, string texture, LSL_Vector offset, double bounce_offset) { m_LSL_Functions.llMakeFountain(particles, scale, vel, lifetime, arc, bounce, texture, offset, bounce_offset); } public void llMakeSmoke(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset) { m_LSL_Functions.llMakeSmoke(particles, scale, vel, lifetime, arc, texture, offset); } public void llMapDestination(string simname, LSL_Vector pos, LSL_Vector look_at) { m_LSL_Functions.llMapDestination(simname, pos, look_at); } public LSL_String llMD5String(string src, int nonce) { return m_LSL_Functions.llMD5String(src, nonce); } public LSL_String llSHA1String(string src) { return m_LSL_Functions.llSHA1String(src); } public void llMessageLinked(int linknum, int num, string str, string id) { m_LSL_Functions.llMessageLinked(linknum, num, str, id); } public void llMinEventDelay(double delay) { m_LSL_Functions.llMinEventDelay(delay); } public void llModifyLand(int action, int brush) { m_LSL_Functions.llModifyLand(action, brush); } public LSL_Integer llModPow(int a, int b, int c) { return m_LSL_Functions.llModPow(a, b, c); } public void llMoveToTarget(LSL_Vector target, double tau) { m_LSL_Functions.llMoveToTarget(target, tau); } public void llOffsetTexture(double u, double v, int face) { m_LSL_Functions.llOffsetTexture(u, v, face); } public void llOpenRemoteDataChannel() { m_LSL_Functions.llOpenRemoteDataChannel(); } public LSL_Integer llOverMyLand(string id) { return m_LSL_Functions.llOverMyLand(id); } public void llOwnerSay(string msg) { m_LSL_Functions.llOwnerSay(msg); } public void llParcelMediaCommandList(LSL_List commandList) { m_LSL_Functions.llParcelMediaCommandList(commandList); } public LSL_List llParcelMediaQuery(LSL_List aList) { return m_LSL_Functions.llParcelMediaQuery(aList); } public LSL_List llParseString2List(string str, LSL_List separators, LSL_List spacers) { return m_LSL_Functions.llParseString2List(str, separators, spacers); } public LSL_List llParseStringKeepNulls(string src, LSL_List seperators, LSL_List spacers) { return m_LSL_Functions.llParseStringKeepNulls(src, seperators, spacers); } public void llParticleSystem(LSL_List rules) { m_LSL_Functions.llParticleSystem(rules); } public void llPassCollisions(int pass) { m_LSL_Functions.llPassCollisions(pass); } public void llPassTouches(int pass) { m_LSL_Functions.llPassTouches(pass); } public void llPlaySound(string sound, double volume) { m_LSL_Functions.llPlaySound(sound, volume); } public void llPlaySoundSlave(string sound, double volume) { m_LSL_Functions.llPlaySoundSlave(sound, volume); } public void llPointAt(LSL_Vector pos) { m_LSL_Functions.llPointAt(pos); } public LSL_Float llPow(double fbase, double fexponent) { return m_LSL_Functions.llPow(fbase, fexponent); } public void llPreloadSound(string sound) { m_LSL_Functions.llPreloadSound(sound); } public void llPushObject(string target, LSL_Vector impulse, LSL_Vector ang_impulse, int local) { m_LSL_Functions.llPushObject(target, impulse, ang_impulse, local); } public void llRefreshPrimURL() { m_LSL_Functions.llRefreshPrimURL(); } public void llRegionSay(int channelID, string text) { m_LSL_Functions.llRegionSay(channelID, text); } public void llRegionSayTo(string key, int channelID, string text) { m_LSL_Functions.llRegionSayTo(key, channelID, text); } public void llReleaseCamera(string avatar) { m_LSL_Functions.llReleaseCamera(avatar); } public void llReleaseURL(string url) { m_LSL_Functions.llReleaseURL(url); } public void llReleaseControls() { m_LSL_Functions.llReleaseControls(); } public void llRemoteDataReply(string channel, string message_id, string sdata, int idata) { m_LSL_Functions.llRemoteDataReply(channel, message_id, sdata, idata); } public void llRemoteDataSetRegion() { m_LSL_Functions.llRemoteDataSetRegion(); } public void llRemoteLoadScript(string target, string name, int running, int start_param) { m_LSL_Functions.llRemoteLoadScript(target, name, running, start_param); } public void llRemoteLoadScriptPin(string target, string name, int pin, int running, int start_param) { m_LSL_Functions.llRemoteLoadScriptPin(target, name, pin, running, start_param); } public void llRemoveFromLandBanList(string avatar) { m_LSL_Functions.llRemoveFromLandBanList(avatar); } public void llRemoveFromLandPassList(string avatar) { m_LSL_Functions.llRemoveFromLandPassList(avatar); } public void llRemoveInventory(string item) { m_LSL_Functions.llRemoveInventory(item); } public void llRemoveVehicleFlags(int flags) { m_LSL_Functions.llRemoveVehicleFlags(flags); } public LSL_Key llRequestAgentData(string id, int data) { return m_LSL_Functions.llRequestAgentData(id, data); } public LSL_Key llRequestInventoryData(string name) { return m_LSL_Functions.llRequestInventoryData(name); } public void llRequestPermissions(string agent, int perm) { m_LSL_Functions.llRequestPermissions(agent, perm); } public LSL_String llRequestSecureURL() { return m_LSL_Functions.llRequestSecureURL(); } public LSL_Key llRequestSimulatorData(string simulator, int data) { return m_LSL_Functions.llRequestSimulatorData(simulator, data); } public LSL_Key llRequestURL() { return m_LSL_Functions.llRequestURL(); } public void llResetLandBanList() { m_LSL_Functions.llResetLandBanList(); } public void llResetLandPassList() { m_LSL_Functions.llResetLandPassList(); } public void llResetOtherScript(string name) { m_LSL_Functions.llResetOtherScript(name); } public void llResetScript() { m_LSL_Functions.llResetScript(); } public void llResetTime() { m_LSL_Functions.llResetTime(); } public void llRezAtRoot(string inventory, LSL_Vector position, LSL_Vector velocity, LSL_Rotation rot, int param) { m_LSL_Functions.llRezAtRoot(inventory, position, velocity, rot, param); } public void llRezObject(string inventory, LSL_Vector pos, LSL_Vector vel, LSL_Rotation rot, int param) { m_LSL_Functions.llRezObject(inventory, pos, vel, rot, param); } public LSL_Float llRot2Angle(LSL_Rotation rot) { return m_LSL_Functions.llRot2Angle(rot); } public LSL_Vector llRot2Axis(LSL_Rotation rot) { return m_LSL_Functions.llRot2Axis(rot); } public LSL_Vector llRot2Euler(LSL_Rotation r) { return m_LSL_Functions.llRot2Euler(r); } public LSL_Vector llRot2Fwd(LSL_Rotation r) { return m_LSL_Functions.llRot2Fwd(r); } public LSL_Vector llRot2Left(LSL_Rotation r) { return m_LSL_Functions.llRot2Left(r); } public LSL_Vector llRot2Up(LSL_Rotation r) { return m_LSL_Functions.llRot2Up(r); } public void llRotateTexture(double rotation, int face) { m_LSL_Functions.llRotateTexture(rotation, face); } public LSL_Rotation llRotBetween(LSL_Vector start, LSL_Vector end) { return m_LSL_Functions.llRotBetween(start, end); } public void llRotLookAt(LSL_Rotation target, double strength, double damping) { m_LSL_Functions.llRotLookAt(target, strength, damping); } public LSL_Integer llRotTarget(LSL_Rotation rot, double error) { return m_LSL_Functions.llRotTarget(rot, error); } public void llRotTargetRemove(int number) { m_LSL_Functions.llRotTargetRemove(number); } public LSL_Integer llRound(double f) { return m_LSL_Functions.llRound(f); } public LSL_Integer llSameGroup(string agent) { return m_LSL_Functions.llSameGroup(agent); } public void llSay(int channelID, string text) { m_LSL_Functions.llSay(channelID, text); } public LSL_Integer llScaleByFactor(double scaling_factor) { return m_LSL_Functions.llScaleByFactor(scaling_factor); } public LSL_Float llGetMaxScaleFactor() { return m_LSL_Functions.llGetMaxScaleFactor(); } public LSL_Float llGetMinScaleFactor() { return m_LSL_Functions.llGetMinScaleFactor(); } public void llScaleTexture(double u, double v, int face) { m_LSL_Functions.llScaleTexture(u, v, face); } public LSL_Integer llScriptDanger(LSL_Vector pos) { return m_LSL_Functions.llScriptDanger(pos); } public void llScriptProfiler(LSL_Integer flags) { m_LSL_Functions.llScriptProfiler(flags); } public LSL_Key llSendRemoteData(string channel, string dest, int idata, string sdata) { return m_LSL_Functions.llSendRemoteData(channel, dest, idata, sdata); } public void llSensor(string name, string id, int type, double range, double arc) { m_LSL_Functions.llSensor(name, id, type, range, arc); } public void llSensorRemove() { m_LSL_Functions.llSensorRemove(); } public void llSensorRepeat(string name, string id, int type, double range, double arc, double rate) { m_LSL_Functions.llSensorRepeat(name, id, type, range, arc, rate); } public void llSetAlpha(double alpha, int face) { m_LSL_Functions.llSetAlpha(alpha, face); } public void llSetBuoyancy(double buoyancy) { m_LSL_Functions.llSetBuoyancy(buoyancy); } public void llSetCameraAtOffset(LSL_Vector offset) { m_LSL_Functions.llSetCameraAtOffset(offset); } public void llSetCameraEyeOffset(LSL_Vector offset) { m_LSL_Functions.llSetCameraEyeOffset(offset); } public void llSetLinkCamera(LSL_Integer link, LSL_Vector eye, LSL_Vector at) { m_LSL_Functions.llSetLinkCamera(link, eye, at); } public void llSetCameraParams(LSL_List rules) { m_LSL_Functions.llSetCameraParams(rules); } public void llSetClickAction(int action) { m_LSL_Functions.llSetClickAction(action); } public void llSetColor(LSL_Vector color, int face) { m_LSL_Functions.llSetColor(color, face); } public void llSetContentType(LSL_Key id, LSL_Integer type) { m_LSL_Functions.llSetContentType(id, type); } public void llSetDamage(double damage) { m_LSL_Functions.llSetDamage(damage); } public void llSetForce(LSL_Vector force, int local) { m_LSL_Functions.llSetForce(force, local); } public void llSetForceAndTorque(LSL_Vector force, LSL_Vector torque, int local) { m_LSL_Functions.llSetForceAndTorque(force, torque, local); } public void llSetVelocity(LSL_Vector force, int local) { m_LSL_Functions.llSetVelocity(force, local); } public void llSetAngularVelocity(LSL_Vector force, int local) { m_LSL_Functions.llSetAngularVelocity(force, local); } public void llSetHoverHeight(double height, int water, double tau) { m_LSL_Functions.llSetHoverHeight(height, water, tau); } public void llSetInventoryPermMask(string item, int mask, int value) { m_LSL_Functions.llSetInventoryPermMask(item, mask, value); } public void llSetLinkAlpha(int linknumber, double alpha, int face) { m_LSL_Functions.llSetLinkAlpha(linknumber, alpha, face); } public void llSetLinkColor(int linknumber, LSL_Vector color, int face) { m_LSL_Functions.llSetLinkColor(linknumber, color, face); } public void llSetLinkPrimitiveParams(int linknumber, LSL_List rules) { m_LSL_Functions.llSetLinkPrimitiveParams(linknumber, rules); } public void llSetLinkTexture(int linknumber, string texture, int face) { m_LSL_Functions.llSetLinkTexture(linknumber, texture, face); } public void llSetLinkTextureAnim(int linknum, int mode, int face, int sizex, int sizey, double start, double length, double rate) { m_LSL_Functions.llSetLinkTextureAnim(linknum, mode, face, sizex, sizey, start, length, rate); } public void llSetLocalRot(LSL_Rotation rot) { m_LSL_Functions.llSetLocalRot(rot); } public LSL_Integer llSetMemoryLimit(LSL_Integer limit) { return m_LSL_Functions.llSetMemoryLimit(limit); } public void llSetObjectDesc(string desc) { m_LSL_Functions.llSetObjectDesc(desc); } public void llSetObjectName(string name) { m_LSL_Functions.llSetObjectName(name); } public void llSetObjectPermMask(int mask, int value) { m_LSL_Functions.llSetObjectPermMask(mask, value); } public void llSetParcelMusicURL(string url) { m_LSL_Functions.llSetParcelMusicURL(url); } public void llSetPayPrice(int price, LSL_List quick_pay_buttons) { m_LSL_Functions.llSetPayPrice(price, quick_pay_buttons); } public void llSetPos(LSL_Vector pos) { m_LSL_Functions.llSetPos(pos); } public LSL_Integer llSetRegionPos(LSL_Vector pos) { return m_LSL_Functions.llSetRegionPos(pos); } public void llSetPrimitiveParams(LSL_List rules) { m_LSL_Functions.llSetPrimitiveParams(rules); } public void llSetLinkPrimitiveParamsFast(int linknum, LSL_List rules) { m_LSL_Functions.llSetLinkPrimitiveParamsFast(linknum, rules); } public void llSetPrimURL(string url) { m_LSL_Functions.llSetPrimURL(url); } public void llSetRemoteScriptAccessPin(int pin) { m_LSL_Functions.llSetRemoteScriptAccessPin(pin); } public void llSetRot(LSL_Rotation rot) { m_LSL_Functions.llSetRot(rot); } public void llSetScale(LSL_Vector scale) { m_LSL_Functions.llSetScale(scale); } public void llSetScriptState(string name, int run) { m_LSL_Functions.llSetScriptState(name, run); } public void llSetSitText(string text) { m_LSL_Functions.llSetSitText(text); } public void llSetSoundQueueing(int queue) { m_LSL_Functions.llSetSoundQueueing(queue); } public void llSetSoundRadius(double radius) { m_LSL_Functions.llSetSoundRadius(radius); } public void llSetStatus(int status, int value) { m_LSL_Functions.llSetStatus(status, value); } public void llSetText(string text, LSL_Vector color, double alpha) { m_LSL_Functions.llSetText(text, color, alpha); } public void llSetTexture(string texture, int face) { m_LSL_Functions.llSetTexture(texture, face); } public void llSetTextureAnim(int mode, int face, int sizex, int sizey, double start, double length, double rate) { m_LSL_Functions.llSetTextureAnim(mode, face, sizex, sizey, start, length, rate); } public void llSetTimerEvent(double sec) { m_LSL_Functions.llSetTimerEvent(sec); } public void llSetTorque(LSL_Vector torque, int local) { m_LSL_Functions.llSetTorque(torque, local); } public void llSetTouchText(string text) { m_LSL_Functions.llSetTouchText(text); } public void llSetVehicleFlags(int flags) { m_LSL_Functions.llSetVehicleFlags(flags); } public void llSetVehicleFloatParam(int param, LSL_Float value) { m_LSL_Functions.llSetVehicleFloatParam(param, value); } public void llSetVehicleRotationParam(int param, LSL_Rotation rot) { m_LSL_Functions.llSetVehicleRotationParam(param, rot); } public void llSetVehicleType(int type) { m_LSL_Functions.llSetVehicleType(type); } public void llSetVehicleVectorParam(int param, LSL_Vector vec) { m_LSL_Functions.llSetVehicleVectorParam(param, vec); } public void llShout(int channelID, string text) { m_LSL_Functions.llShout(channelID, text); } public LSL_Float llSin(double f) { return m_LSL_Functions.llSin(f); } public void llSitTarget(LSL_Vector offset, LSL_Rotation rot) { m_LSL_Functions.llSitTarget(offset, rot); } public void llLinkSitTarget(LSL_Integer link, LSL_Vector offset, LSL_Rotation rot) { m_LSL_Functions.llLinkSitTarget(link, offset, rot); } public void llSleep(double sec) { m_LSL_Functions.llSleep(sec); } public void llSound(string sound, double volume, int queue, int loop) { m_LSL_Functions.llSound(sound, volume, queue, loop); } public void llSoundPreload(string sound) { m_LSL_Functions.llSoundPreload(sound); } public LSL_Float llSqrt(double f) { return m_LSL_Functions.llSqrt(f); } public void llStartAnimation(string anim) { m_LSL_Functions.llStartAnimation(anim); } public void llStopAnimation(string anim) { m_LSL_Functions.llStopAnimation(anim); } public void llStopHover() { m_LSL_Functions.llStopHover(); } public void llStopLookAt() { m_LSL_Functions.llStopLookAt(); } public void llStopMoveToTarget() { m_LSL_Functions.llStopMoveToTarget(); } public void llStopPointAt() { m_LSL_Functions.llStopPointAt(); } public void llStopSound() { m_LSL_Functions.llStopSound(); } public LSL_Integer llStringLength(string str) { return m_LSL_Functions.llStringLength(str); } public LSL_String llStringToBase64(string str) { return m_LSL_Functions.llStringToBase64(str); } public LSL_String llStringTrim(string src, int type) { return m_LSL_Functions.llStringTrim(src, type); } public LSL_Integer llSubStringIndex(string source, string pattern) { return m_LSL_Functions.llSubStringIndex(source, pattern); } public void llTakeCamera(string avatar) { m_LSL_Functions.llTakeCamera(avatar); } public void llTakeControls(int controls, int accept, int pass_on) { m_LSL_Functions.llTakeControls(controls, accept, pass_on); } public LSL_Float llTan(double f) { return m_LSL_Functions.llTan(f); } public LSL_Integer llTarget(LSL_Vector position, double range) { return m_LSL_Functions.llTarget(position, range); } public void llTargetOmega(LSL_Vector axis, double spinrate, double gain) { m_LSL_Functions.llTargetOmega(axis, spinrate, gain); } public void llTargetRemove(int number) { m_LSL_Functions.llTargetRemove(number); } public void llTeleportAgent(string agent, string simname, LSL_Vector pos, LSL_Vector lookAt) { m_LSL_Functions.llTeleportAgent(agent, simname, pos, lookAt); } public void llTeleportAgentGlobalCoords(string agent, LSL_Vector global, LSL_Vector pos, LSL_Vector lookAt) { m_LSL_Functions.llTeleportAgentGlobalCoords(agent, global, pos, lookAt); } public void llTeleportAgentHome(string agent) { m_LSL_Functions.llTeleportAgentHome(agent); } public void llTextBox(string avatar, string message, int chat_channel) { m_LSL_Functions.llTextBox(avatar, message, chat_channel); } public LSL_String llToLower(string source) { return m_LSL_Functions.llToLower(source); } public LSL_String llToUpper(string source) { return m_LSL_Functions.llToUpper(source); } public void llTriggerSound(string sound, double volume) { m_LSL_Functions.llTriggerSound(sound, volume); } public void llTriggerSoundLimited(string sound, double volume, LSL_Vector top_north_east, LSL_Vector bottom_south_west) { m_LSL_Functions.llTriggerSoundLimited(sound, volume, top_north_east, bottom_south_west); } public LSL_String llUnescapeURL(string url) { return m_LSL_Functions.llUnescapeURL(url); } public void llUnSit(string id) { m_LSL_Functions.llUnSit(id); } public LSL_Float llVecDist(LSL_Vector a, LSL_Vector b) { return m_LSL_Functions.llVecDist(a, b); } public LSL_Float llVecMag(LSL_Vector v) { return m_LSL_Functions.llVecMag(v); } public LSL_Vector llVecNorm(LSL_Vector v) { return m_LSL_Functions.llVecNorm(v); } public void llVolumeDetect(int detect) { m_LSL_Functions.llVolumeDetect(detect); } public LSL_Float llWater(LSL_Vector offset) { return m_LSL_Functions.llWater(offset); } public void llWhisper(int channelID, string text) { m_LSL_Functions.llWhisper(channelID, text); } public LSL_Vector llWind(LSL_Vector offset) { return m_LSL_Functions.llWind(offset); } public LSL_String llXorBase64Strings(string str1, string str2) { return m_LSL_Functions.llXorBase64Strings(str1, str2); } public LSL_String llXorBase64StringsCorrect(string str1, string str2) { return m_LSL_Functions.llXorBase64StringsCorrect(str1, str2); } public LSL_List llGetPrimMediaParams(int face, LSL_List rules) { return m_LSL_Functions.llGetPrimMediaParams(face, rules); } public LSL_List llGetLinkMedia(LSL_Integer link, LSL_Integer face, LSL_List rules) { return m_LSL_Functions.llGetLinkMedia(link, face, rules); } public LSL_Integer llSetPrimMediaParams(int face, LSL_List rules) { return m_LSL_Functions.llSetPrimMediaParams(face, rules); } public LSL_Integer llSetLinkMedia(LSL_Integer link, LSL_Integer face, LSL_List rules) { return m_LSL_Functions.llSetLinkMedia(link, face, rules); } public LSL_Integer llClearPrimMedia(LSL_Integer face) { return m_LSL_Functions.llClearPrimMedia(face); } public LSL_Integer llClearLinkMedia(LSL_Integer link, LSL_Integer face) { return m_LSL_Functions.llClearLinkMedia(link, face); } public LSL_Integer llGetLinkNumberOfSides(LSL_Integer link) { return m_LSL_Functions.llGetLinkNumberOfSides(link); } public void llSetKeyframedMotion(LSL_List frames, LSL_List options) { m_LSL_Functions.llSetKeyframedMotion(frames, options); } public void llSetPhysicsMaterial(int material_bits, LSL_Float material_gravity_modifier, LSL_Float material_restitution, LSL_Float material_friction, LSL_Float material_density) { m_LSL_Functions.llSetPhysicsMaterial(material_bits, material_gravity_modifier, material_restitution, material_friction, material_density); } public LSL_List llGetPhysicsMaterial() { return m_LSL_Functions.llGetPhysicsMaterial(); } public void llSetAnimationOverride(LSL_String animState, LSL_String anim) { m_LSL_Functions.llSetAnimationOverride(animState, anim); } public void llResetAnimationOverride(LSL_String anim_state) { m_LSL_Functions.llResetAnimationOverride(anim_state); } public LSL_String llGetAnimationOverride(LSL_String anim_state) { return m_LSL_Functions.llGetAnimationOverride(anim_state); } public LSL_String llJsonGetValue(LSL_String json, LSL_List specifiers) { return m_LSL_Functions.llJsonGetValue(json, specifiers); } public LSL_List llJson2List(LSL_String json) { return m_LSL_Functions.llJson2List(json); } public LSL_String llList2Json(LSL_String type, LSL_List values) { return m_LSL_Functions.llList2Json(type, values); } public LSL_String llJsonSetValue(LSL_String json, LSL_List specifiers, LSL_String value) { return m_LSL_Functions.llJsonSetValue(json, specifiers, value); } public LSL_String llJsonValueType(LSL_String json, LSL_List specifiers) { return m_LSL_Functions.llJsonValueType(json, specifiers); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using FlatRedBall.Math; using Math = System.Math; using FlatRedBall.Math.Geometry; using Vector2 = Microsoft.Xna.Framework.Vector2; using Vector3 = Microsoft.Xna.Framework.Vector3; using Color = Microsoft.Xna.Framework.Color; namespace FlatRedBall.AI.Pathfinding { #region Enums public enum DirectionalType { Four, Eight } #endregion /// <summary> /// A node network optimized for tile-based pathfinding. /// </summary> public class TileNodeNetwork : NodeNetwork { #region Fields const int PropertyIndexSize = 32; PositionedObjectList<Circle> mOccupiedTileCircles = new PositionedObjectList<Circle>(); PositionedNode[][] mTiledNodes; List<OccupiedTile> mOccupiedTiles = new List<OccupiedTile>(); int mNumberOfXTiles; int mNumberOfYTiles; DirectionalType mDirectionalType; float mXSeed; float mYSeed; float mGridSpacing; float[] mCosts; #endregion #region Properties public float OccupiedCircleRadius { get; set; } public float GridSpacing => mGridSpacing; public float NumberOfXTiles => mNumberOfXTiles; public float NumberOfYTiles => mNumberOfYTiles; #endregion #region Methods #region Constructor private TileNodeNetwork() { } /// <summary> /// Creates a new, empty TileNodeNetwork matching the arguments. /// </summary> /// <param name="xOrigin">The X position of the left-most nodes. This, along with the ySeed, define the bottom-left of the node network. /// For tile maps this should be the center X of the first tile column (typically TileWidth / 2).</param> /// <param name="yOrigin">The y position of the bottom-most nodes. This, along with xSeed, define the bottom-left of the node network. /// For tile maps this should be the center Y of the bottom tile row. /// If the top-left of the map is at 0,0, then this value would be (-EntireMapHeight + TileHeight/2)</param> /// <param name="gridSpacing">The X and Y distance between each node. That is, the X distance between two adjacent nodes (assumed to be equal to the Y distance). For a tile map this will equal the width of a tile.</param> /// <param name="numberOfXTiles">The number of nodes vertically.</param> /// <param name="numberOfYTiles">The number of nodes horizontally.</param> /// <param name="directionalType">Whether to create a Four-way or Eight-way node network. Eight creates diagonal links, enabling diagonal movement when following the node network.</param> public TileNodeNetwork(float xOrigin, float yOrigin, float gridSpacing, int numberOfXTiles, int numberOfYTiles, DirectionalType directionalType) { mCosts = new float[PropertyIndexSize]; // Maybe expand this to 64 if we ever move to a long bit field? OccupiedCircleRadius = .5f; mTiledNodes = new PositionedNode[numberOfXTiles][]; mNumberOfXTiles = numberOfXTiles; mNumberOfYTiles = numberOfYTiles; mDirectionalType = directionalType; mXSeed = xOrigin; mYSeed = yOrigin; mGridSpacing = gridSpacing; // Do an initial loop to create the arrays so that // linking works properly for (int x = 0; x < numberOfXTiles; x++) { mTiledNodes[x] = new PositionedNode[numberOfYTiles]; } } #endregion #region Public Methods public override void Shift(Vector3 shiftVector) { mXSeed += shiftVector.X; mYSeed += shiftVector.Y; for (int i = 0; i < this.Nodes.Count; i++) { this.Nodes[i].Position += shiftVector; } } /// <summary> /// Adds a new node at the world X and Y location. Internally the world coordinates are converted to x,y indexes and the node is stored /// in a 2D grid. /// </summary> /// <param name="worldX">The world X units.</param> /// <param name="worldY">The world Y units.</param> /// <returns>The newly-created PositionedNode</returns> public PositionedNode AddAndLinkTiledNodeWorld(float worldX, float worldY) { int x; int y; WorldToIndex(worldX, worldY, out x, out y); return AddAndLinkTiledNode(x, y, mDirectionalType); } /// <summary> /// Adds a new node at the tile index x, y. /// </summary> /// <param name="x">The x index of the tile.</param> /// <param name="y">The y index of the tile.</param> /// <returns>The newly-created PositionedNode</returns> public PositionedNode AddAndLinkTiledNode(int x, int y) { return AddAndLinkTiledNode(x, y, mDirectionalType); } /// <summary> /// Creates a new node at index x, y and links the node to adjacent nodes given the TileNodeNetwork's GridSpacing /// </summary> /// <param name="x">The X index</param> /// <param name="y">The Y index</param> /// <param name="directionalType">The DirectionalType, which is either Four or Eight way. Four will link in cardinal directions, while Eight will also link diagonally.</param> /// <returns></returns> public PositionedNode AddAndLinkTiledNode(int x, int y, DirectionalType directionalType) { PositionedNode node = null; if (mTiledNodes[x][y] != null) { node = mTiledNodes[x][y]; } else { node = base.AddNode(); mTiledNodes[x][y] = node; } node.Position.X = mXSeed + x * mGridSpacing; node.Position.Y = mYSeed + y * mGridSpacing; // Now attach to the adjacent tiles AttachNodeToNodeAtIndex(node, x, y + 1); AttachNodeToNodeAtIndex(node, x + 1, y); AttachNodeToNodeAtIndex(node, x, y - 1); AttachNodeToNodeAtIndex(node, x - 1, y); if (directionalType == DirectionalType.Eight) { AttachNodeToNodeAtIndex(node, x - 1, y + 1); AttachNodeToNodeAtIndex(node, x + 1, y + 1); AttachNodeToNodeAtIndex(node, x + 1, y - 1); AttachNodeToNodeAtIndex(node, x - 1, y - 1); } return node; } /// <summary> /// Adds an already-positioned node to the node network. /// </summary> /// <remarks> /// This method adds a node to the base nodes list, as well as to the /// 2D array of node. The position of the node is used to add the node, so it /// should already be in its final position prior to calling this method. /// </remarks> /// <param name="nodeToAdd">The node to add.</param> public override void AddNode(PositionedNode nodeToAdd) { int xIndex; int yIndex; WorldToIndex(nodeToAdd.X, nodeToAdd.Y, out xIndex, out yIndex); if(mTiledNodes[xIndex][yIndex] != null) { throw new InvalidOperationException($"There is already a node at index ({xIndex}, {yIndex})"); } mTiledNodes[xIndex][yIndex] = nodeToAdd; base.AddNode(nodeToAdd); } /// <summary> /// Populates every possible space on the grid with a node and creates links betwen adjacent links. Diagonal links are created only if /// the DirectionalType is set to DirectionalType.Eight. /// </summary> public void FillCompletely() { for (int x = 0; x < mNumberOfXTiles; x++) { for (int y = 0; y < mNumberOfYTiles; y++) { PositionedNode newNode = AddAndLinkTiledNode(x, y, mDirectionalType); } } } public void EliminateCutCorners() { for (int x = 0; x < this.mNumberOfXTiles; x++) { for (int y = 0; y < this.mNumberOfYTiles; y++) { EliminateCutCornersForNodeAtIndex(x, y); } } } public void EliminateCutCornersForNodeAtIndex(int x, int y) { PositionedNode nodeAtIndex = TiledNodeAt(x, y); if (nodeAtIndex == null) { return; } PositionedNode nodeAL = TiledNodeAt(x - 1, y + 1); PositionedNode nodeA = TiledNodeAt(x , y + 1); PositionedNode nodeAR = TiledNodeAt(x + 1, y + 1); PositionedNode nodeR = TiledNodeAt(x + 1, y ); PositionedNode nodeBR = TiledNodeAt(x + 1, y - 1); PositionedNode nodeB = TiledNodeAt(x , y - 1); PositionedNode nodeBL = TiledNodeAt(x - 1, y - 1); PositionedNode nodeL = TiledNodeAt(x - 1, y ); if (nodeAL != null && nodeAtIndex.IsLinkedTo(nodeAL)) { if (nodeA == null || nodeL == null) { nodeAtIndex.BreakLinkBetween(nodeAL); } } if (nodeAR != null && nodeAtIndex.IsLinkedTo(nodeAR)) { if (nodeA == null || nodeR == null) { nodeAtIndex.BreakLinkBetween(nodeAR); } } if (nodeBR != null && nodeAtIndex.IsLinkedTo(nodeBR)) { if (nodeB == null || nodeR == null) { nodeAtIndex.BreakLinkBetween(nodeBR); } } if (nodeBL != null && nodeAtIndex.IsLinkedTo(nodeBL)) { if (nodeB == null || nodeL == null) { nodeAtIndex.BreakLinkBetween(nodeBL); } } } public PositionedNode GetClosestNodeTo(float x, float y) { #if DEBUG if (float.IsNaN(x)) { throw new ArgumentException("x value is NaN"); } if(float.IsNaN(y)) { throw new ArgumentException("y value is NaN"); } #endif int xTilesFromSeed = MathFunctions.RoundToInt((x - mXSeed) / mGridSpacing); int yTilesFromSeed = MathFunctions.RoundToInt((y - mYSeed) / mGridSpacing); xTilesFromSeed = System.Math.Max(0, xTilesFromSeed); xTilesFromSeed = System.Math.Min(xTilesFromSeed, mNumberOfXTiles - 1); yTilesFromSeed = System.Math.Max(0, yTilesFromSeed); yTilesFromSeed = System.Math.Min(yTilesFromSeed, mNumberOfYTiles - 1); PositionedNode nodeToReturn = TiledNodeAt(xTilesFromSeed, yTilesFromSeed); if (nodeToReturn == null) { // Well, we tried to be efficient here, but it didn't work out, so // let's use our slower Base functionality to get the node that we should return Vector3 vector3 = new Vector3(x, y, 0); nodeToReturn = base.GetClosestNodeTo(ref vector3); } return nodeToReturn; } public override PositionedNode GetClosestNodeTo(ref Microsoft.Xna.Framework.Vector3 position) { return GetClosestNodeTo(position.X, position.Y); } public PositionedNode GetClosestUnoccupiedNodeTo(ref Microsoft.Xna.Framework.Vector3 targetPosition, ref Microsoft.Xna.Framework.Vector3 startPosition) { return GetClosestUnoccupiedNodeTo(ref targetPosition, ref startPosition, false); } public PositionedNode GetClosestUnoccupiedNodeTo(ref Microsoft.Xna.Framework.Vector3 targetPosition, ref Microsoft.Xna.Framework.Vector3 startPosition, bool ignoreCorners) { PositionedNode nodeToReturn = null; int xTile, yTile; WorldToIndex(targetPosition.X, targetPosition.Y, out xTile, out yTile); if (IsTileOccupied(xTile, yTile) == false) nodeToReturn = TiledNodeAt(xTile, yTile); if (nodeToReturn == null) { int startXTile, startYTile, xTileCheck, yTileCheck, deltaX, deltaY; WorldToIndex(startPosition.X, startPosition.Y, out startXTile, out startYTile); float shortestDistanceSquared = 999; int finalTileX = -1, finalTileY = -1; //Get the "target" Node PositionedNode node = TiledNodeAt(xTile, yTile); PositionedNode startNode = TiledNodeAt(startXTile, startYTile); PositionedNode checkNode; if (node != null && startNode != null) { for (int i = 0; i < node.Links.Count; i++) { //skip any tile I am already on... checkNode = node.Links[i].NodeLinkingTo; if (checkNode == startNode) continue; WorldToIndex(checkNode.X, checkNode.Y, out xTileCheck, out yTileCheck); if (IsTileOccupied(xTileCheck, yTileCheck) == false) { deltaX = xTileCheck - xTile; deltaY = yTileCheck - yTile; if (ignoreCorners == false || (ignoreCorners == true && (deltaX == 0 || deltaY == 0))) { float distanceFromStartSquared = ((xTileCheck - startXTile) * (xTileCheck - startXTile)) + ((yTileCheck - startYTile) * (yTileCheck - startYTile)); if (distanceFromStartSquared < shortestDistanceSquared) { shortestDistanceSquared = distanceFromStartSquared; finalTileX = xTileCheck; finalTileY = yTileCheck; } } } } if (finalTileX != -1 && finalTileY != -1) { nodeToReturn = TiledNodeAt(finalTileX, finalTileY); } } } return nodeToReturn; } public bool AreAdjacentTiles(ref Microsoft.Xna.Framework.Vector3 targetPosition, ref Microsoft.Xna.Framework.Vector3 startPosition) { return AreAdjacentTiles(ref targetPosition, ref startPosition, false); } public bool AreAdjacentTiles(ref Microsoft.Xna.Framework.Vector3 targetPosition, ref Microsoft.Xna.Framework.Vector3 startPosition, bool ignoreCorners) { bool areAdjacent = false; int xTileTarget, yTileTarget, xTileStart, yTileStart, deltaX, deltaY; WorldToIndex(targetPosition.X, targetPosition.Y, out xTileTarget, out yTileTarget); WorldToIndex(startPosition.X, startPosition.Y, out xTileStart, out yTileStart); deltaX = xTileTarget - xTileStart; deltaY = yTileTarget - yTileStart; if (ignoreCorners == false || (ignoreCorners == true && (deltaX == 0 || deltaY == 0))) { PositionedNode targetNode = TiledNodeAt(xTileTarget, yTileTarget); PositionedNode startNode = TiledNodeAt(xTileStart, yTileStart); if (targetNode != null && startNode != null) { for (int i = 0; i < targetNode.Links.Count; i++) { if (targetNode.Links[i].NodeLinkingTo == startNode) { areAdjacent = true; break; } } } } return areAdjacent; } public Vector2 GetOccupiedTileLocation(object occupier) { foreach (OccupiedTile occupiedTile in mOccupiedTiles) { if (occupiedTile.Occupier == occupier) { float worldX; float worldY; IndexToWorld(occupiedTile.X, occupiedTile.Y, out worldX, out worldY); return new Vector2(worldX, worldY); } } return new Vector2(float.NaN, float.NaN); } public bool IsTileOccupied(int x, int y) { foreach (OccupiedTile occupiedTile in mOccupiedTiles) { if (occupiedTile.X == x && occupiedTile.Y == y) { return true; } } return false; } public bool IsTileOccupied(int x, int y, out object occupier) { foreach (OccupiedTile occupiedTile in mOccupiedTiles) { if (occupiedTile.X == x && occupiedTile.Y == y) { occupier = occupiedTile.Occupier; return true; } } occupier = null; return false; } public bool IsTileOccupiedWorld(float worldX, float worldY) { int xIndex; int yIndex; WorldToIndex(worldX, worldY, out xIndex, out yIndex); return IsTileOccupied(xIndex, yIndex); } public bool IsTileOccupiedWorld(float worldX, float worldY, out object occupier) { int xIndex; int yIndex; WorldToIndex(worldX, worldY, out xIndex, out yIndex); return IsTileOccupied(xIndex, yIndex, out occupier); } public void OccupyTile(int x, int y) { OccupyTile(x, y, null); } public void OccupyTile(int x, int y, object occupier) { #if DEBUG object objectAlreadyOccupying = GetTileOccupier(x, y); if (objectAlreadyOccupying != null) { throw new InvalidOperationException("The tile at " + x + ", " + y + " is already occupied by " + objectAlreadyOccupying.ToString()); } #endif OccupiedTile occupiedTile = new OccupiedTile(); occupiedTile.X = x; occupiedTile.Y = y; occupiedTile.Occupier = occupier; mOccupiedTiles.Add(occupiedTile); } public void OccupyTileWorld(float worldX, float worldY) { int xIndex; int yIndex; WorldToIndex(worldX, worldY, out xIndex, out yIndex); OccupyTile(xIndex, yIndex, null); } public void OccupyTileWorld(float worldX, float worldY, object occupier) { int xIndex; int yIndex; WorldToIndex(worldX, worldY, out xIndex, out yIndex); OccupyTile(xIndex, yIndex, occupier); } public object GetOccupier(float worldX, float worldY) { object occupier = null; IsTileOccupiedWorld(worldX, worldY, out occupier); return occupier; } public void RecalculateCostsForCostIndex(int costIndex) { int shiftedCost = (1 << costIndex); foreach (PositionedNode positionedNode in mNodes) { if ((positionedNode.PropertyField & shiftedCost) == shiftedCost) { UpdateNodeAccordingToCosts(positionedNode); } } } public void SetCosts(params float[] costs) { for (int i = 0; i < costs.Length; i++) { mCosts[i] = costs[i]; } } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public PositionedNode TiledNodeAtWorld(float xWorld, float yWorld) { int xIndex; int yIndex; xIndex = MathFunctions.RoundToInt((xWorld - mXSeed) / mGridSpacing); yIndex = MathFunctions.RoundToInt((yWorld - mYSeed) / mGridSpacing); // Seems like this code checks the indexes and clamps them inward, but then down below we do null checks // I think we should make this return null if out of bounds //xIndex = System.Math.Max(0, xIndex); //xIndex = System.Math.Min(xIndex, mNumberOfXTiles - 1); //yIndex = System.Math.Max(0, yIndex); //yIndex = System.Math.Min(yIndex, mNumberOfYTiles - 1); if (xIndex < 0 || xIndex >= mNumberOfXTiles || yIndex < 0 || yIndex >= mNumberOfYTiles) { return null; } else { return mTiledNodes[xIndex][yIndex]; } } public PositionedNode TiledNodeAt(int x, int y) { if (x < 0 || x >= mNumberOfXTiles || y < 0 || y >= mNumberOfYTiles) { return null; } else { return mTiledNodes[x][y]; } } public RectangleNodeNetwork ToRectangleNodeNetwork(Axis stripAxis) { var nodeNetwork = new RectangleNodeNetwork(); nodeNetwork.StripAxis = stripAxis; RectangleNode currentNode = null; float halfDimension = mGridSpacing / 2.0f; if (stripAxis == Axis.X) { float startX = 0; for (int y = 0; y < mNumberOfYTiles; y++) { for(int x = 0; x < mNumberOfXTiles; x++) { var nodeAtXY = TiledNodeAt(x, y); if (nodeAtXY != null) { if(currentNode == null) { currentNode = new RectangleNode(); currentNode.Y = nodeAtXY.Y; currentNode.Height = mGridSpacing; startX = nodeAtXY.X - halfDimension; nodeNetwork.AddNode(currentNode); } } else if(nodeAtXY == null && currentNode != null) { var endX = x * mGridSpacing; currentNode.X = (startX + endX) / 2.0f; currentNode.Width = endX - startX; currentNode = null; } } if(currentNode != null) { // got to the end of the row: var endX = mGridSpacing * mNumberOfXTiles; currentNode.X = (startX + endX) / 2.0f; currentNode.Width = endX - startX; currentNode = null; } } } else // Axis.Y { } return nodeNetwork; } public void Unoccupy(int x, int y) { for (int i = mOccupiedTiles.Count - 1; i > -1; i--) { OccupiedTile occupiedTile = mOccupiedTiles[i]; if (occupiedTile.X == x && occupiedTile.Y == y) { mOccupiedTiles.RemoveAt(i); break; } } } public void Unoccupy(object occupier) { for (int i = mOccupiedTiles.Count - 1; i > -1; i--) { OccupiedTile occupiedTile = mOccupiedTiles[i]; if (occupiedTile.Occupier == occupier) { mOccupiedTiles.RemoveAt(i); // Don't do a break here because // one occupier could occupy multiple // tiles. // break; } } } public void UpdateNodeAccordingToCosts(PositionedNode node) { float multiplierForThisNode = 1; for (int propertyIndex = 0; propertyIndex < PropertyIndexSize; propertyIndex++) { int shiftedValue = 1 << propertyIndex; if ((node.PropertyField & shiftedValue) == shiftedValue) { multiplierForThisNode += mCosts[propertyIndex]; } } // Now we know the cost multiplier to get to this node, which is multiplerForThisNode // Next we just have to calculate the distance to get to this node and foreach (Link link in node.mLinks) { PositionedNode otherNode = link.NodeLinkingTo; Link linkBack = otherNode.GetLinkTo(node); if (linkBack != null) { // reacalculate the cost: linkBack.Cost = (node.Position - otherNode.Position).Length() * multiplierForThisNode; } } } public override void UpdateShapes() { base.UpdateShapes(); if (Visible == false) { while (mOccupiedTileCircles.Count != 0) { ShapeManager.Remove(mOccupiedTileCircles[mOccupiedTileCircles.Count - 1]); } } else { // Remove circles if necessary while (mOccupiedTileCircles.Count > mOccupiedTiles.Count) { ShapeManager.Remove(mOccupiedTileCircles.Last); } while (mOccupiedTileCircles.Count < mOccupiedTiles.Count) { Circle circle = new Circle(); circle.Color = Color.Orange; ShapeManager.AddToLayer(circle, LayerToDrawOn); mOccupiedTileCircles.Add(circle); } for (int i = 0; i < mOccupiedTiles.Count; i++) { IndexToWorld(mOccupiedTiles[i].X, mOccupiedTiles[i].Y, out mOccupiedTileCircles[i].Position.X, out mOccupiedTileCircles[i].Position.Y); mOccupiedTileCircles[i].Radius = OccupiedCircleRadius; } } } public void IndexToWorld(int xIndex, int yIndex, out float worldX, out float worldY) { worldX = mXSeed + mGridSpacing * xIndex; worldY = mYSeed + mGridSpacing * yIndex; } public void WorldToIndex(float worldX, float worldY, out int xIndex, out int yIndex) { xIndex = MathFunctions.RoundToInt((worldX - mXSeed) / mGridSpacing); yIndex = MathFunctions.RoundToInt((worldY - mYSeed) / mGridSpacing); xIndex = System.Math.Max(0, xIndex); xIndex = System.Math.Min(xIndex, mNumberOfXTiles - 1); yIndex = System.Math.Max(0, yIndex); yIndex = System.Math.Min(yIndex, mNumberOfYTiles - 1); } public void AttachNodeToNodeAtIndex(PositionedNode node, int x, int y) { PositionedNode nodeToLinkTo = TiledNodeAt(x, y); if (nodeToLinkTo != null && !node.IsLinkedTo(nodeToLinkTo)) { node.LinkTo(nodeToLinkTo); } } public override void Remove(PositionedNode nodeToRemove) { //base.Remove(nodeToRemove); // bake it for performance reasons: for (int i = nodeToRemove.Links.Count - 1; i > -1; i--) { nodeToRemove.Links[i].NodeLinkingTo.BreakLinkBetween(nodeToRemove); } mNodes.Remove(nodeToRemove); int tileX, tileY; WorldToIndex(nodeToRemove.Position.X, nodeToRemove.Position.Y, out tileX, out tileY); mTiledNodes[tileX][tileY] = null; } public void RemoveAndUnlinkNode( ref Microsoft.Xna.Framework.Vector3 positionToRemoveNodeFrom ) { PositionedNode nodeToRemove = GetClosestNodeTo(ref positionToRemoveNodeFrom); Remove( nodeToRemove ); } #endregion #region Private Methods private object GetTileOccupier(int x, int y) { foreach (OccupiedTile occupiedTile in mOccupiedTiles) { if (occupiedTile.X == x && occupiedTile.Y == y) { return occupiedTile.Occupier; } } return null; } #endregion #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Dynamic.Utils; using System.Reflection; using System.Reflection.Emit; using static System.Linq.Expressions.CachedReflectionInfo; namespace System.Linq.Expressions.Compiler { internal partial class LambdaCompiler { private void EmitQuoteUnaryExpression(Expression expr) { EmitQuote((UnaryExpression)expr); } private void EmitQuote(UnaryExpression quote) { // emit the quoted expression as a runtime constant EmitConstant(quote.Operand, quote.Type); // Heuristic: only emit the tree rewrite logic if we have hoisted // locals. if (_scope.NearestHoistedLocals != null) { // HoistedLocals is internal so emit as System.Object EmitConstant(_scope.NearestHoistedLocals, typeof(object)); _scope.EmitGet(_scope.NearestHoistedLocals.SelfVariable); _ilg.Emit(OpCodes.Call, RuntimeOps_Quote); if (quote.Type != typeof(Expression)) { _ilg.Emit(OpCodes.Castclass, quote.Type); } } } private void EmitThrowUnaryExpression(Expression expr) { EmitThrow((UnaryExpression)expr, CompilationFlags.EmitAsDefaultType); } private void EmitThrow(UnaryExpression expr, CompilationFlags flags) { if (expr.Operand == null) { CheckRethrow(); _ilg.Emit(OpCodes.Rethrow); } else { EmitExpression(expr.Operand); _ilg.Emit(OpCodes.Throw); } EmitUnreachable(expr, flags); } private void EmitUnaryExpression(Expression expr, CompilationFlags flags) { EmitUnary((UnaryExpression)expr, flags); } private void EmitUnary(UnaryExpression node, CompilationFlags flags) { if (node.Method != null) { EmitUnaryMethod(node, flags); } else if (node.NodeType == ExpressionType.NegateChecked && node.Operand.Type.IsInteger()) { EmitExpression(node.Operand); LocalBuilder loc = GetLocal(node.Operand.Type); _ilg.Emit(OpCodes.Stloc, loc); _ilg.EmitPrimitive(0); _ilg.EmitConvertToType(typeof(int), node.Operand.Type, isChecked: false, locals: this); _ilg.Emit(OpCodes.Ldloc, loc); FreeLocal(loc); EmitBinaryOperator(ExpressionType.SubtractChecked, node.Operand.Type, node.Operand.Type, node.Type, liftedToNull: false); } else { EmitExpression(node.Operand); EmitUnaryOperator(node.NodeType, node.Operand.Type, node.Type); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] private void EmitUnaryOperator(ExpressionType op, Type operandType, Type resultType) { bool operandIsNullable = operandType.IsNullableType(); if (op == ExpressionType.ArrayLength) { _ilg.Emit(OpCodes.Ldlen); return; } if (operandIsNullable) { switch (op) { case ExpressionType.Not: { if (operandType != typeof(bool?)) { goto case ExpressionType.Negate; } Label labEnd = _ilg.DefineLabel(); LocalBuilder loc = GetLocal(operandType); // store values (reverse order since they are already on the stack) _ilg.Emit(OpCodes.Stloc, loc); // test for null _ilg.Emit(OpCodes.Ldloca, loc); _ilg.EmitHasValue(operandType); _ilg.Emit(OpCodes.Brfalse_S, labEnd); // do op on non-null value _ilg.Emit(OpCodes.Ldloca, loc); _ilg.EmitGetValueOrDefault(operandType); Type nnOperandType = operandType.GetNonNullableType(); EmitUnaryOperator(op, nnOperandType, typeof(bool)); // construct result ConstructorInfo ci = resultType.GetConstructor(ArrayOfType_Bool); _ilg.Emit(OpCodes.Newobj, ci); _ilg.Emit(OpCodes.Stloc, loc); _ilg.MarkLabel(labEnd); _ilg.Emit(OpCodes.Ldloc, loc); FreeLocal(loc); return; } case ExpressionType.UnaryPlus: case ExpressionType.NegateChecked: case ExpressionType.Negate: case ExpressionType.Increment: case ExpressionType.Decrement: case ExpressionType.OnesComplement: case ExpressionType.IsFalse: case ExpressionType.IsTrue: { Debug.Assert(TypeUtils.AreEquivalent(operandType, resultType)); Label labIfNull = _ilg.DefineLabel(); Label labEnd = _ilg.DefineLabel(); LocalBuilder loc = GetLocal(operandType); // check for null _ilg.Emit(OpCodes.Stloc, loc); _ilg.Emit(OpCodes.Ldloca, loc); _ilg.EmitHasValue(operandType); _ilg.Emit(OpCodes.Brfalse_S, labIfNull); // apply operator to non-null value _ilg.Emit(OpCodes.Ldloca, loc); _ilg.EmitGetValueOrDefault(operandType); Type nnOperandType = resultType.GetNonNullableType(); EmitUnaryOperator(op, nnOperandType, nnOperandType); // construct result ConstructorInfo ci = resultType.GetConstructor(new Type[] { nnOperandType }); _ilg.Emit(OpCodes.Newobj, ci); _ilg.Emit(OpCodes.Stloc, loc); _ilg.Emit(OpCodes.Br_S, labEnd); // if null then create a default one _ilg.MarkLabel(labIfNull); _ilg.Emit(OpCodes.Ldloca, loc); _ilg.Emit(OpCodes.Initobj, resultType); _ilg.MarkLabel(labEnd); _ilg.Emit(OpCodes.Ldloc, loc); FreeLocal(loc); return; } case ExpressionType.TypeAs: _ilg.Emit(OpCodes.Box, operandType); _ilg.Emit(OpCodes.Isinst, resultType); if (resultType.IsNullableType()) { _ilg.Emit(OpCodes.Unbox_Any, resultType); } return; default: throw Error.UnhandledUnary(op, nameof(op)); } } else { switch (op) { case ExpressionType.Not: if (operandType == typeof(bool)) { _ilg.Emit(OpCodes.Ldc_I4_0); _ilg.Emit(OpCodes.Ceq); return; } goto case ExpressionType.OnesComplement; case ExpressionType.OnesComplement: _ilg.Emit(OpCodes.Not); if (!operandType.IsUnsigned()) { // Guaranteed to fit within result type: no conversion return; } break; case ExpressionType.IsFalse: _ilg.Emit(OpCodes.Ldc_I4_0); _ilg.Emit(OpCodes.Ceq); // Not an arithmetic operation -> no conversion return; case ExpressionType.IsTrue: _ilg.Emit(OpCodes.Ldc_I4_1); _ilg.Emit(OpCodes.Ceq); // Not an arithmetic operation -> no conversion return; case ExpressionType.UnaryPlus: // Guaranteed to fit within result type: no conversion return; case ExpressionType.Negate: case ExpressionType.NegateChecked: _ilg.Emit(OpCodes.Neg); // Guaranteed to fit within result type: no conversion // (integer NegateChecked was rewritten to 0 - operand and doesn't hit here). return; case ExpressionType.TypeAs: if (operandType.IsValueType) { _ilg.Emit(OpCodes.Box, operandType); } _ilg.Emit(OpCodes.Isinst, resultType); if (resultType.IsNullableType()) { _ilg.Emit(OpCodes.Unbox_Any, resultType); } // Not an arithmetic operation -> no conversion return; case ExpressionType.Increment: EmitConstantOne(resultType); _ilg.Emit(OpCodes.Add); break; case ExpressionType.Decrement: EmitConstantOne(resultType); _ilg.Emit(OpCodes.Sub); break; default: throw Error.UnhandledUnary(op, nameof(op)); } EmitConvertArithmeticResult(op, resultType); } } private void EmitConstantOne(Type type) { switch (type.GetTypeCode()) { case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.Int16: case TypeCode.Int32: _ilg.Emit(OpCodes.Ldc_I4_1); break; case TypeCode.Int64: case TypeCode.UInt64: _ilg.Emit(OpCodes.Ldc_I4_1); _ilg.Emit(OpCodes.Conv_I8); break; case TypeCode.Single: _ilg.Emit(OpCodes.Ldc_R4, 1.0f); break; case TypeCode.Double: _ilg.Emit(OpCodes.Ldc_R8, 1.0d); break; default: // we only have to worry about arithmetic types, see // TypeUtils.IsArithmetic throw ContractUtils.Unreachable; } } private void EmitUnboxUnaryExpression(Expression expr) { var node = (UnaryExpression)expr; Debug.Assert(node.Type.IsValueType); // Unbox_Any leaves the value on the stack EmitExpression(node.Operand); _ilg.Emit(OpCodes.Unbox_Any, node.Type); } private void EmitConvertUnaryExpression(Expression expr, CompilationFlags flags) { EmitConvert((UnaryExpression)expr, flags); } private void EmitConvert(UnaryExpression node, CompilationFlags flags) { if (node.Method != null) { // User-defined conversions are only lifted if both source and // destination types are value types. The C# compiler gets this wrong. // In C#, if you have an implicit conversion from int->MyClass and you // "lift" the conversion to int?->MyClass then a null int? goes to a // null MyClass. This is contrary to the specification, which states // that the correct behaviour is to unwrap the int?, throw an exception // if it is null, and then call the conversion. // // We cannot fix this in C# but there is no reason why we need to // propagate this behavior into the expression tree API. Unfortunately // this means that when the C# compiler generates the lambda // (int? i)=>(MyClass)i, we will get different results for converting // that lambda to a delegate directly and converting that lambda to // an expression tree and then compiling it. We can live with this // discrepancy however. if (node.IsLifted && (!node.Type.IsValueType || !node.Operand.Type.IsValueType)) { ParameterInfo[] pis = node.Method.GetParametersCached(); Debug.Assert(pis != null && pis.Length == 1); Type paramType = pis[0].ParameterType; if (paramType.IsByRef) { paramType = paramType.GetElementType(); } UnaryExpression e = Expression.Convert( Expression.Call( node.Method, Expression.Convert(node.Operand, paramType) ), node.Type ); EmitConvert(e, flags); } else { EmitUnaryMethod(node, flags); } } else if (node.Type == typeof(void)) { EmitExpressionAsVoid(node.Operand, flags); } else { if (TypeUtils.AreEquivalent(node.Operand.Type, node.Type)) { EmitExpression(node.Operand, flags); } else { // A conversion is emitted after emitting the operand, no tail call is emitted EmitExpression(node.Operand); _ilg.EmitConvertToType(node.Operand.Type, node.Type, node.NodeType == ExpressionType.ConvertChecked, this); } } } private void EmitUnaryMethod(UnaryExpression node, CompilationFlags flags) { if (node.IsLifted) { ParameterExpression v = Expression.Variable(node.Operand.Type.GetNonNullableType(), name: null); MethodCallExpression mc = Expression.Call(node.Method, v); Type resultType = mc.Type.GetNullableType(); EmitLift(node.NodeType, resultType, mc, new ParameterExpression[] { v }, new Expression[] { node.Operand }); _ilg.EmitConvertToType(resultType, node.Type, isChecked: false, locals: this); } else { EmitMethodCallExpression(Expression.Call(node.Method, node.Operand), flags); } } } }
using System; using System.Collections; using System.Collections.Specialized; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; namespace BLToolkit.TypeBuilder.Builders { using Reflection; using Reflection.Emit; internal class TypeAccessorBuilder : ITypeBuilder { public TypeAccessorBuilder(Type type, Type originalType) { if (type == null) throw new ArgumentNullException("type"); if (originalType == null) throw new ArgumentNullException("originalType"); _type = type; _originalType = originalType; } readonly TypeHelper _type; readonly TypeHelper _originalType; readonly TypeHelper _accessorType = new TypeHelper(typeof(TypeAccessor)); readonly TypeHelper _memberAccessor = new TypeHelper(typeof(MemberAccessor)); readonly ArrayList _nestedTypes = new ArrayList(); TypeBuilderHelper _typeBuilder; bool _friendlyAssembly; public string AssemblyNameSuffix { get { return "TypeAccessor"; } } public string GetTypeName() { // It's a bad idea to use '.TypeAccessor' here since we got // a class and a namespace with the same full name. // The sgen utility fill fail in such case. // return _type.FullName.Replace('+', '.') + "$TypeAccessor"; } public Type GetBuildingType() { return _type; } public Type Build(AssemblyBuilderHelper assemblyBuilder) { if (assemblyBuilder == null) throw new ArgumentNullException("assemblyBuilder"); // Check InternalsVisibleToAttributes of the source type's assembly. // Even if the sourceType is public, it may have internal fields and props. // _friendlyAssembly = false; // Usually, there is no such attribute in the source assembly. // Therefore we do not cache the result. // object[] attributes = _originalType.Type.Assembly.GetCustomAttributes(typeof(InternalsVisibleToAttribute), true); foreach (InternalsVisibleToAttribute visibleToAttribute in attributes) { AssemblyName an = new AssemblyName(visibleToAttribute.AssemblyName); if (AssemblyName.ReferenceMatchesDefinition(assemblyBuilder.AssemblyName, an)) { _friendlyAssembly = true; break; } } if (!_originalType.Type.IsVisible && !_friendlyAssembly) #if FW3 return typeof (ExprTypeAccessor<,>).MakeGenericType(_type, _originalType); #else throw new TypeBuilderException(string.Format("Can not build type accessor for non-public type '{0}'.", _originalType.FullName)); #endif string typeName = GetTypeName(); _typeBuilder = assemblyBuilder.DefineType(typeName, _accessorType); _typeBuilder.DefaultConstructor.Emitter .ldarg_0 .call (TypeHelper.GetDefaultConstructor(_accessorType)) ; BuildCreateInstanceMethods(); BuildTypeProperties(); BuildMembers(); BuildObjectFactory(); _typeBuilder.DefaultConstructor.Emitter .ret() ; Type result = _typeBuilder.Create(); foreach (TypeBuilderHelper tb in _nestedTypes) tb.Create(); return result; } void BuildCreateInstanceMethods() { bool isValueType = _type.IsValueType; ConstructorInfo baseDefCtor = isValueType? null: _type.GetPublicDefaultConstructor(); ConstructorInfo baseInitCtor = _type.GetPublicConstructor(typeof(InitContext)); if (baseDefCtor == null && baseInitCtor == null && !isValueType) return; // CreateInstance. // MethodBuilderHelper method = _typeBuilder.DefineMethod( _accessorType.GetMethod(false, "CreateInstance", Type.EmptyTypes)); if (baseDefCtor != null) { method.Emitter .newobj (baseDefCtor) .ret() ; } else if (isValueType) { LocalBuilder locObj = method.Emitter.DeclareLocal(_type); method.Emitter .ldloca (locObj) .initobj (_type) .ldloc (locObj) .box (_type) .ret() ; } else { method.Emitter .ldnull .newobj (baseInitCtor) .ret() ; } // CreateInstance(IniContext). // method = _typeBuilder.DefineMethod( _accessorType.GetMethod(false, "CreateInstance", typeof(InitContext))); if (baseInitCtor != null) { method.Emitter .ldarg_1 .newobj (baseInitCtor) .ret() ; } else if (isValueType) { LocalBuilder locObj = method.Emitter.DeclareLocal(_type); method.Emitter .ldloca (locObj) .initobj (_type) .ldloc (locObj) .box (_type) .ret() ; } else { method.Emitter .newobj (baseDefCtor) .ret() ; } } private void BuildTypeProperties() { // Type. // MethodBuilderHelper method = _typeBuilder.DefineMethod(_accessorType.GetProperty("Type").GetGetMethod()); method.Emitter .LoadType(_type) .ret() ; // OriginalType. // method = _typeBuilder.DefineMethod(_accessorType.GetProperty("OriginalType").GetGetMethod()); method.Emitter .LoadType(_originalType) .ret() ; } private void BuildMembers() { ListDictionary members = new ListDictionary(); foreach (FieldInfo fi in _originalType.GetFields(BindingFlags.Instance | BindingFlags.Public)) AddMemberToDictionary(members, fi); if (_friendlyAssembly) { foreach (FieldInfo fi in _originalType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic)) if (fi.IsAssembly || fi.IsFamilyOrAssembly) AddMemberToDictionary(members, fi); } foreach (PropertyInfo pi in _originalType.GetProperties(BindingFlags.Instance | BindingFlags.Public)) if (pi.GetIndexParameters().Length == 0) AddMemberToDictionary(members, pi); foreach (PropertyInfo pi in _originalType.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic)) { if (pi.GetIndexParameters().Length == 0) { MethodInfo getter = pi.GetGetMethod(true); MethodInfo setter = pi.GetSetMethod(true); if (getter != null && getter.IsAbstract || setter != null && setter.IsAbstract) AddMemberToDictionary(members, pi); } } foreach (MemberInfo mi in members.Values) BuildMember(mi); } private static void AddMemberToDictionary(IDictionary members, MemberInfo mi) { string name = mi.Name; if (!members.Contains(name)) { members.Add(name, mi); return; } MemberInfo existing = (MemberInfo) members[name]; if (mi.DeclaringType.IsSubclassOf(existing.DeclaringType)) { // mi is a member of the most descendant type. // members[name] = mi; } } private void BuildMember(MemberInfo mi) { bool isValueType = _originalType.IsValueType; TypeBuilderHelper nestedType = _typeBuilder.DefineNestedType( "Accessor$" + mi.Name, TypeAttributes.NestedPrivate, typeof(MemberAccessor)); ConstructorBuilderHelper ctorBuilder = BuildNestedTypeConstructor(nestedType); BuildGetter (mi, nestedType); if (!isValueType) BuildSetter(mi, nestedType); BuildInitMember(mi, ctorBuilder); Type type = mi is FieldInfo ? ((FieldInfo)mi).FieldType : ((PropertyInfo)mi).PropertyType; BuildIsNull (mi, nestedType, type); if (type.IsEnum) type = Enum.GetUnderlyingType(type); string typedPropertyName = type.Name; if (type.IsGenericType) { Type underlyingType = Nullable.GetUnderlyingType(type); if (underlyingType != null) { BuildTypedGetterForNullable (mi, nestedType, underlyingType); if (!isValueType) BuildTypedSetterForNullable(mi, nestedType, underlyingType); if (underlyingType.IsEnum) { // Note that PEVerify will complain on using Nullable<SomeEnum> as Nullable<Int32>. // It works in the current CLR implementation, bu may not work in future releases. // underlyingType = Enum.GetUnderlyingType(underlyingType); type = typeof(Nullable<>).MakeGenericType(underlyingType); } typedPropertyName = "Nullable" + underlyingType.Name; } else { typedPropertyName = null; } } if (typedPropertyName != null) { BuildTypedGetter (mi, nestedType, typedPropertyName); if (!isValueType) BuildTypedSetter(mi, nestedType, type, typedPropertyName); } if (!isValueType) BuildCloneValueMethod(mi, nestedType, type); // FW 1.1 wants nested types to be created before parent. // _nestedTypes.Add(nestedType); } private void BuildInitMember(MemberInfo mi, ConstructorBuilderHelper ctorBuilder) { _typeBuilder.DefaultConstructor.Emitter .ldarg_0 .ldarg_0 .ldarg_0 .ldc_i4 (mi is FieldInfo? 1: 2) .ldstr (mi.Name) .call (_accessorType.GetMethod("GetMember", typeof(int), typeof(string))) .newobj (ctorBuilder) .call (_accessorType.GetMethod("AddMember", typeof(MemberAccessor))) ; } /// <summary> /// Figure out is base type method is accessible by extension type method. /// </summary> /// <param name="method">A <see cref="MethodInfo"/> instance.</param> /// <returns>True if the method access is Public or Family and it's assembly is friendly.</returns> private bool IsMethodAccessible(MethodInfo method) { if (method == null) throw new ArgumentNullException("method"); return method.IsPublic || (_friendlyAssembly && (method.IsAssembly || method.IsFamilyOrAssembly)); } private void BuildGetter(MemberInfo mi, TypeBuilderHelper nestedType) { Type methodType = mi.DeclaringType; MethodInfo getMethod = null; if (mi is PropertyInfo) { getMethod = ((PropertyInfo)mi).GetGetMethod(); if (getMethod == null) { if (_type != _originalType) { getMethod = _type.GetMethod("get_" + mi.Name); methodType = _type; } if (getMethod == null || !IsMethodAccessible(getMethod)) return; } } MethodBuilderHelper method = nestedType.DefineMethod( _memberAccessor.GetMethod("GetValue", typeof(object))); EmitHelper emit = method.Emitter; emit .ldarg_1 .castType (methodType) .end(); if (mi is FieldInfo) { FieldInfo fi = (FieldInfo)mi; emit .ldfld (fi) .boxIfValueType (fi.FieldType) ; } else { PropertyInfo pi = (PropertyInfo)mi; emit .callvirt (getMethod) .boxIfValueType (pi.PropertyType) ; } emit .ret() ; nestedType.DefineMethod(_memberAccessor.GetProperty("HasGetter").GetGetMethod()).Emitter .ldc_i4_1 .ret() ; } private void BuildSetter(MemberInfo mi, TypeBuilderHelper nestedType) { Type methodType = mi.DeclaringType; MethodInfo setMethod = null; if (mi is PropertyInfo) { setMethod = ((PropertyInfo)mi).GetSetMethod(); if (setMethod == null) { if (_type != _originalType) { setMethod = _type.GetMethod("set_" + mi.Name); methodType = _type; } if (setMethod == null || !IsMethodAccessible(setMethod)) return; } } //else if (((FieldInfo)mi).IsLiteral) // return; MethodBuilderHelper method = nestedType.DefineMethod( _memberAccessor.GetMethod("SetValue", typeof(object), typeof(object))); EmitHelper emit = method.Emitter; emit .ldarg_1 .castType (methodType) .ldarg_2 .end(); if (mi is FieldInfo) { FieldInfo fi = (FieldInfo)mi; emit .CastFromObject (fi.FieldType) .stfld (fi) ; } else { PropertyInfo pi = (PropertyInfo)mi; emit .CastFromObject (pi.PropertyType) .callvirt (setMethod) ; } emit .ret() ; nestedType.DefineMethod(_memberAccessor.GetProperty("HasSetter").GetGetMethod()).Emitter .ldc_i4_1 .ret() ; } private void BuildIsNull( MemberInfo mi, TypeBuilderHelper nestedType, Type memberType) { Type methodType = mi.DeclaringType; MethodInfo getMethod = null; Boolean isNullable = TypeHelper.IsNullable(memberType); Boolean isValueType = (!isNullable && memberType.IsValueType); if (!isValueType && mi is PropertyInfo) { getMethod = ((PropertyInfo)mi).GetGetMethod(); if (getMethod == null) { if (_type != _originalType) { getMethod = _type.GetMethod("get_" + mi.Name); methodType = _type; } if (getMethod == null) return; } } MethodInfo methodInfo = _memberAccessor.GetMethod("IsNull"); if (methodInfo == null) return; MethodBuilderHelper method = nestedType.DefineMethod(methodInfo); EmitHelper emit = method.Emitter; if (isValueType) { emit .ldc_i4_0 .end() ; } else { LocalBuilder locObj = null; if (isNullable) locObj = method.Emitter.DeclareLocal(memberType); emit .ldarg_1 .castType (methodType) .end(); if (mi is FieldInfo) emit.ldfld ((FieldInfo)mi); else emit.callvirt(getMethod); if (isNullable) { emit .stloc(locObj) .ldloca(locObj) .call(memberType, "get_HasValue") .ldc_i4_0 .ceq .end(); } else { emit .ldnull .ceq .end(); } } emit .ret() ; } private void BuildTypedGetter( MemberInfo mi, TypeBuilderHelper nestedType, string typedPropertyName) { Type methodType = mi.DeclaringType; MethodInfo getMethod = null; if (mi is PropertyInfo) { getMethod = ((PropertyInfo)mi).GetGetMethod(); if (getMethod == null) { if (_type != _originalType) { getMethod = _type.GetMethod("get_" + mi.Name); methodType = _type; } if (getMethod == null || !IsMethodAccessible(getMethod)) return; } } MethodInfo methodInfo = _memberAccessor.GetMethod("Get" + typedPropertyName, typeof(object)); if (methodInfo == null) return; MethodBuilderHelper method = nestedType.DefineMethod(methodInfo); EmitHelper emit = method.Emitter; emit .ldarg_1 .castType (methodType) .end(); if (mi is FieldInfo) emit.ldfld ((FieldInfo)mi); else emit.callvirt(getMethod); emit .ret() ; } private void BuildTypedSetter( MemberInfo mi, TypeBuilderHelper nestedType, Type memberType, string typedPropertyName) { Type methodType = mi.DeclaringType; MethodInfo setMethod = null; if (mi is PropertyInfo) { setMethod = ((PropertyInfo)mi).GetSetMethod(); if (setMethod == null) { if (_type != _originalType) { setMethod = _type.GetMethod("set_" + mi.Name); methodType = _type; } if (setMethod == null || !IsMethodAccessible(setMethod)) return; } } MethodInfo methodInfo = _memberAccessor.GetMethod("Set" + typedPropertyName, typeof(object), memberType); if (methodInfo == null) return; MethodBuilderHelper method = nestedType.DefineMethod(methodInfo); EmitHelper emit = method.Emitter; emit .ldarg_1 .castType (methodType) .ldarg_2 .end(); if (mi is FieldInfo) emit.stfld ((FieldInfo)mi); else emit.callvirt(setMethod); emit .ret() ; } private void BuildCloneValueMethod( MemberInfo mi, TypeBuilderHelper nestedType, Type memberType ) { Type methodType = mi.DeclaringType; MethodInfo getMethod = null; MethodInfo setMethod = null; if (mi is PropertyInfo) { getMethod = ((PropertyInfo)mi).GetGetMethod(); if (getMethod == null) { if (_type != _originalType) { getMethod = _type.GetMethod("get_" + mi.Name); methodType = _type; } if (getMethod == null || !IsMethodAccessible(getMethod)) return; } setMethod = ((PropertyInfo)mi).GetSetMethod(); if (setMethod == null) { if (_type != _originalType) { setMethod = _type.GetMethod("set_" + mi.Name); methodType = _type; } if (setMethod == null || !IsMethodAccessible(setMethod)) return; } } MethodBuilderHelper method = nestedType.DefineMethod( _memberAccessor.GetMethod("CloneValue", typeof(object), typeof(object))); EmitHelper emit = method.Emitter; emit .ldarg_2 .castType (methodType) .ldarg_1 .castType (methodType) .end(); if (mi is FieldInfo) emit.ldfld ((FieldInfo)mi); else emit.callvirt(getMethod); if (typeof(string) != memberType && TypeHelper.IsSameOrParent(typeof(ICloneable), memberType)) { if (memberType.IsValueType) emit .box (memberType) .callvirt (typeof(ICloneable), "Clone") .unbox_any (memberType) ; else { Label valueIsNull = emit.DefineLabel(); emit .dup .brfalse_s (valueIsNull) .callvirt (typeof(ICloneable), "Clone") .castclass (memberType) .MarkLabel (valueIsNull) ; } } if (mi is FieldInfo) emit.stfld ((FieldInfo)mi); else emit.callvirt(setMethod); emit .ret() ; } private void BuildTypedGetterForNullable( MemberInfo mi, TypeBuilderHelper nestedType, Type memberType) { Type methodType = mi.DeclaringType; MethodInfo getMethod = null; if (mi is PropertyInfo) { getMethod = ((PropertyInfo)mi).GetGetMethod(); if (getMethod == null) { if (_type != _originalType) { getMethod = _type.GetMethod("get_" + mi.Name); methodType = _type; } if (getMethod == null || !IsMethodAccessible(getMethod)) return; } } Type setterType = (memberType.IsEnum ? Enum.GetUnderlyingType(memberType) : memberType); MethodInfo methodInfo = _memberAccessor.GetMethod("Get" + setterType.Name, typeof(object)); if (methodInfo == null) return; MethodBuilderHelper method = nestedType.DefineMethod(methodInfo); Type nullableType = typeof(Nullable<>).MakeGenericType(memberType); EmitHelper emit = method.Emitter; emit .ldarg_1 .castType (methodType) .end(); if (mi is FieldInfo) { emit.ldflda ((FieldInfo)mi); } else { LocalBuilder locNullable = emit.DeclareLocal(nullableType); emit .callvirt (getMethod) .stloc (locNullable) .ldloca (locNullable) ; } emit .call(nullableType, "get_Value") .ret() ; } private void BuildTypedSetterForNullable( MemberInfo mi, TypeBuilderHelper nestedType, Type memberType) { Type methodType = mi.DeclaringType; MethodInfo setMethod = null; if (mi is PropertyInfo) { setMethod = ((PropertyInfo)mi).GetSetMethod(); if (setMethod == null) { if (_type != _originalType) { setMethod = _type.GetMethod("set_" + mi.Name); methodType = _type; } if (setMethod == null || !IsMethodAccessible(setMethod)) return; } } Type setterType = (memberType.IsEnum ? Enum.GetUnderlyingType(memberType) : memberType); MethodInfo methodInfo = _memberAccessor.GetMethod("Set" + setterType.Name, typeof(object), setterType); if (methodInfo == null) return; MethodBuilderHelper method = nestedType.DefineMethod(methodInfo); EmitHelper emit = method.Emitter; emit .ldarg_1 .castType (methodType) .ldarg_2 .newobj (typeof(Nullable<>).MakeGenericType(memberType), memberType) .end(); if (mi is FieldInfo) emit.stfld ((FieldInfo)mi); else emit.callvirt(setMethod); emit .ret() ; } private static ConstructorBuilderHelper BuildNestedTypeConstructor(TypeBuilderHelper nestedType) { Type[] parameters = { typeof(TypeAccessor), typeof(MemberInfo) }; ConstructorBuilderHelper ctorBuilder = nestedType.DefinePublicConstructor(parameters); ctorBuilder.Emitter .ldarg_0 .ldarg_1 .ldarg_2 .call (TypeHelper.GetConstructor(typeof(MemberAccessor), parameters)) .ret() ; return ctorBuilder; } private void BuildObjectFactory() { Attribute attr = TypeHelper.GetFirstAttribute(_type, typeof(ObjectFactoryAttribute)); if (attr != null) { _typeBuilder.DefaultConstructor.Emitter .ldarg_0 .LoadType (_type) .LoadType (typeof(ObjectFactoryAttribute)) .call (typeof(TypeHelper), "GetFirstAttribute", typeof(Type), typeof(Type)) .castclass (typeof(ObjectFactoryAttribute)) .call (typeof(ObjectFactoryAttribute).GetProperty("ObjectFactory").GetGetMethod()) .call (typeof(TypeAccessor). GetProperty("ObjectFactory").GetSetMethod()) ; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Text; using Microsoft.Win32; namespace System.IO { public sealed class DirectoryInfo : FileSystemInfo { [System.Security.SecuritySafeCritical] public DirectoryInfo(String path) { if (path == null) throw new ArgumentNullException("path"); Contract.EndContractBlock(); Init(path); } [System.Security.SecurityCritical] private void Init(String path) { // Special case "<DriveLetter>:" to point to "<CurrentDirectory>" instead if ((path.Length == 2) && (path[1] == ':')) { OriginalPath = "."; } else { OriginalPath = path; } String fullPath = PathHelpers.GetFullPathInternal(path); FullPath = fullPath; DisplayPath = GetDisplayName(OriginalPath, FullPath); } [System.Security.SecuritySafeCritical] internal DirectoryInfo(String fullPath, IFileSystemObject fileSystemObject) : base(fileSystemObject) { Debug.Assert(PathHelpers.GetRootLength(fullPath) > 0, "fullPath must be fully qualified!"); // Fast path when we know a DirectoryInfo exists. OriginalPath = Path.GetFileName(fullPath); FullPath = fullPath; DisplayPath = GetDisplayName(OriginalPath, FullPath); } public override String Name { get { // DisplayPath is dir name for coreclr Debug.Assert(GetDirName(FullPath) == DisplayPath || DisplayPath == "."); return DisplayPath; } } public DirectoryInfo Parent { [System.Security.SecuritySafeCritical] get { String parentName; // FullPath might be either "c:\bar" or "c:\bar\". Handle // those cases, as well as avoiding mangling "c:\". String s = FullPath; if (s.Length > 3 && s[s.Length - 1] == Path.DirectorySeparatorChar) s = FullPath.Substring(0, FullPath.Length - 1); parentName = Path.GetDirectoryName(s); if (parentName == null) return null; DirectoryInfo dir = new DirectoryInfo(parentName, null); return dir; } } [System.Security.SecuritySafeCritical] public DirectoryInfo CreateSubdirectory(String path) { if (path == null) throw new ArgumentNullException("path"); Contract.EndContractBlock(); return CreateSubdirectoryHelper(path); } [System.Security.SecurityCritical] // auto-generated private DirectoryInfo CreateSubdirectoryHelper(String path) { Contract.Requires(path != null); PathHelpers.ThrowIfEmptyOrRootedPath(path); String newDirs = Path.Combine(FullPath, path); String fullPath = Path.GetFullPath(newDirs); if (0 != String.Compare(FullPath, 0, fullPath, 0, FullPath.Length, PathInternal.GetComparison())) { throw new ArgumentException(SR.Format(SR.Argument_InvalidSubPath, path, DisplayPath)); } FileSystem.Current.CreateDirectory(fullPath); // Check for read permission to directory we hand back by calling this constructor. return new DirectoryInfo(fullPath); } [System.Security.SecurityCritical] public void Create() { FileSystem.Current.CreateDirectory(FullPath); } // Tests if the given path refers to an existing DirectoryInfo on disk. // // Your application must have Read permission to the directory's // contents. // public override bool Exists { [System.Security.SecuritySafeCritical] // auto-generated get { try { return FileSystemObject.Exists; } catch { return false; } } } // Returns an array of Files in the current DirectoryInfo matching the // given search criteria (ie, "*.txt"). [SecurityCritical] public FileInfo[] GetFiles(String searchPattern) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); Contract.EndContractBlock(); return InternalGetFiles(searchPattern, SearchOption.TopDirectoryOnly); } // Returns an array of Files in the current DirectoryInfo matching the // given search criteria (ie, "*.txt"). public FileInfo[] GetFiles(String searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalGetFiles(searchPattern, searchOption); } // Returns an array of Files in the current DirectoryInfo matching the // given search criteria (ie, "*.txt"). private FileInfo[] InternalGetFiles(String searchPattern, SearchOption searchOption) { Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); IEnumerable<FileInfo> enble = (IEnumerable<FileInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Files); List<FileInfo> fileList = new List<FileInfo>(enble); return fileList.ToArray(); } // Returns an array of Files in the DirectoryInfo specified by path public FileInfo[] GetFiles() { return InternalGetFiles("*", SearchOption.TopDirectoryOnly); } // Returns an array of Directories in the current directory. public DirectoryInfo[] GetDirectories() { return InternalGetDirectories("*", SearchOption.TopDirectoryOnly); } // Returns an array of strongly typed FileSystemInfo entries in the path with the // given search criteria (ie, "*.txt"). public FileSystemInfo[] GetFileSystemInfos(String searchPattern) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); Contract.EndContractBlock(); return InternalGetFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly); } // Returns an array of strongly typed FileSystemInfo entries in the path with the // given search criteria (ie, "*.txt"). public FileSystemInfo[] GetFileSystemInfos(String searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalGetFileSystemInfos(searchPattern, searchOption); } // Returns an array of strongly typed FileSystemInfo entries in the path with the // given search criteria (ie, "*.txt"). private FileSystemInfo[] InternalGetFileSystemInfos(String searchPattern, SearchOption searchOption) { Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); IEnumerable<FileSystemInfo> enumerable = FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Both); List<FileSystemInfo> fileList = new List<FileSystemInfo>(enumerable); return fileList.ToArray(); } // Returns an array of strongly typed FileSystemInfo entries which will contain a listing // of all the files and directories. public FileSystemInfo[] GetFileSystemInfos() { return InternalGetFileSystemInfos("*", SearchOption.TopDirectoryOnly); } // Returns an array of Directories in the current DirectoryInfo matching the // given search criteria (ie, "System*" could match the System & System32 // directories). public DirectoryInfo[] GetDirectories(String searchPattern) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); Contract.EndContractBlock(); return InternalGetDirectories(searchPattern, SearchOption.TopDirectoryOnly); } // Returns an array of Directories in the current DirectoryInfo matching the // given search criteria (ie, "System*" could match the System & System32 // directories). public DirectoryInfo[] GetDirectories(String searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalGetDirectories(searchPattern, searchOption); } // Returns an array of Directories in the current DirectoryInfo matching the // given search criteria (ie, "System*" could match the System & System32 // directories). private DirectoryInfo[] InternalGetDirectories(String searchPattern, SearchOption searchOption) { Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); IEnumerable<DirectoryInfo> enumerable = (IEnumerable<DirectoryInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Directories); List<DirectoryInfo> fileList = new List<DirectoryInfo>(enumerable); return fileList.ToArray(); } public IEnumerable<DirectoryInfo> EnumerateDirectories() { return InternalEnumerateDirectories("*", SearchOption.TopDirectoryOnly); } public IEnumerable<DirectoryInfo> EnumerateDirectories(String searchPattern) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); Contract.EndContractBlock(); return InternalEnumerateDirectories(searchPattern, SearchOption.TopDirectoryOnly); } public IEnumerable<DirectoryInfo> EnumerateDirectories(String searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalEnumerateDirectories(searchPattern, searchOption); } private IEnumerable<DirectoryInfo> InternalEnumerateDirectories(String searchPattern, SearchOption searchOption) { Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); return (IEnumerable<DirectoryInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Directories); } public IEnumerable<FileInfo> EnumerateFiles() { return InternalEnumerateFiles("*", SearchOption.TopDirectoryOnly); } public IEnumerable<FileInfo> EnumerateFiles(String searchPattern) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); Contract.EndContractBlock(); return InternalEnumerateFiles(searchPattern, SearchOption.TopDirectoryOnly); } public IEnumerable<FileInfo> EnumerateFiles(String searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalEnumerateFiles(searchPattern, searchOption); } private IEnumerable<FileInfo> InternalEnumerateFiles(String searchPattern, SearchOption searchOption) { Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); return (IEnumerable<FileInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Files); } public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos() { return InternalEnumerateFileSystemInfos("*", SearchOption.TopDirectoryOnly); } public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(String searchPattern) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); Contract.EndContractBlock(); return InternalEnumerateFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly); } public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(String searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalEnumerateFileSystemInfos(searchPattern, searchOption); } private IEnumerable<FileSystemInfo> InternalEnumerateFileSystemInfos(String searchPattern, SearchOption searchOption) { Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); return FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Both); } // Returns the root portion of the given path. The resulting string // consists of those rightmost characters of the path that constitute the // root of the path. Possible patterns for the resulting string are: An // empty string (a relative path on the current drive), "\" (an absolute // path on the current drive), "X:" (a relative path on a given drive, // where X is the drive letter), "X:\" (an absolute path on a given drive), // and "\\server\share" (a UNC path for a given server and share name). // The resulting string is null if path is null. // public DirectoryInfo Root { [System.Security.SecuritySafeCritical] get { String rootPath = Path.GetPathRoot(FullPath); return new DirectoryInfo(rootPath); } } [System.Security.SecuritySafeCritical] public void MoveTo(String destDirName) { if (destDirName == null) throw new ArgumentNullException("destDirName"); if (destDirName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, "destDirName"); Contract.EndContractBlock(); String fullDestDirName = PathHelpers.GetFullPathInternal(destDirName); if (fullDestDirName[fullDestDirName.Length - 1] != Path.DirectorySeparatorChar) fullDestDirName = fullDestDirName + PathHelpers.DirectorySeparatorCharAsString; String fullSourcePath; if (FullPath.Length > 0 && FullPath[FullPath.Length - 1] == Path.DirectorySeparatorChar) fullSourcePath = FullPath; else fullSourcePath = FullPath + PathHelpers.DirectorySeparatorCharAsString; StringComparison pathComparison = PathInternal.GetComparison(); if (String.Compare(fullSourcePath, fullDestDirName, pathComparison) == 0) throw new IOException(SR.IO_SourceDestMustBeDifferent); String sourceRoot = Path.GetPathRoot(fullSourcePath); String destinationRoot = Path.GetPathRoot(fullDestDirName); if (String.Compare(sourceRoot, destinationRoot, pathComparison) != 0) throw new IOException(SR.IO_SourceDestMustHaveSameRoot); FileSystem.Current.MoveDirectory(FullPath, fullDestDirName); FullPath = fullDestDirName; OriginalPath = destDirName; DisplayPath = GetDisplayName(OriginalPath, FullPath); // Flush any cached information about the directory. Invalidate(); } [System.Security.SecuritySafeCritical] public override void Delete() { FileSystem.Current.RemoveDirectory(FullPath, false); } [System.Security.SecuritySafeCritical] public void Delete(bool recursive) { FileSystem.Current.RemoveDirectory(FullPath, recursive); } // Returns the fully qualified path public override String ToString() { return DisplayPath; } private static String GetDisplayName(String originalPath, String fullPath) { Debug.Assert(originalPath != null); Debug.Assert(fullPath != null); String displayName = ""; // Special case "<DriveLetter>:" to point to "<CurrentDirectory>" instead if ((originalPath.Length == 2) && (originalPath[1] == ':')) { displayName = "."; } else { displayName = GetDirName(fullPath); } return displayName; } private static String GetDirName(String fullPath) { Debug.Assert(fullPath != null); String dirName = null; if (fullPath.Length > 3) { String s = fullPath; if (fullPath[fullPath.Length - 1] == Path.DirectorySeparatorChar) { s = fullPath.Substring(0, fullPath.Length - 1); } dirName = Path.GetFileName(s); } else { dirName = fullPath; // For rooted paths, like "c:\" } return dirName; } } }
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using ClientDependency.Core; using System.Linq; using ClientDependency.Core.Controls; using Umbraco.Core.Configuration; namespace umbraco.uicontrols { [ClientDependency(ClientDependencyType.Javascript, "CodeArea/javascript.js", "UmbracoClient")] [ClientDependency(ClientDependencyType.Javascript, "CodeArea/UmbracoEditor.js", "UmbracoClient")] [ClientDependency(ClientDependencyType.Css, "CodeArea/styles.css", "UmbracoClient")] [ClientDependency(ClientDependencyType.Javascript, "Application/jQuery/jquery-fieldselection.js", "UmbracoClient")] public class CodeArea : WebControl { public CodeArea() { //set the default to Css CodeBase = EditorType.Css; } protected TextBox CodeTextBox; public bool AutoResize { get; set; } public bool AutoSuggest { get; set; } public string EditorMimeType { get; set; } public ScrollingMenu Menu = new ScrollingMenu(); public int OffSetX { get; set; } public int OffSetY { get; set; } public string Text { get { EnsureChildControls(); return CodeTextBox.Text; } set { EnsureChildControls(); CodeTextBox.Text = value; } } public bool CodeMirrorEnabled { get { return UmbracoConfig.For.UmbracoSettings().Content.ScriptEditorDisable == false; } } public EditorType CodeBase { get; set; } public string ClientSaveMethod { get; set; } public enum EditorType { JavaScript, Css, Python, XML, HTML, Razor, HtmlMixed } protected override void OnInit(EventArgs e) { base.OnInit(e); EnsureChildControls(); if (CodeMirrorEnabled) { ClientDependencyLoader.Instance.RegisterDependency(0, "lib/CodeMirror/lib/codemirror.js", "UmbracoRoot", ClientDependencyType.Javascript); ClientDependencyLoader.Instance.RegisterDependency(2, "lib/CodeMirror/mode/" + CodeBase.ToString().ToLower() + "/" + CodeBase.ToString().ToLower() + ".js", "UmbracoRoot", ClientDependencyType.Javascript); if (CodeBase == EditorType.HtmlMixed) { ClientDependencyLoader.Instance.RegisterDependency(1, "lib/CodeMirror/mode/htmlmixed/htmlmixed.js", "UmbracoRoot", ClientDependencyType.Javascript); //ClientDependencyLoader.Instance.RegisterDependency(1, "lib/CodeMirror/mode/xml/xml.js", "UmbracoRoot", ClientDependencyType.Javascript); //ClientDependencyLoader.Instance.RegisterDependency(1, "lib/CodeMirror/mode/javascript/javascript.js", "UmbracoRoot", ClientDependencyType.Javascript); //ClientDependencyLoader.Instance.RegisterDependency(1, "lib/CodeMirror/mode/css/css.js", "UmbracoRoot", ClientDependencyType.Javascript); } ClientDependencyLoader.Instance.RegisterDependency(2, "lib/CodeMirror/addon/search/search.js", "UmbracoRoot", ClientDependencyType.Javascript); ClientDependencyLoader.Instance.RegisterDependency(2, "lib/CodeMirror/addon/search/searchcursor.js", "UmbracoRoot", ClientDependencyType.Javascript); ClientDependencyLoader.Instance.RegisterDependency(2, "lib/CodeMirror/addon/dialog/dialog.js", "UmbracoRoot", ClientDependencyType.Javascript); ClientDependencyLoader.Instance.RegisterDependency(2, "lib/CodeMirror/addon/dialog/dialog.css", "UmbracoRoot", ClientDependencyType.Css); ClientDependencyLoader.Instance.RegisterDependency(2, "lib/CodeMirror/lib/codemirror.css", "UmbracoRoot", ClientDependencyType.Css); //ClientDependencyLoader.Instance.RegisterDependency(3, "CodeMirror/css/umbracoCustom.css", "UmbracoClient", ClientDependencyType.Css); ClientDependencyLoader.Instance.RegisterDependency(4, "CodeArea/styles.css", "UmbracoClient", ClientDependencyType.Css); } } protected override void CreateChildControls() { base.CreateChildControls(); CodeTextBox = new TextBox(); CodeTextBox.ID = "CodeTextBox"; if (CodeMirrorEnabled == false) { CodeTextBox.Attributes.Add("class", "codepress"); CodeTextBox.Attributes.Add("wrap", "off"); } CodeTextBox.TextMode = TextBoxMode.MultiLine; this.Controls.Add(Menu); this.Controls.Add(CodeTextBox); } /// <summary> /// Client ID is different if the code editor is turned on/off /// </summary> public override string ClientID { get { if (CodeMirrorEnabled == false) return CodeTextBox.ClientID; else return base.ClientID; } } protected override void Render(HtmlTextWriter writer) { EnsureChildControls(); var jsEventCode = new StringBuilder(); if (CodeMirrorEnabled == false) { CodeTextBox.RenderControl(writer); jsEventCode.Append(RenderBasicEditor()); } else { writer.WriteBeginTag("div"); writer.WriteAttribute("id", this.ClientID); writer.WriteAttribute("class", "umb-editor umb-codeeditor " + this.CssClass); this.ControlStyle.AddAttributesToRender(writer); writer.Write(HtmlTextWriter.TagRightChar); Menu.RenderControl(writer); writer.WriteBeginTag("div"); writer.WriteAttribute("class", "code-container"); this.ControlStyle.AddAttributesToRender(writer); writer.Write(HtmlTextWriter.TagRightChar); CodeTextBox.RenderControl(writer); writer.WriteEndTag("div"); writer.WriteEndTag("div"); jsEventCode.Append(RenderCodeEditor()); } jsEventCode.Append(@" //TODO: for now this is a global var, need to refactor all this so that is using proper js standards //with correct objects, and proper accessors to these objects. var UmbEditor; $(document).ready(function () { //create the editor UmbEditor = new Umbraco.Controls.CodeEditor.UmbracoEditor(" + (CodeMirrorEnabled == false).ToString().ToLower() + @", '" + ClientID + @"');"); if (this.AutoResize) { if (CodeMirrorEnabled) { //reduce the width if using code mirror because of the line numbers OffSetX += 20; OffSetY += 50; } //add the resize code jsEventCode.Append(@" var m_textEditor = jQuery('#" + ClientID + @"'); //with codemirror adding divs for line numbers, we need to target a different element m_textEditor = m_textEditor.find('iframe').length > 0 ? m_textEditor.children('div').get(0) : m_textEditor.get(0); jQuery(window).resize(function(){ resizeTextArea(m_textEditor, " + OffSetX + "," + OffSetY + @"); }); jQuery(document).ready(function(){ resizeTextArea(m_textEditor, " + OffSetX + "," + OffSetY + @"); });"); } jsEventCode.Append(@" });"); writer.WriteLine(@"<script type=""text/javascript"">{0}</script>", jsEventCode); } protected string RenderBasicEditor() { string jsEventCode = @" var m_textEditor = document.getElementById('" + this.ClientID + @"'); tab.watch('" + this.ClientID + @"'); "; return jsEventCode; } protected string RenderCodeEditor() { var extraKeys = ""; var editorMimetype = ""; if (string.IsNullOrEmpty(EditorMimeType) == false) editorMimetype = @", mode: """ + EditorMimeType + "\""; var jsEventCode = @" var textarea = document.getElementById('" + CodeTextBox.ClientID + @"'); var codeEditor = CodeMirror.fromTextArea(textarea, { tabMode: ""shift"", matchBrackets: true, indentUnit: 4, indentWithTabs: true, enterMode: ""keep"", lineWrapping: false" + editorMimetype + @", lineNumbers: true" + extraKeys + @" }); "; return jsEventCode; } } }
/* * MenuCommand.cs - Implementation of the * "System.ComponentModel.Design.MenuCommand" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.ComponentModel.Design { #if CONFIG_COMPONENT_MODEL_DESIGN using System.Text; using System.Runtime.InteropServices; [ComVisible(true)] public class MenuCommand { // Internal state. private EventHandler handler; private CommandID command; private int oleStatus; // Flag bits in "oleStatus". private const int OleStatus_Supported = 1; private const int OleStatus_Enabled = 2; private const int OleStatus_Checked = 4; private const int OleStatus_Invisible = 16; // Constructor. public MenuCommand(EventHandler handler, CommandID command) { this.handler = handler; this.command = command; this.oleStatus = OleStatus_Supported | OleStatus_Enabled; } // Get or set this object's properties. public virtual bool Checked { get { return ((oleStatus & OleStatus_Checked) != 0); } set { int newStatus; if(value) { newStatus = oleStatus | OleStatus_Checked; } else { newStatus = oleStatus & ~OleStatus_Checked; } if(newStatus != oleStatus) { oleStatus = newStatus; OnCommandChanged(EventArgs.Empty); } } } public virtual CommandID CommandID { get { return command; } } public virtual bool Enabled { get { return ((oleStatus & OleStatus_Enabled) != 0); } set { int newStatus; if(value) { newStatus = oleStatus | OleStatus_Enabled; } else { newStatus = oleStatus & ~OleStatus_Enabled; } if(newStatus != oleStatus) { oleStatus = newStatus; OnCommandChanged(EventArgs.Empty); } } } public virtual int OleStatus { get { return oleStatus; } } public virtual bool Supported { get { return ((oleStatus & OleStatus_Supported) != 0); } set { int newStatus; if(value) { newStatus = oleStatus | OleStatus_Supported; } else { newStatus = oleStatus & ~OleStatus_Supported; } if(newStatus != oleStatus) { oleStatus = newStatus; OnCommandChanged(EventArgs.Empty); } } } public virtual bool Visible { get { return ((oleStatus & OleStatus_Invisible) == 0); } set { int newStatus; if(!value) { newStatus = oleStatus | OleStatus_Invisible; } else { newStatus = oleStatus & ~OleStatus_Invisible; } if(newStatus != oleStatus) { oleStatus = newStatus; OnCommandChanged(EventArgs.Empty); } } } // Invoke the menu command. public virtual void Invoke() { if(handler != null) { handler(this, EventArgs.Empty); } } // Convert this object into a string. public override String ToString() { StringBuilder builder = new StringBuilder(); builder.Append(command.ToString()); builder.Append(" : "); bool haveItem = false; if((oleStatus & OleStatus_Supported) != 0) { builder.Append("Supported"); haveItem = true; } if((oleStatus & OleStatus_Enabled) != 0) { if(!haveItem) { builder.Append('|'); } builder.Append("Enabled"); haveItem = true; } if((oleStatus & OleStatus_Invisible) == 0) { if(!haveItem) { builder.Append('|'); } builder.Append("Visible"); haveItem = true; } if((oleStatus & OleStatus_Checked) != 0) { if(!haveItem) { builder.Append('|'); } builder.Append("Checked"); haveItem = true; } return builder.ToString(); } // Event that is emitted when the command is changed. public event EventHandler CommandChanged; // Emit the "CommandChanged" event. protected virtual void OnCommandChanged(EventArgs e) { if(CommandChanged != null) { CommandChanged(this, e); } } }; // class MenuCommand #endif // CONFIG_COMPONENT_MODEL_DESIGN }; // namespace System.ComponentModel.Design
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Text; using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.Dsa.Tests { public static class DSAKeyFileTests { public static bool SupportsFips186_3 => DSAFactory.SupportsFips186_3; [ConditionalFact(typeof(DSAFactory), nameof(DSAFactory.SupportsKeyGeneration))] public static void UseAfterDispose_NewKey() { UseAfterDispose(false); } [Fact] public static void UseAfterDispose_ImportedKey() { UseAfterDispose(true); } private static void UseAfterDispose(bool importKey) { DSA key = importKey ? DSAFactory.Create(DSATestData.GetDSA1024Params()) : DSAFactory.Create(512); byte[] pkcs8Private; byte[] pkcs8EncryptedPrivate; byte[] subjectPublicKeyInfo; string pwStr = "Hello"; // Because the PBE algorithm uses PBES2 the string->byte encoding is UTF-8. byte[] pwBytes = Encoding.UTF8.GetBytes(pwStr); PbeParameters pbeParameters = new PbeParameters( PbeEncryptionAlgorithm.Aes192Cbc, HashAlgorithmName.SHA256, 3072); // Ensure the key was loaded, then dispose it. // Also ensures all of the inputs are valid for the disposed tests. using (key) { pkcs8Private = key.ExportPkcs8PrivateKey(); pkcs8EncryptedPrivate = key.ExportEncryptedPkcs8PrivateKey(pwStr, pbeParameters); subjectPublicKeyInfo = key.ExportSubjectPublicKeyInfo(); } Assert.Throws<ObjectDisposedException>(() => key.ImportPkcs8PrivateKey(pkcs8Private, out _)); Assert.Throws<ObjectDisposedException>(() => key.ImportEncryptedPkcs8PrivateKey(pwStr, pkcs8EncryptedPrivate, out _)); Assert.Throws<ObjectDisposedException>(() => key.ImportEncryptedPkcs8PrivateKey(pwBytes, pkcs8EncryptedPrivate, out _)); Assert.Throws<ObjectDisposedException>(() => key.ImportSubjectPublicKeyInfo(subjectPublicKeyInfo, out _)); Assert.Throws<ObjectDisposedException>(() => key.ExportPkcs8PrivateKey()); Assert.Throws<ObjectDisposedException>(() => key.TryExportPkcs8PrivateKey(pkcs8Private, out _)); Assert.Throws<ObjectDisposedException>(() => key.ExportEncryptedPkcs8PrivateKey(pwStr, pbeParameters)); Assert.Throws<ObjectDisposedException>(() => key.TryExportEncryptedPkcs8PrivateKey(pwStr, pbeParameters, pkcs8EncryptedPrivate, out _)); Assert.Throws<ObjectDisposedException>(() => key.ExportEncryptedPkcs8PrivateKey(pwBytes, pbeParameters)); Assert.Throws<ObjectDisposedException>(() => key.TryExportEncryptedPkcs8PrivateKey(pwBytes, pbeParameters, pkcs8EncryptedPrivate, out _)); Assert.Throws<ObjectDisposedException>(() => key.ExportSubjectPublicKeyInfo()); Assert.Throws<ObjectDisposedException>(() => key.TryExportSubjectPublicKeyInfo(subjectPublicKeyInfo, out _)); // Check encrypted import with the wrong password. // It shouldn't do enough work to realize it was wrong. pwBytes = Array.Empty<byte>(); Assert.Throws<ObjectDisposedException>(() => key.ImportEncryptedPkcs8PrivateKey("", pkcs8EncryptedPrivate, out _)); Assert.Throws<ObjectDisposedException>(() => key.ImportEncryptedPkcs8PrivateKey(pwBytes, pkcs8EncryptedPrivate, out _)); } [Fact] public static void ReadWriteDsa512Pkcs8() { ReadWriteBase64Pkcs8( @" MIHGAgEAMIGoBgcqhkjOOAQBMIGcAkEA1qi38cr3ppZNB2Y/xpHSL2q81Vw3rvWN IHRnQNgv4U4UY2NifZGSUULc3uOEvgoeBO1b9fRxSG9NmG1CoufflQIVAPq19iXV 1eFkMKHvYw6+M4l8wiT5AkAIRMSQ5S71jgWQLGNtZNHV6yxggqDU87/RzgeOh7Q6 fve77OGaTv4qbZwinTYAg86p9yHzmwW6+XBS3vxnpYorBBYCFC49eoTIW2Z4Xh9v 55aYKyKwy5i8", DSATestData.Dsa512Parameters); } [ConditionalFact(nameof(SupportsFips186_3))] public static void ReadWriteDsa2048DeficientXPkcs8() { ReadWriteBase64Pkcs8( @" MIICZAIBADCCAjkGByqGSM44BAEwggIsAoIBAQCU0+SznxcnPo8nsyaS98NNNWGL 0nlUi0c2k5wrpOcpEWyurGAB6VcFwn188MMIvKcCu0cS1LtEihB4tjEVDqtFXJFn imHFHC03HgK7rHDpwsbadXtXgg7I/QluEF7DbAeKT9fdhyTSddMAf5TxL/lhZyk8 ZntGdwfx3Jp8CzS8T8R1sV1RJAp4mlOla2TWnB4Ct8o600GztvbJhvHgZb/mgNh9 7m2VkdjjjlfDesKYOyeUvq/+LHtbbKSbmBJIczJcYd5vggQRAYvpcj/ivagzLBMI iqMqCG0U1vACAQE/UWeGQ/MqzABSXbIvACDZL5wvQIi401oedk3Ni3DAs9LrAiEA 23CgOhWOnMudk9v3Z5bL68pFqHA+gqRYAViO5LaYWrMCggEAPPDxRLcKu9RCYNks TgMq3wpZjmgyPiVK/4cQyejqm+GdDSr5OaoN7HbSB7bqzveCTjZldTVjAcpfmF74 /3r1UYuN8IhaasVw/i5cWVYXDnHydAGUAYyKCkp7D5z5av1+JQJvqAuflya2xN/L xBBeuYaHyml/eXlAwTNbFEMR1H/yHk1cQ8AFhHhrwarkrYWKwGM1HuRCNHC+URVS hpTvzzEtnljU3dHAHig4M/TxSeX5vUVJMEQxthvg2tcXtTjFzVL94ajmYZPonQnB 4Hlo5vcH71YU6D5hEm9qXzk54HZzdFRL4yJcxPjzxQHVolJve7ZNZWp7vf5+cssW 1x6KOAQiAiAAyHG344loXbl9k03XAR+rB2/yfsQoL7AMDWRtKdXk5Q==", DSATestData.Dsa2048DeficientXParameters); } [Fact] public static void ReadWriteDsa512EncryptedPkcs8() { // pbeWithSHA1And40BitRC2-CBC (PKCS12-PBE) ReadBase64EncryptedPkcs8( @" MIHxMBwGCiqGSIb3DQEMAQYwDgQIxVJI9zn2I3oCAggABIHQxWZ9CzDb28iUpwh7 jlX2JTurz7kbP8NkbyuRO1wmnjTDohFek9VSUt+UzmOnl1sQKBg8uqNXzyFsc3Mo me0NEZj19O90HD2+ahdWvlMuPJajYiXHXe4r+EwojEa4/KlMOhIQkv/NGLeIOYsu MmM8IXx9Qg7ztZTNebpceHg0hBrshzFPBvzMCOnErp2YtMixddnBbamIab8wYNPn QBS1HTKE5J9N78nM1DL4L7kE7VlpOezedRpvl+B8pK69QY7DBg98FnUsYPZhD4a+ UCouQg==", "forty", new PbeParameters( PbeEncryptionAlgorithm.Aes128Cbc, HashAlgorithmName.SHA256, 12345), DSATestData.Dsa512Parameters); } [Fact] public static void ReadWriteDsa576EncryptedPkcs8() { // pbeWithSHA1And128BitRC2-CBC (PKCS12-PBE) ReadBase64EncryptedPkcs8( @" MIIBATAcBgoqhkiG9w0BDAEFMA4ECBh9UuBb/JhlAgIIAASB4GqfDHTQYRRbRbdn HJT0o+FUPzleK0noTuW6LXQEaJZscvmKA3fE1HC53qbNemN90RSrwz1fFBaRzhII VWC+E+2uaM/Qi64e0ZqKJ86kE4sIe1AiGPz4PtyBauUYsMUTCuwLnrRyhzYv5d4Q 1aSE3jTZlwsNYmIiWO/+XUVIvNKGxW+DJTVAaI/Zxldxu31BmRt8caIUlrBHcNRI h/A6S/A3PvZuJ3hh4vwneBpk1eeJNuKvjJ5fBza/OQQaiNfef8ad0lJfpQF1i3kL itsfZ16jNKxoJbAx3psVTGdzxnw8", "If I had a trillion dollars...", new PbeParameters( PbeEncryptionAlgorithm.Aes128Cbc, HashAlgorithmName.SHA256, 12345), DSATestData.Dsa576Parameters); } [Fact] public static void ReadWriteDsa1024EncryptedPkcs8() { // pbeWithSHA1AndDES-CBC (PBES1) ReadBase64EncryptedPkcs8( @" MIIBcTAbBgkqhkiG9w0BBQowDgQIEibTj5fv8jUCAggABIIBUPDssHf/llBiWN/M e3cyuqVHA89Zda1Myh/YcKmGWpQgflr2CKOrmsw7nin+9bWlZDYP795EEKSAkCZg ABHwJlTI9BKMUiXQUW8AwM5zqBJb/P/JOG2bFNXsZHUYUNh9g7I5mBwdCAih4D+R QT4YuclwLvQmTewyjLtDGiDF/mC+4kpyBePeO9kfkRUDHiwSNk/efN4ug1xQgwhu 2RXvjJaAYu3JVTp9Gp86suix1gRWMOg+pHCamtCjC4B+91q3LLMdseAoSHmy25/x qE3Db1UI4anCCnyEj/jDA8R6hZTFDjxu6bG0Z66g7I2GBDEYaaB+8x0vtiyu5LXo 6UZ53SX6S+jfIqJoF5YME9zVMoO2kwS/EGvc64+epCGcee1Nx4SGgUcr5HJYz1P4 CU+l4wPQR0rRmYHIJJIvFh5OXk84pV0crsOrekw7tHeNU6DMzw==", "Password > cipher", new PbeParameters( PbeEncryptionAlgorithm.Aes192Cbc, HashAlgorithmName.SHA256, 12345), DSATestData.GetDSA1024Params()); } [Fact] public static void ReadWriteDsa1024EncryptedPkcs8_PasswordBytes() { // pbeWithSHA1AndDES-CBC (PBES1) ReadBase64EncryptedPkcs8( @" MIIBcTAbBgkqhkiG9w0BBQowDgQIEibTj5fv8jUCAggABIIBUPDssHf/llBiWN/M e3cyuqVHA89Zda1Myh/YcKmGWpQgflr2CKOrmsw7nin+9bWlZDYP795EEKSAkCZg ABHwJlTI9BKMUiXQUW8AwM5zqBJb/P/JOG2bFNXsZHUYUNh9g7I5mBwdCAih4D+R QT4YuclwLvQmTewyjLtDGiDF/mC+4kpyBePeO9kfkRUDHiwSNk/efN4ug1xQgwhu 2RXvjJaAYu3JVTp9Gp86suix1gRWMOg+pHCamtCjC4B+91q3LLMdseAoSHmy25/x qE3Db1UI4anCCnyEj/jDA8R6hZTFDjxu6bG0Z66g7I2GBDEYaaB+8x0vtiyu5LXo 6UZ53SX6S+jfIqJoF5YME9zVMoO2kwS/EGvc64+epCGcee1Nx4SGgUcr5HJYz1P4 CU+l4wPQR0rRmYHIJJIvFh5OXk84pV0crsOrekw7tHeNU6DMzw==", Encoding.UTF8.GetBytes("Password > cipher"), new PbeParameters( PbeEncryptionAlgorithm.Aes192Cbc, HashAlgorithmName.SHA256, 12345), DSATestData.GetDSA1024Params()); } [ConditionalFact(nameof(SupportsFips186_3))] public static void ReadWriteDsa2048EncryptedPkcs8() { ReadBase64EncryptedPkcs8( @" MIICkTAbBgkqhkiG9w0BBQMwDgQIiFvwvRtsR00CAggABIICcLdrPIpSA2oPwA7S /SBV43oICErpXe3XIjXwWTCRD+xgzQ1IUxJRHau8kIqz+mYwmN4tG9QZp/kc1HYx 1b72PtNc/NaduA6eT3DNZO7SslpnXkXKdXhMRsyzwawI4QfPlTZsL7bUgn4/O/GQ yN1gHns7AHk6HOO3fLujSSqrosLQOvHkgvsxLJhcBhGTKUZqwA6SFwvWsYKh7ML2 Rwx336Nlzf7wpd49l8meJyZReqJ8Fg4kIhhcJTDAhaxWEdIw1dolshz1FSyZIb75 dhNVrpHtp+fQbWZpMRLGB+6qmWHjfzrSdSRda898P9oLgXpKffXDuFFcW+opW3uV QZ2kM2Xx6NzcvdP4Bp3NKQmaW6inaES/IJvOasJd1KLTKb5Q16kq/0hrRw2fhBoc YxXkO34answHx3Oapx3tJ40fwxi0RjPdEY+qNpMlHLiZrV6/dK6jfo3i9MT7xbQE XLVGx9Yqp2eHNLPKnHuEaeDmOkYhsjVgrVGhDydqrN+9R6K6LOgU2Gxo7M/vhQiL TwE5xKbUF6u82nyjma7DR7P6YDDY/RNfGRBusiMn7xlJs7ssG3ZTa0BBwlh6C4Iw ak2nknIOVBrzyh+FJhcKRyExSDUt39uz0h+HH2MHNBs3gJv/xmURDRmlhwcqF7ZA EDVKgNkAxxCnPVjTUalttxCxTv7FC/vxfN7ulB2uKzicegsf6t/nS6i2dpJjUYDF 8SU3qholnkPCi+bN+pNLtHiTo6o/7dhUf+/Y0DclLakVTduuOBc0v5arTtOB1Qlc /NbPGH1ELzGP6HO8JzNYWabsAuY4AYoXuaTa7F0ygo6t9FP90w==", "Chicken Cannon", new PbeParameters( PbeEncryptionAlgorithm.TripleDes3KeyPkcs12, HashAlgorithmName.SHA1, 0x0202), DSATestData.GetDSA2048Params()); } [ConditionalFact(nameof(SupportsFips186_3))] public static void ReadWriteDsa2048DeficientXEncryptedPkcs8() { ReadBase64EncryptedPkcs8( @" MIICkjAcBgoqhkiG9w0BDAEDMA4ECIE+VJLKiCq5AgIIAASCAnDa5K+uH8d1SVg6 NUGrayJH9pJ//k8Y8vP6/t7iZBsNnhcBXcntM9CuiXlFGi11utbhW9WLhUEzx9rL qNb09aC0axeUko4JZC27fvr4IrifNURrMXB1D1QOwzZZNggaqsoIsZ/VSdgr6MSL ek8D7YQ9sA0Zjex63H+XN2fiO98doD7foOIM0LbfSc2uue3MS0HYY8GkSIlbbcSq Mk+GjYKRF0kHUOvRVei3CYaFM54X/RbYCV+9JXzRN9Rx33JH/0QqBBmdsE4UTLiZ TUNhu/d/qRZusOVDix+5UiAaQ4juxuvT/rHdLaM/5W65yyH9ARK1qSiQWOYV9cgr bDo3rWwxSAxKmMJt1BfiiN+Zhg9m50lkdLNen2xOJrkvjb1/XJRaqYGFTpWnCcRc iQVhTB+7navPKuUjCPNhhR61ev7zLoahzmqVaRsSxsaBWUyWWysi1RnBZ/Om7xer idEK+c8u8DYBXXzEe/DGzYL7O4pwk6CiszlwQKbLrdS4hb7OpD3ApZsxY+fI5gf1 qpyisiOqbpfk51m8MekT+NyKh24RIa7uCgEm6hP3RN4YHwk+GtW+FLT7Dy095A85 LMW+AUTTx0nzbTr0JrF/xHDYjjR5sxYx7oETgVKaglsErc8GGtiZLJT0mzV7hJ6T RMCochA67WSoCIkJxwvSWyH6c2+9c7SP/Zi7pQqSMgV9KfWker5cFmwvbJGUOHvA BcNFpff98LJz3xpSE8iHr5iynJ4mOfkmMMzRczyVE+xblz1zcTwS5JBDyVRch1Tj dOwrkyNhKY+C3S3Hrg+1jGkxn95eJRPX7giU2GBUdc535JhKZH4=", "watchX", new PbeParameters( PbeEncryptionAlgorithm.TripleDes3KeyPkcs12, HashAlgorithmName.SHA1, 0x0101), DSATestData.Dsa2048DeficientXParameters); } [Fact] public static void ReadWriteDsa576SubjectPublicKeyInfo() { ReadWriteBase64SubjectPublicKeyInfo( @" MIIBCjCBuQYHKoZIzjgEATCBrQJJAOIWcwa//Ya7YvQye3eLv6B7pCMj7FZ7EGuV Y4gr3dbX8u5zYPKZiI3p9Aphx40L2EQu+pwyK4aK02ezlB1yt6MyyVTrFikTKwIV AMzc7M9fCyyP4jji8G8iE38X+usbAkkArxfUBhMCB54zA0p3oFjdtLgyrLEUt7jS 065EUd/4XrjdddRHQhg2nUhbIgZQZAYESrTmQH/apaKeldSWTKVZ6BxvfPzahyZl A0wAAkkAgVpUm2/QztrwRLALfP4TUZAtdyfW1/tzYAOk4cTNjfv0MeT/RzPz+pLH ZfDP+UTj7VaoW3WVPrFpASSJhbtfiROY6rXjlkXn", DSATestData.Dsa576Parameters); } [Fact] public static void ReadWriteDsa1024SubjectPublicKeyInfo() { ReadWriteBase64SubjectPublicKeyInfo( @" MIIBtjCCASsGByqGSM44BAEwggEeAoGBAMFtJsdNbBYneZwJGFSOVT/ljHiB2khG Kcr2QxH0snz+9r2w8hIGsP/EmZov7VO0O57ikQxo2ixDaoAY9JOPZHI2n1ZH0AW8 yW4iWQzBXjzU6g0TL12lr2qqCAewzE7zQEr1QvRUaze91qR+ZBEwg325k5fIRWNd fcNtBTfkqEsxAhUA2DwOy3NVHi/jDVH89CNsZRiDrdcCgYBrw2a2Y1VUXgmPH+kO VGm1Z+Cfp52Bfys2e0XezUMBpZyB1pEfdpHTcOFaxpLAS8EYcsFxp/5lTpY9fdpX Wp6YzgJvt9OTSiWGCBNKjsXtaaKu3IlAG2et3kJ/F+2uty169F2asdWeGxPU770X x2QzAmfd41LCDgW4DbPBCf6LnAOBhAACgYBpC7N6kUXgXW57R8RXiYqu3XJQHJ0W 55sa11qHLPAXqpC7+5Dxs7f1wDyH5G6HJWZVJv00FXsm9Zah8Jl/WfPmXvxhWlUt XnVpxf/EWT1aApkRDnHJfhIhpaA/6aaTWu3YjvCzsvedOpntdfe4cebq8mgNltV0 pfTBO6zjtLRN4Q==", DSATestData.GetDSA1024Params()); } [ConditionalFact(nameof(SupportsFips186_3))] public static void ReadWriteDsa2048SubjectPublicKeyInfo() { ReadWriteBase64SubjectPublicKeyInfo( @" MIIDRjCCAjkGByqGSM44BAEwggIsAoIBAQCvj7mysUfJbzkjYGOb2qZUT/LNCGtg SjMk9IVZXwLOrzLS1J8t062fU4TdCdAxgtuPCqBs4KD8ojZqWwMb0OL615e63IdK DGeBUpwB4NaXBLQ983GuSps92B6wP12uKDeAESVoZjN7c6gk9+isphmBp8Z2STY9 LX0SzCMFMI0IS+xozDsbPvV3BTpeI0Sfujw+tvjNjqafEWs3SL0jf5f09+kRxBw5 TW99LVO3Z2GPDe1I571/MMZWiUgmSlTADTWKdumCbteRxrbL+MKcJFFzsdjSGUOO WTc851VO9Jx4QKjFXOLl4sM8EKrY2Q8ox8su8UrV7YxOaZK0Hs7GUoj1AiEAyTqy KSNygpl/I1QaOZu/dc7NML4L6VksBwQ+0wIh6ssCggEARKfSLeuinOGdZ40twR8R i6oQ476pTeKcPsNsEKtNaIAEobf0OH/BzJYT5oUf7bvVRTGe3lRLlOT66cEGnnc0 +eavyKC4QGls3/4obhrxrW45Yp0MjGAWrGJfEAus9f90sjJcnZmm2LAxCyaPY+Nf XRyNpmP5SrqQJEzsz5qM5dtUebAG+RMeXqeCIqMuKhA8H+8WkpsVbjIwyVQpXNo+ X5H3G1Z/o7d0uELxKM0NND1UaNuQc0pngDXmXmohzHMB9PU+a2ZxioP/KFpv3onK WuHRuWM6JaNKkm+dKAj5v3ldk2eH/0xyhrx/xKgq+psGyRJRCakjuvPjd1XxV0uv tQOCAQUAAoIBAAEb2FmGosQTFf8BxVSkXlqcRbOOvcwmYLbReIlgToAKb96OAXzt N5P0pvuvu3YT/re6h4QavVmTXRiFiTnACm5GGbZWJHWVXW1yshNL7PWrNBGPYNhL H/JodT8YjoYSVRMthMoKq2gbhVGHM5Txjg2u9rX5V37HyiqmMoG1Oa9YlCg+P7bc xVN9ksi/58ByOsIS7vO3cY01w/3Zn3rgkSzHxHUhpW+lEb4xcS2XmuZ/F6e8xOWB DqnKE43u09eCOe7vI5p3KULSPCgQwpciGVJWRhJ/nEuBYSwSrtwtyR6BFTsKIHwf vAB5Wz646GeWztKawSR/9xIqHq8IECV1FXI=", DSATestData.GetDSA2048Params()); } [Fact] public static void NoFuzzySubjectPublicKeyInfo() { using (DSA key = DSAFactory.Create()) { key.ImportParameters(DSATestData.GetDSA1024Params()); int bytesRead = -1; byte[] pkcs8 = key.ExportPkcs8PrivateKey(); Assert.ThrowsAny<CryptographicException>( () => key.ImportSubjectPublicKeyInfo(pkcs8, out bytesRead)); Assert.Equal(-1, bytesRead); ReadOnlySpan<byte> passwordBytes = pkcs8.AsSpan(0, 15); byte[] encryptedPkcs8 = key.ExportEncryptedPkcs8PrivateKey( passwordBytes, new PbeParameters( PbeEncryptionAlgorithm.Aes256Cbc, HashAlgorithmName.SHA512, 123)); Assert.ThrowsAny<CryptographicException>( () => key.ImportSubjectPublicKeyInfo(encryptedPkcs8, out bytesRead)); Assert.Equal(-1, bytesRead); } } [Fact] public static void NoFuzzyPkcs8() { using (DSA key = DSAFactory.Create()) { key.ImportParameters(DSATestData.GetDSA1024Params()); int bytesRead = -1; byte[] spki = key.ExportSubjectPublicKeyInfo(); Assert.ThrowsAny<CryptographicException>( () => key.ImportPkcs8PrivateKey(spki, out bytesRead)); Assert.Equal(-1, bytesRead); ReadOnlySpan<byte> passwordBytes = spki.AsSpan(0, 15); byte[] encryptedPkcs8 = key.ExportEncryptedPkcs8PrivateKey( passwordBytes, new PbeParameters( PbeEncryptionAlgorithm.Aes256Cbc, HashAlgorithmName.SHA512, 123)); Assert.ThrowsAny<CryptographicException>( () => key.ImportPkcs8PrivateKey(encryptedPkcs8, out bytesRead)); Assert.Equal(-1, bytesRead); } } [Fact] public static void NoFuzzyEncryptedPkcs8() { using (DSA key = DSAFactory.Create()) { key.ImportParameters(DSATestData.GetDSA1024Params()); int bytesRead = -1; byte[] spki = key.ExportSubjectPublicKeyInfo(); byte[] empty = Array.Empty<byte>(); Assert.ThrowsAny<CryptographicException>( () => key.ImportEncryptedPkcs8PrivateKey(empty, spki, out bytesRead)); Assert.Equal(-1, bytesRead); byte[] pkcs8 = key.ExportPkcs8PrivateKey(); Assert.ThrowsAny<CryptographicException>( () => key.ImportEncryptedPkcs8PrivateKey(empty, pkcs8, out bytesRead)); Assert.Equal(-1, bytesRead); } } [Fact] public static void NoPrivKeyFromPublicOnly() { using (DSA key = DSAFactory.Create()) { DSAParameters dsaParameters = DSATestData.GetDSA1024Params(); dsaParameters.X = null; key.ImportParameters(dsaParameters); Assert.ThrowsAny<CryptographicException>( () => key.ExportPkcs8PrivateKey()); Assert.ThrowsAny<CryptographicException>( () => key.TryExportPkcs8PrivateKey(Span<byte>.Empty, out _)); Assert.ThrowsAny<CryptographicException>( () => key.ExportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte>.Empty, new PbeParameters(PbeEncryptionAlgorithm.Aes192Cbc, HashAlgorithmName.SHA256, 72))); Assert.ThrowsAny<CryptographicException>( () => key.TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte>.Empty, new PbeParameters(PbeEncryptionAlgorithm.Aes192Cbc, HashAlgorithmName.SHA256, 72), Span<byte>.Empty, out _)); } } [Fact] public static void BadPbeParameters() { using (DSA key = DSAFactory.Create()) { key.ImportParameters(DSATestData.GetDSA1024Params()); Assert.ThrowsAny<ArgumentNullException>( () => key.ExportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte>.Empty, null)); Assert.ThrowsAny<ArgumentNullException>( () => key.ExportEncryptedPkcs8PrivateKey( ReadOnlySpan<char>.Empty, null)); Assert.ThrowsAny<ArgumentNullException>( () => key.TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte>.Empty, null, Span<byte>.Empty, out _)); Assert.ThrowsAny<ArgumentNullException>( () => key.TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan<char>.Empty, null, Span<byte>.Empty, out _)); // PKCS12 requires SHA-1 Assert.ThrowsAny<CryptographicException>( () => key.ExportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte>.Empty, new PbeParameters(PbeEncryptionAlgorithm.TripleDes3KeyPkcs12, HashAlgorithmName.SHA256, 72))); Assert.ThrowsAny<CryptographicException>( () => key.TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte>.Empty, new PbeParameters(PbeEncryptionAlgorithm.TripleDes3KeyPkcs12, HashAlgorithmName.SHA256, 72), Span<byte>.Empty, out _)); // PKCS12 requires SHA-1 Assert.ThrowsAny<CryptographicException>( () => key.ExportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte>.Empty, new PbeParameters(PbeEncryptionAlgorithm.TripleDes3KeyPkcs12, HashAlgorithmName.MD5, 72))); Assert.ThrowsAny<CryptographicException>( () => key.TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte>.Empty, new PbeParameters(PbeEncryptionAlgorithm.TripleDes3KeyPkcs12, HashAlgorithmName.MD5, 72), Span<byte>.Empty, out _)); // PKCS12 requires a char-based password Assert.ThrowsAny<CryptographicException>( () => key.ExportEncryptedPkcs8PrivateKey( new byte[3], new PbeParameters(PbeEncryptionAlgorithm.TripleDes3KeyPkcs12, HashAlgorithmName.SHA1, 72))); Assert.ThrowsAny<CryptographicException>( () => key.TryExportEncryptedPkcs8PrivateKey( new byte[3], new PbeParameters(PbeEncryptionAlgorithm.TripleDes3KeyPkcs12, HashAlgorithmName.SHA1, 72), Span<byte>.Empty, out _)); // Unknown encryption algorithm Assert.ThrowsAny<CryptographicException>( () => key.ExportEncryptedPkcs8PrivateKey( new byte[3], new PbeParameters(0, HashAlgorithmName.SHA1, 72))); Assert.ThrowsAny<CryptographicException>( () => key.TryExportEncryptedPkcs8PrivateKey( new byte[3], new PbeParameters(0, HashAlgorithmName.SHA1, 72), Span<byte>.Empty, out _)); // Unknown encryption algorithm (negative enum value) Assert.ThrowsAny<CryptographicException>( () => key.ExportEncryptedPkcs8PrivateKey( new byte[3], new PbeParameters((PbeEncryptionAlgorithm)(-5), HashAlgorithmName.SHA1, 72))); Assert.ThrowsAny<CryptographicException>( () => key.TryExportEncryptedPkcs8PrivateKey( new byte[3], new PbeParameters((PbeEncryptionAlgorithm)(-5), HashAlgorithmName.SHA1, 72), Span<byte>.Empty, out _)); // Unknown encryption algorithm (overly-large enum value) Assert.ThrowsAny<CryptographicException>( () => key.ExportEncryptedPkcs8PrivateKey( new byte[3], new PbeParameters((PbeEncryptionAlgorithm)15, HashAlgorithmName.SHA1, 72))); Assert.ThrowsAny<CryptographicException>( () => key.TryExportEncryptedPkcs8PrivateKey( new byte[3], new PbeParameters((PbeEncryptionAlgorithm)15, HashAlgorithmName.SHA1, 72), Span<byte>.Empty, out _)); // Unknown hash algorithm Assert.ThrowsAny<CryptographicException>( () => key.ExportEncryptedPkcs8PrivateKey( new byte[3], new PbeParameters(PbeEncryptionAlgorithm.Aes192Cbc, new HashAlgorithmName("Potato"), 72))); Assert.ThrowsAny<CryptographicException>( () => key.TryExportEncryptedPkcs8PrivateKey( new byte[3], new PbeParameters(PbeEncryptionAlgorithm.Aes192Cbc, new HashAlgorithmName("Potato"), 72), Span<byte>.Empty, out _)); } } [Fact] public static void DecryptPkcs12WithBytes() { using (DSA key = DSAFactory.Create()) { key.ImportParameters(DSATestData.GetDSA1024Params()); string charBased = "hello"; byte[] byteBased = Encoding.UTF8.GetBytes(charBased); byte[] encrypted = key.ExportEncryptedPkcs8PrivateKey( charBased, new PbeParameters( PbeEncryptionAlgorithm.TripleDes3KeyPkcs12, HashAlgorithmName.SHA1, 123)); Assert.ThrowsAny<CryptographicException>( () => key.ImportEncryptedPkcs8PrivateKey(byteBased, encrypted, out _)); } } private static void ReadBase64EncryptedPkcs8( string base64EncPkcs8, string password, PbeParameters pbeParameters, in DSAParameters expected) { ReadWriteKey( base64EncPkcs8, expected, (DSA dsa, ReadOnlySpan<byte> source, out int read) => dsa.ImportEncryptedPkcs8PrivateKey(password, source, out read), dsa => dsa.ExportEncryptedPkcs8PrivateKey(password, pbeParameters), (DSA dsa, Span<byte> destination, out int written) => dsa.TryExportEncryptedPkcs8PrivateKey(password, pbeParameters, destination, out written), isEncrypted: true); } private static void ReadBase64EncryptedPkcs8( string base64EncPkcs8, byte[] passwordBytes, PbeParameters pbeParameters, in DSAParameters expected) { ReadWriteKey( base64EncPkcs8, expected, (DSA dsa, ReadOnlySpan<byte> source, out int read) => dsa.ImportEncryptedPkcs8PrivateKey(passwordBytes, source, out read), dsa => dsa.ExportEncryptedPkcs8PrivateKey(passwordBytes, pbeParameters), (DSA dsa, Span<byte> destination, out int written) => dsa.TryExportEncryptedPkcs8PrivateKey(passwordBytes, pbeParameters, destination, out written), isEncrypted: true); } private static void ReadWriteBase64SubjectPublicKeyInfo( string base64SubjectPublicKeyInfo, in DSAParameters expected) { DSAParameters expectedPublic = new DSAParameters { P = expected.P, G = expected.G, Q = expected.Q, Y = expected.Y, }; ReadWriteKey( base64SubjectPublicKeyInfo, expectedPublic, (DSA dsa, ReadOnlySpan<byte> source, out int read) => dsa.ImportSubjectPublicKeyInfo(source, out read), dsa => dsa.ExportSubjectPublicKeyInfo(), (DSA dsa, Span<byte> destination, out int written) => dsa.TryExportSubjectPublicKeyInfo(destination, out written)); } private static void ReadWriteBase64Pkcs8(string base64Pkcs8, in DSAParameters expected) { ReadWriteKey( base64Pkcs8, expected, (DSA dsa, ReadOnlySpan<byte> source, out int read) => dsa.ImportPkcs8PrivateKey(source, out read), dsa => dsa.ExportPkcs8PrivateKey(), (DSA dsa, Span<byte> destination, out int written) => dsa.TryExportPkcs8PrivateKey(destination, out written)); } private static void ReadWriteKey( string base64, in DSAParameters expected, ReadKeyAction readAction, Func<DSA, byte[]> writeArrayFunc, WriteKeyToSpanFunc writeSpanFunc, bool isEncrypted = false) { bool isPrivateKey = expected.X != null; byte[] derBytes = Convert.FromBase64String(base64); byte[] arrayExport; byte[] tooBig; const int OverAllocate = 30; const int WriteShift = 6; using (DSA dsa = DSAFactory.Create()) { readAction(dsa, derBytes, out int bytesRead); Assert.Equal(derBytes.Length, bytesRead); arrayExport = writeArrayFunc(dsa); DSAParameters dsaParameters = dsa.ExportParameters(isPrivateKey); DSAImportExport.AssertKeyEquals(expected, dsaParameters); } // Public key formats are stable. // Private key formats are not, since CNG recomputes the D value // and then all of the CRT parameters. if (!isPrivateKey) { Assert.Equal(derBytes.Length, arrayExport.Length); Assert.Equal(derBytes.ByteArrayToHex(), arrayExport.ByteArrayToHex()); } using (DSA dsa = DSAFactory.Create()) { Assert.ThrowsAny<CryptographicException>( () => readAction(dsa, arrayExport.AsSpan(1), out _)); Assert.ThrowsAny<CryptographicException>( () => readAction(dsa, arrayExport.AsSpan(0, arrayExport.Length - 1), out _)); readAction(dsa, arrayExport, out int bytesRead); Assert.Equal(arrayExport.Length, bytesRead); DSAParameters dsaParameters = dsa.ExportParameters(isPrivateKey); DSAImportExport.AssertKeyEquals(expected, dsaParameters); Assert.False( writeSpanFunc(dsa, Span<byte>.Empty, out int bytesWritten), "Write to empty span"); Assert.Equal(0, bytesWritten); Assert.False( writeSpanFunc( dsa, derBytes.AsSpan(0, Math.Min(derBytes.Length, arrayExport.Length) - 1), out bytesWritten), "Write to too-small span"); Assert.Equal(0, bytesWritten); tooBig = new byte[arrayExport.Length + OverAllocate]; tooBig.AsSpan().Fill(0xC4); Assert.True(writeSpanFunc(dsa, tooBig.AsSpan(WriteShift), out bytesWritten)); Assert.Equal(arrayExport.Length, bytesWritten); Assert.Equal(0xC4, tooBig[WriteShift - 1]); Assert.Equal(0xC4, tooBig[WriteShift + bytesWritten + 1]); // If encrypted, the data should have had a random salt applied, so unstable. // Otherwise, we've normalized the data (even for private keys) so the output // should match what it output previously. if (isEncrypted) { Assert.NotEqual( arrayExport.ByteArrayToHex(), tooBig.AsSpan(WriteShift, bytesWritten).ByteArrayToHex()); } else { Assert.Equal( arrayExport.ByteArrayToHex(), tooBig.AsSpan(WriteShift, bytesWritten).ByteArrayToHex()); } } using (DSA dsa = DSAFactory.Create()) { readAction(dsa, tooBig.AsSpan(WriteShift), out int bytesRead); Assert.Equal(arrayExport.Length, bytesRead); arrayExport.AsSpan().Fill(0xCA); Assert.True( writeSpanFunc(dsa, arrayExport, out int bytesWritten), "Write to precisely allocated Span"); if (isEncrypted) { Assert.NotEqual( tooBig.AsSpan(WriteShift, bytesWritten).ByteArrayToHex(), arrayExport.ByteArrayToHex()); } else { Assert.Equal( tooBig.AsSpan(WriteShift, bytesWritten).ByteArrayToHex(), arrayExport.ByteArrayToHex()); } } } private delegate void ReadKeyAction(DSA dsa, ReadOnlySpan<byte> source, out int bytesRead); private delegate bool WriteKeyToSpanFunc(DSA dsa, Span<byte> destination, out int bytesWritten); } }
/*************************************************************************************************************************************** * Copyright (C) 2001-2012 LearnLift USA * * Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, [email protected] * * * * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License * * as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public License along with this library; if not, * * write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************************************************************************/ using System; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Threading; using System.Windows.Forms; using Kerido.Controls; using MLifter.BusinessLayer; using MLifter.Controls.Properties; using MLifter.DAL; using MLifter.DAL.Interfaces; using MLifter.Components; namespace MLifter.Controls.LearningWindow { [Docking(DockingBehavior.AutoDock)] public partial class AnswerPanel : UserControl, ILearnUserControl { #region override private Image BackupBackgroundImage = null; /// <summary> /// Paints the background of the control. /// </summary> /// <param name="e">A <see cref="T:System.Windows.Forms.PaintEventArgs"/> that contains the event data.</param> /// <remarks>Documented by Dev07, 2009-05-05</remarks> protected override void OnPaintBackground(PaintEventArgs e) { if (ComponentsHelper.IsResizing) { if (BackgroundImage != null) { BackupBackgroundImage = BackgroundImage.Clone() as Image; BackgroundImage = null; } base.OnPaintBackground(e); } else if (!ComponentsHelper.IsResizing) { if (BackupBackgroundImage != null) { BackgroundImage = BackupBackgroundImage; BackupBackgroundImage = null; } base.OnPaintBackground(e); using (Graphics g = e.Graphics) { //paint Image if (imageRightCorner != null) { Size size = new Size(imageRightCorner.Width, imageRightCorner.Height); Point start = new Point(this.Width - size.Width - 5, this.Height - size.Height - 10); if (this.Width < imageRightCorner.Width) { do { double factor = 0.5; size = new Size((int)(imageRightCorner.Width * factor), (int)(imageRightCorner.Height * factor)); start = new Point(this.Width - size.Width - 5, this.Height - size.Height - 10); } while (this.Width <= size.Width); } Rectangle dest = new Rectangle(start, size); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; g.DrawImage(imageRightCorner, dest); } } } } #endregion override #region properties private Image imageRightCorner; [DefaultValue(typeof(Image), null), Category("Appearance-BackgroundImage"), Description("The Image for the lower right corner")] public Image ImageRightCorner { get { return imageRightCorner; } set { imageRightCorner = value; } } /// <summary> /// Gets or sets the title. /// </summary> /// <value>The title.</value> /// <remarks>Documented by Dev02, 2008-04-22</remarks> [DefaultValue("Answer"), Category("Appearance"), Localizable(true)] public string Title { get { return labelAnswer.Text; } set { labelAnswer.Text = value; } } /// <summary> /// Gets or sets the color of the title. /// </summary> /// <value>The color of the title.</value> /// <remarks>Documented by Dev02, 2008-04-22</remarks> [DefaultValue(typeof(Color), "White"), Category("Appearance")] public Color TitleColor { get { return labelAnswer.ForeColor; } set { labelAnswer.ForeColor = value; } } Thread generateAnswerThread = null; LearnLogic learnlogic = null; DateTime learnLogicWorkingStart; private EventArgs cardEventArgs = null; #endregion properties #region constructor /// <summary> /// Initializes a new instance of the <see cref="AnswerPanel"/> class. /// </summary> /// <remarks>Documented by Dev02, 2008-04-22</remarks> public AnswerPanel() { this.SuspendLayout(); InitializeComponent(); this.ResumeLayout(); DoubleBuffered = true; SetStyle(ControlStyles.OptimizedDoubleBuffer, true); SetStyle(ControlStyles.AllPaintingInWmPaint, true); SetStyle(ControlStyles.UserPaint, true); webBrowserAnswer.PreviewKeyDown += new PreviewKeyDownEventHandler(webBrowserAnswer_PreviewKeyDown); mLifterTextBox.Correct += new EventHandler(mLifterTextBox_Correct); mLifterTextBox.Wrong += new EventHandler(mLifterTextBox_Wrong); multipleChoice.ButtonKeyUp += new KeyEventHandler(multipleChoice_ButtonKeyUp); mLifterTextBox.WelcomeTipp = Resources.MLIFTER_TEXTBOX_WELCOME_TIPP; mLifterTextBox.Resize += new EventHandler(mLifterTextBox_Resize); panelTextBox.Resize += new EventHandler(panelTextBox_Resize); //reset pages multiPaneControlMain.SelectedPage = null; //set tooltips dockingButtonDontAskAgain.SetToolTip(Resources.TOOLTIP_SELF_ASSESSEMENT_DONTASK); } #endregion constructor #region controls public void UpdateCulture() { dockingButtonDontAskAgain.SetToolTip(Resources.TOOLTIP_SELF_ASSESSEMENT_DONTASK); dockingButtonDontAskAgain.Text = new ComponentResourceManager(this.GetType()).GetString(dockingButtonDontAskAgain.Name + ".Text"); mLifterTextBox.WelcomeTipp = Resources.MLIFTER_TEXTBOX_WELCOME_TIPP; } /// <summary> /// Gets the info bar control. /// </summary> /// <value>The info bar control.</value> /// <remarks>Documented by Dev05, 2009-04-16</remarks> public Control InfoBarControl { get { return panelMultiPane; } } /// <summary> /// Gets the additional info bar suspend control. /// </summary> /// <value>The additional info bar suspend control.</value> /// <remarks>Documented by Dev05, 2009-04-16</remarks> public Control AdditionalInfoBarSuspendControl { get { return gradientPanelAnswer; } } #endregion controls #region selfAssesment public event EventHandler SelfAssesmentKeyUp; protected virtual void OnSelfAssesmentKeyUp(EventArgs e) { if (SelfAssesmentKeyUp != null) SelfAssesmentKeyUp(this, e); } public event EventHandler SelfAssesmentKeyDown; protected virtual void OnSelfAssesmentKeyDown(EventArgs e) { if (SelfAssesmentKeyDown != null) SelfAssesmentKeyDown(this, e); } /// <summary> /// Submits the self assessment reponse. /// </summary> /// <param name="doknow">if set to <c>true</c> [doknow].</param> /// <remarks>Documented by Dev02, 2008-04-23</remarks> public void SubmitSelfAssessmentReponse(bool doknow, bool dontaskagain) { if (learnlogic != null && cardEventArgs is CardStateChangedShowResultEventArgs) { //whether the question was answered right or wrong by the user AnswerResult result = ((CardStateChangedShowResultEventArgs)cardEventArgs).result; string answer = ((CardStateChangedShowResultEventArgs)cardEventArgs).answer; UserInputSubmitSelfAssessmentResponseEventArgs args = new UserInputSubmitSelfAssessmentResponseEventArgs(doknow, dontaskagain, result, answer); UserInputSubmit(this, args); } } /// <summary> /// Submits the deactivate card response. /// </summary> /// <remarks>Documented by Dev02, 2009-09-09</remarks> public void SubmitDeactivateCard() { if (learnlogic != null) { UserInputSubmitDeactivateCardEventArgs args = new UserInputSubmitDeactivateCardEventArgs(); UserInputSubmit(this, args); } } /// <summary> /// Handles the KeyUp event of the buttonSelfAssessment control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Windows.Forms.KeyEventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev02, 2008-04-29</remarks> private void buttonSelfAssessment_KeyUp(object sender, KeyEventArgs e) { //In self assessment mode, up & down arrow keys can be used to pro/demote if (e.KeyCode == Keys.Up) OnSelfAssesmentKeyUp(null); else if (e.KeyCode == Keys.Down) OnSelfAssesmentKeyDown(null); } #endregion selfAssesment #region buttonFocus public event MLifter.BusinessLayer.LearnLogic.CardStateChangedEventHandler SetButtonFocus; protected virtual void OnSetButtonFocus(CardStateChangedEventArgs e) { if (SetButtonFocus != null) SetButtonFocus(this, e); } #endregion buttonFocus #region learnlogic void learnlogic_LearnLogicIdle(object sender, EventArgs e) { TimeSpan ts = DateTime.Now - learnLogicWorkingStart; Debug.WriteLine(ts.TotalMilliseconds.ToString() + " ms", "Working time of LearnLogic"); } void learnlogic_LearnLogicIsWorking(object sender, EventArgs e) { learnLogicWorkingStart = DateTime.Now; } /// <summary> /// Registers the learn logic. /// </summary> /// <param name="learnlogic">The learnlogic.</param> /// <remarks>Documented by Dev02, 2008-04-22</remarks> public void RegisterLearnLogic(LearnLogic learnlogic) { this.learnlogic = learnlogic; this.learnlogic.CardStateChanged += new LearnLogic.CardStateChangedEventHandler(learnlogic_CardStateChanged); this.learnlogic.LearningModuleClosed += new EventHandler(learnlogic_LearningModuleClosed); this.learnlogic.LearnLogicIsWorking += new EventHandler(learnlogic_LearnLogicIsWorking); this.learnlogic.LearnLogicIdle += new EventHandler(learnlogic_LearnLogicIdle); } /// <summary> /// Handles the LearningModuleClosed event of the learnlogic control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev08, 2008-11-27</remarks> void learnlogic_LearningModuleClosed(object sender, EventArgs e) { //set the browser to an empty page AnswerBrowserContent = "<html></html>"; } /// <summary> /// Handles the CardStateChanged event of the learnlogic control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="MLifter.BusinessLayer.CardStateChangedEventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev02, 2008-04-23</remarks> void learnlogic_CardStateChanged(object sender, CardStateChangedEventArgs e) { Card card = e.dictionary.Cards.GetCardByID(e.cardid); //prepare title labels for either a new card, or the result in slideshow mode if (e is CardStateChangedNewCardEventArgs || (e is CardStateChangedShowResultEventArgs && ((CardStateChangedShowResultEventArgs)e).slideshow)) { string title = card != null ? card.CurrentAnswerCaption : string.Empty; if ((this.learnlogic == null) || (this.learnlogic.SlideShow == false)) { switch (e.dictionary.LearnMode) { case BusinessLayer.LearnModes.MultipleChoice: title = String.Format(Resources.MAINFORM_LBLANSWER_MULTI_TEXT, title); break; case BusinessLayer.LearnModes.Sentence: title = String.Format(Resources.MAINFORM_LBLANSWER_SENTENCES_TEXT, title); break; default: if (card.CurrentAnswer.Words.Count > 1) //in case of synonyms title = String.Format(Resources.MAINFORM_LBLANSWER_DEFAULT_TEXT2, title, card.CurrentAnswer.Words.Count); else title = String.Format(Resources.MAINFORM_LBLANSWER_DEFAULT_TEXT1, title); break; } } this.Title = title; } if (e is CardStateChangedNewCardEventArgs) { ComponentsHelper.IsResizing = true; //reset controls mLifterTextBox.Text = string.Empty; webBrowserAnswer.Stop(); MLifter.Components.InfoBar.CleanUpInfobars(InfoBarControl); if (generateAnswerThread != null && generateAnswerThread.IsAlive) generateAnswerThread.Abort(); //fix for [ML-1335] Problems with bidirectional Text (RTL languages) RightToLeft controlTextDirection = (e.dictionary.CurrentQueryDirection == EQueryDirection.Answer2Question ? card.BaseCard.Question.Culture : card.BaseCard.Answer.Culture).TextInfo.IsRightToLeft ? RightToLeft.Yes : RightToLeft.No; mLifterTextBox.RightToLeft = multipleChoice.RightToLeft = controlTextDirection; //switch main multipane according to current learn mode if (e.dictionary.LearnMode == BusinessLayer.LearnModes.MultipleChoice) { multiPaneControlMain.SelectedPage = multiPanePageMainMultipleChoice; BusinessLayer.MultipleChoice multipleChoiceQuery = e.dictionary.GetChoices(card.BaseCard); if (multipleChoiceQuery.Count > 0) { multipleChoice.Options = e.dictionary.CurrentMultipleChoiceOptions; multipleChoice.Show(multipleChoiceQuery); multipleChoice.Focus(); } } else { multiPaneControlMain.SelectedPage = multiPanePageMainTextbox; mLifterTextBox.IgnoreChars = e.dictionary.Settings.StripChars; mLifterTextBox.CaseSensitive = e.dictionary.Settings.CaseSensitive.Value; mLifterTextBox.IgnoreAccentChars = e.dictionary.Settings.IgnoreAccentChars.Value; mLifterTextBox.CorrectOnTheFly = e.dictionary.Settings.CorrectOnTheFly.Value; mLifterTextBox.Synonyms = (e.dictionary.LearnMode == BusinessLayer.LearnModes.Sentence ? card.CurrentAnswerExample : card.CurrentAnswer).ToStringList(); //show synonym notification infobar if (mLifterTextBox.Synonyms.Count > 1 && learnlogic.SynonymInfoMessage) { string notificationText; if (e.dictionary.Settings.CorrectOnTheFly.Value) notificationText = Resources.SYNONYM_PROMPT_FLY_TEXT; else notificationText = Resources.SYNONYM_PROMPT_TEXT; MLifter.Components.InfoBar infobar = new MLifter.Components.InfoBar(notificationText, this.InfoBarControl, DockStyle.Top, true, true, gradientPanelAnswer); infobar.DontShowAgainChanged += new EventHandler(infobar_DontShowAgainChanged); } PositionTextBox(); mLifterTextBox.Focus(); } ComponentsHelper.IsResizing = false; Invalidate(); } else if (e is CardStateChangedShowResultEventArgs) { CardStateChangedShowResultEventArgs args = (CardStateChangedShowResultEventArgs)e; if (generateAnswerThread != null && generateAnswerThread.IsAlive) generateAnswerThread.Abort(); generateAnswerThread = new Thread(delegate() { this.Invoke(new MethodInvoker(delegate() { this.AnswerBrowserUrl = new Uri("about:blank"); //[ML-1621] Flicker in the answer result })); // WORKAROUND for Windows Media Player 6.4 [ML-2122] if (MLifter.Generics.Methods.IsWMP7OrGreater()) { Uri answer = MLifter.DAL.DB.DbMediaServer.DbMediaServer.PrepareAnswer(args.dictionary.DictionaryDAL.Parent, args.cardid, args.dictionary.GenerateAnswer(args.cardid, args.answer, args.promoted)); this.Invoke(new MethodInvoker(delegate() { this.AnswerBrowserUrl = answer; multiPaneControlMain.SelectedPage = multiPanePageMainViewer; if (!args.slideshow && e.dictionary.Settings.SelfAssessment.Value) cardEventArgs = args;//this tag is needed for the submit of the answer OnSetButtonFocus(e); })); } else { string content = args.dictionary.GenerateAnswer(args.cardid, args.answer, args.promoted); this.Invoke(new MethodInvoker(delegate() { this.AnswerBrowserContent = content; multiPaneControlMain.SelectedPage = multiPanePageMainViewer; if (!args.slideshow && e.dictionary.Settings.SelfAssessment.Value) cardEventArgs = args;//this tag is needed for the submit of the answer OnSetButtonFocus(e); })); } }); generateAnswerThread.IsBackground = true; generateAnswerThread.Name = "Generate Answer Thread"; generateAnswerThread.CurrentCulture = Thread.CurrentThread.CurrentCulture; generateAnswerThread.CurrentUICulture = Thread.CurrentThread.CurrentUICulture; generateAnswerThread.Start(); } else if (e is CardStateChangedCountdownTimerEventArgs) { //submit answers in case the timer is finished CardStateChangedCountdownTimerEventArgs args = (CardStateChangedCountdownTimerEventArgs)e; if (args.TimerFinished) { if (multiPaneControlMain.SelectedPage == multiPanePageMainTextbox) { mLifterTextBox.AllowAnswerSubmit = false; mLifterTextBox.ManualOnKeyPress(new KeyPressEventArgs((char)Keys.Enter)); mLifterTextBox.AllowAnswerSubmit = true; SubmitUserInput(); } else if (multiPaneControlMain.SelectedPage == multiPanePageMainMultipleChoice) SubmitMultipleChoice(); else if (learnlogic.SlideShow) SubmitSlideShow(false); } } } #endregion learnlogic #region panelTextBox #region infobar /// <summary> /// Handles the DontShowAgainChanged event of the infobar control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev02, 2008-06-09</remarks> void infobar_DontShowAgainChanged(object sender, EventArgs e) { if (learnlogic != null && sender is MLifter.Components.InfoBar) learnlogic.SynonymInfoMessage = !((MLifter.Components.InfoBar)sender).DontShowAgain; } #endregion infobar #region textBox /// <summary> /// Handles the FileDropped event of the mLifterTextBox control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Windows.Forms.DragEventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev02, 2008-05-08</remarks> private void mLifterTextBox_FileDropped(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) { string file = ((string[])e.Data.GetData(DataFormats.FileDrop))[0]; OnFileDropped(new FileDroppedEventArgs(file)); } } /// <summary> /// Handles the Wrong event of the mLifterTextBox control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev02, 2008-04-23</remarks> void mLifterTextBox_Wrong(object sender, EventArgs e) { SubmitUserInput(); } /// <summary> /// Handles the Correct event of the mLifterTextBox control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev02, 2008-04-23</remarks> void mLifterTextBox_Correct(object sender, EventArgs e) { SubmitUserInput(); } #endregion textBox /// <summary> /// Handles the Resize event of the panelTextBox control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev03, 2009-04-30</remarks> void panelTextBox_Resize(object sender, EventArgs e) { if (multiPaneControlMain.SelectedPage == multiPanePageMainTextbox) PositionTextBox(); } /// <summary> /// Handles the Resize event of the mLifterTextBox control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev03, 2009-04-30</remarks> void mLifterTextBox_Resize(object sender, EventArgs e) { if (multiPaneControlMain.SelectedPage == multiPanePageMainTextbox) PositionTextBox(); } /// <summary> /// Positions the text box. /// </summary> /// <remarks>Documented by Dev03, 2009-04-14</remarks> private void PositionTextBox() { mLifterTextBox.Top = Convert.ToInt32((panelTextBox.Height - mLifterTextBox.Height) / 2); } #endregion panelTextBox #region others /// <summary> /// Handles the Click event of the dockingButtonDontAskAgain control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev02, 2008-04-23</remarks> private void dockingButtonDontAskAgain_Click(object sender, EventArgs e) { SubmitDeactivateCard(); //SubmitSelfAssessmentReponse(false, true); } /// <summary> /// Focus the single control, when it is the only one on the specified page. /// </summary> /// <param name="page">The page.</param> /// <remarks>Documented by Dev02, 2008-04-23</remarks> private void FocusSingleControl(MultiPanePage page) { if (page != null && page.Controls.Count == 1) page.Controls[0].Focus(); } /// <summary> /// Submits the slide show. /// </summary> /// <param name="stopslideshow">if set to <c>true</c> [stopslideshow].</param> /// <remarks>Documented by Dev02, 2008-04-23</remarks> public void SubmitSlideShow(bool stopslideshow) { if (learnlogic != null) { UserInputSubmitSlideshowEventArgs args = new UserInputSubmitSlideshowEventArgs(stopslideshow); UserInputSubmit(this, args); } } /// <summary> /// Gets a value indicating whether [result page visible]. /// </summary> /// <value><c>true</c> if [result page visible]; otherwise, <c>false</c>.</value> /// <remarks>Documented by Dev02, 2009-05-07</remarks> public bool ResultPageVisible { get { return multiPaneControlMain.SelectedPage == multiPanePageMainViewer; } } #endregion others #region multiPane /// <summary> /// Handles the SelectedPageChanged event of the multiPaneControlButtons control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev02, 2008-04-21</remarks> private void multiPaneControlButtons_SelectedPageChanged(object sender, EventArgs e) { } /// <summary> /// Handles the SelectedPageChanged event of the multiPaneControlMain control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev02, 2008-04-23</remarks> private void multiPaneControlMain_SelectedPageChanged(object sender, EventArgs e) { if (multiPaneControlMain.SelectedPage != multiPanePageMainViewer) AnswerBrowserUrl = new Uri("about:blank"); FocusSingleControl(multiPaneControlMain.SelectedPage); } /// <summary> /// Handles the SelectedPageChanging event of the multiPaneControlMain control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev02, 2008-05-07</remarks> private void multiPaneControlMain_SelectedPageChanging(object sender, EventArgs e) { MLifter.Components.InfoBar.CleanUpInfobars(multiPaneControlMain.SelectedPage); } #endregion multiPane #region multipleChoice /// <summary> /// Handles the ButtonKeyUp event of the multipleChoice control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev02, 2008-04-24</remarks> void multipleChoice_ButtonKeyUp(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) SubmitMultipleChoice(); } /// <summary> /// Submits the multiple choice. /// </summary> /// <remarks>Documented by Dev02, 2008-04-23</remarks> private void SubmitMultipleChoice() { //[ML-2123] Null reference exception thrown when submitting MC answer if (learnlogic != null && multipleChoice != null && multipleChoice.Choices != null) { string answer = multipleChoice.Choices.GetAnswers(); UserInputSubmitMultipleChoiceEventArgs args = new UserInputSubmitMultipleChoiceEventArgs(answer, multipleChoice.Choices.GetResult()); UserInputSubmit(this, args); } } #endregion multipleChoice #region answerBrowser /// <summary> /// Gets or sets the HTML content. /// </summary> /// <value>The content of the answer browser.</value> /// <remarks>Documented by Dev02, 2008-04-22</remarks> private string AnswerBrowserContent { get { try { return webBrowserAnswer.DocumentText; } catch (Exception exp) { Trace.WriteLine(exp.ToString()); return string.Empty; } } set { try { webBrowserAnswer.Stop(); webBrowserAnswer.DocumentText = value; } catch (Exception exp) { Trace.WriteLine("Error setting DocumentText: " + exp.ToString()); } } } /// <summary> /// Gets or sets the Uri. /// </summary> /// <value>The Uri.</value> /// <remarks>Documented by Dev02, 2008-04-22</remarks> private Uri AnswerBrowserUrl { get { return webBrowserAnswer.Url; } set { webBrowserAnswer.Stop(); webBrowserAnswer.Url = value; } } #endregion answerBrowser #region logic /// <summary> /// Checks the answer. /// </summary> /// <remarks>Documented by Dev07, 2009-04-16</remarks> public void CheckAnswer() { if (learnlogic.Dictionary.LearnMode == MLifter.BusinessLayer.LearnModes.MultipleChoice) SubmitMultipleChoice(); else { this.mLifterTextBox.AllowAnswerSubmit = false; this.mLifterTextBox.ManualOnKeyPress(new KeyPressEventArgs((char)Keys.Enter)); //this simults a "pressing ENTER" this.mLifterTextBox.AllowAnswerSubmit = true; SubmitUserInput(); } } /// <summary> /// Shows the next card, depending on slideshow mode or word mode /// </summary> /// <remarks>Documented by Dev07, 2009-04-16</remarks> public void ShowNextCard() { if (learnlogic == null) return; if (learnlogic.SlideShow == true) { SubmitSlideShow(false); return; } UserInputSubmit(this, new UserInputSubmitEventArgs()); } /// <summary> /// Submits the user input. /// </summary> /// <remarks>Documented by Dev02, 2008-04-23</remarks> void SubmitUserInput() { if (learnlogic != null) { UserInputSubmitTextEventArgs args = new UserInputSubmitTextEventArgs( mLifterTextBox.Errors, mLifterTextBox.CorrectSynonyms, mLifterTextBox.Synonyms.Count, mLifterTextBox.CorrectFirstSynonym, mLifterTextBox.Text); UserInputSubmit(this, args); } } /// <summary> /// Users the input submit. /// </summary> /// <param name="sender">The sender.</param> /// <param name="args">The <see cref="MLifter.BusinessLayer.UserInputSubmitTextEventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev03, 2009-04-28</remarks> void UserInputSubmit(object sender, UserInputSubmitEventArgs args) { try { learnlogic.OnUserInputSubmit(this, args); } catch (Generics.ServerOfflineException) { TaskDialog.MessageBox(Resources.LEARNING_WINDOW_SERVER_OFFLINE_DIALOG_TITLE, Resources.LEARNING_WINDOW_SERVER_OFFLINE_DIALOG_TITLE, Resources.LEARNING_WINDOW_SERVER_OFFLINE_DIALOG_CONTENT, TaskDialogButtons.OK, TaskDialogIcons.Error); learnlogic.CloseLearningModuleWithoutSaving(); } } #endregion logic #region browserControl /// <summary> /// Handles the Navigating event of the webBrowserAnswer control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Windows.Forms.WebBrowserNavigatingEventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev02, 2008-05-08</remarks> private void webBrowserAnswer_Navigating(object sender, WebBrowserNavigatingEventArgs e) { if (e.Url.ToString() != "about:blank" && e.Url.Scheme != "http") { e.Cancel = true; OnFileDropped(new FileDroppedEventArgs(e.Url.OriginalString)); } } /// <summary> /// Occurs when [file dropped]. /// </summary> /// <remarks>Documented by Dev02, 2008-05-08</remarks> [Description("Occurs when a file was dropped onto this control.")] public event FileDroppedEventHandler FileDropped; /// <summary> /// Raises the <see cref="E:FileDropped"/> event. /// </summary> /// <param name="e">The <see cref="MLifter.Controls.LearningWindow.FileDroppedEventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev02, 2008-05-08</remarks> private void OnFileDropped(FileDroppedEventArgs e) { if (FileDropped != null) FileDropped(this, e); } /// <summary> /// Occurs when [browser key down]. /// </summary> /// <remarks>Documented by Dev02, 2008-05-13</remarks> public event PreviewKeyDownEventHandler BrowserKeyDown; /// <summary> /// Handles the PreviewKeyDown event of the webBrowserAnswer control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Windows.Forms.PreviewKeyDownEventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev02, 2008-05-13</remarks> private void webBrowserAnswer_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) { if (BrowserKeyDown != null) BrowserKeyDown(sender, e); } #endregion browserControl } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using gagr = Google.Api.Gax.ResourceNames; using wkt = Google.Protobuf.WellKnownTypes; using gr = Google.Rpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Scheduler.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedCloudSchedulerClientTest { [xunit::FactAttribute] public void GetJobRequestObject() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); GetJobRequest request = new GetJobRequest { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), }; Job expectedResponse = new Job { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), Description = "description2cf9da67", PubsubTarget = new PubsubTarget(), AppEngineHttpTarget = new AppEngineHttpTarget(), HttpTarget = new HttpTarget(), UserUpdateTime = new wkt::Timestamp(), State = Job.Types.State.Disabled, Status = new gr::Status(), ScheduleTime = new wkt::Timestamp(), LastAttemptTime = new wkt::Timestamp(), RetryConfig = new RetryConfig(), Schedule = "schedule59559879", TimeZone = "time_zone73f23b20", AttemptDeadline = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.GetJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); Job response = client.GetJob(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetJobRequestObjectAsync() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); GetJobRequest request = new GetJobRequest { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), }; Job expectedResponse = new Job { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), Description = "description2cf9da67", PubsubTarget = new PubsubTarget(), AppEngineHttpTarget = new AppEngineHttpTarget(), HttpTarget = new HttpTarget(), UserUpdateTime = new wkt::Timestamp(), State = Job.Types.State.Disabled, Status = new gr::Status(), ScheduleTime = new wkt::Timestamp(), LastAttemptTime = new wkt::Timestamp(), RetryConfig = new RetryConfig(), Schedule = "schedule59559879", TimeZone = "time_zone73f23b20", AttemptDeadline = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.GetJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Job>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); Job responseCallSettings = await client.GetJobAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Job responseCancellationToken = await client.GetJobAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetJob() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); GetJobRequest request = new GetJobRequest { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), }; Job expectedResponse = new Job { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), Description = "description2cf9da67", PubsubTarget = new PubsubTarget(), AppEngineHttpTarget = new AppEngineHttpTarget(), HttpTarget = new HttpTarget(), UserUpdateTime = new wkt::Timestamp(), State = Job.Types.State.Disabled, Status = new gr::Status(), ScheduleTime = new wkt::Timestamp(), LastAttemptTime = new wkt::Timestamp(), RetryConfig = new RetryConfig(), Schedule = "schedule59559879", TimeZone = "time_zone73f23b20", AttemptDeadline = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.GetJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); Job response = client.GetJob(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetJobAsync() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); GetJobRequest request = new GetJobRequest { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), }; Job expectedResponse = new Job { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), Description = "description2cf9da67", PubsubTarget = new PubsubTarget(), AppEngineHttpTarget = new AppEngineHttpTarget(), HttpTarget = new HttpTarget(), UserUpdateTime = new wkt::Timestamp(), State = Job.Types.State.Disabled, Status = new gr::Status(), ScheduleTime = new wkt::Timestamp(), LastAttemptTime = new wkt::Timestamp(), RetryConfig = new RetryConfig(), Schedule = "schedule59559879", TimeZone = "time_zone73f23b20", AttemptDeadline = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.GetJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Job>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); Job responseCallSettings = await client.GetJobAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Job responseCancellationToken = await client.GetJobAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetJobResourceNames() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); GetJobRequest request = new GetJobRequest { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), }; Job expectedResponse = new Job { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), Description = "description2cf9da67", PubsubTarget = new PubsubTarget(), AppEngineHttpTarget = new AppEngineHttpTarget(), HttpTarget = new HttpTarget(), UserUpdateTime = new wkt::Timestamp(), State = Job.Types.State.Disabled, Status = new gr::Status(), ScheduleTime = new wkt::Timestamp(), LastAttemptTime = new wkt::Timestamp(), RetryConfig = new RetryConfig(), Schedule = "schedule59559879", TimeZone = "time_zone73f23b20", AttemptDeadline = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.GetJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); Job response = client.GetJob(request.JobName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetJobResourceNamesAsync() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); GetJobRequest request = new GetJobRequest { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), }; Job expectedResponse = new Job { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), Description = "description2cf9da67", PubsubTarget = new PubsubTarget(), AppEngineHttpTarget = new AppEngineHttpTarget(), HttpTarget = new HttpTarget(), UserUpdateTime = new wkt::Timestamp(), State = Job.Types.State.Disabled, Status = new gr::Status(), ScheduleTime = new wkt::Timestamp(), LastAttemptTime = new wkt::Timestamp(), RetryConfig = new RetryConfig(), Schedule = "schedule59559879", TimeZone = "time_zone73f23b20", AttemptDeadline = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.GetJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Job>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); Job responseCallSettings = await client.GetJobAsync(request.JobName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Job responseCancellationToken = await client.GetJobAsync(request.JobName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateJobRequestObject() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); CreateJobRequest request = new CreateJobRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Job = new Job(), }; Job expectedResponse = new Job { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), Description = "description2cf9da67", PubsubTarget = new PubsubTarget(), AppEngineHttpTarget = new AppEngineHttpTarget(), HttpTarget = new HttpTarget(), UserUpdateTime = new wkt::Timestamp(), State = Job.Types.State.Disabled, Status = new gr::Status(), ScheduleTime = new wkt::Timestamp(), LastAttemptTime = new wkt::Timestamp(), RetryConfig = new RetryConfig(), Schedule = "schedule59559879", TimeZone = "time_zone73f23b20", AttemptDeadline = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.CreateJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); Job response = client.CreateJob(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateJobRequestObjectAsync() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); CreateJobRequest request = new CreateJobRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Job = new Job(), }; Job expectedResponse = new Job { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), Description = "description2cf9da67", PubsubTarget = new PubsubTarget(), AppEngineHttpTarget = new AppEngineHttpTarget(), HttpTarget = new HttpTarget(), UserUpdateTime = new wkt::Timestamp(), State = Job.Types.State.Disabled, Status = new gr::Status(), ScheduleTime = new wkt::Timestamp(), LastAttemptTime = new wkt::Timestamp(), RetryConfig = new RetryConfig(), Schedule = "schedule59559879", TimeZone = "time_zone73f23b20", AttemptDeadline = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.CreateJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Job>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); Job responseCallSettings = await client.CreateJobAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Job responseCancellationToken = await client.CreateJobAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateJob() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); CreateJobRequest request = new CreateJobRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Job = new Job(), }; Job expectedResponse = new Job { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), Description = "description2cf9da67", PubsubTarget = new PubsubTarget(), AppEngineHttpTarget = new AppEngineHttpTarget(), HttpTarget = new HttpTarget(), UserUpdateTime = new wkt::Timestamp(), State = Job.Types.State.Disabled, Status = new gr::Status(), ScheduleTime = new wkt::Timestamp(), LastAttemptTime = new wkt::Timestamp(), RetryConfig = new RetryConfig(), Schedule = "schedule59559879", TimeZone = "time_zone73f23b20", AttemptDeadline = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.CreateJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); Job response = client.CreateJob(request.Parent, request.Job); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateJobAsync() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); CreateJobRequest request = new CreateJobRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Job = new Job(), }; Job expectedResponse = new Job { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), Description = "description2cf9da67", PubsubTarget = new PubsubTarget(), AppEngineHttpTarget = new AppEngineHttpTarget(), HttpTarget = new HttpTarget(), UserUpdateTime = new wkt::Timestamp(), State = Job.Types.State.Disabled, Status = new gr::Status(), ScheduleTime = new wkt::Timestamp(), LastAttemptTime = new wkt::Timestamp(), RetryConfig = new RetryConfig(), Schedule = "schedule59559879", TimeZone = "time_zone73f23b20", AttemptDeadline = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.CreateJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Job>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); Job responseCallSettings = await client.CreateJobAsync(request.Parent, request.Job, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Job responseCancellationToken = await client.CreateJobAsync(request.Parent, request.Job, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateJobResourceNames() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); CreateJobRequest request = new CreateJobRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Job = new Job(), }; Job expectedResponse = new Job { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), Description = "description2cf9da67", PubsubTarget = new PubsubTarget(), AppEngineHttpTarget = new AppEngineHttpTarget(), HttpTarget = new HttpTarget(), UserUpdateTime = new wkt::Timestamp(), State = Job.Types.State.Disabled, Status = new gr::Status(), ScheduleTime = new wkt::Timestamp(), LastAttemptTime = new wkt::Timestamp(), RetryConfig = new RetryConfig(), Schedule = "schedule59559879", TimeZone = "time_zone73f23b20", AttemptDeadline = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.CreateJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); Job response = client.CreateJob(request.ParentAsLocationName, request.Job); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateJobResourceNamesAsync() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); CreateJobRequest request = new CreateJobRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Job = new Job(), }; Job expectedResponse = new Job { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), Description = "description2cf9da67", PubsubTarget = new PubsubTarget(), AppEngineHttpTarget = new AppEngineHttpTarget(), HttpTarget = new HttpTarget(), UserUpdateTime = new wkt::Timestamp(), State = Job.Types.State.Disabled, Status = new gr::Status(), ScheduleTime = new wkt::Timestamp(), LastAttemptTime = new wkt::Timestamp(), RetryConfig = new RetryConfig(), Schedule = "schedule59559879", TimeZone = "time_zone73f23b20", AttemptDeadline = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.CreateJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Job>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); Job responseCallSettings = await client.CreateJobAsync(request.ParentAsLocationName, request.Job, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Job responseCancellationToken = await client.CreateJobAsync(request.ParentAsLocationName, request.Job, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateJobRequestObject() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); UpdateJobRequest request = new UpdateJobRequest { Job = new Job(), UpdateMask = new wkt::FieldMask(), }; Job expectedResponse = new Job { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), Description = "description2cf9da67", PubsubTarget = new PubsubTarget(), AppEngineHttpTarget = new AppEngineHttpTarget(), HttpTarget = new HttpTarget(), UserUpdateTime = new wkt::Timestamp(), State = Job.Types.State.Disabled, Status = new gr::Status(), ScheduleTime = new wkt::Timestamp(), LastAttemptTime = new wkt::Timestamp(), RetryConfig = new RetryConfig(), Schedule = "schedule59559879", TimeZone = "time_zone73f23b20", AttemptDeadline = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.UpdateJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); Job response = client.UpdateJob(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateJobRequestObjectAsync() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); UpdateJobRequest request = new UpdateJobRequest { Job = new Job(), UpdateMask = new wkt::FieldMask(), }; Job expectedResponse = new Job { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), Description = "description2cf9da67", PubsubTarget = new PubsubTarget(), AppEngineHttpTarget = new AppEngineHttpTarget(), HttpTarget = new HttpTarget(), UserUpdateTime = new wkt::Timestamp(), State = Job.Types.State.Disabled, Status = new gr::Status(), ScheduleTime = new wkt::Timestamp(), LastAttemptTime = new wkt::Timestamp(), RetryConfig = new RetryConfig(), Schedule = "schedule59559879", TimeZone = "time_zone73f23b20", AttemptDeadline = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.UpdateJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Job>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); Job responseCallSettings = await client.UpdateJobAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Job responseCancellationToken = await client.UpdateJobAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateJob() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); UpdateJobRequest request = new UpdateJobRequest { Job = new Job(), UpdateMask = new wkt::FieldMask(), }; Job expectedResponse = new Job { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), Description = "description2cf9da67", PubsubTarget = new PubsubTarget(), AppEngineHttpTarget = new AppEngineHttpTarget(), HttpTarget = new HttpTarget(), UserUpdateTime = new wkt::Timestamp(), State = Job.Types.State.Disabled, Status = new gr::Status(), ScheduleTime = new wkt::Timestamp(), LastAttemptTime = new wkt::Timestamp(), RetryConfig = new RetryConfig(), Schedule = "schedule59559879", TimeZone = "time_zone73f23b20", AttemptDeadline = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.UpdateJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); Job response = client.UpdateJob(request.Job, request.UpdateMask); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateJobAsync() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); UpdateJobRequest request = new UpdateJobRequest { Job = new Job(), UpdateMask = new wkt::FieldMask(), }; Job expectedResponse = new Job { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), Description = "description2cf9da67", PubsubTarget = new PubsubTarget(), AppEngineHttpTarget = new AppEngineHttpTarget(), HttpTarget = new HttpTarget(), UserUpdateTime = new wkt::Timestamp(), State = Job.Types.State.Disabled, Status = new gr::Status(), ScheduleTime = new wkt::Timestamp(), LastAttemptTime = new wkt::Timestamp(), RetryConfig = new RetryConfig(), Schedule = "schedule59559879", TimeZone = "time_zone73f23b20", AttemptDeadline = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.UpdateJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Job>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); Job responseCallSettings = await client.UpdateJobAsync(request.Job, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Job responseCancellationToken = await client.UpdateJobAsync(request.Job, request.UpdateMask, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteJobRequestObject() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); DeleteJobRequest request = new DeleteJobRequest { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); client.DeleteJob(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteJobRequestObjectAsync() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); DeleteJobRequest request = new DeleteJobRequest { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); await client.DeleteJobAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteJobAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteJob() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); DeleteJobRequest request = new DeleteJobRequest { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); client.DeleteJob(request.Name); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteJobAsync() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); DeleteJobRequest request = new DeleteJobRequest { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); await client.DeleteJobAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteJobAsync(request.Name, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteJobResourceNames() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); DeleteJobRequest request = new DeleteJobRequest { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); client.DeleteJob(request.JobName); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteJobResourceNamesAsync() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); DeleteJobRequest request = new DeleteJobRequest { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); await client.DeleteJobAsync(request.JobName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteJobAsync(request.JobName, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void PauseJobRequestObject() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); PauseJobRequest request = new PauseJobRequest { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), }; Job expectedResponse = new Job { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), Description = "description2cf9da67", PubsubTarget = new PubsubTarget(), AppEngineHttpTarget = new AppEngineHttpTarget(), HttpTarget = new HttpTarget(), UserUpdateTime = new wkt::Timestamp(), State = Job.Types.State.Disabled, Status = new gr::Status(), ScheduleTime = new wkt::Timestamp(), LastAttemptTime = new wkt::Timestamp(), RetryConfig = new RetryConfig(), Schedule = "schedule59559879", TimeZone = "time_zone73f23b20", AttemptDeadline = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.PauseJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); Job response = client.PauseJob(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task PauseJobRequestObjectAsync() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); PauseJobRequest request = new PauseJobRequest { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), }; Job expectedResponse = new Job { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), Description = "description2cf9da67", PubsubTarget = new PubsubTarget(), AppEngineHttpTarget = new AppEngineHttpTarget(), HttpTarget = new HttpTarget(), UserUpdateTime = new wkt::Timestamp(), State = Job.Types.State.Disabled, Status = new gr::Status(), ScheduleTime = new wkt::Timestamp(), LastAttemptTime = new wkt::Timestamp(), RetryConfig = new RetryConfig(), Schedule = "schedule59559879", TimeZone = "time_zone73f23b20", AttemptDeadline = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.PauseJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Job>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); Job responseCallSettings = await client.PauseJobAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Job responseCancellationToken = await client.PauseJobAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void PauseJob() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); PauseJobRequest request = new PauseJobRequest { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), }; Job expectedResponse = new Job { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), Description = "description2cf9da67", PubsubTarget = new PubsubTarget(), AppEngineHttpTarget = new AppEngineHttpTarget(), HttpTarget = new HttpTarget(), UserUpdateTime = new wkt::Timestamp(), State = Job.Types.State.Disabled, Status = new gr::Status(), ScheduleTime = new wkt::Timestamp(), LastAttemptTime = new wkt::Timestamp(), RetryConfig = new RetryConfig(), Schedule = "schedule59559879", TimeZone = "time_zone73f23b20", AttemptDeadline = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.PauseJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); Job response = client.PauseJob(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task PauseJobAsync() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); PauseJobRequest request = new PauseJobRequest { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), }; Job expectedResponse = new Job { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), Description = "description2cf9da67", PubsubTarget = new PubsubTarget(), AppEngineHttpTarget = new AppEngineHttpTarget(), HttpTarget = new HttpTarget(), UserUpdateTime = new wkt::Timestamp(), State = Job.Types.State.Disabled, Status = new gr::Status(), ScheduleTime = new wkt::Timestamp(), LastAttemptTime = new wkt::Timestamp(), RetryConfig = new RetryConfig(), Schedule = "schedule59559879", TimeZone = "time_zone73f23b20", AttemptDeadline = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.PauseJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Job>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); Job responseCallSettings = await client.PauseJobAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Job responseCancellationToken = await client.PauseJobAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void PauseJobResourceNames() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); PauseJobRequest request = new PauseJobRequest { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), }; Job expectedResponse = new Job { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), Description = "description2cf9da67", PubsubTarget = new PubsubTarget(), AppEngineHttpTarget = new AppEngineHttpTarget(), HttpTarget = new HttpTarget(), UserUpdateTime = new wkt::Timestamp(), State = Job.Types.State.Disabled, Status = new gr::Status(), ScheduleTime = new wkt::Timestamp(), LastAttemptTime = new wkt::Timestamp(), RetryConfig = new RetryConfig(), Schedule = "schedule59559879", TimeZone = "time_zone73f23b20", AttemptDeadline = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.PauseJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); Job response = client.PauseJob(request.JobName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task PauseJobResourceNamesAsync() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); PauseJobRequest request = new PauseJobRequest { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), }; Job expectedResponse = new Job { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), Description = "description2cf9da67", PubsubTarget = new PubsubTarget(), AppEngineHttpTarget = new AppEngineHttpTarget(), HttpTarget = new HttpTarget(), UserUpdateTime = new wkt::Timestamp(), State = Job.Types.State.Disabled, Status = new gr::Status(), ScheduleTime = new wkt::Timestamp(), LastAttemptTime = new wkt::Timestamp(), RetryConfig = new RetryConfig(), Schedule = "schedule59559879", TimeZone = "time_zone73f23b20", AttemptDeadline = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.PauseJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Job>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); Job responseCallSettings = await client.PauseJobAsync(request.JobName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Job responseCancellationToken = await client.PauseJobAsync(request.JobName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ResumeJobRequestObject() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); ResumeJobRequest request = new ResumeJobRequest { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), }; Job expectedResponse = new Job { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), Description = "description2cf9da67", PubsubTarget = new PubsubTarget(), AppEngineHttpTarget = new AppEngineHttpTarget(), HttpTarget = new HttpTarget(), UserUpdateTime = new wkt::Timestamp(), State = Job.Types.State.Disabled, Status = new gr::Status(), ScheduleTime = new wkt::Timestamp(), LastAttemptTime = new wkt::Timestamp(), RetryConfig = new RetryConfig(), Schedule = "schedule59559879", TimeZone = "time_zone73f23b20", AttemptDeadline = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.ResumeJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); Job response = client.ResumeJob(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ResumeJobRequestObjectAsync() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); ResumeJobRequest request = new ResumeJobRequest { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), }; Job expectedResponse = new Job { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), Description = "description2cf9da67", PubsubTarget = new PubsubTarget(), AppEngineHttpTarget = new AppEngineHttpTarget(), HttpTarget = new HttpTarget(), UserUpdateTime = new wkt::Timestamp(), State = Job.Types.State.Disabled, Status = new gr::Status(), ScheduleTime = new wkt::Timestamp(), LastAttemptTime = new wkt::Timestamp(), RetryConfig = new RetryConfig(), Schedule = "schedule59559879", TimeZone = "time_zone73f23b20", AttemptDeadline = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.ResumeJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Job>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); Job responseCallSettings = await client.ResumeJobAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Job responseCancellationToken = await client.ResumeJobAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ResumeJob() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); ResumeJobRequest request = new ResumeJobRequest { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), }; Job expectedResponse = new Job { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), Description = "description2cf9da67", PubsubTarget = new PubsubTarget(), AppEngineHttpTarget = new AppEngineHttpTarget(), HttpTarget = new HttpTarget(), UserUpdateTime = new wkt::Timestamp(), State = Job.Types.State.Disabled, Status = new gr::Status(), ScheduleTime = new wkt::Timestamp(), LastAttemptTime = new wkt::Timestamp(), RetryConfig = new RetryConfig(), Schedule = "schedule59559879", TimeZone = "time_zone73f23b20", AttemptDeadline = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.ResumeJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); Job response = client.ResumeJob(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ResumeJobAsync() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); ResumeJobRequest request = new ResumeJobRequest { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), }; Job expectedResponse = new Job { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), Description = "description2cf9da67", PubsubTarget = new PubsubTarget(), AppEngineHttpTarget = new AppEngineHttpTarget(), HttpTarget = new HttpTarget(), UserUpdateTime = new wkt::Timestamp(), State = Job.Types.State.Disabled, Status = new gr::Status(), ScheduleTime = new wkt::Timestamp(), LastAttemptTime = new wkt::Timestamp(), RetryConfig = new RetryConfig(), Schedule = "schedule59559879", TimeZone = "time_zone73f23b20", AttemptDeadline = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.ResumeJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Job>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); Job responseCallSettings = await client.ResumeJobAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Job responseCancellationToken = await client.ResumeJobAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ResumeJobResourceNames() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); ResumeJobRequest request = new ResumeJobRequest { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), }; Job expectedResponse = new Job { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), Description = "description2cf9da67", PubsubTarget = new PubsubTarget(), AppEngineHttpTarget = new AppEngineHttpTarget(), HttpTarget = new HttpTarget(), UserUpdateTime = new wkt::Timestamp(), State = Job.Types.State.Disabled, Status = new gr::Status(), ScheduleTime = new wkt::Timestamp(), LastAttemptTime = new wkt::Timestamp(), RetryConfig = new RetryConfig(), Schedule = "schedule59559879", TimeZone = "time_zone73f23b20", AttemptDeadline = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.ResumeJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); Job response = client.ResumeJob(request.JobName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ResumeJobResourceNamesAsync() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); ResumeJobRequest request = new ResumeJobRequest { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), }; Job expectedResponse = new Job { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), Description = "description2cf9da67", PubsubTarget = new PubsubTarget(), AppEngineHttpTarget = new AppEngineHttpTarget(), HttpTarget = new HttpTarget(), UserUpdateTime = new wkt::Timestamp(), State = Job.Types.State.Disabled, Status = new gr::Status(), ScheduleTime = new wkt::Timestamp(), LastAttemptTime = new wkt::Timestamp(), RetryConfig = new RetryConfig(), Schedule = "schedule59559879", TimeZone = "time_zone73f23b20", AttemptDeadline = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.ResumeJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Job>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); Job responseCallSettings = await client.ResumeJobAsync(request.JobName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Job responseCancellationToken = await client.ResumeJobAsync(request.JobName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void RunJobRequestObject() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); RunJobRequest request = new RunJobRequest { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), }; Job expectedResponse = new Job { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), Description = "description2cf9da67", PubsubTarget = new PubsubTarget(), AppEngineHttpTarget = new AppEngineHttpTarget(), HttpTarget = new HttpTarget(), UserUpdateTime = new wkt::Timestamp(), State = Job.Types.State.Disabled, Status = new gr::Status(), ScheduleTime = new wkt::Timestamp(), LastAttemptTime = new wkt::Timestamp(), RetryConfig = new RetryConfig(), Schedule = "schedule59559879", TimeZone = "time_zone73f23b20", AttemptDeadline = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.RunJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); Job response = client.RunJob(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task RunJobRequestObjectAsync() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); RunJobRequest request = new RunJobRequest { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), }; Job expectedResponse = new Job { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), Description = "description2cf9da67", PubsubTarget = new PubsubTarget(), AppEngineHttpTarget = new AppEngineHttpTarget(), HttpTarget = new HttpTarget(), UserUpdateTime = new wkt::Timestamp(), State = Job.Types.State.Disabled, Status = new gr::Status(), ScheduleTime = new wkt::Timestamp(), LastAttemptTime = new wkt::Timestamp(), RetryConfig = new RetryConfig(), Schedule = "schedule59559879", TimeZone = "time_zone73f23b20", AttemptDeadline = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.RunJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Job>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); Job responseCallSettings = await client.RunJobAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Job responseCancellationToken = await client.RunJobAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void RunJob() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); RunJobRequest request = new RunJobRequest { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), }; Job expectedResponse = new Job { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), Description = "description2cf9da67", PubsubTarget = new PubsubTarget(), AppEngineHttpTarget = new AppEngineHttpTarget(), HttpTarget = new HttpTarget(), UserUpdateTime = new wkt::Timestamp(), State = Job.Types.State.Disabled, Status = new gr::Status(), ScheduleTime = new wkt::Timestamp(), LastAttemptTime = new wkt::Timestamp(), RetryConfig = new RetryConfig(), Schedule = "schedule59559879", TimeZone = "time_zone73f23b20", AttemptDeadline = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.RunJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); Job response = client.RunJob(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task RunJobAsync() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); RunJobRequest request = new RunJobRequest { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), }; Job expectedResponse = new Job { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), Description = "description2cf9da67", PubsubTarget = new PubsubTarget(), AppEngineHttpTarget = new AppEngineHttpTarget(), HttpTarget = new HttpTarget(), UserUpdateTime = new wkt::Timestamp(), State = Job.Types.State.Disabled, Status = new gr::Status(), ScheduleTime = new wkt::Timestamp(), LastAttemptTime = new wkt::Timestamp(), RetryConfig = new RetryConfig(), Schedule = "schedule59559879", TimeZone = "time_zone73f23b20", AttemptDeadline = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.RunJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Job>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); Job responseCallSettings = await client.RunJobAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Job responseCancellationToken = await client.RunJobAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void RunJobResourceNames() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); RunJobRequest request = new RunJobRequest { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), }; Job expectedResponse = new Job { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), Description = "description2cf9da67", PubsubTarget = new PubsubTarget(), AppEngineHttpTarget = new AppEngineHttpTarget(), HttpTarget = new HttpTarget(), UserUpdateTime = new wkt::Timestamp(), State = Job.Types.State.Disabled, Status = new gr::Status(), ScheduleTime = new wkt::Timestamp(), LastAttemptTime = new wkt::Timestamp(), RetryConfig = new RetryConfig(), Schedule = "schedule59559879", TimeZone = "time_zone73f23b20", AttemptDeadline = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.RunJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); Job response = client.RunJob(request.JobName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task RunJobResourceNamesAsync() { moq::Mock<CloudScheduler.CloudSchedulerClient> mockGrpcClient = new moq::Mock<CloudScheduler.CloudSchedulerClient>(moq::MockBehavior.Strict); RunJobRequest request = new RunJobRequest { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), }; Job expectedResponse = new Job { JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"), Description = "description2cf9da67", PubsubTarget = new PubsubTarget(), AppEngineHttpTarget = new AppEngineHttpTarget(), HttpTarget = new HttpTarget(), UserUpdateTime = new wkt::Timestamp(), State = Job.Types.State.Disabled, Status = new gr::Status(), ScheduleTime = new wkt::Timestamp(), LastAttemptTime = new wkt::Timestamp(), RetryConfig = new RetryConfig(), Schedule = "schedule59559879", TimeZone = "time_zone73f23b20", AttemptDeadline = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.RunJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Job>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudSchedulerClient client = new CloudSchedulerClientImpl(mockGrpcClient.Object, null); Job responseCallSettings = await client.RunJobAsync(request.JobName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Job responseCancellationToken = await client.RunJobAsync(request.JobName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
using System; using System.Diagnostics; using u8 = System.Byte; using u32 = System.UInt32; namespace CleanSqlite { using sqlite3_value = Sqlite3.Mem; public partial class Sqlite3 { /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains C code routines that are called by the parser ** to handle UPDATE statements. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 ** ************************************************************************* */ //#include "sqliteInt.h" #if !SQLITE_OMIT_VIRTUALTABLE /* Forward declaration */ //static void updateVirtualTable( //Parse pParse, /* The parsing context */ //SrcList pSrc, /* The virtual table to be modified */ //Table pTab, /* The virtual table */ //ExprList pChanges, /* The columns to change in the UPDATE statement */ //Expr pRowidExpr, /* Expression used to recompute the rowid */ //int aXRef, /* Mapping from columns of pTab to entries in pChanges */ //Expr *pWhere, /* WHERE clause of the UPDATE statement */ //int onError /* ON CONFLICT strategy */ //); #endif // * SQLITE_OMIT_VIRTUALTABLE */ /* ** The most recently coded instruction was an OP_Column to retrieve the ** i-th column of table pTab. This routine sets the P4 parameter of the ** OP_Column to the default value, if any. ** ** The default value of a column is specified by a DEFAULT clause in the ** column definition. This was either supplied by the user when the table ** was created, or added later to the table definition by an ALTER TABLE ** command. If the latter, then the row-records in the table btree on disk ** may not contain a value for the column and the default value, taken ** from the P4 parameter of the OP_Column instruction, is returned instead. ** If the former, then all row-records are guaranteed to include a value ** for the column and the P4 value is not required. ** ** Column definitions created by an ALTER TABLE command may only have ** literal default values specified: a number, null or a string. (If a more ** complicated default expression value was provided, it is evaluated ** when the ALTER TABLE is executed and one of the literal values written ** into the sqlite_master table.) ** ** Therefore, the P4 parameter is only required if the default value for ** the column is a literal number, string or null. The sqlite3ValueFromExpr() ** function is capable of transforming these types of expressions into ** sqlite3_value objects. ** ** If parameter iReg is not negative, code an OP_RealAffinity instruction ** on register iReg. This is used when an equivalent integer value is ** stored in place of an 8-byte floating point value in order to save ** space. */ static void sqlite3ColumnDefault( Vdbe v, Table pTab, int i, int iReg ) { Debug.Assert( pTab != null ); if ( null == pTab.pSelect ) { sqlite3_value pValue = new sqlite3_value(); int enc = ENC( sqlite3VdbeDb( v ) ); Column pCol = pTab.aCol[i]; #if SQLITE_DEBUG VdbeComment( v, "%s.%s", pTab.zName, pCol.zName ); #endif Debug.Assert( i < pTab.nCol ); sqlite3ValueFromExpr( sqlite3VdbeDb( v ), pCol.pDflt, enc, pCol.affinity, ref pValue ); if ( pValue != null ) { sqlite3VdbeChangeP4( v, -1, pValue, P4_MEM ); } #if !SQLITE_OMIT_FLOATING_POINT if ( iReg >= 0 && pTab.aCol[i].affinity == SQLITE_AFF_REAL ) { sqlite3VdbeAddOp1( v, OP_RealAffinity, iReg ); } #endif } } /* ** Process an UPDATE statement. ** ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL; ** \_______/ \________/ \______/ \________________/ * onError pTabList pChanges pWhere */ static void sqlite3Update( Parse pParse, /* The parser context */ SrcList pTabList, /* The table in which we should change things */ ExprList pChanges, /* Things to be changed */ Expr pWhere, /* The WHERE clause. May be null */ int onError /* How to handle constraint errors */ ) { int i, j; /* Loop counters */ Table pTab; /* The table to be updated */ int addr = 0; /* VDBE instruction address of the start of the loop */ WhereInfo pWInfo; /* Information about the WHERE clause */ Vdbe v; /* The virtual database engine */ Index pIdx; /* For looping over indices */ int nIdx; /* Number of indices that need updating */ int iCur; /* VDBE Cursor number of pTab */ sqlite3 db; /* The database structure */ int[] aRegIdx = null; /* One register assigned to each index to be updated */ int[] aXRef = null; /* aXRef[i] is the index in pChanges.a[] of the ** an expression for the i-th column of the table. ** aXRef[i]==-1 if the i-th column is not changed. */ bool chngRowid; /* True if the record number is being changed */ Expr pRowidExpr = null; /* Expression defining the new record number */ bool openAll = false; /* True if all indices need to be opened */ AuthContext sContext; /* The authorization context */ NameContext sNC; /* The name-context to resolve expressions in */ int iDb; /* Database containing the table being updated */ bool okOnePass; /* True for one-pass algorithm without the FIFO */ bool hasFK; /* True if foreign key processing is required */ #if !SQLITE_OMIT_TRIGGER bool isView; /* True when updating a view (INSTEAD OF trigger) */ Trigger pTrigger; /* List of triggers on pTab, if required */ int tmask = 0; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */ #endif int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */ /* Register Allocations */ int regRowCount = 0; /* A count of rows changed */ int regOldRowid; /* The old rowid */ int regNewRowid; /* The new rowid */ int regNew; int regOld = 0; int regRowSet = 0; /* Rowset of rows to be updated */ sContext = new AuthContext(); //memset( &sContext, 0, sizeof( sContext ) ); db = pParse.db; if ( pParse.nErr != 0 /*|| db.mallocFailed != 0 */ ) { goto update_cleanup; } Debug.Assert( pTabList.nSrc == 1 ); /* Locate the table which we want to update. */ pTab = sqlite3SrcListLookup( pParse, pTabList ); if ( pTab == null ) goto update_cleanup; iDb = sqlite3SchemaToIndex( pParse.db, pTab.pSchema ); /* Figure out if we have any triggers and if the table being ** updated is a view. */ #if !SQLITE_OMIT_TRIGGER pTrigger = sqlite3TriggersExist( pParse, pTab, TK_UPDATE, pChanges, out tmask ); isView = pTab.pSelect != null; Debug.Assert( pTrigger != null || tmask == 0 ); #else const Trigger pTrigger = null;//# define pTrigger 0 const int tmask = 0; //# define tmask 0 #endif #if SQLITE_OMIT_TRIGGER || SQLITE_OMIT_VIEW // # undef isView const bool isView = false; //# define isView 0 #endif if ( sqlite3ViewGetColumnNames( pParse, pTab ) != 0 ) { goto update_cleanup; } if ( sqlite3IsReadOnly( pParse, pTab, tmask ) ) { goto update_cleanup; } aXRef = new int[pTab.nCol];// sqlite3DbMallocRaw(db, sizeof(int) * pTab.nCol); //if ( aXRef == null ) goto update_cleanup; for ( i = 0; i < pTab.nCol; i++ ) aXRef[i] = -1; /* Allocate a cursors for the main database table and for all indices. ** The index cursors might not be used, but if they are used they ** need to occur right after the database cursor. So go ahead and ** allocate enough space, just in case. */ pTabList.a[0].iCursor = iCur = pParse.nTab++; for ( pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext ) { pParse.nTab++; } /* Initialize the name-context */ sNC = new NameContext();// memset(&sNC, 0, sNC).Length; sNC.pParse = pParse; sNC.pSrcList = pTabList; /* Resolve the column names in all the expressions of the ** of the UPDATE statement. Also find the column index ** for each column to be updated in the pChanges array. For each ** column to be updated, make sure we have authorization to change ** that column. */ chngRowid = false; for ( i = 0; i < pChanges.nExpr; i++ ) { if ( sqlite3ResolveExprNames( sNC, ref pChanges.a[i].pExpr ) != 0 ) { goto update_cleanup; } for ( j = 0; j < pTab.nCol; j++ ) { if ( pTab.aCol[j].zName.Equals( pChanges.a[i].zName, StringComparison.InvariantCultureIgnoreCase ) ) { if ( j == pTab.iPKey ) { chngRowid = true; pRowidExpr = pChanges.a[i].pExpr; } aXRef[j] = i; break; } } if ( j >= pTab.nCol ) { if ( sqlite3IsRowid( pChanges.a[i].zName ) ) { chngRowid = true; pRowidExpr = pChanges.a[i].pExpr; } else { sqlite3ErrorMsg( pParse, "no such column: %s", pChanges.a[i].zName ); pParse.checkSchema = 1; goto update_cleanup; } } #if !SQLITE_OMIT_AUTHORIZATION { int rc; rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab.zName, pTab.aCol[j].zName, db.aDb[iDb].zName); if( rc==SQLITE_DENY ){ goto update_cleanup; }else if( rc==SQLITE_IGNORE ){ aXRef[j] = -1; } } #endif } hasFK = sqlite3FkRequired( pParse, pTab, aXRef, chngRowid ? 1 : 0 ) != 0; /* Allocate memory for the array aRegIdx[]. There is one entry in the ** array for each index associated with table being updated. Fill in ** the value with a register number for indices that are to be used ** and with zero for unused indices. */ for ( nIdx = 0, pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext, nIdx++ ) { } if ( nIdx > 0 ) { aRegIdx = new int[nIdx]; // sqlite3DbMallocRaw(db, Index*.Length * nIdx); if ( aRegIdx == null ) goto update_cleanup; } for ( j = 0, pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext, j++ ) { int reg; if ( hasFK || chngRowid ) { reg = ++pParse.nMem; } else { reg = 0; for ( i = 0; i < pIdx.nColumn; i++ ) { if ( aXRef[pIdx.aiColumn[i]] >= 0 ) { reg = ++pParse.nMem; break; } } } aRegIdx[j] = reg; } /* Begin generating code. */ v = sqlite3GetVdbe( pParse ); if ( v == null ) goto update_cleanup; if ( pParse.nested == 0 ) sqlite3VdbeCountChanges( v ); sqlite3BeginWriteOperation( pParse, 1, iDb ); #if !SQLITE_OMIT_VIRTUALTABLE /* Virtual tables must be handled separately */ if ( IsVirtual( pTab ) ) { updateVirtualTable( pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef, pWhere, onError ); pWhere = null; pTabList = null; goto update_cleanup; } #endif /* Allocate required registers. */ regOldRowid = regNewRowid = ++pParse.nMem; if ( pTrigger != null || hasFK ) { regOld = pParse.nMem + 1; pParse.nMem += pTab.nCol; } if ( chngRowid || pTrigger != null || hasFK ) { regNewRowid = ++pParse.nMem; } regNew = pParse.nMem + 1; pParse.nMem += pTab.nCol; /* Start the view context. */ if ( isView ) { sqlite3AuthContextPush( pParse, sContext, pTab.zName ); } /* If we are trying to update a view, realize that view into ** a ephemeral table. */ #if !(SQLITE_OMIT_VIEW) && !(SQLITE_OMIT_TRIGGER) if ( isView ) { sqlite3MaterializeView( pParse, pTab, pWhere, iCur ); } #endif /* Resolve the column names in all the expressions in the ** WHERE clause. */ if ( sqlite3ResolveExprNames( sNC, ref pWhere ) != 0 ) { goto update_cleanup; } /* Begin the database scan */ sqlite3VdbeAddOp2( v, OP_Null, 0, regOldRowid ); ExprList NullOrderby = null; pWInfo = sqlite3WhereBegin( pParse, pTabList, pWhere, ref NullOrderby, WHERE_ONEPASS_DESIRED ); if ( pWInfo == null ) goto update_cleanup; okOnePass = pWInfo.okOnePass != 0; /* Remember the rowid of every item to be updated. */ sqlite3VdbeAddOp2( v, OP_Rowid, iCur, regOldRowid ); if ( !okOnePass ) { regRowSet = ++pParse.nMem; sqlite3VdbeAddOp2( v, OP_RowSetAdd, regRowSet, regOldRowid ); } /* End the database scan loop. */ sqlite3WhereEnd( pWInfo ); /* Initialize the count of updated rows */ if ( ( db.flags & SQLITE_CountRows ) != 0 && null == pParse.pTriggerTab ) { regRowCount = ++pParse.nMem; sqlite3VdbeAddOp2( v, OP_Integer, 0, regRowCount ); } if ( !isView ) { /* ** Open every index that needs updating. Note that if any ** index could potentially invoke a REPLACE conflict resolution ** action, then we need to open all indices because we might need ** to be deleting some records. */ if ( !okOnePass ) sqlite3OpenTable( pParse, iCur, iDb, pTab, OP_OpenWrite ); if ( onError == OE_Replace ) { openAll = true; } else { openAll = false; for ( pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext ) { if ( pIdx.onError == OE_Replace ) { openAll = true; break; } } } for ( i = 0, pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext, i++ ) { if ( openAll || aRegIdx[i] > 0 ) { KeyInfo pKey = sqlite3IndexKeyinfo( pParse, pIdx ); sqlite3VdbeAddOp4( v, OP_OpenWrite, iCur + i + 1, pIdx.tnum, iDb, pKey, P4_KEYINFO_HANDOFF ); Debug.Assert( pParse.nTab > iCur + i + 1 ); } } } /* Top of the update loop */ if ( okOnePass ) { int a1 = sqlite3VdbeAddOp1( v, OP_NotNull, regOldRowid ); addr = sqlite3VdbeAddOp0( v, OP_Goto ); sqlite3VdbeJumpHere( v, a1 ); } else { addr = sqlite3VdbeAddOp3( v, OP_RowSetRead, regRowSet, 0, regOldRowid ); } /* Make cursor iCur point to the record that is being updated. If ** this record does not exist for some reason (deleted by a trigger, ** for example, then jump to the next iteration of the RowSet loop. */ sqlite3VdbeAddOp3( v, OP_NotExists, iCur, addr, regOldRowid ); /* If the record number will change, set register regNewRowid to ** contain the new value. If the record number is not being modified, ** then regNewRowid is the same register as regOldRowid, which is ** already populated. */ Debug.Assert( chngRowid || pTrigger != null || hasFK || regOldRowid == regNewRowid ); if ( chngRowid ) { sqlite3ExprCode( pParse, pRowidExpr, regNewRowid ); sqlite3VdbeAddOp1( v, OP_MustBeInt, regNewRowid ); } /* If there are triggers on this table, populate an array of registers ** with the required old.* column data. */ if ( hasFK || pTrigger != null ) { u32 oldmask = ( hasFK ? sqlite3FkOldmask( pParse, pTab ) : 0 ); oldmask |= sqlite3TriggerColmask( pParse, pTrigger, pChanges, 0, TRIGGER_BEFORE | TRIGGER_AFTER, pTab, onError ); for ( i = 0; i < pTab.nCol; i++ ) { if ( aXRef[i] < 0 || oldmask == 0xffffffff || ( i < 32 && 0 != ( oldmask & ( 1 << i ) ) ) ) { sqlite3ExprCodeGetColumnOfTable( v, pTab, iCur, i, regOld + i ); } else { sqlite3VdbeAddOp2( v, OP_Null, 0, regOld + i ); } } if ( chngRowid == false ) { sqlite3VdbeAddOp2( v, OP_Copy, regOldRowid, regNewRowid ); } } /* Populate the array of registers beginning at regNew with the new ** row data. This array is used to check constaints, create the new ** table and index records, and as the values for any new.* references ** made by triggers. ** ** If there are one or more BEFORE triggers, then do not populate the ** registers associated with columns that are (a) not modified by ** this UPDATE statement and (b) not accessed by new.* references. The ** values for registers not modified by the UPDATE must be reloaded from ** the database after the BEFORE triggers are fired anyway (as the trigger ** may have modified them). So not loading those that are not going to ** be used eliminates some redundant opcodes. */ newmask = (int)sqlite3TriggerColmask( pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError ); for ( i = 0; i < pTab.nCol; i++ ) { if ( i == pTab.iPKey ) { sqlite3VdbeAddOp2( v, OP_Null, 0, regNew + i ); } else { j = aXRef[i]; if ( j >= 0 ) { sqlite3ExprCode( pParse, pChanges.a[j].pExpr, regNew + i ); } else if ( 0 == ( tmask & TRIGGER_BEFORE ) || i > 31 || ( newmask & ( 1 << i ) ) != 0 ) { /* This branch loads the value of a column that will not be changed ** into a register. This is done if there are no BEFORE triggers, or ** if there are one or more BEFORE triggers that use this value via ** a new.* reference in a trigger program. */ testcase( i == 31 ); testcase( i == 32 ); sqlite3VdbeAddOp3( v, OP_Column, iCur, i, regNew + i ); sqlite3ColumnDefault( v, pTab, i, regNew + i ); } } } /* Fire any BEFORE UPDATE triggers. This happens before constraints are ** verified. One could argue that this is wrong. */ if ( ( tmask & TRIGGER_BEFORE ) != 0 ) { sqlite3VdbeAddOp2( v, OP_Affinity, regNew, pTab.nCol ); sqlite3TableAffinityStr( v, pTab ); sqlite3CodeRowTrigger( pParse, pTrigger, TK_UPDATE, pChanges, TRIGGER_BEFORE, pTab, regOldRowid, onError, addr ); /* The row-trigger may have deleted the row being updated. In this ** case, jump to the next row. No updates or AFTER triggers are ** required. This behaviour - what happens when the row being updated ** is deleted or renamed by a BEFORE trigger - is left undefined in the ** documentation. */ sqlite3VdbeAddOp3( v, OP_NotExists, iCur, addr, regOldRowid ); /* If it did not delete it, the row-trigger may still have modified ** some of the columns of the row being updated. Load the values for ** all columns not modified by the update statement into their ** registers in case this has happened. */ for ( i = 0; i < pTab.nCol; i++ ) { if ( aXRef[i] < 0 && i != pTab.iPKey ) { sqlite3VdbeAddOp3( v, OP_Column, iCur, i, regNew + i ); sqlite3ColumnDefault( v, pTab, i, regNew + i ); } } } if ( !isView ) { int j1; /* Address of jump instruction */ /* Do constraint checks. */ int iDummy; sqlite3GenerateConstraintChecks( pParse, pTab, iCur, regNewRowid, aRegIdx, ( chngRowid ? regOldRowid : 0 ), true, onError, addr, out iDummy ); /* Do FK constraint checks. */ if ( hasFK ) { sqlite3FkCheck( pParse, pTab, regOldRowid, 0 ); } /* Delete the index entries associated with the current record. */ j1 = sqlite3VdbeAddOp3( v, OP_NotExists, iCur, 0, regOldRowid ); sqlite3GenerateRowIndexDelete( pParse, pTab, iCur, aRegIdx ); /* If changing the record number, delete the old record. */ if ( hasFK || chngRowid ) { sqlite3VdbeAddOp2( v, OP_Delete, iCur, 0 ); } sqlite3VdbeJumpHere( v, j1 ); if ( hasFK ) { sqlite3FkCheck( pParse, pTab, 0, regNewRowid ); } /* Insert the new index entries and the new record. */ sqlite3CompleteInsertion( pParse, pTab, iCur, regNewRowid, aRegIdx, true, false, false ); /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to ** handle rows (possibly in other tables) that refer via a foreign key ** to the row just updated. */ if ( hasFK ) { sqlite3FkActions( pParse, pTab, pChanges, regOldRowid ); } } /* Increment the row counter */ if ( ( db.flags & SQLITE_CountRows ) != 0 && null == pParse.pTriggerTab ) { sqlite3VdbeAddOp2( v, OP_AddImm, regRowCount, 1 ); } sqlite3CodeRowTrigger( pParse, pTrigger, TK_UPDATE, pChanges, TRIGGER_AFTER, pTab, regOldRowid, onError, addr ); /* Repeat the above with the next record to be updated, until ** all record selected by the WHERE clause have been updated. */ sqlite3VdbeAddOp2( v, OP_Goto, 0, addr ); sqlite3VdbeJumpHere( v, addr ); /* Close all tables */ for ( i = 0, pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext, i++ ) { if ( openAll || aRegIdx[i] > 0 ) { sqlite3VdbeAddOp2( v, OP_Close, iCur + i + 1, 0 ); } } sqlite3VdbeAddOp2( v, OP_Close, iCur, 0 ); /* Update the sqlite_sequence table by storing the content of the ** maximum rowid counter values recorded while inserting into ** autoincrement tables. */ if ( pParse.nested == 0 && pParse.pTriggerTab == null ) { sqlite3AutoincrementEnd( pParse ); } /* ** Return the number of rows that were changed. If this routine is ** generating code because of a call to sqlite3NestedParse(), do not ** invoke the callback function. */ if ( ( db.flags & SQLITE_CountRows ) != 0 && null == pParse.pTriggerTab && 0 == pParse.nested ) { sqlite3VdbeAddOp2( v, OP_ResultRow, regRowCount, 1 ); sqlite3VdbeSetNumCols( v, 1 ); sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC ); } update_cleanup: #if !SQLITE_OMIT_AUTHORIZATION sqlite3AuthContextPop(sContext); #endif sqlite3DbFree( db, ref aRegIdx ); sqlite3DbFree( db, ref aXRef ); sqlite3SrcListDelete( db, ref pTabList ); sqlite3ExprListDelete( db, ref pChanges ); sqlite3ExprDelete( db, ref pWhere ); return; } /* Make sure "isView" and other macros defined above are undefined. Otherwise ** thely may interfere with compilation of other functions in this file ** (or in another file, if this file becomes part of the amalgamation). */ //#if isView // #undef isView //#endif //#if pTrigger // #undef pTrigger //#endif #if !SQLITE_OMIT_VIRTUALTABLE /* ** Generate code for an UPDATE of a virtual table. ** ** The strategy is that we create an ephemerial table that contains ** for each row to be changed: ** ** (A) The original rowid of that row. ** (B) The revised rowid for the row. (note1) ** (C) The content of every column in the row. ** ** Then we loop over this ephemeral table and for each row in ** the ephermeral table call VUpdate. ** ** When finished, drop the ephemeral table. ** ** (note1) Actually, if we know in advance that (A) is always the same ** as (B) we only store (A), then duplicate (A) when pulling ** it out of the ephemeral table before calling VUpdate. */ static void updateVirtualTable( Parse pParse, /* The parsing context */ SrcList pSrc, /* The virtual table to be modified */ Table pTab, /* The virtual table */ ExprList pChanges, /* The columns to change in the UPDATE statement */ Expr pRowid, /* Expression used to recompute the rowid */ int[] aXRef, /* Mapping from columns of pTab to entries in pChanges */ Expr pWhere, /* WHERE clause of the UPDATE statement */ int onError /* ON CONFLICT strategy */ ) { Vdbe v = pParse.pVdbe; /* Virtual machine under construction */ ExprList pEList = null; /* The result set of the SELECT statement */ Select pSelect = null; /* The SELECT statement */ Expr pExpr; /* Temporary expression */ int ephemTab; /* Table holding the result of the SELECT */ int i; /* Loop counter */ int addr; /* Address of top of loop */ int iReg; /* First register in set passed to OP_VUpdate */ sqlite3 db = pParse.db; /* Database connection */ VTable pVTab = sqlite3GetVTable( db, pTab ); SelectDest dest = new SelectDest(); /* Construct the SELECT statement that will find the new values for ** all updated rows. */ pEList = sqlite3ExprListAppend( pParse, 0, sqlite3Expr( db, TK_ID, "_rowid_" ) ); if ( pRowid != null) { pEList = sqlite3ExprListAppend( pParse, pEList, sqlite3ExprDup( db, pRowid, 0 ) ); } Debug.Assert( pTab.iPKey < 0 ); for ( i = 0; i < pTab.nCol; i++ ) { if ( aXRef[i] >= 0 ) { pExpr = sqlite3ExprDup( db, pChanges.a[aXRef[i]].pExpr, 0 ); } else { pExpr = sqlite3Expr( db, TK_ID, pTab.aCol[i].zName ); } pEList = sqlite3ExprListAppend( pParse, pEList, pExpr ); } pSelect = sqlite3SelectNew( pParse, pEList, pSrc, pWhere, null, null, null, 0, null, null ); /* Create the ephemeral table into which the update results will ** be stored. */ Debug.Assert( v != null); ephemTab = pParse.nTab++; sqlite3VdbeAddOp2( v, OP_OpenEphemeral, ephemTab, pTab.nCol + 1 + ( ( pRowid != null ) ? 1 : 0 ) ); sqlite3VdbeChangeP5( v, BTREE_UNORDERED ); /* fill the ephemeral table */ sqlite3SelectDestInit( dest, SRT_Table, ephemTab ); sqlite3Select( pParse, pSelect, ref dest ); /* Generate code to scan the ephemeral table and call VUpdate. */ iReg = ++pParse.nMem; pParse.nMem += pTab.nCol + 1; addr = sqlite3VdbeAddOp2( v, OP_Rewind, ephemTab, 0 ); sqlite3VdbeAddOp3( v, OP_Column, ephemTab, 0, iReg ); sqlite3VdbeAddOp3( v, OP_Column, ephemTab, ( pRowid != null ? 1 : 0 ), iReg + 1 ); for ( i = 0; i < pTab.nCol; i++ ) { sqlite3VdbeAddOp3( v, OP_Column, ephemTab, i + 1 + ( ( pRowid != null ) ? 1 : 0 ), iReg + 2 + i ); } sqlite3VtabMakeWritable( pParse, pTab ); sqlite3VdbeAddOp4( v, OP_VUpdate, 0, pTab.nCol + 2, iReg, pVTab, P4_VTAB ); sqlite3VdbeChangeP5( v, (byte)( onError == OE_Default ? OE_Abort : onError ) ); sqlite3MayAbort( pParse ); sqlite3VdbeAddOp2( v, OP_Next, ephemTab, addr + 1 ); sqlite3VdbeJumpHere( v, addr ); sqlite3VdbeAddOp2( v, OP_Close, ephemTab, 0 ); /* Cleanup */ sqlite3SelectDelete( db, ref pSelect ); } #endif // * SQLITE_OMIT_VIRTUALTABLE */ } }
using System; using System.IO; using System.Text.Encodings.Web; using System.Threading.Tasks; using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Mvc.TagHelpers.Cache; using Microsoft.AspNetCore.Razor.TagHelpers; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Options; using OrchardCore.DisplayManagement; using OrchardCore.Environment.Cache; namespace OrchardCore.DynamicCache.TagHelpers { [HtmlTargetElement("dynamic-cache", Attributes = CacheIdAttributeName)] public class DynamicCacheTagHelper : TagHelper { private const string CacheIdAttributeName = "cache-id"; private const string VaryByAttributeName = "vary-by"; private const string DependenciesAttributeNAme = "dependencies"; private const string ExpiresOnAttributeName = "expires-on"; private const string ExpiresAfterAttributeName = "expires-after"; private const string ExpiresSlidingAttributeName = "expires-sliding"; private const string EnabledAttributeName = "enabled"; private static readonly char[] SplitChars = new[] { ',', ' ' }; /// <summary> /// The default duration, from the time the cache entry was added, when it should be evicted. /// This default duration will only be used if no other expiration criteria is specified. /// The default expiration time is a sliding expiration of 30 seconds. /// </summary> public static readonly TimeSpan DefaultExpiration = TimeSpan.FromSeconds(30); /// <summary> /// Gets the <see cref="System.Text.Encodings.Web.HtmlEncoder"/> which encodes the content to be cached. /// </summary> protected HtmlEncoder HtmlEncoder { get; } /// <summary> /// Gets or sets a <see cref="string" /> identifying this cache entry. /// </summary> [HtmlAttributeName(CacheIdAttributeName)] public string CacheId { get; set; } /// <summary> /// Gets or sets a <see cref="string" /> to vary the cached result by. /// </summary> [HtmlAttributeName(VaryByAttributeName)] public string VaryBy { get; set; } /// <summary> /// Gets or sets a <see cref="string" /> with the dependencies to invalidate the cache with. /// </summary> [HtmlAttributeName(DependenciesAttributeNAme)] public string Dependencies { get; set; } /// <summary> /// Gets or sets the exact <see cref="DateTimeOffset"/> the cache entry should be evicted. /// </summary> [HtmlAttributeName(ExpiresOnAttributeName)] public DateTimeOffset? ExpiresOn { get; set; } /// <summary> /// Gets or sets the duration, from the time the cache entry was added, when it should be evicted. /// </summary> [HtmlAttributeName(ExpiresAfterAttributeName)] public TimeSpan? ExpiresAfter { get; set; } /// <summary> /// Gets or sets the duration from last access that the cache entry should be evicted. /// </summary> [HtmlAttributeName(ExpiresSlidingAttributeName)] public TimeSpan? ExpiresSliding { get; set; } /// <summary> /// Gets or sets the value which determines if the tag helper is enabled or not. /// </summary> [HtmlAttributeName(EnabledAttributeName)] public bool Enabled { get; set; } = true; /// <summary> /// Prefix used by <see cref="CacheTagHelper"/> instances when creating entries in <see cref="IDynamicCacheService"/>. /// </summary> public static readonly string CacheKeyPrefix = nameof(DynamicCacheTagHelper); private const string CachePriorityAttributeName = "priority"; private readonly IDynamicCacheService _dynamicCacheService; private readonly ICacheScopeManager _cacheScopeManager; private readonly DynamicCacheTagHelperService _dynamicCacheTagHelperService; private readonly CacheOptions _cacheOptions; public DynamicCacheTagHelper( IDynamicCacheService dynamicCacheService, ICacheScopeManager cacheScopeManager, HtmlEncoder htmlEncoder, DynamicCacheTagHelperService dynamicCacheTagHelperService, IOptions<CacheOptions> cacheOptions) { _dynamicCacheService = dynamicCacheService; _cacheScopeManager = cacheScopeManager; HtmlEncoder = htmlEncoder; _dynamicCacheTagHelperService = dynamicCacheTagHelperService; _cacheOptions = cacheOptions.Value; } /// <summary> /// Gets the <see cref="IMemoryCache"/> instance used to cache entries. /// </summary> protected IMemoryCache MemoryCache { get; } /// <summary> /// Gets or sets the <see cref="CacheItemPriority"/> policy for the cache entry. /// </summary> [HtmlAttributeName(CachePriorityAttributeName)] public CacheItemPriority? Priority { get; set; } /// <inheritdoc /> public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (output == null) { throw new ArgumentNullException(nameof(output)); } IHtmlContent content; if (Enabled) { var cacheContext = new CacheContext(CacheId); if (!String.IsNullOrEmpty(VaryBy)) { cacheContext.AddContext(VaryBy.Split(SplitChars, StringSplitOptions.RemoveEmptyEntries)); } if (!String.IsNullOrEmpty(Dependencies)) { cacheContext.AddTag(Dependencies.Split(SplitChars, StringSplitOptions.RemoveEmptyEntries)); } var hasEvictionCriteria = false; if (ExpiresOn.HasValue) { hasEvictionCriteria = true; cacheContext.WithExpiryOn(ExpiresOn.Value); } if (ExpiresAfter.HasValue) { hasEvictionCriteria = true; cacheContext.WithExpiryAfter(ExpiresAfter.Value); } if (ExpiresSliding.HasValue) { hasEvictionCriteria = true; cacheContext.WithExpirySliding(ExpiresSliding.Value); } if (!hasEvictionCriteria) { cacheContext.WithExpirySliding(DefaultExpiration); } _cacheScopeManager.EnterScope(cacheContext); try { content = await ProcessContentAsync(output, cacheContext); } finally { _cacheScopeManager.ExitScope(); } } else { content = await output.GetChildContentAsync(); } // Clear the contents of the "cache" element since we don't want to render it. output.SuppressOutput(); output.Content.SetHtmlContent(content); } public async Task<IHtmlContent> ProcessContentAsync(TagHelperOutput output, CacheContext cacheContext) { IHtmlContent content = null; while (content == null) { Task<IHtmlContent> result; // Is there any request already processing the value? if (!_dynamicCacheTagHelperService.Workers.TryGetValue(CacheId, out result)) { // There is a small race condition here between TryGetValue and TryAdd that might cause the // content to be computed more than once. We don't care about this race as the probability of // happening is very small and the impact is not critical. var tcs = new TaskCompletionSource<IHtmlContent>(); _dynamicCacheTagHelperService.Workers.TryAdd(CacheId, tcs.Task); try { var value = await _dynamicCacheService.GetCachedValueAsync(cacheContext); if (value == null) { // The value is not cached, we need to render the tag helper output var processedContent = await output.GetChildContentAsync(); using (var sb = StringBuilderPool.GetInstance()) { using (var writer = new StringWriter(sb.Builder)) { // Write the start of a cache debug block. if (_cacheOptions.DebugMode) { // No need to optimize this code as it will be used for debugging purpose. writer.WriteLine(); writer.WriteLine($"<!-- CACHE BLOCK: {cacheContext.CacheId} ({Guid.NewGuid()})"); writer.WriteLine($" VARY BY: {String.Join(", ", cacheContext.Contexts)}"); writer.WriteLine($" DEPENDENCIES: {String.Join(", ", cacheContext.Tags)}"); writer.WriteLine($" EXPIRES ON: {cacheContext.ExpiresOn}"); writer.WriteLine($" EXPIRES AFTER: {cacheContext.ExpiresAfter}"); writer.WriteLine($" EXPIRES SLIDING: {cacheContext.ExpiresSliding}"); writer.WriteLine("-->"); } // Always write the content regardless of debug mode. processedContent.WriteTo(writer, HtmlEncoder); // Write the end of a cache debug block. if (_cacheOptions.DebugMode) { writer.WriteLine(); writer.WriteLine($"<!-- END CACHE BLOCK: {cacheContext.CacheId} -->"); } await writer.FlushAsync(); } var html = sb.Builder.ToString(); var formattingContext = new DistributedCacheTagHelperFormattingContext { Html = new HtmlString(html) }; await _dynamicCacheService.SetCachedValueAsync(cacheContext, html); content = formattingContext.Html; } } else { content = new HtmlString(value); } } catch { content = null; throw; } finally { // Remove the worker task before setting the result. // If the result is null, other threads would potentially // acquire it otherwise. _dynamicCacheTagHelperService.Workers.TryRemove(CacheId, out result); // Notify all other awaiters to render the content tcs.TrySetResult(content); } } else { content = await result; } } return content; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Security; using System.Text; using System.Windows.Forms; using System.Xml; namespace Localizer { /// <summary> /// By Opata Chibueze. August 2013 /// Easily localize your Windows Forms apps /// todo: Use an online translation tool to automatically translate extracted resource file output /// todo: Correct progress bar for better syncing /// todo: Develop better naming algorithm for variables /// todo: Implement for multiple contstructors in forms /// </summary> public partial class Form1 : Form { private string directoryName; private Dictionary<string, string> duplicates; private Dictionary<string, List<string>> files; private Dictionary<string, string[]> found; private Dictionary<string, string> variables; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { if (buttonLoad.Text != Localizer.myLocalizer.Form1buttonLoadTextLocalize) { if (ofd.ShowDialog() == DialogResult.OK) { dataGridView1.Rows.Clear(); variables = new Dictionary<string, string>(); duplicates = new Dictionary<string, string>(); files = new Dictionary<string, List<string>>(); found = new Dictionary<string, string[]>(); directoryName = Path.GetDirectoryName(ofd.FileName); if (directoryName == null) return; //Let's process designer codes first if specified if (checkBox1.Checked) { foreach (string s in Directory.EnumerateFiles(directoryName, "*.Designer.cs")) { var lines = new List<string>(); foreach (string line in File.ReadAllLines(s)) { if (line.Contains(".Name")) continue; //ignore names if (line.Contains("= \"")) { lines.Add(line.Trim()); } } string oFile = s.Replace("Designer.", ""); if (!File.Exists(oFile)) continue; string formCode = File.ReadAllText(oFile); if (formCode.Contains("InitializeUI()")) continue; //processed before, skip int init = formCode.IndexOf("InitializeComponent();", StringComparison.Ordinal) + 22; int endtag = formCode.IndexOf('}', init); int begintag = formCode.IndexOf('{', init); while (begintag != -1 && begintag < endtag) { begintag = formCode.IndexOf('{', begintag + 1); endtag = formCode.IndexOf('}', endtag + 1); } formCode = formCode.Remove(endtag, 1); File.WriteAllText(oFile, formCode.Insert(endtag, string.Format(@" InitializeUI(); }} private void InitializeUI() {{ {0} }}", String.Join(Environment.NewLine + " ", lines)))); } } foreach (string s in Directory.EnumerateFiles(directoryName, "*.cs")) { if (checkBox1.Checked && s.EndsWith("Designer.cs")) { //already processed ignore continue; } string tempName = Path.GetFileNameWithoutExtension(s); string allText = File.ReadAllText(s); //extract strings string[] splits = allText.Split('"'); found.Add(s, splits); int last = 0; for (int i = 1; i < splits.Length; i += 2) { try { string text = splits[i]; //we don't need to localize paths, links or empty strings if (text.Trim() == String.Empty || text.Contains(":\\") || text.StartsWith("http:")) continue; int fi = allText.IndexOf('"' + text + '"', last, StringComparison.Ordinal); last = fi + text.Length; int index = allText.LastIndexOf('=', fi); int sindex = allText.LastIndexOf(" ", index, StringComparison.Ordinal); switch (allText[fi - 1]) { case '\'': i -= 1; //account for fake trail continue; //this is probably a character, not a string. get out... case '@': text = "@" + text; allText = allText.Remove(fi - 1, 1); break; } //create variable name var sb = new StringBuilder(); for (int t = sindex;; t--) { if (Char.IsLetter(allText[t])) { sb.Append(allText[t]); } else { if (allText[t] == '/' || allText[t] == '<') { sb.Clear(); //comment zone, let's get out break; } if (allText[t] == '.') { continue; } if (sb.Length != 0) break; } } if (sb.Length == 0) continue; char[] array = sb.ToString().Trim().ToCharArray(); Array.Reverse(array); string varname = tempName + new string(array) + text.Split(' ')[0].CleanString().Replace(".", ""); while (variables.ContainsKey(varname)) { varname += 1; } if (variables.ContainsValue(text)) { if (!duplicates.ContainsKey(text)) duplicates.Add(text, variables.First(n => n.Value == text).Key); } variables.Add(varname, text); if (files.ContainsKey(s)) { files[s].Add(varname); } else { files.Add(s, new List<string>(new[] {varname})); } progressBar1.Value = Convert.ToInt32((i + 0.0D)/splits.Length*100); //todo: Use text content as summary info for variable //this makes it easier to work with localized strings dataGridView1.Rows.Add(new object[] {varname, text}); } catch (ArgumentOutOfRangeException) { //todo: anaylze possible causes } } } progressBar1.Value = 100; buttonLoad.Text = Localizer.myLocalizer.Form1buttonLoadTextLocalize; } } else { if (!Directory.Exists(directoryName + ".backup")) { Directory.CreateDirectory(directoryName + ".backup"); //let's backup first foreach (string sf in Directory.EnumerateFiles(directoryName)) { File.Copy(sf, directoryName + ".backup\\" + Path.GetFileName(sf)); } } string namesp = Localizer.myLocalizer.Form1namespGlobalizer; var document = new XmlDocument(); var ns = new XmlNamespaceManager(document.NameTable); ns.AddNamespace("msbld", "http://schemas.microsoft.com/developer/msbuild/2003"); document.Load(ofd.FileName); if (document.DocumentElement != null) { XmlNode node = document.DocumentElement.SelectSingleNode("//msbld:RootNamespace", ns); if (node != null) { namesp = node.InnerText; } } variables.Clear(); foreach (DataGridViewRow row in dataGridView1.Rows) { if (row.Cells[0].Value == null || row.Cells[1].Value == null) continue; variables.Add(row.Cells[0].Value.ToString(), row.Cells[1].Value.ToString()); } foreach (var entry in files) { string newText = File.ReadAllText(entry.Key); foreach (string v in entry.Value) { if (variables.ContainsKey(v)) { //replace text with variable name newText = newText.Replace('"' + variables[v] + '"', "Localizer.myLocalizer." + v); } } File.WriteAllText(entry.Key, newText); } #region Spoiler Write Localizer File.WriteAllText(directoryName + "\\Localizer.cs", string.Format(@"using System; using System.IO; using System.Xml.Serialization; namespace {0} {{ /// <summary> /// Provides a model for localizing application /// </summary> public class Localizer {{ /// <summary> /// Default constructor /// </summary> public Localizer() {{ Language = ""en""; }} /// <summary> /// Public constructor for Localizer with default language initialization /// </summary> /// <param name=""lang"">The language key to intialize</param> public Localizer(string lang) {{ Language = lang; }} private static Localizer _localizer; internal static Localizer myLocalizer {{ set {{ _localizer = value; }} get {{ return _localizer; }} }} /// <summary> /// Contains the current language /// </summary> public static string Language; /// <summary> /// Serializes the language resources file /// </summary> /// <param name=""locals"">The language resource object to serialize</param> public void Serialize(Localizer locals) {{ try {{ var xs = new XmlSerializer(typeof(Localizer)); using (TextWriter tw = new StreamWriter(""locals.resources."" + Language)) {{ xs.Serialize(tw, locals); }} }} catch(Exception ex) {{ throw new Exception(""An error occurred while trying to save the language resources. Please try again."", ex.InnerException); }} }} /// <summary> /// Returns the string in the original form if it was previously escaped /// </summary> /// <param name=""s"">The string to unescape</param> /// <returns>The unescaped string</returns> public static string UnEscapeXml(string s) {{ if (string.IsNullOrEmpty(s)) return s; string output = s; output = output.Replace(""&apos;"", ""'"") .Replace(""&quot;"", ""\"""") .Replace(""&gt;"", "">"") .Replace(""&lt;"", ""<"") .Replace(""&amp;"", ""&""); return output; }} /// <summary> /// De-Serializes the language resource file. /// </summary> /// <returns>The language resource object returned form the XML Deserialization</returns> public Localizer Deserialize() {{ if (!File.Exists(""locals.resources.""+Language)) return null; var xs = new XmlSerializer(typeof (Localizer)); using (FileStream fs = File.Open(""locals.resources.""+Language, FileMode.Open)) {{ return xs.Deserialize(fs) as Localizer; }} }} {1} }} }}", namesp, ExpandVariables())); #endregion File.WriteAllText(directoryName + "\\locals.resources.en", @"<?xml version=""1.0"" encoding=""utf-8""?> <Localizer xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">" + ExpandResources() + "</Localizer>"); string allText = File.ReadAllText(ofd.FileName); File.WriteAllText(ofd.FileName, allText.Insert(allText.IndexOf("<Compile", StringComparison.Ordinal), @" <Compile Include=""Localizer.cs"" /> <Content Include=""locals.resources.en""> <CopyToOutputDirectory>Always</CopyToOutputDirectory> </Content>")); //todo: Try detect actual file that contains entry point if not if (File.Exists(directoryName + "\\Program.cs")) { string entry = File.ReadAllText(directoryName + "\\Program.cs"); int isert = entry.IndexOf("static void Main(", StringComparison.Ordinal); File.WriteAllText(directoryName + "\\Program.cs", entry.Insert(entry.IndexOf("{", isert, StringComparison.Ordinal) + 1, @" Localizer.myLocalizer = new Localizer(""en""); Localizer.myLocalizer = Localizer.myLocalizer.Deserialize(); ")); } MessageBox.Show( Localizer.myLocalizer.Form1LocalizermyLocalizerYour, Localizer.myLocalizer.Form1LocalizermyLocalizerLocalization, MessageBoxButtons.OK, MessageBoxIcon.Information); buttonLoad.Text = Localizer.myLocalizer.Form1buttonLoadTextLoad; Process.Start("explorer.exe", directoryName); } } internal string ExpandVariables() { string output = ""; foreach (var v in variables) { output += string.Format("{0}/// <summary>{2}{0}///Original: {3}{2}{0}///Returns unescaped _{1}{2}{0}/// </summary>{2}{0}[XmlIgnore]{2}{0}public string {1}", " ", v.Key, Environment.NewLine, v.Value.EscapeXml()); output += string.Format(@" {{ get {{ return UnEscapeXml(_{0}); }} }} /// <summary> /// Serializer for {0} /// </summary> public string _{0}; " + Environment.NewLine, v.Key); } return output; } internal string ExpandResources() { string output = ""; foreach (var v in variables) { output += string.Format(@" <{0}>{1}</{0}>", v.Key, v.Value.EscapeXml()) + Environment.NewLine; } return output; } private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e) { string key = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString(); variables[key] = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString(); } private void labelStatus_Click(object sender, EventArgs e) { buttonLoad.Text = Localizer.myLocalizer.Form1buttonLoadTextLoad; } } internal static class Utils { private static readonly bool[] BadCharValues; static Utils() { BadCharValues = new bool[char.MaxValue + 1]; foreach (char c in @"[!@#$%^&~`(|)=+-<>?,._]*/\\;:{}'") BadCharValues[c] = true; } public static string CleanString(this string str) { var result = new StringBuilder(str.Length); for (int i = 0; i < str.Length; i++) { if (!BadCharValues[str[i]]) result.Append(str[i]); } return result.ToString(); } /// <summary> /// Escapes a string to make it valid xml if needed /// </summary> /// <param name="s">The string to convert</param> /// <returns>The escaped string</returns> public static string EscapeXml(this string s) { if (string.IsNullOrEmpty(s)) return s; return SecurityElement.Escape(s); } } }
using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Web.UI.WebControls; namespace YAF.Pages.Admin { #region Using using System; using System.Data; using VZF.Data.Common; using YAF.Core; using YAF.Core.Services; using YAF.Types; using YAF.Types.Constants; using YAF.Types.Flags; using YAF.Types.Interfaces; using VZF.Utils; using VZF.Utils.Helpers; #endregion /// <summary> /// Summary description for WebForm1. /// </summary> public partial class pageaccessedit : AdminPage { /* Construction */ #region Methods /// <summary> /// The cancel_ click. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> protected void Cancel_Click([NotNull] object sender, [NotNull] EventArgs e) { // get back to access admin list YafBuildLink.Redirect(ForumPages.admin_pageaccesslist); } /// <summary> /// Creates navigation page links on top of forum (breadcrumbs). /// </summary> protected override void CreatePageLinks() { // beard index this.PageLinks.AddLink(this.PageContext.BoardSettings.Name, YafBuildLink.GetLink(ForumPages.forum)); // administration index this.PageLinks.AddLink(this.GetText("ADMIN_ADMIN", "Administration"), YafBuildLink.GetLink(ForumPages.admin_admin)); // current page label (no link) this.PageLinks.AddLink(this.GetText("ADMIN_PAGEACCESSEDIT", "TITLE"), string.Empty); this.Page.Header.Title = "{0} - {1} - {2}".FormatWith( this.GetText("ADMIN_ADMIN", "Administration"), this.GetText("ADMIN_PAGEACCESSLIST", "TITLE"), this.GetText("ADMIN_PAGEACCESSEDIT", "TITLE")); } /* Event Handlers */ /// <summary> /// The page_ load. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e) { if (this.IsPostBack) { return; } this.Save.Text = this.GetText("ADMIN_PAGEACCESSEDIT", "SAVE"); this.Cancel.Text = this.GetText("ADMIN_PAGEACCESSEDIT", "CANCEL"); this.GrantAll.Text = this.GetText("ADMIN_PAGEACCESSEDIT", "GRANTALL"); this.RevokeAll.Text = this.GetText("ADMIN_PAGEACCESSEDIT", "REVOKEALL"); // create page links this.CreatePageLinks(); // bind data this.BindData(); } /// <summary> /// The save_ click. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> protected void Save_Click([NotNull] object sender, [NotNull] EventArgs e) { // retrieve access mask ID from parameter (if applicable) if (this.Request.QueryString.GetFirstOrDefault("u") != null) { object userId = this.Request.QueryString.GetFirstOrDefault("u"); foreach (RepeaterItem ri in this.AccessList.Items) { bool readAccess = ((CheckBox) ri.FindControl("ReadAccess")).Checked; string pageName = ((Label) ri.FindControl("PageName")).Text.Trim(); if (readAccess || "admin_admin".ToLowerInvariant() == pageName.ToLowerInvariant()) { // save it CommonDb.adminpageaccess_save(PageContext.PageModuleID, userId, pageName); } else { CommonDb.adminpageaccess_delete(PageContext.PageModuleID, userId, pageName); } } YafBuildLink.Redirect(ForumPages.admin_pageaccesslist); } } /// <summary> /// The Grant All click. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> protected void GrantAll_Click([NotNull] object sender, [NotNull] EventArgs e) { // save permissions to table - checked only if (this.Request.QueryString.GetFirstOrDefault("u") != null) { object userId = this.Request.QueryString.GetFirstOrDefault("u"); foreach (RepeaterItem ri in this.AccessList.Items) { // save it CommonDb.adminpageaccess_save(PageContext.PageModuleID, userId, ((Label)ri.FindControl("PageName")).Text.Trim()); } } YafBuildLink.Redirect(ForumPages.admin_pageaccesslist); } /// <summary> /// The RevokeAll _Click. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> protected void RevokeAll_Click([NotNull] object sender, [NotNull] EventArgs e) { // revoke permissions by deleting records from table. Number of records ther should be minimal. if (this.Request.QueryString.GetFirstOrDefault("u") != null) { object userId = this.Request.QueryString.GetFirstOrDefault("u"); foreach (RepeaterItem ri in this.AccessList.Items) { string pageName = ((Label) ri.FindControl("PageName")).Text.Trim(); // save it - admin index should be always available if ("admin_admin".ToLowerInvariant() != pageName.ToLowerInvariant()) { CommonDb.adminpageaccess_delete(PageContext.PageModuleID, userId, ((Label) ri.FindControl("PageName")).Text.Trim()); } } } YafBuildLink.Redirect(ForumPages.admin_pageaccesslist); } /* Methods */ /// <summary> /// The bind data. /// </summary> private void BindData() { bool found = false; if (this.Request.QueryString.GetFirstOrDefault("u") != null) { // Load the page access list. DataTable dt = CommonDb.adminpageaccess_list(PageContext.PageModuleID, this.Request.QueryString.GetFirstOrDefault("u"), null); // Get admin pages by page prefixes. var listPages = Enum.GetNames(typeof(ForumPages)).Where( e => e.IndexOf("admin_", System.StringComparison.Ordinal) >= 0); // Initialize list with a helper class. var adminPageAccesses = new List<AdminPageAccess>(); // Protected hostadmin pages var hostPages = new[] { "admin_boards", "admin_hostsettings", "admin_pageaccesslist", "admin_pageaccessedit", "admin_eventloggroups", "admin_eventloggroupaccess" }; // Iterate thru all admin pages foreach (var listPage in listPages.ToList()) { if (dt != null && dt.Rows.Cast<DataRow>().Any(dr => dr["PageName"].ToString() == listPage && hostPages.All(s => s != dr["PageName"].ToString()))) { found = true; adminPageAccesses.Add(new AdminPageAccess { UserId = this.Request.QueryString.GetFirstOrDefault("u").ToType<int>(), PageName = listPage, ReadAccess = true }); } // If it doesn't contain page for the user add it. if (!found && hostPages.All(s => s != listPage)) { adminPageAccesses.Add(new AdminPageAccess { UserId = this.Request.QueryString.GetFirstOrDefault("u").ToType<int>(), PageName = listPage, ReadAccess = false }); } // Reset flag in the end of the outer loop found = false; } this.UserName.Text = this.HtmlEncode(this.Get<IUserDisplayName>().GetName(this.Request.QueryString.GetFirstOrDefault("u").ToType<int>())); // get admin pages list with access flags. this.AccessList.DataSource = adminPageAccesses.AsEnumerable(); } this.DataBind(); } /// <summary> /// The PollGroup item command. /// </summary> /// <param name="source"> /// The source. /// </param> /// <param name="e"> /// The e. /// </param> protected void AccessList_OnItemDataBound([NotNull] object source, [NotNull] RepeaterItemEventArgs e) { RepeaterItem item = e.Item; var drowv = (AdminPageAccess)e.Item.DataItem; if (item.ItemType != ListItemType.Item && item.ItemType != ListItemType.AlternatingItem) return; var pageName = item.FindControlRecursiveAs<Label>("PageName"); var pageText = item.FindControlRecursiveAs<Label>("PageText"); var readAccess = item.FindControlRecursiveAs<CheckBox>("ReadAccess"); pageText.Text = this.GetText("ACTIVELOCATION", drowv.PageName.ToUpperInvariant()); pageName.Text = drowv.PageName; readAccess.Checked = drowv.ReadAccess; } #endregion } /// <summary> /// Provides a common wrapper for variables of various origins. /// </summary> internal class AdminPageAccess { internal int UserId { get; set; } internal string PageName { get; set; } internal bool ReadAccess { get; set; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Net; using System.Text; using OpenMetaverse; using OpenMetaverse.Imaging; using OpenMetaverse.Packets; using OpenSim.Framework; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Client.VWoHTTP.ClientStack { class VWHClientView : IClientAPI { private Scene m_scene; public bool ProcessInMsg(OSHttpRequest req, OSHttpResponse resp) { // 0 1 2 3 // http://simulator.com:9000/vwohttp/sessionid/methodname/param string[] urlparts = req.Url.AbsolutePath.Split(new char[] {'/'}, StringSplitOptions.RemoveEmptyEntries); UUID sessionID; // Check for session if (!UUID.TryParse(urlparts[1], out sessionID)) return false; // Check we match session if (sessionID != SessionId) return false; string method = urlparts[2]; string param = String.Empty; if (urlparts.Length > 3) param = urlparts[3]; bool found; switch (method.ToLower()) { case "textures": found = ProcessTextureRequest(param, resp); break; default: found = false; break; } return found; } private bool ProcessTextureRequest(string param, OSHttpResponse resp) { UUID assetID; if (!UUID.TryParse(param, out assetID)) return false; AssetBase asset = m_scene.AssetService.Get(assetID.ToString()); if (asset == null) return false; ManagedImage tmp; Image imgData; byte[] jpegdata; OpenJPEG.DecodeToImage(asset.Data, out tmp, out imgData); using (MemoryStream ms = new MemoryStream()) { imgData.Save(ms, ImageFormat.Jpeg); jpegdata = ms.GetBuffer(); } resp.ContentType = "image/jpeg"; resp.ContentLength = jpegdata.Length; resp.StatusCode = 200; resp.Body.Write(jpegdata, 0, jpegdata.Length); return true; } public VWHClientView(UUID sessionID, UUID agentID, string agentName, Scene scene) { m_scene = scene; } #region Implementation of IClientAPI public Vector3 StartPos { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public UUID AgentId { get { throw new System.NotImplementedException(); } } public UUID SessionId { get { throw new System.NotImplementedException(); } } public UUID SecureSessionId { get { throw new System.NotImplementedException(); } } public UUID ActiveGroupId { get { throw new System.NotImplementedException(); } } public string ActiveGroupName { get { throw new System.NotImplementedException(); } } public ulong ActiveGroupPowers { get { throw new System.NotImplementedException(); } } public ulong GetGroupPowers(UUID groupID) { throw new System.NotImplementedException(); } public bool IsGroupMember(UUID GroupID) { throw new System.NotImplementedException(); } public string FirstName { get { throw new System.NotImplementedException(); } } public string LastName { get { throw new System.NotImplementedException(); } } public IScene Scene { get { throw new System.NotImplementedException(); } } public int NextAnimationSequenceNumber { get { throw new System.NotImplementedException(); } } public string Name { get { throw new System.NotImplementedException(); } } public bool IsActive { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public bool SendLogoutPacketWhenClosing { set { throw new System.NotImplementedException(); } } public uint CircuitCode { get { throw new System.NotImplementedException(); } } public IPEndPoint RemoteEndPoint { get { throw new System.NotImplementedException(); } } public event GenericMessage OnGenericMessage = delegate { }; public event ImprovedInstantMessage OnInstantMessage = delegate { }; public event ChatMessage OnChatFromClient = delegate { }; public event TextureRequest OnRequestTexture = delegate { }; public event RezObject OnRezObject = delegate { }; public event ModifyTerrain OnModifyTerrain = delegate { }; public event BakeTerrain OnBakeTerrain = delegate { }; public event EstateChangeInfo OnEstateChangeInfo = delegate { }; public event SetAppearance OnSetAppearance = delegate { }; public event AvatarNowWearing OnAvatarNowWearing = delegate { }; public event RezSingleAttachmentFromInv OnRezSingleAttachmentFromInv = delegate { return new UUID(); }; public event RezMultipleAttachmentsFromInv OnRezMultipleAttachmentsFromInv = delegate { }; public event UUIDNameRequest OnDetachAttachmentIntoInv = delegate { }; public event ObjectAttach OnObjectAttach = delegate { }; public event ObjectDeselect OnObjectDetach = delegate { }; public event ObjectDrop OnObjectDrop = delegate { }; public event StartAnim OnStartAnim = delegate { }; public event StopAnim OnStopAnim = delegate { }; public event LinkObjects OnLinkObjects = delegate { }; public event DelinkObjects OnDelinkObjects = delegate { }; public event RequestMapBlocks OnRequestMapBlocks = delegate { }; public event RequestMapName OnMapNameRequest = delegate { }; public event TeleportLocationRequest OnTeleportLocationRequest = delegate { }; public event DisconnectUser OnDisconnectUser = delegate { }; public event RequestAvatarProperties OnRequestAvatarProperties = delegate { }; public event SetAlwaysRun OnSetAlwaysRun = delegate { }; public event TeleportLandmarkRequest OnTeleportLandmarkRequest = delegate { }; public event DeRezObject OnDeRezObject = delegate { }; public event Action<IClientAPI> OnRegionHandShakeReply = delegate { }; public event GenericCall2 OnRequestWearables = delegate { }; public event GenericCall2 OnCompleteMovementToRegion = delegate { }; public event UpdateAgent OnAgentUpdate = delegate { }; public event AgentRequestSit OnAgentRequestSit = delegate { }; public event AgentSit OnAgentSit = delegate { }; public event AvatarPickerRequest OnAvatarPickerRequest = delegate { }; public event Action<IClientAPI> OnRequestAvatarsData = delegate { }; public event AddNewPrim OnAddPrim = delegate { }; public event FetchInventory OnAgentDataUpdateRequest = delegate { }; public event TeleportLocationRequest OnSetStartLocationRequest = delegate { }; public event RequestGodlikePowers OnRequestGodlikePowers = delegate { }; public event GodKickUser OnGodKickUser = delegate { }; public event ObjectDuplicate OnObjectDuplicate = delegate { }; public event ObjectDuplicateOnRay OnObjectDuplicateOnRay = delegate { }; public event GrabObject OnGrabObject = delegate { }; public event DeGrabObject OnDeGrabObject = delegate { }; public event MoveObject OnGrabUpdate = delegate { }; public event SpinStart OnSpinStart = delegate { }; public event SpinObject OnSpinUpdate = delegate { }; public event SpinStop OnSpinStop = delegate { }; public event UpdateShape OnUpdatePrimShape = delegate { }; public event ObjectExtraParams OnUpdateExtraParams = delegate { }; public event ObjectRequest OnObjectRequest = delegate { }; public event ObjectSelect OnObjectSelect = delegate { }; public event ObjectDeselect OnObjectDeselect = delegate { }; public event GenericCall7 OnObjectDescription = delegate { }; public event GenericCall7 OnObjectName = delegate { }; public event GenericCall7 OnObjectClickAction = delegate { }; public event GenericCall7 OnObjectMaterial = delegate { }; public event RequestObjectPropertiesFamily OnRequestObjectPropertiesFamily = delegate { }; public event UpdatePrimFlags OnUpdatePrimFlags = delegate { }; public event UpdatePrimTexture OnUpdatePrimTexture = delegate { }; public event UpdateVector OnUpdatePrimGroupPosition = delegate { }; public event UpdateVector OnUpdatePrimSinglePosition = delegate { }; public event UpdatePrimRotation OnUpdatePrimGroupRotation = delegate { }; public event UpdatePrimSingleRotation OnUpdatePrimSingleRotation = delegate { }; public event UpdatePrimSingleRotationPosition OnUpdatePrimSingleRotationPosition = delegate { }; public event UpdatePrimGroupRotation OnUpdatePrimGroupMouseRotation = delegate { }; public event UpdateVector OnUpdatePrimScale = delegate { }; public event UpdateVector OnUpdatePrimGroupScale = delegate { }; public event StatusChange OnChildAgentStatus = delegate { }; public event GenericCall2 OnStopMovement = delegate { }; public event Action<UUID> OnRemoveAvatar = delegate { }; public event ObjectPermissions OnObjectPermissions = delegate { }; public event CreateNewInventoryItem OnCreateNewInventoryItem = delegate { }; public event CreateInventoryFolder OnCreateNewInventoryFolder = delegate { }; public event UpdateInventoryFolder OnUpdateInventoryFolder = delegate { }; public event MoveInventoryFolder OnMoveInventoryFolder = delegate { }; public event FetchInventoryDescendents OnFetchInventoryDescendents = delegate { }; public event PurgeInventoryDescendents OnPurgeInventoryDescendents = delegate { }; public event FetchInventory OnFetchInventory = delegate { }; public event RequestTaskInventory OnRequestTaskInventory = delegate { }; public event UpdateInventoryItem OnUpdateInventoryItem = delegate { }; public event CopyInventoryItem OnCopyInventoryItem = delegate { }; public event MoveInventoryItem OnMoveInventoryItem = delegate { }; public event RemoveInventoryFolder OnRemoveInventoryFolder = delegate { }; public event RemoveInventoryItem OnRemoveInventoryItem = delegate { }; public event UDPAssetUploadRequest OnAssetUploadRequest = delegate { }; public event XferReceive OnXferReceive = delegate { }; public event RequestXfer OnRequestXfer = delegate { }; public event ConfirmXfer OnConfirmXfer = delegate { }; public event AbortXfer OnAbortXfer = delegate { }; public event RezScript OnRezScript = delegate { }; public event UpdateTaskInventory OnUpdateTaskInventory = delegate { }; public event MoveTaskInventory OnMoveTaskItem = delegate { }; public event RemoveTaskInventory OnRemoveTaskItem = delegate { }; public event RequestAsset OnRequestAsset = delegate { }; public event UUIDNameRequest OnNameFromUUIDRequest = delegate { }; public event ParcelAccessListRequest OnParcelAccessListRequest = delegate { }; public event ParcelAccessListUpdateRequest OnParcelAccessListUpdateRequest = delegate { }; public event ParcelPropertiesRequest OnParcelPropertiesRequest = delegate { }; public event ParcelDivideRequest OnParcelDivideRequest = delegate { }; public event ParcelJoinRequest OnParcelJoinRequest = delegate { }; public event ParcelPropertiesUpdateRequest OnParcelPropertiesUpdateRequest = delegate { }; public event ParcelSelectObjects OnParcelSelectObjects = delegate { }; public event ParcelObjectOwnerRequest OnParcelObjectOwnerRequest = delegate { }; public event ParcelAbandonRequest OnParcelAbandonRequest = delegate { }; public event ParcelGodForceOwner OnParcelGodForceOwner = delegate { }; public event ParcelReclaim OnParcelReclaim = delegate { }; public event ParcelReturnObjectsRequest OnParcelReturnObjectsRequest = delegate { }; public event ParcelDeedToGroup OnParcelDeedToGroup = delegate { }; public event RegionInfoRequest OnRegionInfoRequest = delegate { }; public event EstateCovenantRequest OnEstateCovenantRequest = delegate { }; public event FriendActionDelegate OnApproveFriendRequest = delegate { }; public event FriendActionDelegate OnDenyFriendRequest = delegate { }; public event FriendshipTermination OnTerminateFriendship = delegate { }; public event MoneyTransferRequest OnMoneyTransferRequest = delegate { }; public event EconomyDataRequest OnEconomyDataRequest = delegate { }; public event MoneyBalanceRequest OnMoneyBalanceRequest = delegate { }; public event UpdateAvatarProperties OnUpdateAvatarProperties = delegate { }; public event ParcelBuy OnParcelBuy = delegate { }; public event RequestPayPrice OnRequestPayPrice = delegate { }; public event ObjectSaleInfo OnObjectSaleInfo = delegate { }; public event ObjectBuy OnObjectBuy = delegate { }; public event BuyObjectInventory OnBuyObjectInventory = delegate { }; public event RequestTerrain OnRequestTerrain = delegate { }; public event RequestTerrain OnUploadTerrain = delegate { }; public event ObjectIncludeInSearch OnObjectIncludeInSearch = delegate { }; public event UUIDNameRequest OnTeleportHomeRequest = delegate { }; public event ScriptAnswer OnScriptAnswer = delegate { }; public event AgentSit OnUndo = delegate { }; public event ForceReleaseControls OnForceReleaseControls = delegate { }; public event GodLandStatRequest OnLandStatRequest = delegate { }; public event DetailedEstateDataRequest OnDetailedEstateDataRequest = delegate { }; public event SetEstateFlagsRequest OnSetEstateFlagsRequest = delegate { }; public event SetEstateTerrainBaseTexture OnSetEstateTerrainBaseTexture = delegate { }; public event SetEstateTerrainDetailTexture OnSetEstateTerrainDetailTexture = delegate { }; public event SetEstateTerrainTextureHeights OnSetEstateTerrainTextureHeights = delegate { }; public event CommitEstateTerrainTextureRequest OnCommitEstateTerrainTextureRequest = delegate { }; public event SetRegionTerrainSettings OnSetRegionTerrainSettings = delegate { }; public event EstateRestartSimRequest OnEstateRestartSimRequest = delegate { }; public event EstateChangeCovenantRequest OnEstateChangeCovenantRequest = delegate { }; public event UpdateEstateAccessDeltaRequest OnUpdateEstateAccessDeltaRequest = delegate { }; public event SimulatorBlueBoxMessageRequest OnSimulatorBlueBoxMessageRequest = delegate { }; public event EstateBlueBoxMessageRequest OnEstateBlueBoxMessageRequest = delegate { }; public event EstateDebugRegionRequest OnEstateDebugRegionRequest = delegate { }; public event EstateTeleportOneUserHomeRequest OnEstateTeleportOneUserHomeRequest = delegate { }; public event EstateTeleportAllUsersHomeRequest OnEstateTeleportAllUsersHomeRequest = delegate { }; public event UUIDNameRequest OnUUIDGroupNameRequest = delegate { }; public event RegionHandleRequest OnRegionHandleRequest = delegate { }; public event ParcelInfoRequest OnParcelInfoRequest = delegate { }; public event RequestObjectPropertiesFamily OnObjectGroupRequest = delegate { }; public event ScriptReset OnScriptReset = delegate { }; public event GetScriptRunning OnGetScriptRunning = delegate { }; public event SetScriptRunning OnSetScriptRunning = delegate { }; public event UpdateVector OnAutoPilotGo = delegate { }; public event TerrainUnacked OnUnackedTerrain = delegate { }; public event ActivateGesture OnActivateGesture = delegate { }; public event DeactivateGesture OnDeactivateGesture = delegate { }; public event ObjectOwner OnObjectOwner = delegate { }; public event DirPlacesQuery OnDirPlacesQuery = delegate { }; public event DirFindQuery OnDirFindQuery = delegate { }; public event DirLandQuery OnDirLandQuery = delegate { }; public event DirPopularQuery OnDirPopularQuery = delegate { }; public event DirClassifiedQuery OnDirClassifiedQuery = delegate { }; public event EventInfoRequest OnEventInfoRequest = delegate { }; public event ParcelSetOtherCleanTime OnParcelSetOtherCleanTime = delegate { }; public event MapItemRequest OnMapItemRequest = delegate { }; public event OfferCallingCard OnOfferCallingCard = delegate { }; public event AcceptCallingCard OnAcceptCallingCard = delegate { }; public event DeclineCallingCard OnDeclineCallingCard = delegate { }; public event SoundTrigger OnSoundTrigger = delegate { }; public event StartLure OnStartLure = delegate { }; public event TeleportLureRequest OnTeleportLureRequest = delegate { }; public event NetworkStats OnNetworkStatsUpdate = delegate { }; public event ClassifiedInfoRequest OnClassifiedInfoRequest = delegate { }; public event ClassifiedInfoUpdate OnClassifiedInfoUpdate = delegate { }; public event ClassifiedDelete OnClassifiedDelete = delegate { }; public event ClassifiedDelete OnClassifiedGodDelete = delegate { }; public event EventNotificationAddRequest OnEventNotificationAddRequest = delegate { }; public event EventNotificationRemoveRequest OnEventNotificationRemoveRequest = delegate { }; public event EventGodDelete OnEventGodDelete = delegate { }; public event ParcelDwellRequest OnParcelDwellRequest = delegate { }; public event UserInfoRequest OnUserInfoRequest = delegate { }; public event UpdateUserInfo OnUpdateUserInfo = delegate { }; public event RetrieveInstantMessages OnRetrieveInstantMessages = delegate { }; public event PickDelete OnPickDelete = delegate { }; public event PickGodDelete OnPickGodDelete = delegate { }; public event PickInfoUpdate OnPickInfoUpdate = delegate { }; public event AvatarNotesUpdate OnAvatarNotesUpdate = delegate { }; public event MuteListRequest OnMuteListRequest = delegate { }; public event AvatarInterestUpdate OnAvatarInterestUpdate = delegate { }; public event PlacesQuery OnPlacesQuery = delegate { }; public void SetDebugPacketLevel(int newDebug) { throw new System.NotImplementedException(); } public void InPacket(object NewPack) { throw new System.NotImplementedException(); } public void ProcessInPacket(Packet NewPack) { throw new System.NotImplementedException(); } public void Close() { throw new System.NotImplementedException(); } public void Kick(string message) { throw new System.NotImplementedException(); } public void Start() { throw new System.NotImplementedException(); } public void Stop() { throw new System.NotImplementedException(); } public void SendWearables(AvatarWearable[] wearables, int serial) { throw new System.NotImplementedException(); } public void SendAppearance(UUID agentID, byte[] visualParams, byte[] textureEntry) { throw new System.NotImplementedException(); } public void SendStartPingCheck(byte seq) { throw new System.NotImplementedException(); } public void SendKillObject(ulong regionHandle, uint localID) { throw new System.NotImplementedException(); } public void SendAnimations(UUID[] animID, int[] seqs, UUID sourceAgentId, UUID[] objectIDs) { throw new System.NotImplementedException(); } public void SendRegionHandshake(RegionInfo regionInfo, RegionHandshakeArgs args) { throw new System.NotImplementedException(); } public void SendChatMessage(string message, byte type, Vector3 fromPos, string fromName, UUID fromAgentID, byte source, byte audible) { throw new System.NotImplementedException(); } public void SendInstantMessage(GridInstantMessage im) { throw new System.NotImplementedException(); } public void SendGenericMessage(string method, List<string> message) { throw new System.NotImplementedException(); } public void SendLayerData(float[] map) { throw new System.NotImplementedException(); } public void SendLayerData(int px, int py, float[] map) { throw new System.NotImplementedException(); } public void SendWindData(Vector2[] windSpeeds) { throw new System.NotImplementedException(); } public void SendCloudData(float[] cloudCover) { throw new System.NotImplementedException(); } public void MoveAgentIntoRegion(RegionInfo regInfo, Vector3 pos, Vector3 look) { throw new System.NotImplementedException(); } public void InformClientOfNeighbour(ulong neighbourHandle, IPEndPoint neighbourExternalEndPoint) { throw new System.NotImplementedException(); } public AgentCircuitData RequestClientInfo() { throw new System.NotImplementedException(); } public void CrossRegion(ulong newRegionHandle, Vector3 pos, Vector3 lookAt, IPEndPoint newRegionExternalEndPoint, string capsURL) { throw new System.NotImplementedException(); } public void SendMapBlock(List<MapBlockData> mapBlocks, uint flag) { throw new System.NotImplementedException(); } public void SendLocalTeleport(Vector3 position, Vector3 lookAt, uint flags) { throw new System.NotImplementedException(); } public void SendRegionTeleport(ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint, uint locationID, uint flags, string capsURL) { throw new System.NotImplementedException(); } public void SendTeleportFailed(string reason) { throw new System.NotImplementedException(); } public void SendTeleportLocationStart() { throw new System.NotImplementedException(); } public void SendMoneyBalance(UUID transaction, bool success, byte[] description, int balance) { throw new System.NotImplementedException(); } public void SendPayPrice(UUID objectID, int[] payPrice) { throw new System.NotImplementedException(); } public void SendAvatarData(SendAvatarData data) { throw new System.NotImplementedException(); } public void SendAvatarTerseUpdate(SendAvatarTerseData data) { throw new System.NotImplementedException(); } public void SendCoarseLocationUpdate(List<UUID> users, List<Vector3> CoarseLocations) { throw new System.NotImplementedException(); } public void AttachObject(uint localID, Quaternion rotation, byte attachPoint, UUID ownerID) { throw new System.NotImplementedException(); } public void SetChildAgentThrottle(byte[] throttle) { throw new System.NotImplementedException(); } public void SendPrimitiveToClient(SendPrimitiveData data) { throw new System.NotImplementedException(); } public void SendPrimTerseUpdate(SendPrimitiveTerseData data) { throw new System.NotImplementedException(); } public void ReprioritizeUpdates(StateUpdateTypes type, UpdatePriorityHandler handler) { throw new System.NotImplementedException(); } public void FlushPrimUpdates() { throw new System.NotImplementedException(); } public void SendInventoryFolderDetails(UUID ownerID, UUID folderID, List<InventoryItemBase> items, List<InventoryFolderBase> folders, bool fetchFolders, bool fetchItems) { throw new System.NotImplementedException(); } public void SendInventoryItemDetails(UUID ownerID, InventoryItemBase item) { throw new System.NotImplementedException(); } public void SendInventoryItemCreateUpdate(InventoryItemBase Item, uint callbackId) { throw new System.NotImplementedException(); } public void SendRemoveInventoryItem(UUID itemID) { throw new System.NotImplementedException(); } public void SendTakeControls(int controls, bool passToAgent, bool TakeControls) { throw new System.NotImplementedException(); } public void SendTaskInventory(UUID taskID, short serial, byte[] fileName) { throw new System.NotImplementedException(); } public void SendBulkUpdateInventory(InventoryNodeBase node) { throw new System.NotImplementedException(); } public void SendXferPacket(ulong xferID, uint packet, byte[] data) { throw new System.NotImplementedException(); } public void SendEconomyData(float EnergyEfficiency, int ObjectCapacity, int ObjectCount, int PriceEnergyUnit, int PriceGroupCreate, int PriceObjectClaim, float PriceObjectRent, float PriceObjectScaleFactor, int PriceParcelClaim, float PriceParcelClaimFactor, int PriceParcelRent, int PricePublicObjectDecay, int PricePublicObjectDelete, int PriceRentLight, int PriceUpload, int TeleportMinPrice, float TeleportPriceExponent) { throw new System.NotImplementedException(); } public void SendAvatarPickerReply(AvatarPickerReplyAgentDataArgs AgentData, List<AvatarPickerReplyDataArgs> Data) { throw new System.NotImplementedException(); } public void SendAgentDataUpdate(UUID agentid, UUID activegroupid, string firstname, string lastname, ulong grouppowers, string groupname, string grouptitle) { throw new System.NotImplementedException(); } public void SendPreLoadSound(UUID objectID, UUID ownerID, UUID soundID) { throw new System.NotImplementedException(); } public void SendPlayAttachedSound(UUID soundID, UUID objectID, UUID ownerID, float gain, byte flags) { throw new System.NotImplementedException(); } public void SendTriggeredSound(UUID soundID, UUID ownerID, UUID objectID, UUID parentID, ulong handle, Vector3 position, float gain) { throw new System.NotImplementedException(); } public void SendAttachedSoundGainChange(UUID objectID, float gain) { throw new System.NotImplementedException(); } public void SendNameReply(UUID profileId, string firstname, string lastname) { throw new System.NotImplementedException(); } public void SendAlertMessage(string message) { throw new System.NotImplementedException(); } public void SendAgentAlertMessage(string message, bool modal) { throw new System.NotImplementedException(); } public void SendLoadURL(string objectname, UUID objectID, UUID ownerID, bool groupOwned, string message, string url) { throw new System.NotImplementedException(); } public void SendDialog(string objectname, UUID objectID, string ownerFirstName, string ownerLastName, string msg, UUID textureID, int ch, string[] buttonlabels) { throw new System.NotImplementedException(); } public bool AddMoney(int debit) { throw new System.NotImplementedException(); } public void SendSunPos(Vector3 sunPos, Vector3 sunVel, ulong CurrentTime, uint SecondsPerSunCycle, uint SecondsPerYear, float OrbitalPosition) { throw new System.NotImplementedException(); } public void SendViewerEffect(ViewerEffectPacket.EffectBlock[] effectBlocks) { throw new System.NotImplementedException(); } public void SendViewerTime(int phase) { throw new System.NotImplementedException(); } public UUID GetDefaultAnimation(string name) { throw new System.NotImplementedException(); } public void SendAvatarProperties(UUID avatarID, string aboutText, string bornOn, byte[] charterMember, string flAbout, uint flags, UUID flImageID, UUID imageID, string profileURL, UUID partnerID) { throw new System.NotImplementedException(); } public void SendScriptQuestion(UUID taskID, string taskName, string ownerName, UUID itemID, int question) { throw new System.NotImplementedException(); } public void SendHealth(float health) { throw new System.NotImplementedException(); } public void SendEstateManagersList(UUID invoice, UUID[] EstateManagers, uint estateID) { throw new System.NotImplementedException(); } public void SendBannedUserList(UUID invoice, EstateBan[] banlist, uint estateID) { throw new System.NotImplementedException(); } public void SendRegionInfoToEstateMenu(RegionInfoForEstateMenuArgs args) { throw new System.NotImplementedException(); } public void SendEstateCovenantInformation(UUID covenant) { throw new System.NotImplementedException(); } public void SendDetailedEstateData(UUID invoice, string estateName, uint estateID, uint parentEstate, uint estateFlags, uint sunPosition, UUID covenant, string abuseEmail, UUID estateOwner) { throw new System.NotImplementedException(); } public void SendLandProperties(int sequence_id, bool snap_selection, int request_result, LandData landData, float simObjectBonusFactor, int parcelObjectCapacity, int simObjectCapacity, uint regionFlags) { throw new System.NotImplementedException(); } public void SendLandAccessListData(List<UUID> avatars, uint accessFlag, int localLandID) { throw new System.NotImplementedException(); } public void SendForceClientSelectObjects(List<uint> objectIDs) { throw new System.NotImplementedException(); } public void SendCameraConstraint(Vector4 ConstraintPlane) { } public void SendLandObjectOwners(LandData land, List<UUID> groups, Dictionary<UUID, int> ownersAndCount) { throw new System.NotImplementedException(); } public void SendLandParcelOverlay(byte[] data, int sequence_id) { throw new System.NotImplementedException(); } public void SendParcelMediaCommand(uint flags, ParcelMediaCommandEnum command, float time) { throw new System.NotImplementedException(); } public void SendParcelMediaUpdate(string mediaUrl, UUID mediaTextureID, byte autoScale, string mediaType, string mediaDesc, int mediaWidth, int mediaHeight, byte mediaLoop) { throw new System.NotImplementedException(); } public void SendAssetUploadCompleteMessage(sbyte AssetType, bool Success, UUID AssetFullID) { throw new System.NotImplementedException(); } public void SendConfirmXfer(ulong xferID, uint PacketID) { throw new System.NotImplementedException(); } public void SendXferRequest(ulong XferID, short AssetType, UUID vFileID, byte FilePath, byte[] FileName) { throw new System.NotImplementedException(); } public void SendInitiateDownload(string simFileName, string clientFileName) { throw new System.NotImplementedException(); } public void SendImageFirstPart(ushort numParts, UUID ImageUUID, uint ImageSize, byte[] ImageData, byte imageCodec) { throw new System.NotImplementedException(); } public void SendImageNextPart(ushort partNumber, UUID imageUuid, byte[] imageData) { throw new System.NotImplementedException(); } public void SendImageNotFound(UUID imageid) { throw new System.NotImplementedException(); } public void SendShutdownConnectionNotice() { throw new System.NotImplementedException(); } public void SendSimStats(SimStats stats) { throw new System.NotImplementedException(); } public void SendObjectPropertiesFamilyData(uint RequestFlags, UUID ObjectUUID, UUID OwnerID, UUID GroupID, uint BaseMask, uint OwnerMask, uint GroupMask, uint EveryoneMask, uint NextOwnerMask, int OwnershipCost, byte SaleType, int SalePrice, uint Category, UUID LastOwnerID, string ObjectName, string Description) { throw new System.NotImplementedException(); } public void SendObjectPropertiesReply(UUID ItemID, ulong CreationDate, UUID CreatorUUID, UUID FolderUUID, UUID FromTaskUUID, UUID GroupUUID, short InventorySerial, UUID LastOwnerUUID, UUID ObjectUUID, UUID OwnerUUID, string TouchTitle, byte[] TextureID, string SitTitle, string ItemName, string ItemDescription, uint OwnerMask, uint NextOwnerMask, uint GroupMask, uint EveryoneMask, uint BaseMask, byte saleType, int salePrice) { throw new System.NotImplementedException(); } public void SendAgentOffline(UUID[] agentIDs) { throw new System.NotImplementedException(); } public void SendAgentOnline(UUID[] agentIDs) { throw new System.NotImplementedException(); } public void SendSitResponse(UUID TargetID, Vector3 OffsetPos, Quaternion SitOrientation, bool autopilot, Vector3 CameraAtOffset, Vector3 CameraEyeOffset, bool ForceMouseLook) { throw new System.NotImplementedException(); } public void SendAdminResponse(UUID Token, uint AdminLevel) { throw new System.NotImplementedException(); } public void SendGroupMembership(GroupMembershipData[] GroupMembership) { throw new System.NotImplementedException(); } public void SendGroupNameReply(UUID groupLLUID, string GroupName) { throw new System.NotImplementedException(); } public void SendJoinGroupReply(UUID groupID, bool success) { throw new System.NotImplementedException(); } public void SendEjectGroupMemberReply(UUID agentID, UUID groupID, bool success) { throw new System.NotImplementedException(); } public void SendLeaveGroupReply(UUID groupID, bool success) { throw new System.NotImplementedException(); } public void SendCreateGroupReply(UUID groupID, bool success, string message) { throw new System.NotImplementedException(); } public void SendLandStatReply(uint reportType, uint requestFlags, uint resultCount, LandStatReportItem[] lsrpia) { throw new System.NotImplementedException(); } public void SendScriptRunningReply(UUID objectID, UUID itemID, bool running) { throw new System.NotImplementedException(); } public void SendAsset(AssetRequestToClient req) { throw new System.NotImplementedException(); } public void SendTexture(AssetBase TextureAsset) { throw new System.NotImplementedException(); } public byte[] GetThrottlesPacked(float multiplier) { throw new System.NotImplementedException(); } public event ViewerEffectEventHandler OnViewerEffect; public event Action<IClientAPI> OnLogout; public event Action<IClientAPI> OnConnectionClosed; public void SendBlueBoxMessage(UUID FromAvatarID, string FromAvatarName, string Message) { throw new System.NotImplementedException(); } public void SendLogoutPacket() { throw new System.NotImplementedException(); } public EndPoint GetClientEP() { return null; } public ClientInfo GetClientInfo() { throw new System.NotImplementedException(); } public void SetClientInfo(ClientInfo info) { throw new System.NotImplementedException(); } public void SetClientOption(string option, string value) { throw new System.NotImplementedException(); } public string GetClientOption(string option) { throw new System.NotImplementedException(); } public void Terminate() { throw new System.NotImplementedException(); } public void SendSetFollowCamProperties(UUID objectID, SortedDictionary<int, float> parameters) { throw new System.NotImplementedException(); } public void SendClearFollowCamProperties(UUID objectID) { throw new System.NotImplementedException(); } public void SendRegionHandle(UUID regoinID, ulong handle) { throw new System.NotImplementedException(); } public void SendParcelInfo(RegionInfo info, LandData land, UUID parcelID, uint x, uint y) { throw new System.NotImplementedException(); } public void SendScriptTeleportRequest(string objName, string simName, Vector3 pos, Vector3 lookAt) { throw new System.NotImplementedException(); } public void SendDirPlacesReply(UUID queryID, DirPlacesReplyData[] data) { throw new System.NotImplementedException(); } public void SendDirPeopleReply(UUID queryID, DirPeopleReplyData[] data) { throw new System.NotImplementedException(); } public void SendDirEventsReply(UUID queryID, DirEventsReplyData[] data) { throw new System.NotImplementedException(); } public void SendDirGroupsReply(UUID queryID, DirGroupsReplyData[] data) { throw new System.NotImplementedException(); } public void SendDirClassifiedReply(UUID queryID, DirClassifiedReplyData[] data) { throw new System.NotImplementedException(); } public void SendDirLandReply(UUID queryID, DirLandReplyData[] data) { throw new System.NotImplementedException(); } public void SendDirPopularReply(UUID queryID, DirPopularReplyData[] data) { throw new System.NotImplementedException(); } public void SendEventInfoReply(EventData info) { throw new System.NotImplementedException(); } public void SendMapItemReply(mapItemReply[] replies, uint mapitemtype, uint flags) { throw new System.NotImplementedException(); } public void SendAvatarGroupsReply(UUID avatarID, GroupMembershipData[] data) { throw new System.NotImplementedException(); } public void SendOfferCallingCard(UUID srcID, UUID transactionID) { throw new System.NotImplementedException(); } public void SendAcceptCallingCard(UUID transactionID) { throw new System.NotImplementedException(); } public void SendDeclineCallingCard(UUID transactionID) { throw new System.NotImplementedException(); } public void SendTerminateFriend(UUID exFriendID) { throw new System.NotImplementedException(); } public void SendAvatarClassifiedReply(UUID targetID, UUID[] classifiedID, string[] name) { throw new System.NotImplementedException(); } public void SendClassifiedInfoReply(UUID classifiedID, UUID creatorID, uint creationDate, uint expirationDate, uint category, string name, string description, UUID parcelID, uint parentEstate, UUID snapshotID, string simName, Vector3 globalPos, string parcelName, byte classifiedFlags, int price) { throw new System.NotImplementedException(); } public void SendAgentDropGroup(UUID groupID) { throw new System.NotImplementedException(); } public void RefreshGroupMembership() { throw new System.NotImplementedException(); } public void SendAvatarNotesReply(UUID targetID, string text) { throw new System.NotImplementedException(); } public void SendAvatarPicksReply(UUID targetID, Dictionary<UUID, string> picks) { throw new System.NotImplementedException(); } public void SendPickInfoReply(UUID pickID, UUID creatorID, bool topPick, UUID parcelID, string name, string desc, UUID snapshotID, string user, string originalName, string simName, Vector3 posGlobal, int sortOrder, bool enabled) { throw new System.NotImplementedException(); } public void SendAvatarClassifiedReply(UUID targetID, Dictionary<UUID, string> classifieds) { throw new System.NotImplementedException(); } public void SendAvatarInterestUpdate(IClientAPI client, uint wantmask, string wanttext, uint skillsmask, string skillstext, string languages) { throw new System.NotImplementedException(); } public void SendParcelDwellReply(int localID, UUID parcelID, float dwell) { throw new System.NotImplementedException(); } public void SendUserInfoReply(bool imViaEmail, bool visible, string email) { throw new System.NotImplementedException(); } public void SendUseCachedMuteList() { throw new System.NotImplementedException(); } public void SendMuteListUpdate(string filename) { throw new System.NotImplementedException(); } public void KillEndDone() { throw new System.NotImplementedException(); } public bool AddGenericPacketHandler(string MethodName, GenericMessage handler) { throw new System.NotImplementedException(); } #endregion public void SendRebakeAvatarTextures(UUID textureID) { } } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace OD4B.Configuration.Async.WebJob { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// </summary> /// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns> public string GetDatabaseConnectionString() { string dbConnectionString = null; using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost()) { if (clientContext != null) { var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext); clientContext.ExecuteQuery(); dbConnectionString = result.Value; } } if (dbConnectionString == null) { const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging"; var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey]; dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null; } return dbConnectionString; } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey])) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //////////////////////////////////////////////////////////////// // // Description // ____________ // On IA64 if the only use of a parameter is assigning to it // inside and EH clause and the parameter is a GC pointer, then // the JIT reports a stack slot as live for the duration of the method, // but never initializes it. Sort of the inverse of a GC hole. // Thus the runtime sees random stack garbage as a GC pointer and // bad things happen. Workarounds include using the parameter, // assinging to a different local, removing the assignment (since // it has no subsequent uses). // // // Right Behavior // ________________ // No Assertion // // Wrong Behavior // ________________ // Assertion // // Commands to issue // __________________ // > test1.exe // // External files // _______________ // None //////////////////////////////////////////////////////////////// using System; using System.Collections; using System.Runtime.InteropServices; class ApplicationException : Exception { } #pragma warning disable 1917,1918 public enum TestEnum { red = 1, green = 2, blue = 4, } public class AA<TA, TB, TC, TD, TE, TF> where TA : IComparable where TB : IComparable where TC : IComparable where TD : IComparable where TE : IComparable { public TC m_aguiGeneric1; public short[][][] Method1(uint[,,,] param1, ref TestEnum param2) { uint local1 = ((uint)(((ulong)(17.0f)))); double local2 = ((double)(((ulong)(113.0f)))); String[] local3 = new String[] { "113", "92", "26", "24" }; while (Convert.ToBoolean(((short)(local1)))) { local3[23] = "69"; do { char[][] local4 = new char[][]{(new char[48u]), new char[]{'\x3f', '\x00', '\x47' }, new char[]{'\x58', '\x39', '\x70', '\x31' }, (new char[48u]), new char[]{'\x62', '\x6b', '\x19', '\x30', '\x17' } }; local3 = ((String[])(((Array)(null)))); while ((((short)(local2)) == ((short)(local2)))) { for (App.m_byFwd1 = App.m_byFwd1; ((bool)(((object)(new BB())))); local1--) { do { while (Convert.ToBoolean((local1 >> 100))) { local2 = local2; } while ((new AA<TA, TB, TC, TD, TE, TF>() == new AA<TA, TB, TC, TD, TE, TF>())) { if (((bool)(((object)(new AA<TA, TB, TC, TD, TE, TF>()))))) param1 = (new uint[local1, 107u, 22u, local1]); if (((bool)(((object)(param2))))) continue; if (App.m_bFwd2) continue; if ((/*2 REFS*/((byte)(local1)) != /*2 REFS*/((byte)(local1)))) { throw new ApplicationException(); } } local1 -= 88u; while (((bool)(((object)(local2))))) { } if (Convert.ToBoolean(((int)(local2)))) do { } while (App.m_bFwd2); else { } } while ((null != new AA<TA, TB, TC, TD, TE, TF>())); local4 = (local4 = (local4 = new char[][]{(new char[local1]), (new char[ local1]), (new char[113u]) })); do { } while (Convert.ToBoolean(local2)); for (App.m_byFwd1 = ((byte)(local1)); ((bool)(((object)(local1)))); local2 -= (local2 + local2)) { } while (Convert.ToBoolean(((short)(local1)))) { } } if (((bool)(((object)(new BB()))))) { } else for (App.m_iFwd3 -= 33; ((bool)(((object)(local2)))); App.m_bFwd2 = App. m_bFwd2) { } } for (App.m_iFwd3 /= (Convert.ToByte(33.0) ^ ((byte)(local1))); App.m_bFwd2; App.m_shFwd4 = ((short)(((sbyte)(local2))))) { } while (App.m_bFwd2) { } break; } while ((/*2 REFS*/((object)(new BB())) != ((AA<TA, TB, TC, TD, TE, TF>)( /*2 REFS*/((object)(new BB())))))); for (App.m_iFwd3 = 60; ((bool)(((object)(new BB())))); local2 = local2) { } local3 = ((String[])(((object)(local2)))); } local3[((int)(((byte)(65))))] = "47"; try { } catch (IndexOutOfRangeException) { } return new short[][][]{/*2 REFS*/(new short[36u][]), new short[][]{ }, /*2 REFS*/ (new short[36u][]) }; } public static ulong Static1(TF param1) { byte local5 = ((byte)(((long)(69.0)))); float[,][,] local6 = (new float[9u, 6u][,]); TestEnum local7 = TestEnum.blue; do { bool[,,,,][,] local8 = (new bool[81u, 98u, ((uint)(58.0f)), ((uint)(36.0f)), 74u][,]); while ((((uint)(local5)) != 4u)) { if (Convert.ToBoolean((local5 + local5))) local6 = (new float[((uint)(116.0)), 94u][,]); else for (App.m_iFwd3 -= 97; Convert.ToBoolean(((ushort)(local5))); App.m_ushFwd5 = Math.Max(((ushort)(26)), ((ushort)(43)))) { local7 = local7; } } local8[69, 1, 61, 62, 122][24, 40] = true; local8[97, (((short)(115)) >> ((ushort)(local5))), 29, 29, ((int)(((ulong)( local5))))][((int)(((long)(119u)))), 52] = false; try { param1 = param1; param1 = param1; while ((/*2 REFS*/((sbyte)(local5)) == /*2 REFS*/((sbyte)(local5)))) { try { throw new IndexOutOfRangeException(); } catch (InvalidOperationException) { try { while (((bool)(((object)(local7))))) { return ((ulong)(((int)(7u)))); } while ((new AA<TA, TB, TC, TD, TE, TF>() == new AA<TA, TB, TC, TD, TE, TF>())) { local7 = local7; local5 = (local5 += local5); } while (((bool)(((object)(local5))))) { } goto label1; } catch (InvalidOperationException) { } do { } while ((new AA<TA, TB, TC, TD, TE, TF>() == new AA<TA, TB, TC, TD, TE, TF>( ))); label1: try { } catch (Exception) { } } for (App.m_fFwd6 = App.m_fFwd6; ((bool)(((object)(new BB())))); App.m_dblFwd7 /= 94.0) { } for (App.m_shFwd4--; App.m_bFwd2; App.m_ulFwd8 = ((ulong)(((ushort)(local5)) ))) { } local7 = local7; local8[((int)(Convert.ToUInt64(26.0))), 60, ((int)(((long)(local5)))), (( int)(local5)), 96] = (new bool[((uint)(48.0)), 97u]); } param1 = (param1 = param1); } finally { } local8 = local8; } while (((bool)(((object)(local7))))); if ((local5 == (local5 -= local5))) while ((((Array)(null)) != ((object)(local7)))) { } else { } for (App.m_dblFwd7++; App.m_bFwd2; App.m_chFwd9 += '\x69') { } return ((ulong)(105)); } public static char[] Static2(ulong param1, short param2, ref uint param3, ref TA param4) { long[,,,,][,,][][,,,] local9 = (new long[((uint)(5.0)), 24u, 65u, 9u, 29u] [,,][][,,,]); char local10 = ((char)(97)); double local11 = 102.0; sbyte[,][,,,][] local12 = (new sbyte[41u, 15u][,,,][]); try { local12[26, 65] = ((sbyte[,,,][])(((object)(new AA<TA, TB, TC, TD, TE, TF>() )))); try { do { do { do { try { do { try { local11 *= 27.0; try { if (Convert.ToBoolean(((ushort)(param1)))) for (App.m_ushFwd5 /= ((ushort)(17.0f)); (new AA<TA, TB, TC, TD, TE, TF>() != new AA<TA, TB, TC, TD, TE, TF>()); App.m_ushFwd5 *= ((ushort)(((sbyte)(param1))))) { } } catch (IndexOutOfRangeException) { } do { } while (((bool)(((object)(param1))))); } catch (InvalidOperationException) { } } while (("95" == Convert.ToString(local10))); local11 -= ((double)(30)); while (((bool)(((object)(local10))))) { } } catch (NullReferenceException) { } try { } catch (InvalidOperationException) { } param3 /= ((param3 /= param3) / param3); } while ((((long)(param2)) != (55 | param3))); local10 = ((char)(((object)(local10)))); param1 *= ((ulong)(((ushort)(54u)))); try { } catch (ApplicationException) { } param4 = (param4 = param4); } while ((param2 == param2)); do { } while (((bool)(((object)(new AA<TA, TB, TC, TD, TE, TF>()))))); throw new DivideByZeroException(); } while ((param3 == (65u / param3))); do { } while ((((sbyte)(local11)) == ((sbyte)(local11)))); local12[116, ((int)((param2 *= param2)))] = (new sbyte[((uint)(param2)), ( param3 += param3), 67u, 116u][]); try { } finally { } } finally { } for (App.m_lFwd10 = (60 * param3); ((bool)(((object)(local10)))); local11--) { } local12 = (local12 = (local12 = local12)); } catch (IndexOutOfRangeException) { } local9 = local9; param1 *= (param1 >> ((ushort)(30))); return new char[] { (local10 = local10), local10, (local10 = local10), '\x7e' }; } public static sbyte[][][,,,,][][,,] Static3(TestEnum param1, short param2) { param1 = param1; do { sbyte local13 = ((sbyte)(89.0)); double local14 = 103.0; uint[,][][,,][,] local15 = (new uint[92u, 102u][][,,][,]); short[][,,,][,][] local16 = (new short[32u][,,,][,][]); local15[((int)(((float)(69.0)))), 9][((int)(((ushort)(75.0f))))][((int)(66u)) , (((byte)(local13)) ^ ((byte)(param2))), ((local13 << local13) << ((ushort )(local13)))][((int)(63u)), ((int)(((char)(8))))] *= 82u; param1 = (param1 = param1); } while (((bool)(((object)(param1))))); param1 = param1; param2 = (param2 /= (param2 = param2)); return (new sbyte[36u][][,,,,][][,,]); } public static long[][,,] Static4(char param1) { sbyte[][] local17 = ((sbyte[][])(((Array)(null)))); ulong[,,] local18 = ((ulong[,,])(((Array)(null)))); sbyte[][] local19 = new sbyte[][] { (new sbyte[16u]), (new sbyte[126u]) }; byte local20 = ((byte)(((sbyte)(90u)))); return (new long[15u][,,]); } public static int Static5(ref TE param1, ref char[][,,,] param2, Array param3, ref ulong[,,,,] param4, ref long[,,,][][][][,] param5) { BB[] local21 = ((BB[])(((Array)(null)))); sbyte local22 = ((sbyte)(121)); bool local23 = (new AA<TA, TB, TC, TD, TE, TF>() == new AA<TA, TB, TC, TD, TE, TF>()); object[][,,][][,,][,] local24 = (new object[115u][,,][][,,][,]); while (local23) { param1 = param1; while (local23) { try { local23 = false; } catch (ApplicationException) { param2[1] = (new char[57u, ((uint)(68)), 104u, ((uint)(local22))]); try { local22 = local22; do { do { local21[((int)(((long)(102u))))].m_achField1[((int)(local22))] = (( char[,])(((object)(new BB())))); param3 = ((Array)(null)); throw new IndexOutOfRangeException(); } while (local23); param3 = ((Array)(null)); local22 = local22; local22 = (local22 *= local22); while ((local23 && (null != new AA<TA, TB, TC, TD, TE, TF>()))) { for (local22 = local22; local23; App.m_abyFwd11 = App.m_abyFwd11) { while (local23) { } } local22 = local22; } } while ((/*3 REFS*/((uint)(local22)) != (local23 ?/*3 REFS*/((uint)(local22)) :/*3 REFS*/((uint)(local22))))); local21[38].m_achField1 = new char[][,]{((char[,])(param3)), (new char[ 102u, 36u]) }; } catch (DivideByZeroException) { } local21 = local21; } try { } catch (Exception) { } throw new InvalidOperationException(); } try { } catch (ApplicationException) { } for (App.m_uFwd12--; local23; App.m_lFwd10 /= ((long)(((short)(28u))))) { } } param5 = (new long[108u, 115u, 20u, 126u][][][][,]); local21[(((ushort)(local22)) << ((int)(local22)))].m_achField1[101] = (new char[21u, 43u]); for (App.m_shFwd4 = ((short)(76.0f)); ((bool)(((object)(local23)))); App. m_chFwd9 *= '\x67') { } if (local23) try { } catch (InvalidOperationException) { } else while (local23) { } return 83; } } [StructLayout(LayoutKind.Sequential)] public struct BB { public char[][,] m_achField1; public void Method1(ref uint[][][,] param1, ref String[][] param2, ref char[,] param3, AA<sbyte, byte, uint, uint, long, bool> param4, ref AA<sbyte, byte, uint, uint, long, bool> param5, int param6) { do { ushort[] local25 = (new ushort[62u]); do { BB local26 = ((BB)(((object)(new AA<sbyte, byte, uint, uint, long, bool>())) )); param4.m_aguiGeneric1 = new AA<sbyte, byte, uint, uint, long, bool>(). m_aguiGeneric1; try { ulong[,,][] local27 = ((ulong[,,][])(((Array)(null)))); ushort[,] local28 = (new ushort[8u, 8u]); if ((/*2 REFS*/((short)(param6)) == /*2 REFS*/((short)(param6)))) while (App.m_bFwd2) { for (App.m_ushFwd5--; App.m_bFwd2; App.m_ulFwd8--) { param1 = param1; } AA<sbyte, byte, uint, uint, long, bool>.Static3( TestEnum.blue, App.m_shFwd4); param1[(5 ^ param6)][param6] = (new uint[2u, ((uint)(param6))]); } else local28[param6, (((ushort)(param6)) << ((sbyte)(47)))] += ((ushort)((( ulong)(25u)))); while (((bool)(((object)(param4))))) { AA<sbyte, byte, uint, uint, long, bool>.Static2( ((ulong)(114.0)), ((short)(((long)(49.0f)))), ref App.m_uFwd12, ref App.m_gsbFwd13); try { if ((null == new AA<sbyte, byte, uint, uint, long, bool>())) if ((((char)(25)) != ((char)(param6)))) if (App.m_bFwd2) try { param6 /= param6; while ((((long)(44u)) != ((long)(param6)))) { try { } catch (InvalidOperationException) { } do { } while (App.m_bFwd2); local25 = local25; for (App.m_shFwd4 -= App.m_shFwd4; Convert.ToBoolean(param6); App. m_byFwd1 *= Math.Max(((byte)(9u)), ((byte)(40u)))) { } } local25[12] = App.m_ushFwd5; local28 = (new ushort[111u, 80u]); for (App.m_dblFwd7 = App.m_dblFwd7; (param6 == ((int)(101.0))); param6 *= param6) { } } catch (IndexOutOfRangeException) { } param1 = param1; param2[param6] = ((String[])(((Array)(null)))); try { } catch (ApplicationException) { } } finally { } } } catch (Exception) { } } while (App.m_bFwd2); for (App.m_xFwd14 = App.m_xFwd14; ((param6 - (0.0f)) == 86.0f); App.m_fFwd6 += ( 108u - ((float)(param6)))) { } if ((((object)(new AA<sbyte, byte, uint, uint, long, bool>())) == "32")) param5.m_aguiGeneric1 = new AA<sbyte, byte, uint, uint, long, bool>(). m_aguiGeneric1; else do { } while (((bool)(((object)(new AA<sbyte, byte, uint, uint, long, bool>()))))); if (App.m_bFwd2) { } } while (Convert.ToBoolean(param6)); param5.m_aguiGeneric1 = (param4 = param4).m_aguiGeneric1; do { } while (Convert.ToBoolean(param6)); ; } } public class App { private static int Main() { try { Console.WriteLine("Testing AA::Method1"); ((AA<sbyte, byte, uint, uint, long, bool>)(((object)(new BB())))).Method1( (new uint[12u, 115u, 95u, 13u]), ref App.m_xFwd15); } catch (Exception x) { Console.WriteLine("Exception handled: " + x.ToString()); } try { Console.WriteLine("Testing AA::Static1"); AA<sbyte, byte, uint, uint, long, bool>.Static1(App.m_agboFwd16); } catch (Exception x) { Console.WriteLine("Exception handled: " + x.ToString()); } try { Console.WriteLine("Testing AA::Static2"); AA<sbyte, byte, uint, uint, long, bool>.Static2( ((ulong)(((ushort)(10.0)))), ((short)(70.0)), ref App.m_uFwd12, ref App.m_gsbFwd13); } catch (Exception x) { Console.WriteLine("Exception handled: " + x.ToString()); } try { Console.WriteLine("Testing AA::Static3"); AA<sbyte, byte, uint, uint, long, bool>.Static3( TestEnum.green, ((short)(((sbyte)(69.0))))); } catch (Exception x) { Console.WriteLine("Exception handled: " + x.ToString()); } try { Console.WriteLine("Testing AA::Static4"); AA<sbyte, byte, uint, uint, long, bool>.Static4('\x02'); } catch (Exception x) { Console.WriteLine("Exception handled: " + x.ToString()); } try { Console.WriteLine("Testing AA::Static5"); AA<sbyte, byte, uint, uint, long, bool>.Static5( ref App.m_aglFwd17, ref App.m_achFwd18, ((Array)(null)), ref App.m_aulFwd19, ref App.m_alFwd20); } catch (Exception x) { Console.WriteLine("Exception handled: " + x.ToString()); } try { Console.WriteLine("Testing BB::Method1"); new BB().Method1( ref App.m_auFwd21, ref App.m_axFwd22, ref App.m_achFwd23, new AA<sbyte, byte, uint, uint, long, bool>(), ref App.m_axFwd24, 87); } catch (Exception x) { Console.WriteLine("Exception handled: " + x.ToString()); } Console.WriteLine("Passed."); return 100; } public static byte m_byFwd1; public static bool m_bFwd2; public static int m_iFwd3; public static short m_shFwd4; public static ushort m_ushFwd5; public static float m_fFwd6; public static double m_dblFwd7; public static ulong m_ulFwd8; public static char m_chFwd9; public static long m_lFwd10; public static byte[] m_abyFwd11; public static uint m_uFwd12; public static sbyte m_gsbFwd13; public static Array m_xFwd14; public static TestEnum m_xFwd15; public static bool m_agboFwd16; public static long m_aglFwd17; public static char[][,,,] m_achFwd18; public static ulong[,,,,] m_aulFwd19; public static long[,,,][][][][,] m_alFwd20; public static uint[][][,] m_auFwd21; public static String[][] m_axFwd22; public static char[,] m_achFwd23; public static AA<sbyte, byte, uint, uint, long, bool> m_axFwd24; }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using Xunit; using Should; using System.Linq; namespace AutoMapper.UnitTests { namespace ArraysAndLists { public class When_mapping_to_an_existing_array_typed_as_IEnumerable : AutoMapperSpecBase { private Destination _destination = new Destination(); public class Source { public int[] IntCollection { get; set; } = new int[0]; } public class Destination { public IEnumerable<int> IntCollection { get; set; } = new[] { 1, 2, 3, 4, 5 }; } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>(); }); protected override void Because_of() { _destination = Mapper.Map(new Source(), _destination); } [Fact] public void Should_create_destination_array_the_same_size_as_the_source() { _destination.IntCollection.Count().ShouldEqual(0); } } public class When_mapping_to_a_concrete_non_generic_ienumerable : AutoMapperSpecBase { private Destination _destination; public class Source { public int[] Values { get; set; } public List<int> Values2 { get; set; } } public class Destination { public IEnumerable Values { get; set; } public IEnumerable Values2 { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>(); }); protected override void Because_of() { _destination = Mapper.Map<Source, Destination>(new Source { Values = new[] { 1, 2, 3, 4 }, Values2 = new List<int> { 9, 8, 7, 6 } }); } [Fact] public void Should_map_the_list_of_source_items() { _destination.Values.ShouldNotBeNull(); _destination.Values.ShouldContain(1); _destination.Values.ShouldContain(2); _destination.Values.ShouldContain(3); _destination.Values.ShouldContain(4); } [Fact] public void Should_map_from_the_generic_list_of_values() { _destination.Values2.ShouldNotBeNull(); _destination.Values2.ShouldContain(9); _destination.Values2.ShouldContain(8); _destination.Values2.ShouldContain(7); _destination.Values2.ShouldContain(6); } } public class When_mapping_to_a_concrete_generic_ienumerable : AutoMapperSpecBase { private Destination _destination; public class Source { public int[] Values { get; set; } public List<int> Values2 { get; set; } } public class Destination { public IEnumerable<int> Values { get; set; } public IEnumerable<string> Values2 { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>(); }); protected override void Because_of() { _destination = Mapper.Map<Source, Destination>(new Source { Values = new[] { 1, 2, 3, 4 }, Values2 = new List<int> { 9, 8, 7, 6 } }); } [Fact] public void Should_map_the_list_of_source_items() { _destination.Values.ShouldNotBeNull(); _destination.Values.ShouldContain(1); _destination.Values.ShouldContain(2); _destination.Values.ShouldContain(3); _destination.Values.ShouldContain(4); } [Fact] public void Should_map_from_the_generic_list_of_values_with_formatting() { _destination.Values2.ShouldNotBeNull(); _destination.Values2.ShouldContain("9"); _destination.Values2.ShouldContain("8"); _destination.Values2.ShouldContain("7"); _destination.Values2.ShouldContain("6"); } } public class When_mapping_to_a_concrete_non_generic_icollection : AutoMapperSpecBase { private Destination _destination; public class Source { public int[] Values { get; set; } public List<int> Values2 { get; set; } } public class Destination { public ICollection Values { get; set; } public ICollection Values2 { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>(); }); protected override void Because_of() { _destination = Mapper.Map<Source, Destination>(new Source { Values = new[] { 1, 2, 3, 4 }, Values2 = new List<int> { 9, 8, 7, 6 } }); } [Fact] public void Should_map_the_list_of_source_items() { _destination.Values.ShouldNotBeNull(); _destination.Values.ShouldContain(1); _destination.Values.ShouldContain(2); _destination.Values.ShouldContain(3); _destination.Values.ShouldContain(4); } [Fact] public void Should_map_from_a_non_array_source() { _destination.Values2.ShouldNotBeNull(); _destination.Values2.ShouldContain(9); _destination.Values2.ShouldContain(8); _destination.Values2.ShouldContain(7); _destination.Values2.ShouldContain(6); } } public class When_mapping_to_a_concrete_generic_icollection : AutoMapperSpecBase { private Destination _destination; public class Source { public int[] Values { get; set; } } public class Destination { public ICollection<string> Values { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>(); }); protected override void Because_of() { _destination = Mapper.Map<Source, Destination>(new Source { Values = new[] { 1, 2, 3, 4 } }); } [Fact] public void Should_map_the_list_of_source_items() { _destination.Values.ShouldNotBeNull(); _destination.Values.ShouldContain("1"); _destination.Values.ShouldContain("2"); _destination.Values.ShouldContain("3"); _destination.Values.ShouldContain("4"); } } public class When_mapping_to_a_concrete_ilist : AutoMapperSpecBase { private Destination _destination; public class Source { public int[] Values { get; set; } } public class Destination { public IList Values { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>(); }); protected override void Because_of() { _destination = Mapper.Map<Source, Destination>(new Source { Values = new[] { 1, 2, 3, 4 } }); } [Fact] public void Should_map_the_list_of_source_items() { _destination.Values.ShouldNotBeNull(); _destination.Values.ShouldContain(1); _destination.Values.ShouldContain(2); _destination.Values.ShouldContain(3); _destination.Values.ShouldContain(4); } } public class When_mapping_to_a_concrete_generic_ilist : AutoMapperSpecBase { private Destination _destination; public class Source { public int[] Values { get; set; } } public class Destination { public IList<string> Values { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>(); }); protected override void Because_of() { _destination = Mapper.Map<Source, Destination>(new Source { Values = new[] { 1, 2, 3, 4 } }); } [Fact] public void Should_map_the_list_of_source_items() { _destination.Values.ShouldNotBeNull(); _destination.Values.ShouldContain("1"); _destination.Values.ShouldContain("2"); _destination.Values.ShouldContain("3"); _destination.Values.ShouldContain("4"); } } public class When_mapping_to_a_custom_list_with_the_same_type : AutoMapperSpecBase { private Destination _destination; private Source _source; public class ValueCollection : Collection<int> { } public class Source { public ValueCollection Values { get; set; } } public class Destination { public ValueCollection Values { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>(); }); protected override void Because_of() { _source = new Source { Values = new ValueCollection { 1, 2, 3, 4 } }; _destination = Mapper.Map<Source, Destination>(_source); } [Fact] public void Should_assign_the_value_directly() { _source.Values.ShouldEqual(_destination.Values); } } public class When_mapping_to_a_custom_collection_with_the_same_type_not_implementing_IList : AutoMapperSpecBase { private Source _source; private Destination _destination; public class ValueCollection : IEnumerable<int> { private List<int> implementation = new List<int>(); public ValueCollection(IEnumerable<int> items) { implementation = items.ToList(); } public IEnumerator<int> GetEnumerator() { return implementation.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)implementation).GetEnumerator(); } } public class Source { public ValueCollection Values { get; set; } } public class Destination { public ValueCollection Values { get; set; } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>(); }); protected override void Establish_context() { _source = new Source { Values = new ValueCollection(new[] { 1, 2, 3, 4 }) }; } protected override void Because_of() { _destination = Mapper.Map<Source, Destination>(_source); } [Fact] public void Should_map_the_list_of_source_items() { // here not the EnumerableMapper is used, but just the AssignableMapper! _destination.Values.ShouldBeSameAs(_source.Values); _destination.Values.ShouldNotBeNull(); _destination.Values.ShouldContain(1); _destination.Values.ShouldContain(2); _destination.Values.ShouldContain(3); _destination.Values.ShouldContain(4); } } public class When_mapping_to_a_collection_with_instantiation_managed_by_the_destination : AutoMapperSpecBase { private Destination _destination; private Source _source; public class SourceItem { public int Value { get; set; } } public class DestItem { public int Value { get; set; } } public class Source { public List<SourceItem> Values { get; set; } } public class Destination { private List<DestItem> _values = new List<DestItem>(); public List<DestItem> Values { get { return _values; } } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>() .ForMember(dest => dest.Values, opt => opt.UseDestinationValue()); cfg.CreateMap<SourceItem, DestItem>(); }); protected override void Because_of() { _source = new Source { Values = new List<SourceItem> { new SourceItem { Value = 5 }, new SourceItem { Value = 10 } } }; _destination = Mapper.Map<Source, Destination>(_source); } [Fact] public void Should_assign_the_value_directly() { _destination.Values.Count.ShouldEqual(2); _destination.Values[0].Value.ShouldEqual(5); _destination.Values[1].Value.ShouldEqual(10); } } public class When_mapping_to_an_existing_list_with_existing_items : AutoMapperSpecBase { private Destination _destination; private Source _source; public class SourceItem { public int Value { get; set; } } public class DestItem { public int Value { get; set; } } public class Source { public List<SourceItem> Values { get; set; } } public class Destination { private List<DestItem> _values = new List<DestItem>(); public List<DestItem> Values { get { return _values; } } } protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>() .ForMember(dest => dest.Values, opt => opt.UseDestinationValue()); cfg.CreateMap<SourceItem, DestItem>(); }); protected override void Because_of() { _source = new Source { Values = new List<SourceItem> { new SourceItem { Value = 5 }, new SourceItem { Value = 10 } } }; _destination = new Destination(); _destination.Values.Add(new DestItem()); Mapper.Map(_source, _destination); } [Fact] public void Should_clear_the_list_before_mapping() { _destination.Values.Count.ShouldEqual(2); } } public class When_mapping_a_collection_with_null_members : AutoMapperSpecBase { const string FirstString = null; private IEnumerable<string> _strings = new List<string> { FirstString }; private List<string> _mappedStrings = new List<string>(); protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.AllowNullDestinationValues = true; }); protected override void Because_of() { _mappedStrings = Mapper.Map<IEnumerable<string>, List<string>>(_strings); } [Fact] public void Should_map_correctly() { _mappedStrings.ShouldNotBeNull(); _mappedStrings.Count.ShouldEqual(1); _mappedStrings[0].ShouldBeNull(); } } } }