context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Reflection; /// <summary> /// Use this class to tween properties of objects /// </summary> public class OTTween { /// <summary> /// Tween notification delegate /// </summary> /// <param name="tween">Tween for this notification</param> public delegate void TweenDelegate(OTTween tween); /// <summary> /// Will be fired when a tween has finished. /// </summary> public TweenDelegate onTweenFinish; /// <summary> /// Will be true when a tween is running /// </summary> public bool isRunning { get { return _running; } } public object target { get { return _target; } } List<string> vars = new List<string>(); List<OTEase> easings = new List<OTEase>(); List<OTEase> pongEasings = new List<OTEase>(); List<object> fromValues = new List<object>(); List<object> toValues = new List<object>(); List<FieldInfo> fields = new List<FieldInfo>(); List<PropertyInfo> props = new List<PropertyInfo>(); List<Component> callBackTargets = new List<Component>(); OTEase easing; object _target; float duration; float time = 0; float waitTime = 0; bool _running = false; bool _doStop = false; static OTTweenController controller = null; void CheckController() { if (controller == null) { controller = OT.Controller(typeof(OTTweenController)) as OTTweenController; if (controller == null) { controller = new OTTweenController(); OT.AddController(controller); } } else { if ((OT.Controller(typeof(OTTweenController)) as OTTweenController) == null) OT.AddController(controller); } if (controller != null) controller.Add(this); } /// <summary> /// OTTween constructor /// </summary> /// <param name="target">Object on which to tween properties</param> /// <param name="duration">Tween duration</param> /// <param name="easing">Tween 'default' easing function</param> public OTTween(object target, float duration, OTEase easing) { this._target = target; this.duration = duration; this.easing = easing; CheckController(); } /// <summary> /// OTTween constructor (easing Linear) /// </summary> /// <param name="target">Object on which to tween properties</param> /// <param name="duration">Tween duration</param> public OTTween(object target, float duration) { this._target = target; this.duration = duration; this.easing = OTEasing.Linear; CheckController(); } // ----------------------------------------------------------------- // class methods // ----------------------------------------------------------------- /// <summary> /// Tween has to use callback functions. /// </summary> /// <param name="target">target class that will receive the callbacks.</param> public void InitCallBacks(Component target) { callBackTargets.Add(target); } private void SetVar(string name) { if (target != null) { FieldInfo field = target.GetType().GetField(name); if (field != null) { fromValues.Add(field.GetValue(target)); fields.Add(field); props.Add(null); } else { PropertyInfo prop = target.GetType().GetProperty(name); if (prop != null) { fromValues.Add(prop.GetValue(target, null)); props.Add(prop); fields.Add(null); } else { fromValues.Add(null); fields.Add(null); props.Add(null); } } } } private void TweenVar(object fromValue, object toValue, OTEase easing, FieldInfo field, PropertyInfo prop) { object value = null; if (toValue == null || fromValue == null) return; switch (fromValue.GetType().Name.ToLower()) { case "single": if (!(toValue is float)) toValue = System.Convert.ToSingle(toValue); value = easing.ease(time, (float)fromValue, (float)toValue - (float)fromValue, duration); break; case "double": if (!(toValue is double)) toValue = System.Convert.ToDouble(toValue); value = easing.ease(time, (float)fromValue, (float)toValue - (float)fromValue, duration); break; case "int": case "int32": if (!(toValue is int)) toValue = System.Convert.ToInt32(toValue); value = (int)easing.ease(time, (int)fromValue, (int)toValue - (int)fromValue, duration); break; case "vector2": Vector2 _toValue2 = (Vector2)toValue; Vector2 _fromValue2 = (Vector2)fromValue; Vector2 _value2 = Vector2.zero; if ((_toValue2 - _fromValue2).x != 0) _value2.x = easing.ease(time, _fromValue2.x, (_toValue2 - _fromValue2).x, duration); else _value2.x = _fromValue2.x; if ((_toValue2 - _fromValue2).y != 0) _value2.y = easing.ease(time, _fromValue2.y, (_toValue2 - _fromValue2).y, duration); else _value2.y = _fromValue2.y; value = _value2; break; case "vector3": Vector3 _toValue3 = (Vector3)toValue; Vector3 _fromValue3 = (Vector3)fromValue; Vector3 _value3 = Vector3.zero; if ((_toValue3 - _fromValue3).x != 0) _value3.x = easing.ease(time, _fromValue3.x, (_toValue3 - _fromValue3).x, duration); else _value3.y = _fromValue3.y; if ((_toValue3 - _fromValue3).y != 0) _value3.y = easing.ease(time, _fromValue3.y, (_toValue3 - _fromValue3).y, duration); else _value3.y = _fromValue3.y; if ((_toValue3 - _fromValue3).z != 0) _value3.z = easing.ease(time, _fromValue3.z, (_toValue3 - _fromValue3).z, duration); else _value3.z = _fromValue3.z; value = _value3; break; case "color": Color _toColor = (Color)toValue; Color _fromColor = (Color)fromValue; float r = easing.ease(time, _fromColor.r, _toColor.r - _fromColor.r, duration); float g = easing.ease(time, _fromColor.g, _toColor.g - _fromColor.g, duration); float b = easing.ease(time, _fromColor.b, _toColor.b - _fromColor.b, duration); float a = easing.ease(time, _fromColor.a, _toColor.a - _fromColor.a, duration); value = new Color(r, g, b, a); break; } try { if (field != null) field.SetValue(target, value); else if (prop != null) prop.SetValue(target, value, null); } catch(System.Exception) { _doStop = true; return; }; } protected bool CallBack(string handler, object[] param) { for (int t = 0; t < callBackTargets.Count; t++) { MethodInfo mi = callBackTargets[t].GetType().GetMethod(handler); if (mi != null) { mi.Invoke(callBackTargets[t], param); return true; } } return false; } public bool Update(float deltaTime) { if (_doStop) { _running = false; return true; } if (waitTime > 0) { waitTime -= Time.deltaTime; if (waitTime > 0) return false; } if (vars.Count == 0) return false; _running = true; time += deltaTime; if (time > duration) time = duration; for (int v = 0; v < vars.Count; v++) { OTEase easing = this.easing; if (easings[v] != null) easing = easings[v]; TweenVar(fromValues[v], toValues[v], easing, fields[v], props[v]); } if (time == duration) { _running = false; if (onTweenFinish != null) onTweenFinish(this); if (!CallBack("onTweenFinish", new object[] { this })) CallBack("OnTweenFinish", new object[] { this }); return true; } else return false; } /// <summary> /// Sets the wait time (start delay) for this tween /// </summary> /// <param name="waitTime"></param> /// <returns></returns> public OTTween Wait(float waitTime) { this.waitTime = waitTime; return this; } /// <summary> /// Tween a 'public' property of the tween's target object /// </summary> /// <param name="var">Property name</param> /// <param name="fromValue">From value</param> /// <param name="toValue">To value</param> /// <param name="easing">Easing function</param> /// <param name="pongEasing">Easing when 'ponging'</param> /// <returns>Tween object</returns> public OTTween Tween(string var, object fromValue, object toValue, OTEase easing, OTEase pongEasing) { vars.Add(var); SetVar(var); if (fromValue != null) { object fv = fromValues[fromValues.Count - 1]; if (fv != null) { if (fv is float && fromValue is int) fromValue = System.Convert.ToSingle(fromValue); else if (fv is double && fromValue is int) fromValue = System.Convert.ToDouble(fromValue); } fromValues[fromValues.Count - 1] = fromValue; } toValues.Add(toValue); easings.Add(easing); pongEasings.Add(pongEasing); return this; } /// <summary> /// Tween a 'public' property of the tween's target object /// </summary> /// <param name="var">Property name</param> /// <param name="fromValue">From value</param> /// <param name="toValue">To value</param> /// <param name="easing">Easing function</param> /// <returns>Tween object</returns> public OTTween Tween(string var, object fromValue, object toValue, OTEase easing) { return Tween(var, fromValue, toValue, easing, null); } /// <summary> /// Tween a 'public' property of the tween's target object /// </summary> /// <param name="var">Property name</param> /// <param name="fromValue">From value</param> /// <param name="toValue">To value</param> /// <returns>Tween object</returns> public OTTween Tween(string var, object fromValue, object toValue) { return Tween(var, fromValue, toValue, null, null); } /// <summary> /// Tween a 'public' property of the tween's target object /// </summary> /// <param name="var">Property name</param> /// <param name="toValue">To value</param> /// <param name="easing">Easing function</param> /// <param name="pongEasing">Easing when 'ponging'</param> /// <returns>Tween object</returns> public OTTween Tween(string var, object toValue, OTEase easing, OTEase pongEasing) { return Tween(var, null, toValue, easing, pongEasing); } /// <summary> /// Tween a 'public' property of the tween's target object /// </summary> /// <param name="var">Property name</param> /// <param name="toValue">To value</param> /// <param name="easing">Easing function</param> /// <returns>Tween object</returns> public OTTween Tween(string var, object toValue, OTEase easing) { return Tween(var, null, toValue, easing, null); } /// <summary> /// Tween a 'public' property of the tween's target object /// </summary> /// <param name="var">Property name</param> /// <param name="toValue">To value</param> /// <returns>Tween object</returns> public OTTween Tween(string var, object toValue) { return Tween(var, null, toValue, null, null); } /// <summary> /// Tween a 'public' property, adding a value, of the tween's target object. /// </summary> /// <param name="var">Property name</param> /// <param name="addValue">Value to add</param> /// <param name="easing">Easing function</param> /// <param name="pongEasing">Easing when 'ponging'</param> /// <returns>Tween object</returns> public OTTween TweenAdd(string var, object addValue, OTEase easing, OTEase pongEasing) { vars.Add(var); SetVar(var); easings.Add(easing); pongEasings.Add(pongEasing); object fromValue = fromValues[fromValues.Count - 1]; if (fromValue is int) { try { addValue = System.Convert.ToInt32(addValue); } catch (System.Exception) { addValue = 0; } } else if (fromValue is float) { try { addValue = System.Convert.ToSingle(addValue); } catch (System.Exception) { addValue = 0.0f; } } else if (fromValue is double) { try { addValue = System.Convert.ToDouble(addValue); } catch (System.Exception) { addValue = 0.0; } } switch (fromValue.GetType().Name.ToLower()) { case "single": toValues.Add((float)fromValue + (float)addValue); break; case "double": toValues.Add((double)fromValue + (double)addValue); break; case "int": toValues.Add((int)fromValue + (int)addValue); break; case "int32": toValues.Add((int)fromValue + (int)addValue); break; case "vector2": toValues.Add((Vector2)fromValue + (Vector2)addValue); break; case "vector3": toValues.Add((Vector3)fromValue + (Vector3)addValue); break; default: toValues.Add(null); break; } return this; } /// <summary> /// Tween a 'public' property, adding a value, of the tween's target object. /// </summary> /// <param name="var">Property name</param> /// <param name="addValue">Value to add</param> /// <param name="easing">Easing function</param> /// <returns>Tween object</returns> public OTTween TweenAdd(string var, object addValue, OTEase easing) { return TweenAdd(var, addValue, easing, null); } /// <summary> /// Tween a 'public' property, adding a value, of the tween's target object. /// </summary> /// <param name="var">Property name</param> /// <param name="addValue">Value to add</param> /// <returns>Tween object</returns> public OTTween TweenAdd(string var, object addValue) { return TweenAdd(var, addValue, null, null); } /// <summary> /// Stop this tween. /// </summary> public void Stop() { if (isRunning) _doStop = true; } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Plivo.Client; using Plivo.Resource.PhoneNumber ; namespace Plivo.Resource.Powerpack { /// <summary> /// Powerpack interface. /// </summary> public class PowerpackInterface : ResourceInterface { /// <summary> /// Initializes a new instance of the <see cref="T:plivo.Resource.Powerpack.PowerpackInterface"/> class. /// </summary> /// <param name="client">Client.</param> public PowerpackInterface(HttpClient client) : base(client) { Uri = "Account/" + Client.GetAuthId() + "/"; } #region Create /// <summary> /// Create Message with the specified src, dst, text, type, url, method and log. /// </summary> /// <returns>The create.</returns> /// <param name="name">Name.</param> /// <param name="sticky_sender">StickySender.</param> /// <param name="local_connect">LocalConnect.</param> /// <param name="application_type">ApplicationType.</param> /// <param name="application_id">ApplicationID.</param> /// <param name="number_priority">NumberPriority</param> public Powerpack Create( string name, string application_type = null, string application_id = null, bool? sticky_sender = null, bool? local_connect = null, List<NumberPriority> number_priority = null) { var mandatoryParams = new List<string>{"name"}; var data = CreateData( mandatoryParams, new { name, application_type, application_id, sticky_sender, local_connect, number_priority }); return ExecuteWithExceptionUnwrap(() => { var result = Task.Run(async () => await Client.Update<Powerpack>(Uri + "Powerpack/", data).ConfigureAwait(false)).Result; result.Object.StatusCode = result.StatusCode; return result.Object; }); } /// <summary> /// Create Message with the specified src, dst, text, type, url, method and log. /// </summary> /// <returns>The create.</returns> /// <param name="name">Name.</param> /// <param name="sticky_sender">StickySender.</param> /// <param name="local_connect">LocalConnect.</param> /// <param name="application_type">ApplicationType.</param> /// <param name="application_id">ApplicationID.</param> /// <param name="number_priority">NumberPriority.<param> public async Task<Powerpack> CreateAsync( string name, string application_type = null, string application_id = null, bool? sticky_sender = null, bool? local_connect = null, List<NumberPriority> number_priority = null) { var mandatoryParams = new List<string>{"name"}; var data = CreateData( mandatoryParams, new { name, application_type, application_id, sticky_sender, local_connect, number_priority }); var result = await Client.Update<Powerpack>(Uri + "Powerpack/", data); result.Object.StatusCode = result.StatusCode; return result.Object; } #endregion #region GET /// <summary> /// Get Powerpack with the specified uuid. /// </summary> /// <returns>The get.</returns> /// <param name="uuid">Powerpack UUID.</param> public Powerpack Get(string uuid) { return ExecuteWithExceptionUnwrap(() => { var powerpack = Task.Run(async () => await GetResource<Powerpack>("Powerpack/"+uuid).ConfigureAwait(false)).Result; powerpack.Interface = this; powerpack.number_pool_id = powerpack.number_pool.Split('/')[5]; powerpack._phonenumber = new Lazy<PhoneNumberInterface>(() => new PhoneNumberInterface(Client)); powerpack.numberpool = new NumberPool(powerpack.number_pool_id, Client); return powerpack; }); } /// <summary> /// Asynchronously get Powerpack with the specified uuid. /// </summary> /// <returns>The get.</returns> /// <param name="uuid"> UUID.</param> public async Task<Powerpack> GetAsync(string uuid) { var powerpack = await GetResource<Powerpack>("Powerpack/"+uuid); powerpack.Interface = this; powerpack.number_pool_id = powerpack.number_pool.Split('/')[5]; return powerpack; } #endregion #region Delete /// <summary> /// Delete Powerpack with the specified uuid. /// </summary> /// <returns>The delete.</returns> /// <param name="uuid">powerpack identifier.</param> public DeleteResponse<Powerpack> Delete(string uuid, bool? unrent_numbers = false ) { var mandatoryParams = new List<string>{""}; var data = CreateData( mandatoryParams, new { unrent_numbers, }); return ExecuteWithExceptionUnwrap(() => { return Task.Run(async () => await DeleteResource<DeleteResponse<Powerpack>>("Powerpack/"+uuid, data).ConfigureAwait(false)).Result; }); } /// <summary> /// Asynchronously delete Powerpack with the specified uuid. /// </summary> /// <returns>The delete.</returns> /// <param name="uuid">Powerpack identifier.</param> public async Task<DeleteResponse<Powerpack>> DeleteAsync(string uuid, bool? unrent_numbers = false) { var mandatoryParams = new List<string>{""}; var data = CreateData( mandatoryParams, new { unrent_numbers, }); return await DeleteResource<DeleteResponse<Powerpack>>("Powerpack/"+uuid, data); } #endregion #region List /// <summary> /// <summary> /// List Powerpack list limit and offset. /// </summary> /// <returns>The list.</returns> /// <param name="limit">Limit.</param> /// <param name="offset">Offset.</param> public ListResponse<Powerpack> List( uint? limit = null, uint? offset = null) { var mandatoryParams = new List<string> {""}; var data = CreateData( mandatoryParams, new { limit, offset }); return ExecuteWithExceptionUnwrap(() => { var resources = Task.Run(async () => await ListResources<ListResponse<Powerpack>>("Powerpack",data).ConfigureAwait(false)).Result; resources.Objects.ForEach( (obj) => obj.Interface = this ); return resources; }); } /// <summary> /// List Powerpack list limit and offset. /// </summary> /// <returns>The list.</returns> /// <param name="limit">Limit.</param> /// <param name="offset">Offset.</param> public async Task<ListResponse<Powerpack>> ListAsync( uint? limit = null, uint? offset = null) { var mandatoryParams = new List<string> { "" }; var data = CreateData( mandatoryParams, new { limit, offset }); var resources = await ListResources<ListResponse<Powerpack>>("Powerpack", data); resources.Objects.ForEach( (obj) => obj.Interface = this ); return resources; } #endregion #region Update /// <summary> /// Update the specified name, city, address and state. /// </summary> /// <returns>The update.</returns> /// <param name="name">Name.</param> /// <param name="sticky_sender">StickySender.</param> /// <param name="local_connect">LocalConnect.</param> /// <param name="application_type">ApplicationType.</param> /// <param name="application_id">ApplicationID.</param> ///<param name="uuid">UUID.</param> /// <param name="number_priority">NumberPriority.</param> public UpdateResponse<Powerpack> Update(string uuid, string name=null, string application_type = null, string application_id = null, bool? sticky_sender = null, bool? local_connect = null, List<NumberPriority> number_priority = null) { var mandatoryParams = new List<string> { "uuid" }; var data = CreateData(mandatoryParams, new { name, application_type, application_id, sticky_sender, local_connect, number_priority }); return ExecuteWithExceptionUnwrap(() => { var result = Task.Run(async () => await Client.Update<UpdateResponse<Powerpack>>(Uri +"Powerpack/"+uuid+"/", data).ConfigureAwait(false)).Result; result.Object.StatusCode = result.StatusCode; return result.Object; }); } /// <summary> /// Update the specified name, sticky_sender, localconnect. /// </summary> /// <returns>The create.</returns> /// <param name="name">Name.</param> /// <param name="sticky_sender">StickySender.</param> /// <param name="local_connect">LocalConnect.</param> /// <param name="application_type">ApplicationType.</param> /// <param name="application_id">ApplicationID.</param> ///<param name="uuid">UUID.</param> /// <param name="number_priority">NumberPriority.</param> public async Task<UpdateResponse<Powerpack>> UpdateAsync(string uuid, string name=null, string application_type = null, string application_id = null, bool? sticky_sender = null, bool? local_connect = null, List<NumberPriority> number_priority = null) { var mandatoryParams = new List<string> { "uuid" }; var data = CreateData( mandatoryParams, new { name, application_type, application_id, sticky_sender, local_connect, number_priority }); var result = await Client.Update<UpdateResponse<Powerpack>>(Uri +"Powerpack/"+uuid, data); result.Object.StatusCode = result.StatusCode; return result.Object; } #endregion #region ListNumber /// <summary> /// List Powerpack Number limit and offset. /// </summary> /// <returns>The list.</returns> /// <param name="starts_with">StartWith.</param> /// <param name="country_iso2">Countryiso2.</param> /// <param name="type">Type.</param> /// <param name="limit">Limit.</param> /// <param uuid="uuid">UUID</param> /// <param name="offset">Offset.</param> public ListResponse<Numbers> List_Numbers(string uuid, string starts_with =null, string country_iso2 =null, string type=null, uint? limit = null, uint? offset = null, string service = null) { var mandatoryParams = new List<string> {""}; var data = CreateData( mandatoryParams, new { starts_with, country_iso2, type, limit, offset, service }); return ExecuteWithExceptionUnwrap(() => { var resources = Task.Run(async () => await ListResources<ListResponse<Numbers>>("NumberPool/"+uuid+"/Number", data).ConfigureAwait(false)).Result; resources.Objects.ForEach( (obj) => obj.Interface = this ); return resources; }); } /// <summary> /// List Powerpack Number limit and offset. /// </summary> /// <returns>The list.</returns> /// <param name="starts_with">StartWith.</param> /// <param name="country_iso2">Countryiso2.</param> /// <param name="type">Type.</param> /// <param name="limit">Limit.</param> /// <param uuid="uuid">UUID</param> /// <param name="offset">Offset.</param> public async Task<ListResponse<Numbers>> List_NumbersAsync( string uuid, string starts_with =null, string country_iso2 =null, string type=null, uint? limit = null, uint? offset = null, string service = null) { var mandatoryParams = new List<string> { "" }; var data = CreateData( mandatoryParams, new { starts_with, country_iso2, type, limit, offset, service }); var resources = await ListResources<ListResponse<Numbers>>("NumberPool/"+uuid+"/Number", data); resources.Objects.ForEach( (obj) => obj.Interface = this ); return resources; } public string Hello(){ return "Hi"; } #endregion #region GETNUMBERCOUNT /// <summary> /// List Powerpack Number limit and offset. /// </summary> /// <returns>The list.</returns> /// <param name="starts_with">StartWith.</param> /// <param name="country_iso2">Countryiso2.</param> /// <param name="type">Type.</param> /// <param name="limit">Limit.</param> /// <param uuid="uuid">UUID</param> /// <param name="offset">Offset.</param> public uint Count_Number(string uuid, string starts_with =null, string country_iso2 =null, string type=null, uint? limit = null, uint? offset = null, string service = null) { var mandatoryParams = new List<string> {""}; var data = CreateData( mandatoryParams, new { starts_with, country_iso2, type, limit, offset, service }); // return ExecuteWithExceptionUnwrap(() => // { var resources = Task.Run(async () => await ListResources<ListResponse<Numbers>>("NumberPool/"+uuid+"/Number", data).ConfigureAwait(false)).Result; resources.Objects.ForEach( (obj) => obj.Interface = this ); return resources.Meta.TotalCount; // Need to check // }); } /// <summary> /// List Powerpack Number limit and offset. /// </summary> /// <returns>The list.</returns> /// <param name="starts_with">StartWith.</param> /// <param name="country_iso2">Countryiso2.</param> /// <param name="type">Type.</param> /// <param name="limit">Limit.</param> /// <param uuid="uuid">UUID</param> /// <param name="offset">Offset.</param> public async Task<uint> Count_NumbersAsync( string uuid, string starts_with =null, string country_iso2 =null, string type=null, uint? limit = null, uint? offset = null, string service = null) { var mandatoryParams = new List<string> { "" }; var data = CreateData( mandatoryParams, new { starts_with, country_iso2, type, limit, offset, service }); var resources = await ListResources<ListResponse<Numbers>>("NumberPool/"+uuid+"/Number", data); resources.Objects.ForEach( (obj) => obj.Interface = this ); return resources.Meta.TotalCount; } #endregion #region ADDNUMBER /// <summary> /// Add a number /// </summary> /// <returns>The Number resource.</returns> /// <param name="uuid">UUID.</param> /// <param name="number">Number.</param> public Numbers Add_Number( string uuid, string number, string service = null, bool rent=false) { var mandatoryParams = new List<string>{""}; var data= CreateData( mandatoryParams, new { rent, service }); return ExecuteWithExceptionUnwrap(() => { var result = Task.Run(async () => await Client.Update<Numbers>(Uri + "NumberPool/"+uuid.ToString()+"/Number/"+number.ToString()+"/", data).ConfigureAwait(false)).Result; result.Object.StatusCode = result.StatusCode; return result.Object; }); } /// <summary> /// Add a number /// </summary> /// <returns>The Number resource.</returns> /// <param name="uuid">UUID.</param> /// <param name="number">Number.</param> public async Task<Numbers> Add_NumberAsync( string uuid, string number, string service = null, bool rent=false) { var mandatoryParams = new List<string>{""}; var data = CreateData( mandatoryParams, new { rent, service }); var result = await Client.Update<Numbers>(Uri + "NumberPool/"+uuid+"/Number/"+number+"/", data); result.Object.StatusCode = result.StatusCode; return result.Object; } #endregion #region ADDTOLLFREE /// <summary> /// Add a tollfree /// </summary> /// <returns>The Tollfree resource.</returns> /// <param name="uuid">UUID.</param> /// <param name="tollfree">Tollfree.</param> public Tollfree Add_Tollfree( string uuid, string tollfree, bool rent=false ) { var mandatoryParams = new List<string>{""}; var data= CreateData( mandatoryParams, new { rent }); return ExecuteWithExceptionUnwrap(() => { var result = Task.Run(async () => await Client.Update<Tollfree>(Uri + "NumberPool/"+uuid.ToString()+"/Tollfree/"+tollfree.ToString()+"/", data).ConfigureAwait(false)).Result; result.Object.StatusCode = result.StatusCode; return result.Object; }); } /// <summary> /// Add a tollfree /// </summary> /// <returns>The Tollfree resource.</returns> /// <param name="uuid">UUID.</param> /// <param name="tollfree">Tollfree.</param> public async Task<Tollfree> Add_TollfreeAsync( string uuid, string tollfree, bool rent=false) { var mandatoryParams = new List<string>{""}; var data = CreateData( mandatoryParams, new { rent }); var result = await Client.Update<Tollfree>(Uri + "NumberPool/"+uuid+"/Tollfree/"+tollfree+"/", data); result.Object.StatusCode = result.StatusCode; return result.Object; } #endregion #region REMOVENUMBER /// <summary> /// Remove a number /// </summary> /// <returns>The Number resource.</returns> /// <param name="uuid">UUID.</param> /// <param name="number">Number.</param> public DeleteResponse<Numbers> Remove_Number(string uuid, string number, bool? unrent=null) { var mandatoryParams = new List<string>{""}; var data = CreateData( mandatoryParams, new { unrent, }); return ExecuteWithExceptionUnwrap(() => { return Task.Run(async () => await DeleteResource<DeleteResponse<Numbers>>("NumberPool/"+uuid+"/Number/"+number, data).ConfigureAwait(false)).Result; }); } /// <summary> /// Add a number /// </summary> /// <returns>The Number resource.</returns> /// <param name="uuid">UUID.</param> /// <param name="number">Number.</param> public async Task<DeleteResponse<Numbers>> Remove_NumberAsync( string uuid, string number, bool? unrent=null) { var mandatoryParams = new List<string>{""}; var data = CreateData( mandatoryParams, new { unrent, }); return await DeleteResource<DeleteResponse<Numbers>>("NumberPool/"+uuid+"/Number/"+number, data); } #endregion #region REMOVETOLLFREE /// <summary> /// Remove a tollfree /// </summary> /// <returns>The Tollfree resource.</returns> /// <param name="uuid">UUID.</param> /// <param name="tollfree">Tollfree.</param> public DeleteResponse<Tollfree> Remove_Tollfree(string uuid, string tollfree, bool? unrent=null) { var mandatoryParams = new List<string>{""}; var data = CreateData( mandatoryParams, new { unrent, }); return ExecuteWithExceptionUnwrap(() => { return Task.Run(async () => await DeleteResource<DeleteResponse<Tollfree>>("NumberPool/"+uuid+"/Tollfree/"+tollfree, data).ConfigureAwait(false)).Result; }); } /// <summary> /// Add a number /// </summary> /// <returns>The Number resource.</returns> /// <param name="uuid">UUID.</param> /// <param name="tollfree">Tollfree.</param> public async Task<DeleteResponse<Tollfree>> Remove_TollfreeAsync( string uuid, string tollfree, bool? unrent=null) { var mandatoryParams = new List<string>{""}; var data = CreateData( mandatoryParams, new { unrent, }); return await DeleteResource<DeleteResponse<Tollfree>>("NumberPool/"+uuid+"/Tollfree/"+tollfree, data); } #endregion #region FINDNUMBER /// <summary> /// Find a number /// </summary> /// <returns>The Number resource.</returns> /// <param name="uuid">UUID.</param> /// <param name="number">Number.</param> /// <param name="service">Service.</param> public Numbers Find_Number(string uuid,string number, string service = null) { var mandatoryParams = new List<string>{""}; var data= CreateData( mandatoryParams, new { service }); return ExecuteWithExceptionUnwrap(() => { var numberpoolResponse = Task.Run(async () => await GetResource<Numbers>("NumberPool/"+uuid+"/Number/"+number, data).ConfigureAwait(false)).Result; numberpoolResponse.Interface = this; return numberpoolResponse; }); } public async Task<Numbers> Find_NumberAsync(string uuid, string number, string service = null) { var mandatoryParams = new List<string>{""}; var data= CreateData( mandatoryParams, new { service }); var numberpoolresp = await GetResource<Numbers>("NumberPool/"+uuid+"/Number/"+number, data); numberpoolresp.Interface = this; return numberpoolresp; } #endregion #region LISTSHORTCODE /// <summary> /// Find a number /// </summary> /// <returns>The Number resource.</returns> public ListResponse<Shortcode> ListShortcode(string uuid, uint? limit = null, uint? offset = null) { var mandatoryParams = new List<string> {""}; var data = CreateData( mandatoryParams, new { limit, offset }); return ExecuteWithExceptionUnwrap(() => { var resources = Task.Run(async () => await ListResources<ListResponse<Shortcode>>("NumberPool/"+uuid+"/Shortcode", data).ConfigureAwait(false)).Result; resources.Objects.ForEach( (obj) => obj.Interface = this ); return resources; }); } /// <summary> /// List Powerpack Shortcode limit and offset. /// </summary> /// <returns>The list.</returns> /// <param name="limit">Limit.</param> /// <param uuid="uuid">UUID</param> /// <param name="offset">Offset.</param> public async Task<ListResponse<Shortcode>> List_ShortcodeAsync( string uuid, uint? limit = null, uint? offset = null) { var mandatoryParams = new List<string> { "" }; var data = CreateData( mandatoryParams, new { limit, offset }); var resources = await ListResources<ListResponse<Shortcode>>("NumberPool/"+uuid+"/Shortcode", data); resources.Objects.ForEach( (obj) => obj.Interface = this ); return resources; } #endregion #region FINDSHORTCODE /// <summary> /// Find a shortcode /// </summary> /// <returns>The Shortcode resource.</returns> /// <param name="uuid">UUID.</param> /// <param name="shortcode">Shortcode.</param> public Shortcode Find_Shortcode(string shortcode, string uuid) { return ExecuteWithExceptionUnwrap(() => { var powerpackresp = Task.Run(async () => await GetResource<Shortcode>("NumberPool/"+uuid+"/Shortcode/"+shortcode).ConfigureAwait(false)).Result; powerpackresp.Interface = this; return powerpackresp; }); } public async Task<Shortcode> Find_ShortcodeAsync( string shortcode, string uuid) { var shortcodeResponse = await GetResource<Shortcode>("NumberPool/"+uuid+"/Shortcode/"+shortcode); shortcodeResponse.Interface = this; return shortcodeResponse; } #endregion #region REMOVESHORTCODE /// <summary> /// Remove a shortcode /// </summary> /// <returns>The Shortcode resource.</returns> /// <param name="uuid">UUID.</param> /// <param name="shortcode">Shortcode.</param> public DeleteResponse<Shortcode> Remove_Shortcode(string uuid, string shortcode, bool? unrent=null) { var mandatoryParams = new List<string>{""}; var data = CreateData( mandatoryParams, new { unrent, }); return ExecuteWithExceptionUnwrap(() => { return Task.Run(async () => await DeleteResource<DeleteResponse<Shortcode>>("NumberPool/"+uuid+"/Shortcode/"+shortcode, data).ConfigureAwait(false)).Result; }); } /// <summary> /// Add a number /// </summary> /// <returns>The Number resource.</returns> /// <param name="uuid">UUID.</param> /// <param name="shortcode">Shortcode.</param> public async Task<DeleteResponse<Shortcode>> Remove_ShortcodeAsync( string uuid, string shortcode, bool? unrent=null) { var mandatoryParams = new List<string>{""}; var data = CreateData( mandatoryParams, new { unrent, }); return await DeleteResource<DeleteResponse<Shortcode>>("NumberPool/"+uuid+"/Shortcode/"+shortcode, data); } #endregion #region LISTTOLLFREE /// <summary> /// Find a number /// </summary> /// <returns>The Number resource.</returns> public ListResponse<Tollfree> ListTollfree(string uuid, uint? limit = null, uint? offset = null) { var mandatoryParams = new List<string> {""}; var data = CreateData( mandatoryParams, new { limit, offset }); return ExecuteWithExceptionUnwrap(() => { var resources = Task.Run(async () => await ListResources<ListResponse<Tollfree>>("NumberPool/"+uuid+"/Tollfree", data).ConfigureAwait(false)).Result; resources.Objects.ForEach( (obj) => obj.Interface = this ); return resources; }); } /// <summary> /// List Powerpack Tollfree limit and offset. /// </summary> /// <returns>The list.</returns> /// <param name="limit">Limit.</param> /// <param uuid="uuid">UUID</param> /// <param name="offset">Offset.</param> public async Task<ListResponse<Tollfree>> List_TollfreeAsync( string uuid, uint? limit = null, uint? offset = null) { var mandatoryParams = new List<string> { "" }; var data = CreateData( mandatoryParams, new { limit, offset }); var resources = await ListResources<ListResponse<Tollfree>>("NumberPool/"+uuid+"/Tollfree", data); resources.Objects.ForEach( (obj) => obj.Interface = this ); return resources; } #endregion #region FINDTOLLFREE /// <summary> /// Find a tollfree /// </summary> /// <returns>The Tikkfree resource.</returns> /// <param name="uuid">UUID.</param> /// <param name="tollfree">Tollfree.</param> public Tollfree Find_Tollfree(string tollfree, string uuid) { return ExecuteWithExceptionUnwrap(() => { var powerpackresp = Task.Run(async () => await GetResource<Tollfree>("NumberPool/"+uuid+"/Tollfree/"+tollfree).ConfigureAwait(false)).Result; powerpackresp.Interface = this; return powerpackresp; }); } public async Task<Tollfree> Find_TollfreeAsync( string tollfree, string uuid) { var tollfreeResponse = await GetResource<Tollfree>("NumberPool/"+uuid+"/Tollfree/"+tollfree); tollfreeResponse.Interface = this; return tollfreeResponse; } #endregion } }
#region License /* Copyright (c) 2003-2015 Llewellyn Pritchard * All rights reserved. * This source code is subject to terms and conditions of the BSD License. * See license.txt. */ #endregion using System; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using IronScheme.Editor.Collections; using System.Reflection; using LSharp; namespace IronScheme.Editor.ComponentModel { /// <summary> /// Provide keyboard handling services /// </summary> public interface IKeyboardService : IService { // bool Register(string method, ICollection keys); // bool Register(string method, ICollection keys, bool ignoreshift, ApplicationState state); } /// <summary> /// Summary description for KeyboardHandler. /// </summary> sealed class KeyboardHandler : ServiceBase, IKeyboardService { readonly HashTree tree = new HashTree(); readonly Stack stack = new Stack(); readonly static TypeConverter keyconv = new KeysConverterEx(); readonly Hashtable targets = new Hashtable(); sealed class KeysConverterEx : KeysConverter { public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { if (value is string) { // Ctrl+Shift+Alt+(J,K,L) string[] tokens = ((string)value).Split('+'); string last = tokens[tokens.Length - 1].Trim(); if (last.StartsWith("(") && last.EndsWith(")")) { string[] skeys = last.TrimEnd(')').TrimStart('(').Split(','); Keys[] keys = new Keys[skeys.Length]; Keys mod = 0; for (int i = 0; i < tokens.Length - 1; i++) { mod |= (Keys)ConvertFrom(context, culture, tokens[i].Trim()); } for (int i = 0; i < keys.Length; i++) { keys[i] = (Keys)ConvertFrom(context, culture, skeys[i].Trim()); keys[i] |= mod; } return keys; } } return base.ConvertFrom (context, culture, value); } } public void DumpKeys() { Set t = new Set(); foreach (Keys[] keys in targets.Values) { if (tree.Contains(keys)) { foreach (Action a in tree[keys] as ArrayList) { string sa = string.Format("{0,-60} Keys: {1}", a, KeyString(keys)); t.Add(sa); } } } ArrayList st = new ArrayList(t); st.Sort(); foreach (string h in st) { Console.WriteLine(h); } } public void DumpTargets() { Set t = new Set(); foreach (Action a in targets.Keys) { string sa = string.Format("{0,-60} Keys: {1}", a, KeyString(targets[a] as Keys[])); t.Add(sa); } ArrayList st = new ArrayList(t); st.Sort(); foreach (string h in st) { Console.WriteLine(h); } } internal abstract class Action { public ApplicationState State = 0; protected static readonly object[] NOPARAMS = {}; public IService target; public bool StartInvoke() { try { if (target is ServiceBase) { if ((((ServiceBase)target).MenuState & State) == State) { System.Diagnostics.Trace.WriteLine(this.ToString()); Invoke(); return true; } } else { System.Diagnostics.Trace.WriteLine(this.ToString()); Invoke(); return true; } } catch (Exception ex) { #if DEBUG System.Diagnostics.Trace.WriteLine(ex.ToString(), "Action.Invoke"); #else throw ex; #endif } return false; } public abstract void Invoke(); } static string GetServiceName(IService svc) { if (Attribute.IsDefined(svc.GetType(), typeof(NameAttribute))) { NameAttribute na = Attribute.GetCustomAttribute(svc.GetType(), typeof(NameAttribute)) as NameAttribute; return na.Name; } return svc.ToString(); } internal sealed class ToggleAction : Action { public PropertyInfo pi; public override void Invoke() { pi.SetValue(target,!((bool)pi.GetValue(target, NOPARAMS)), NOPARAMS); } public override string ToString() { return string.Format("Toggle: {0}.{1} [{2}]", GetServiceName(target), pi.Name, State); } public override bool Equals(object obj) { ToggleAction a = obj as ToggleAction; if (a == null) { return false; } return a.target == target && a.pi == pi && a.State == State; } public override int GetHashCode() { return target.GetHashCode() ^ pi.GetHashCode() ^ (int)State; } } internal sealed class ClosureAction : Action { public Closure clos; public override void Invoke() { clos.Invoke(); } public override string ToString() { return string.Format("Closure:{0} [{1}]", clos.ToString().Replace("LSharp.Closure ", string.Empty), State); } public override bool Equals(object obj) { ClosureAction a = obj as ClosureAction; if (a == null) { return false; } return a.clos == clos && a.State == State; } public override int GetHashCode() { return clos.GetHashCode() ^ (int)State; } } internal sealed class InvokeAction : Action { public MethodInfo mi; public override void Invoke() { mi.Invoke(target, NOPARAMS); } public override string ToString() { return string.Format("Action: {0}.{1} [{2}]", GetServiceName(target), mi.Name, State); } public override bool Equals(object obj) { InvokeAction a = obj as InvokeAction; if (a == null) { return false; } return a.target == target && a.mi == mi && a.State == State; } public override int GetHashCode() { return target.GetHashCode() ^ mi.GetHashCode() ^ (int)State; } } internal sealed class DialogInvokeAction : Action { public MethodInfo mi; object[] pars = null; public override void Invoke() { if (pars == null) { ParameterInfo[] pis = mi.GetParameters(); int plen = pis.Length; pars = new object[plen]; for (int i = 0; i < pars.Length; i++) { pars[i] = TypeDescriptor.GetConverter(pis[i].ParameterType).ConvertToString(pis[i].DefaultValue); } } Controls.DialogInvokeActionForm df = new IronScheme.Editor.Controls.DialogInvokeActionForm(mi); if (df.ShowDialog(ServiceHost.Window.MainForm) == DialogResult.OK) { pars = df.GetValues(); try { mi.Invoke(target, pars); } catch (Exception ex) { MessageBox.Show(ServiceHost.Window.MainForm, ex.GetBaseException().Message, "Error running command!", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } public override string ToString() { return string.Format("Dialog: {0}.{1} [{2}]", GetServiceName(target), mi.Name, State); } public override bool Equals(object obj) { InvokeAction a = obj as InvokeAction; if (a == null) { return false; } return a.target == target && a.mi == mi && a.State == State; } public override int GetHashCode() { return target.GetHashCode() ^ mi.GetHashCode() ^ (int)State; } } public void AddToggle(IService t, PropertyInfo pi) { ToggleAction a = new ToggleAction(); a.target = t; a.pi = pi; targets[a] = new Keys[] {Keys.None}; } public void AddTarget(IService t, MethodInfo mi) { InvokeAction a = new InvokeAction(); a.target = t; a.mi = mi; targets[a] = new Keys[] {Keys.None}; } public KeyboardHandler() { ServiceHost.Window.MainForm.KeyDown +=new KeyEventHandler(MainForm_KeyDown); ServiceHost.Window.MainForm.KeyUp += new KeyEventHandler(MainForm_KeyUp); } public bool Register(Closure clos, ICollection keys, bool ignoreshift, ApplicationState state) { if (ignoreshift) { ArrayList k = new ArrayList(keys); for (int i = 0; i < k.Count; i++) { k[i] = "Shift+" + k[i]; } Register(clos, k, state); } return Register(clos, keys, state); } public bool Register(Closure clos, ICollection keys, bool ignoreshift) { return Register(clos, keys, ignoreshift, ApplicationState.Normal); } public bool Register(Closure clos, ICollection keys) { return Register(clos, keys, ApplicationState.Normal); } public bool Register(Closure clos, ICollection keys, ApplicationState state) { ArrayList kk = new ArrayList(keys); Keys[] k = new Keys[keys.Count]; if (keys.Count > 1) { for (int i = 0; i < k.Length; i++) { k[i] = (Keys)keyconv.ConvertFrom(kk[i]); } } else { object o = keyconv.ConvertFrom(kk[0]); if (o is Keys[]) { k = o as Keys[]; } else { k[0] = (Keys)o; } } ClosureAction a = new ClosureAction(); a.clos = clos; a.State = state; return Register(a, k); } public bool Register(string method, ICollection keys, bool ignoreshift, ApplicationState state) { if (ignoreshift) { ArrayList k = new ArrayList(keys); for (int i = 0; i < k.Count; i++) { k[i] = "Shift+" + k[i]; } Register(method, k, state); } return Register(method, keys, state); } public bool Register(string method, ICollection keys, bool ignoreshift) { return Register(method, keys, ignoreshift, ApplicationState.Normal); } public bool Register(string method, ICollection keys) { return Register(method, keys, ApplicationState.Normal); } public bool Register(string method, ICollection keys, ApplicationState state) { const BindingFlags BF = BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Instance; ArrayList kk = new ArrayList(keys); Keys[] k = new Keys[keys.Count]; if (keys.Count > 1) { for (int i = 0; i < k.Length; i++) { k[i] = (Keys)keyconv.ConvertFrom(kk[i]); } } else { object o = keyconv.ConvertFrom(kk[0]); if (o is Keys[]) { k = o as Keys[]; } else { k[0] = (Keys)o; } } // service.member(type,...) Type[] types = null; string[] tokens = method.Split('.', '('); string last = tokens[tokens.Length - 1].Trim(); if (last.EndsWith(")")) { string[] stypes = last.TrimEnd(')').Split(','); types = new Type[stypes.Length]; for (int i = 0; i < types.Length; i++) { types[i] = LSharp.TypeCache.FindType(stypes[i].Trim()); } } IService svc = typeof(ServiceHost).GetProperty(tokens[0], BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly ).GetValue(null, new object[0]) as IService; if (svc == null) { Trace.WriteLine("Invalid service: {0}", tokens[0]); return false; } Action a = null; PropertyInfo pi = svc.GetType().GetProperty(tokens[1], BF, null, typeof(bool), new Type[0], null); if (pi != null) { ToggleAction ta = new ToggleAction(); ta.target = svc; ta.pi = pi; a = ta; } if (types == null) { MethodInfo mi = svc.GetType().GetMethod(tokens[1], BF, null, new Type[0], null); if (mi != null && mi.ReturnType == typeof(void)) { InvokeAction ta = new InvokeAction(); ta.target = svc; ta.mi = mi; a = ta; } } else { MethodInfo mi = svc.GetType().GetMethod(tokens[1], BF, null, types, null); if (mi != null) { DialogInvokeAction ta = new DialogInvokeAction(); ta.target = svc; ta.mi = mi; a = ta; } } if (a == null) { Trace.WriteLine("WARNING: {0} NOT BOUND to {1} . Target not found.", KeyString(k), method); return false; } a.State = state; return Register(a, k); } static string KeyString(Keys[] keys) { string[] ks = new string[keys.Length]; for (int i = 0; i < ks.Length; i++) { ks[i] = "(" + keyconv.ConvertToString(keys[i]) + ")"; } return string.Join(" ", ks); } internal bool Register(Action handler, params Keys[] keys) { if (keys.Length == 0) { return false; } targets[handler] = keys; ArrayList handlers = tree[keys] as ArrayList; if (handlers == null) { tree[keys] = (handlers = new ArrayList()); } for (int i = 0; i < handlers.Count; i++) { if (((Action)handlers[i]).State == handler.State) { handlers[i] = handler; goto SUCCESS; } } handlers.Add(handler); SUCCESS: //tree[keys] = handler; Trace.WriteLine("Key: {0,-35} {1}", KeyString(keys), handler); return true; } bool MatchStack(object[] keys) { #if CHECK System.Diagnostics.Trace.Write("Current:\t"); foreach (Keys k in keys) { System.Diagnostics.Trace.Write("(" + k + ") "); } System.Diagnostics.Trace.WriteLine(""); #endif if (tree.Contains(keys)) { ArrayList hs = (tree[keys] as ArrayList); #if CHECK System.Diagnostics.Trace.Write("Accepts:\t"); foreach (Keys k in keys) { System.Diagnostics.Trace.Write("(" + k + ") "); } #endif bool success = false; foreach (Action h in new ArrayList(hs)) { success = h.StartInvoke(); if (success) { break; } } #if CHECK if (!success) { System.Diagnostics.Trace.WriteLine("Action: No action bound at current state, ignoring."); } #endif stack.Clear(); return success; } else { if (keys.Length == 1) { return false; } object[] subkeys = new object[keys.Length - 1]; Array.Copy(keys, 1, subkeys, 0, subkeys.Length); if (MatchStack(subkeys)) { return true; } if (!tree.IsInPath(keys)) { object[] current = stack.ToArray(); Array.Reverse(current); stack.Clear(); for (int i = 1; i < current.Length; i++) { stack.Push(current[i]); } } } return false; } internal void MainForm_KeyDown(object sender, KeyEventArgs e) { stack.Push(e.KeyData); object[] keys = stack.ToArray(); Array.Reverse(keys); //System.Diagnostics.Trace.Write("KeyDown:\t"); //foreach (Keys k in keys) //{ // System.Diagnostics.Trace.Write("(" + k + ") "); //} //System.Diagnostics.Trace.WriteLine(""); e.Handled = MatchStack(keys); #warning FIX MULTIPLE KEYSTROKES SOMEHOW } void MainForm_KeyUp(object sender, KeyEventArgs e) { //System.Diagnostics.Trace.Write("KeyUp:\t"); //System.Diagnostics.Trace.Write("(" + e.KeyData + ") "); //System.Diagnostics.Trace.WriteLine(""); } } }
using NUnit.Framework; using Ui.Console.Startup; using ContentType = Core.Model.ContentType; namespace Ui.Console.Test.Startup { [TestFixture] public class ApplicationArgumentsTest { private ApplicationArguments arguments; [TestFixture] public class IsValidOperationTest : ApplicationArgumentsTest { [TestFixture] public class ShouldBeTrueWhen : IsValidOperationTest { [SetUp] public void Setup() { arguments = new ApplicationArguments { CreateOperation = OperationTarget.None, VerifyOperation = OperationTarget.None, IsConvertOperation = false }; } [TestCase(OperationTarget.Key, ExpectedResult = true)] [TestCase(OperationTarget.Signature, ExpectedResult = true)] public bool CreateOperationIsNotNone(OperationTarget target) { arguments.CreateOperation = target; return arguments.IsValidOperation; } [TestCase(OperationTarget.Key, ExpectedResult = true)] [TestCase(OperationTarget.Signature, ExpectedResult = true)] public bool VerifyOperationIsNotNone(OperationTarget target) { arguments.VerifyOperation = target; return arguments.IsValidOperation; } [Test] public void IsConvertOperationIsNotFalse() { arguments.IsConvertOperation = true; Assert.IsTrue(arguments.IsValidOperation); } } [TestFixture] public class ShouldBeFalseWhen : IsValidOperationTest { [SetUp] public void Setup() { arguments = new ApplicationArguments { CreateOperation = OperationTarget.Key, VerifyOperation = OperationTarget.None, IsConvertOperation = false }; } [TestCase(OperationTarget.Key, OperationTarget.Key, ExpectedResult = false)] [TestCase(OperationTarget.Key, OperationTarget.Signature, ExpectedResult = false)] [TestCase(OperationTarget.Signature, OperationTarget.Key, ExpectedResult = false)] [TestCase(OperationTarget.Signature, OperationTarget.Signature, ExpectedResult = false)] public bool CreateAndVerifyOperationsAreNotNone(OperationTarget create, OperationTarget verify) { arguments.CreateOperation = create; arguments.VerifyOperation = verify; return arguments.IsValidOperation; } [Test] public void CreateAndVerifyOperationsAreNoneAndIsConvertIsFalse() { arguments.CreateOperation = OperationTarget.None; arguments.IsConvertOperation = false; Assert.IsFalse(arguments.IsValidOperation); } } } [TestFixture] public class IsCreate : ApplicationArgumentsTest { [Test] public void ShouldBeFalseWhenCreateIsNone() { arguments = new ApplicationArguments { CreateOperation = OperationTarget.None }; Assert.IsFalse(arguments.IsCreate); } [TestCase(OperationTarget.Key, TestName = "Key")] [TestCase(OperationTarget.Signature, TestName = "Signature")] public void ShouldBeTrueWhenCreateIsNotNone(OperationTarget target) { arguments = new ApplicationArguments { CreateOperation = target }; Assert.IsTrue(arguments.IsCreate); } } [TestFixture] public class HasSignature : ApplicationArgumentsTest { [Test] public void ShouldBeTrueWhenSignatureHasContent() { arguments = new ApplicationArguments { Signature = "." }; Assert.IsTrue(arguments.HasSignature); } [TestCase(null, TestName = "null")] [TestCase("", TestName = "empty")] [TestCase(" ", TestName = "whitespace")] public void ShouldBeFalseWhenSignatureHasNoContent(string signature) { arguments = new ApplicationArguments { Signature = signature }; Assert.IsFalse(arguments.HasSignature); } } [TestFixture] public class HasFileOutput : ApplicationArgumentsTest { [Test] public void ShouldBeTrueWhenFileOutputHasContent() { arguments = new ApplicationArguments { FileOutput = "foo" }; Assert.IsTrue(arguments.HasFileOutput); } [TestCase(null, TestName = "null")] [TestCase("", TestName = "empty")] [TestCase(" ", TestName = "whitespace")] public void ShouldBeFalseWhenFileOutputHasNoContent(string output) { arguments = new ApplicationArguments { FileOutput = output }; Assert.IsFalse(arguments.HasFileOutput); } } [TestFixture] public class HasFileInput : ApplicationArgumentsTest { [Test] public void ShouldBeTrueWhenFileInputHasContent() { arguments = new ApplicationArguments { FileInput = "foobar" }; Assert.IsTrue(arguments.HasFileInput); } [TestCase(null, TestName = "null")] [TestCase("", TestName = "empty")] [TestCase(" ", TestName = "whitespace")] public void ShouldBeFalseWhenFileInputHasNoContent(string input) { arguments = new ApplicationArguments { FileInput = input }; Assert.IsFalse(arguments.HasFileInput); } } [TestFixture] public class IsContentTypeSsh : ApplicationArgumentsTest { [SetUp] public void Setup() { arguments = new ApplicationArguments(); } [TestCase(ContentType.OpenSsh)] [TestCase(ContentType.Ssh2)] public void ShouldReturnTrueWhenContentTypeIsSsh(ContentType type) { arguments.ContentType = type; Assert.IsTrue(arguments.IsContentTypeSsh); } [TestCase(ContentType.Der)] [TestCase(ContentType.Pem)] [TestCase(ContentType.NotSpecified)] public void ShouldReturnFalseWhenContentTypeIsNotSsh(ContentType type) { arguments.ContentType = type; Assert.IsFalse(arguments.IsContentTypeSsh); } } } }
// 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.Linq; using Xunit; namespace System.Net.Http.Tests { public class CurlResponseParseUtilsTest { private const string StatusCodeTemplate = "HTTP/1.1 {0} {1}"; private const string MissingSpaceFormat = "HTTP/1.1 {0}InvalidPhrase"; private const string StatusCodeVersionFormat = "HTTP/{0}.{1} 200 OK"; private const string StatusCodeMajorVersionOnlyFormat = "HTTP/{0} 200 OK"; private const string ValidHeader = "Content-Type: text/xml; charset=utf-8"; private const string HeaderNameWithInvalidChar = "Content{0}Type: text/xml; charset=utf-8"; private const string invalidChars = "()<>@,;\\\"/[]?={} \t"; public static readonly IEnumerable<object[]> ValidStatusCodeLines = GetStatusCodeLines(StatusCodeTemplate); public static IEnumerable<object[]> InvalidStatusCodeLines => GetStatusCodeLines(MissingSpaceFormat).Select(o => new object[] { o[0] }); public static readonly IEnumerable<object[]> StatusCodeVersionLines = GetStatusCodeLinesForMajorVersions(1, 10).Concat(GetStatusCodeLinesForMajorMinorVersions(1, 10)); public static readonly IEnumerable<object[]> InvalidHeaderLines = GetInvalidHeaderLines(); private static IEnumerable<object[]> GetStatusCodeLines(string template) { const string reasonPhrase = "Test Phrase"; foreach (int code in Enum.GetValues(typeof(HttpStatusCode))) { yield return new object[] { string.Format(template, code, reasonPhrase), code, reasonPhrase}; } } private static IEnumerable<object[]> GetStatusCodeLinesForMajorVersions(int min, int max) { for (int major = min; major < max; major++) { yield return new object[] { string.Format(StatusCodeMajorVersionOnlyFormat, major), major, 0 }; } } private static IEnumerable<object[]> GetStatusCodeLinesForMajorMinorVersions(int min, int max) { for (int major = min; major < max; major++) { for (int minor = min; minor < max; minor++) { yield return new object[] {string.Format(StatusCodeVersionFormat, major, minor), major, minor}; } } } private static IEnumerable<object[]> GetInvalidHeaderLines() { foreach (char c in invalidChars) { yield return new object[] { string.Format(HeaderNameWithInvalidChar, c) }; } } #region StatusCode [Theory, MemberData(nameof(ValidStatusCodeLines))] public unsafe void ReadStatusLine_ValidStatusCode_ResponseMessageValueSet(string statusLine, HttpStatusCode expectedCode, string expectedPhrase) { byte[] buffer = statusLine.Select(c => checked((byte)c)).ToArray(); fixed (byte* pBuffer = buffer) { var reader = new CurlResponseHeaderReader(new IntPtr(pBuffer), checked((ulong)buffer.Length)); using (var response = new HttpResponseMessage()) { Assert.True(reader.ReadStatusLine(response)); Assert.Equal(expectedCode, response.StatusCode); Assert.Equal(expectedPhrase, response.ReasonPhrase); } } } [Theory, MemberData(nameof(InvalidStatusCodeLines))] public unsafe void ReadStatusLine_InvalidStatusCode_ThrowsHttpRequestException(string statusLine) { byte[] buffer = statusLine.Select(c => checked((byte)c)).ToArray(); fixed (byte* pBuffer = buffer) { var reader = new CurlResponseHeaderReader(new IntPtr(pBuffer), checked((ulong)buffer.Length)); using (var response = new HttpResponseMessage()) { Assert.Throws<HttpRequestException>(() => reader.ReadStatusLine(response)); } } } [Theory, MemberData(nameof(StatusCodeVersionLines))] public unsafe void ReadStatusLine_ValidStatusCodeLine_ResponseMessageVersionSet(string statusLine, int major, int minor) { byte[] buffer = statusLine.Select(c => checked((byte)c)).ToArray(); fixed (byte* pBuffer = buffer) { var reader = new CurlResponseHeaderReader(new IntPtr(pBuffer), checked((ulong)buffer.Length)); using (var response = new HttpResponseMessage()) { Assert.True(reader.ReadStatusLine(response)); int expectedMajor = 0; int expectedMinor = 0; if (major == 1 && (minor == 0 || minor == 1)) { expectedMajor = 1; expectedMinor = minor; } else if (major == 2 && minor == 0) { expectedMajor = 2; expectedMinor = 0; } Assert.Equal(expectedMajor, response.Version.Major); Assert.Equal(expectedMinor, response.Version.Minor); } } } #endregion #region Headers public static IEnumerable<object[]> ReadHeader_ValidHeaderLine_HeaderReturned_MemberData() { var namesAndValues = new KeyValuePair<string, string>[] { new KeyValuePair<string, string>("TestHeader", "Test header value"), new KeyValuePair<string, string>("TestHeader", ""), new KeyValuePair<string, string>("Server", "IIS"), new KeyValuePair<string, string>("Server", "I:I:S"), }; var whitespaces = new string[] { "", " ", " ", " \t" }; foreach (KeyValuePair<string, string> nameAndValue in namesAndValues) { foreach (string beforeColon in whitespaces) // only "" is valid according to the RFC, but we parse more leniently { foreach (string afterColon in whitespaces) { yield return new object[] { $"{nameAndValue.Key}{beforeColon}:{afterColon}{nameAndValue.Value}", nameAndValue.Key, nameAndValue.Value }; } } } } [Theory] [MemberData(nameof(ReadHeader_ValidHeaderLine_HeaderReturned_MemberData))] public unsafe void ReadHeader_ValidHeaderLine_HeaderReturned(string headerLine, string expectedHeaderName, string expectedHeaderValue) { byte[] buffer = headerLine.Select(c => checked((byte)c)).ToArray(); fixed (byte* pBuffer = buffer) { var reader = new CurlResponseHeaderReader(new IntPtr(pBuffer), checked((ulong)buffer.Length)); string headerName; string headerValue; Assert.True(reader.ReadHeader(out headerName, out headerValue)); Assert.Equal(expectedHeaderName, headerName); Assert.Equal(expectedHeaderValue, headerValue); } } [Fact] public unsafe void ReadHeader_EmptyBuffer_ReturnsFalse() { byte[] buffer = new byte[2]; // Non-empty array so we can get a valid pointer using fixed. ulong length = 0; // But a length of 0 for empty. fixed (byte* pBuffer = buffer) { var reader = new CurlResponseHeaderReader(new IntPtr(pBuffer), length); string headerName; string headerValue; Assert.False(reader.ReadHeader(out headerName, out headerValue)); Assert.Null(headerName); Assert.Null(headerValue); } } [Theory, MemberData(nameof(InvalidHeaderLines))] public unsafe void ReadHeaderName_InvalidHeaderLine_ThrowsHttpRequestException(string headerLine) { byte[] buffer = headerLine.Select(c => checked((byte)c)).ToArray(); fixed (byte* pBuffer = buffer) { var reader = new CurlResponseHeaderReader(new IntPtr(pBuffer), checked((ulong)buffer.Length)); string headerName; string headerValue; Assert.Throws<HttpRequestException>(() => reader.ReadHeader(out headerName, out headerValue)); } } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // The Regex class represents a single compiled instance of a regular // expression. using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Threading; namespace System.Text.RegularExpressions { /// <summary> /// Represents an immutable, compiled regular expression. Also /// contains static methods that allow use of regular expressions without instantiating /// a Regex explicitly. /// </summary> public class Regex { internal string _pattern; // The string pattern provided internal RegexOptions _roptions; // the top-level options from the options string // *********** Match timeout fields { *********** // We need this because time is queried using Environment.TickCount for performance reasons // (Environment.TickCount returns milliseconds as an int and cycles): private static readonly TimeSpan MaximumMatchTimeout = TimeSpan.FromMilliseconds(Int32.MaxValue - 1); // InfiniteMatchTimeout specifies that match timeout is switched OFF. It allows for faster code paths // compared to simply having a very large timeout. // We do not want to ask users to use System.Threading.Timeout.InfiniteTimeSpan as a parameter because: // (1) We do not want to imply any relation between having using a RegEx timeout and using multi-threading. // (2) We do not want to require users to take ref to a contract assembly for threading just to use RegEx. // There may in theory be a SKU that has RegEx, but no multithreading. // We create a public Regex.InfiniteMatchTimeout constant, which for consistency uses the save underlying // value as Timeout.InfiniteTimeSpan creating an implementation detail dependency only. public static readonly TimeSpan InfiniteMatchTimeout = Timeout.InfiniteTimeSpan; internal TimeSpan _internalMatchTimeout; // timeout for the execution of this regex // DefaultMatchTimeout specifies the match timeout to use if no other timeout was specified // by one means or another. Typically, it is set to InfiniteMatchTimeout. internal static readonly TimeSpan DefaultMatchTimeout = InfiniteMatchTimeout; // *********** } match timeout fields *********** internal Dictionary<Int32, Int32> _caps; // if captures are sparse, this is the hashtable capnum->index internal Dictionary<String, Int32> _capnames; // if named captures are used, this maps names->index internal String[] _capslist; // if captures are sparse or named captures are used, this is the sorted list of names internal int _capsize; // the size of the capture array internal ExclusiveReference _runnerref; // cached runner internal SharedReference _replref; // cached parsed replacement pattern internal RegexCode _code; // if interpreted, this is the code for RegexInterpreter internal bool _refsInitialized = false; internal static LinkedList<CachedCodeEntry> s_livecode = new LinkedList<CachedCodeEntry>();// the cache of code and factories that are currently loaded internal static int s_cacheSize = 15; internal const int MaxOptionShift = 10; protected Regex() { _internalMatchTimeout = DefaultMatchTimeout; } /// <summary> /// Creates and compiles a regular expression object for the specified regular /// expression. /// </summary> public Regex(String pattern) : this(pattern, RegexOptions.None, DefaultMatchTimeout, false) { } /// <summary> /// Creates and compiles a regular expression object for the /// specified regular expression with options that modify the pattern. /// </summary> public Regex(String pattern, RegexOptions options) : this(pattern, options, DefaultMatchTimeout, false) { } public Regex(String pattern, RegexOptions options, TimeSpan matchTimeout) : this(pattern, options, matchTimeout, false) { } private Regex(String pattern, RegexOptions options, TimeSpan matchTimeout, bool useCache) { RegexTree tree; CachedCodeEntry cached = null; string cultureKey = null; if (pattern == null) throw new ArgumentNullException("pattern"); if (options < RegexOptions.None || (((int)options) >> MaxOptionShift) != 0) throw new ArgumentOutOfRangeException("options"); if ((options & RegexOptions.ECMAScript) != 0 && (options & ~(RegexOptions.ECMAScript | RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant #if DEBUG | RegexOptions.Debug #endif )) != 0) throw new ArgumentOutOfRangeException("options"); ValidateMatchTimeout(matchTimeout); // Try to look up this regex in the cache. We do this regardless of whether useCache is true since there's // really no reason not to. if ((options & RegexOptions.CultureInvariant) != 0) cultureKey = CultureInfo.InvariantCulture.ToString(); // "English (United States)" else cultureKey = CultureInfo.CurrentCulture.ToString(); var key = new CachedCodeEntryKey(options, cultureKey, pattern); cached = LookupCachedAndUpdate(key); _pattern = pattern; _roptions = options; _internalMatchTimeout = matchTimeout; if (cached == null) { // Parse the input tree = RegexParser.Parse(pattern, _roptions); // Extract the relevant information _capnames = tree._capnames; _capslist = tree._capslist; _code = RegexWriter.Write(tree); _caps = _code._caps; _capsize = _code._capsize; InitializeReferences(); tree = null; if (useCache) cached = CacheCode(key); } else { _caps = cached._caps; _capnames = cached._capnames; _capslist = cached._capslist; _capsize = cached._capsize; _code = cached._code; _runnerref = cached._runnerref; _replref = cached._replref; _refsInitialized = true; } } // Note: "&lt;" is the XML entity for smaller ("<"). /// <summary> /// Validates that the specified match timeout value is valid. /// The valid range is <code>TimeSpan.Zero &lt; matchTimeout &lt;= Regex.MaximumMatchTimeout</code>. /// </summary> /// <param name="matchTimeout">The timeout value to validate.</param> /// <exception cref="System.ArgumentOutOfRangeException">If the specified timeout is not within a valid range. /// </exception> internal static void ValidateMatchTimeout(TimeSpan matchTimeout) { if (InfiniteMatchTimeout == matchTimeout) return; // Change this to make sure timeout is not longer then Environment.Ticks cycle length: if (TimeSpan.Zero < matchTimeout && matchTimeout <= MaximumMatchTimeout) return; throw new ArgumentOutOfRangeException("matchTimeout"); } /// <summary> /// Escapes a minimal set of metacharacters (\, *, +, ?, |, {, [, (, ), ^, $, ., #, and /// whitespace) by replacing them with their \ codes. This converts a string so that /// it can be used as a constant within a regular expression safely. (Note that the /// reason # and whitespace must be escaped is so the string can be used safely /// within an expression parsed with x mode. If future Regex features add /// additional metacharacters, developers should depend on Escape to escape those /// characters as well.) /// </summary> public static String Escape(String str) { if (str == null) throw new ArgumentNullException("str"); return RegexParser.Escape(str); } /// <summary> /// Unescapes any escaped characters in the input string. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Unescape", Justification = "Already shipped since v1 - can't fix without causing a breaking change")] public static String Unescape(String str) { if (str == null) throw new ArgumentNullException("str"); return RegexParser.Unescape(str); } [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety")] public static int CacheSize { get { return s_cacheSize; } set { if (value < 0) throw new ArgumentOutOfRangeException("value"); s_cacheSize = value; if (s_livecode.Count > s_cacheSize) { lock (s_livecode) { while (s_livecode.Count > s_cacheSize) s_livecode.RemoveLast(); } } } } /// <summary> /// Returns the options passed into the constructor /// </summary> public RegexOptions Options { get { return _roptions; } } /// <summary> /// The match timeout used by this Regex instance. /// </summary> public TimeSpan MatchTimeout { get { return _internalMatchTimeout; } } /// <summary> /// Indicates whether the regular expression matches from right to left. /// </summary> public bool RightToLeft { get { return UseOptionR(); } } /// <summary> /// Returns the regular expression pattern passed into the constructor /// </summary> public override string ToString() { return _pattern; } /* * Returns an array of the group names that are used to capture groups * in the regular expression. Only needed if the regex is not known until * runtime, and one wants to extract captured groups. (Probably unusual, * but supplied for completeness.) */ /// <summary> /// Returns the GroupNameCollection for the regular expression. This collection contains the /// set of strings used to name capturing groups in the expression. /// </summary> public String[] GetGroupNames() { String[] result; if (_capslist == null) { int max = _capsize; result = new String[max]; for (int i = 0; i < max; i++) { result[i] = Convert.ToString(i, CultureInfo.InvariantCulture); } } else { result = new String[_capslist.Length]; System.Array.Copy(_capslist, 0, result, 0, _capslist.Length); } return result; } /* * Returns an array of the group numbers that are used to capture groups * in the regular expression. Only needed if the regex is not known until * runtime, and one wants to extract captured groups. (Probably unusual, * but supplied for completeness.) */ /// <summary> /// Returns the integer group number corresponding to a group name. /// </summary> public int[] GetGroupNumbers() { int[] result; if (_caps == null) { int max = _capsize; result = new int[max]; for (int i = 0; i < max; i++) { result[i] = i; } } else { result = new int[_caps.Count]; foreach (KeyValuePair<int, int> kvp in _caps) { result[kvp.Value] = kvp.Key; } } return result; } /* * Given a group number, maps it to a group name. Note that numbered * groups automatically get a group name that is the decimal string * equivalent of its number. * * Returns null if the number is not a recognized group number. */ /// <summary> /// Retrieves a group name that corresponds to a group number. /// </summary> public String GroupNameFromNumber(int i) { if (_capslist == null) { if (i >= 0 && i < _capsize) return i.ToString(CultureInfo.InvariantCulture); return String.Empty; } else { if (_caps != null) { if (!_caps.ContainsKey(i)) return String.Empty; i = _caps[i]; } if (i >= 0 && i < _capslist.Length) return _capslist[i]; return String.Empty; } } /* * Given a group name, maps it to a group number. Note that numbered * groups automatically get a group name that is the decimal string * equivalent of its number. * * Returns -1 if the name is not a recognized group name. */ /// <summary> /// Returns a group number that corresponds to a group name. /// </summary> public int GroupNumberFromName(String name) { int result = -1; if (name == null) throw new ArgumentNullException("name"); // look up name if we have a hashtable of names if (_capnames != null) { if (!_capnames.ContainsKey(name)) return -1; return _capnames[name]; } // convert to an int if it looks like a number result = 0; for (int i = 0; i < name.Length; i++) { char ch = name[i]; if (ch > '9' || ch < '0') return -1; result *= 10; result += (ch - '0'); } // return int if it's in range if (result >= 0 && result < _capsize) return result; return -1; } /* * Static version of simple IsMatch call */ /// <summary> /// Searches the input string for one or more occurrences of the text supplied in the given pattern. /// </summary> public static bool IsMatch(String input, String pattern) { return IsMatch(input, pattern, RegexOptions.None, DefaultMatchTimeout); } /* * Static version of simple IsMatch call */ /// <summary> /// Searches the input string for one or more occurrences of the text /// supplied in the pattern parameter with matching options supplied in the options /// parameter. /// </summary> public static bool IsMatch(String input, String pattern, RegexOptions options) { return IsMatch(input, pattern, options, DefaultMatchTimeout); } public static bool IsMatch(String input, String pattern, RegexOptions options, TimeSpan matchTimeout) { return new Regex(pattern, options, matchTimeout, true).IsMatch(input); } /* * Returns true if the regex finds a match within the specified string */ /// <summary> /// Searches the input string for one or more matches using the previous pattern, /// options, and starting position. /// </summary> public bool IsMatch(String input) { if (input == null) throw new ArgumentNullException("input"); return IsMatch(input, UseOptionR() ? input.Length : 0); } /* * Returns true if the regex finds a match after the specified position * (proceeding leftward if the regex is leftward and rightward otherwise) */ /// <summary> /// Searches the input string for one or more matches using the previous pattern and options, /// with a new starting position. /// </summary> public bool IsMatch(String input, int startat) { if (input == null) throw new ArgumentNullException("input"); return (null == Run(true, -1, input, 0, input.Length, startat)); } /* * Static version of simple Match call */ /// <summary> /// Searches the input string for one or more occurrences of the text /// supplied in the pattern parameter. /// </summary> public static Match Match(String input, String pattern) { return Match(input, pattern, RegexOptions.None, DefaultMatchTimeout); } /* * Static version of simple Match call */ /// <summary> /// Searches the input string for one or more occurrences of the text /// supplied in the pattern parameter. Matching is modified with an option /// string. /// </summary> public static Match Match(String input, String pattern, RegexOptions options) { return Match(input, pattern, options, DefaultMatchTimeout); } public static Match Match(String input, String pattern, RegexOptions options, TimeSpan matchTimeout) { return new Regex(pattern, options, matchTimeout, true).Match(input); } /* * Finds the first match for the regular expression starting at the beginning * of the string (or at the end of the string if the regex is leftward) */ /// <summary> /// Matches a regular expression with a string and returns /// the precise result as a RegexMatch object. /// </summary> public Match Match(String input) { if (input == null) throw new ArgumentNullException("input"); return Match(input, UseOptionR() ? input.Length : 0); } /* * Finds the first match, starting at the specified position */ /// <summary> /// Matches a regular expression with a string and returns /// the precise result as a RegexMatch object. /// </summary> public Match Match(String input, int startat) { if (input == null) throw new ArgumentNullException("input"); return Run(false, -1, input, 0, input.Length, startat); } /* * Finds the first match, restricting the search to the specified interval of * the char array. */ /// <summary> /// Matches a regular expression with a string and returns the precise result as a /// RegexMatch object. /// </summary> public Match Match(String input, int beginning, int length) { if (input == null) throw new ArgumentNullException("input"); return Run(false, -1, input, beginning, length, UseOptionR() ? beginning + length : beginning); } /* * Static version of simple Matches call */ /// <summary> /// Returns all the successful matches as if Match were called iteratively numerous times. /// </summary> public static MatchCollection Matches(String input, String pattern) { return Matches(input, pattern, RegexOptions.None, DefaultMatchTimeout); } /* * Static version of simple Matches call */ /// <summary> /// Returns all the successful matches as if Match were called iteratively numerous times. /// </summary> public static MatchCollection Matches(String input, String pattern, RegexOptions options) { return Matches(input, pattern, options, DefaultMatchTimeout); } public static MatchCollection Matches(String input, String pattern, RegexOptions options, TimeSpan matchTimeout) { return new Regex(pattern, options, matchTimeout, true).Matches(input); } /* * Finds the first match for the regular expression starting at the beginning * of the string Enumerator(or at the end of the string if the regex is leftward) */ /// <summary> /// Returns all the successful matches as if Match was called iteratively numerous times. /// </summary> public MatchCollection Matches(String input) { if (input == null) throw new ArgumentNullException("input"); return Matches(input, UseOptionR() ? input.Length : 0); } /* * Finds the first match, starting at the specified position */ /// <summary> /// Returns all the successful matches as if Match was called iteratively numerous times. /// </summary> public MatchCollection Matches(String input, int startat) { if (input == null) throw new ArgumentNullException("input"); return new MatchCollection(this, input, 0, input.Length, startat); } /// <summary> /// Replaces all occurrences of the pattern with the <paramref name="replacement"/> pattern, starting at /// the first character in the input string. /// </summary> public static String Replace(String input, String pattern, String replacement) { return Replace(input, pattern, replacement, RegexOptions.None, DefaultMatchTimeout); } /// <summary> /// Replaces all occurrences of /// the <paramref name="pattern "/>with the <paramref name="replacement "/> /// pattern, starting at the first character in the input string. /// </summary> public static String Replace(String input, String pattern, String replacement, RegexOptions options) { return Replace(input, pattern, replacement, options, DefaultMatchTimeout); } public static String Replace(String input, String pattern, String replacement, RegexOptions options, TimeSpan matchTimeout) { return new Regex(pattern, options, matchTimeout, true).Replace(input, replacement); } /// <summary> /// Replaces all occurrences of the previously defined pattern with the /// <paramref name="replacement"/> pattern, starting at the first character in the /// input string. /// </summary> public String Replace(String input, String replacement) { if (input == null) throw new ArgumentNullException("input"); return Replace(input, replacement, -1, UseOptionR() ? input.Length : 0); } /// <summary> /// Replaces all occurrences of the previously defined pattern with the /// <paramref name="replacement"/> pattern, starting at the first character in the /// input string. /// </summary> public String Replace(String input, String replacement, int count) { if (input == null) throw new ArgumentNullException("input"); return Replace(input, replacement, count, UseOptionR() ? input.Length : 0); } /// <summary> /// Replaces all occurrences of the previously defined pattern with the /// <paramref name="replacement"/> pattern, starting at the character position /// <paramref name="startat"/>. /// </summary> public String Replace(String input, String replacement, int count, int startat) { if (input == null) throw new ArgumentNullException("input"); if (replacement == null) throw new ArgumentNullException("replacement"); // a little code to grab a cached parsed replacement object RegexReplacement repl = (RegexReplacement)_replref.Get(); if (repl == null || !repl.Pattern.Equals(replacement)) { repl = RegexParser.ParseReplacement(replacement, _caps, _capsize, _capnames, _roptions); _replref.Cache(repl); } return repl.Replace(this, input, count, startat); } /// <summary> /// Replaces all occurrences of the <paramref name="pattern"/> with the recent /// replacement pattern. /// </summary> public static String Replace(String input, String pattern, MatchEvaluator evaluator) { return Replace(input, pattern, evaluator, RegexOptions.None, DefaultMatchTimeout); } /// <summary> /// Replaces all occurrences of the <paramref name="pattern"/> with the recent /// replacement pattern, starting at the first character. /// </summary> public static String Replace(String input, String pattern, MatchEvaluator evaluator, RegexOptions options) { return Replace(input, pattern, evaluator, options, DefaultMatchTimeout); } public static String Replace(String input, String pattern, MatchEvaluator evaluator, RegexOptions options, TimeSpan matchTimeout) { return new Regex(pattern, options, matchTimeout, true).Replace(input, evaluator); } /// <summary> /// Replaces all occurrences of the previously defined pattern with the recent /// replacement pattern, starting at the first character position. /// </summary> public String Replace(String input, MatchEvaluator evaluator) { if (input == null) throw new ArgumentNullException("input"); return Replace(input, evaluator, -1, UseOptionR() ? input.Length : 0); } /// <summary> /// Replaces all occurrences of the previously defined pattern with the recent /// replacement pattern, starting at the first character position. /// </summary> public String Replace(String input, MatchEvaluator evaluator, int count) { if (input == null) throw new ArgumentNullException("input"); return Replace(input, evaluator, count, UseOptionR() ? input.Length : 0); } /// <summary> /// Replaces all occurrences of the previously defined pattern with the recent /// replacement pattern, starting at the character position /// <paramref name="startat"/>. /// </summary> public String Replace(String input, MatchEvaluator evaluator, int count, int startat) { if (input == null) throw new ArgumentNullException("input"); return RegexReplacement.Replace(evaluator, this, input, count, startat); } /// <summary> /// Splits the <paramref name="input "/>string at the position defined /// by <paramref name="pattern"/>. /// </summary> public static String[] Split(String input, String pattern) { return Split(input, pattern, RegexOptions.None, DefaultMatchTimeout); } /// <summary> /// Splits the <paramref name="input "/>string at the position defined by <paramref name="pattern"/>. /// </summary> public static String[] Split(String input, String pattern, RegexOptions options) { return Split(input, pattern, options, DefaultMatchTimeout); } public static String[] Split(String input, String pattern, RegexOptions options, TimeSpan matchTimeout) { return new Regex(pattern, options, matchTimeout, true).Split(input); } /// <summary> /// Splits the <paramref name="input"/> string at the position defined by a /// previous pattern. /// </summary> public String[] Split(String input) { if (input == null) throw new ArgumentNullException("input"); return Split(input, 0, UseOptionR() ? input.Length : 0); } /// <summary> /// Splits the <paramref name="input"/> string at the position defined by a /// previous pattern. /// </summary> public String[] Split(String input, int count) { if (input == null) throw new ArgumentNullException("input"); return RegexReplacement.Split(this, input, count, UseOptionR() ? input.Length : 0); } /// <summary> /// Splits the <paramref name="input"/> string at the position defined by a /// previous pattern. /// </summary> public String[] Split(String input, int count, int startat) { if (input == null) throw new ArgumentNullException("input"); return RegexReplacement.Split(this, input, count, startat); } internal void InitializeReferences() { if (_refsInitialized) throw new NotSupportedException(SR.OnlyAllowedOnce); _refsInitialized = true; _runnerref = new ExclusiveReference(); _replref = new SharedReference(); } /* * Internal worker called by all the public APIs */ internal Match Run(bool quick, int prevlen, String input, int beginning, int length, int startat) { Match match; RegexRunner runner = null; if (startat < 0 || startat > input.Length) throw new ArgumentOutOfRangeException("start", SR.BeginIndexNotNegative); if (length < 0 || length > input.Length) throw new ArgumentOutOfRangeException("length", SR.LengthNotNegative); // There may be a cached runner; grab ownership of it if we can. runner = (RegexRunner)_runnerref.Get(); // Create a RegexRunner instance if we need to if (runner == null) { runner = new RegexInterpreter(_code, UseOptionInvariant() ? CultureInfo.InvariantCulture : CultureInfo.CurrentCulture); } try { // Do the scan starting at the requested position match = runner.Scan(this, input, beginning, beginning + length, startat, prevlen, quick, _internalMatchTimeout); } finally { // Release or fill the cache slot _runnerref.Release(runner); } #if DEBUG if (Debug && match != null) match.Dump(); #endif return match; } /* * Find code cache based on options+pattern */ private static CachedCodeEntry LookupCachedAndUpdate(CachedCodeEntryKey key) { lock (s_livecode) { for (LinkedListNode<CachedCodeEntry> current = s_livecode.First; current != null; current = current.Next) { if (current.Value._key == key) { // If we find an entry in the cache, move it to the head at the same time. s_livecode.Remove(current); s_livecode.AddFirst(current); return current.Value; } } } return null; } /* * Add current code to the cache */ private CachedCodeEntry CacheCode(CachedCodeEntryKey key) { CachedCodeEntry newcached = null; lock (s_livecode) { // first look for it in the cache and move it to the head for (LinkedListNode<CachedCodeEntry> current = s_livecode.First; current != null; current = current.Next) { if (current.Value._key == key) { s_livecode.Remove(current); s_livecode.AddFirst(current); return current.Value; } } // it wasn't in the cache, so we'll add a new one. Shortcut out for the case where cacheSize is zero. if (s_cacheSize != 0) { newcached = new CachedCodeEntry(key, _capnames, _capslist, _code, _caps, _capsize, _runnerref, _replref); s_livecode.AddFirst(newcached); if (s_livecode.Count > s_cacheSize) s_livecode.RemoveLast(); } } return newcached; } /* * True if the L option was set */ internal bool UseOptionR() { return (_roptions & RegexOptions.RightToLeft) != 0; } internal bool UseOptionInvariant() { return (_roptions & RegexOptions.CultureInvariant) != 0; } #if DEBUG /* * True if the regex has debugging enabled */ internal bool Debug { get { return (_roptions & RegexOptions.Debug) != 0; } } #endif } /* * Callback class */ public delegate String MatchEvaluator(Match match); /* * Used as a key for CacheCodeEntry */ internal struct CachedCodeEntryKey : IEquatable<CachedCodeEntryKey> { private readonly RegexOptions _options; private readonly string _cultureKey; private readonly string _pattern; internal CachedCodeEntryKey(RegexOptions options, string cultureKey, string pattern) { _options = options; _cultureKey = cultureKey; _pattern = pattern; } public override bool Equals(object obj) { return obj is CachedCodeEntryKey && Equals((CachedCodeEntryKey)obj); } public bool Equals(CachedCodeEntryKey other) { return this == other; } public static bool operator ==(CachedCodeEntryKey left, CachedCodeEntryKey right) { return left._options == right._options && left._cultureKey == right._cultureKey && left._pattern == right._pattern; } public static bool operator !=(CachedCodeEntryKey left, CachedCodeEntryKey right) { return !(left == right); } public override int GetHashCode() { return ((int)_options) ^ _cultureKey.GetHashCode() ^ _pattern.GetHashCode(); } } /* * Used to cache byte codes */ internal sealed class CachedCodeEntry { internal CachedCodeEntryKey _key; internal RegexCode _code; internal Dictionary<Int32, Int32> _caps; internal Dictionary<String, Int32> _capnames; internal String[] _capslist; internal int _capsize; internal ExclusiveReference _runnerref; internal SharedReference _replref; internal CachedCodeEntry(CachedCodeEntryKey key, Dictionary<String, Int32> capnames, String[] capslist, RegexCode code, Dictionary<Int32, Int32> caps, int capsize, ExclusiveReference runner, SharedReference repl) { _key = key; _capnames = capnames; _capslist = capslist; _code = code; _caps = caps; _capsize = capsize; _runnerref = runner; _replref = repl; } } /* * Used to cache one exclusive runner reference */ internal sealed class ExclusiveReference { private RegexRunner _ref; private Object _obj; private int _locked; /* * Return an object and grab an exclusive lock. * * If the exclusive lock can't be obtained, null is returned; * if the object can't be returned, the lock is released. * */ internal Object Get() { // try to obtain the lock if (0 == Interlocked.Exchange(ref _locked, 1)) { // grab reference Object obj = _ref; // release the lock and return null if no reference if (obj == null) { _locked = 0; return null; } // remember the reference and keep the lock _obj = obj; return obj; } return null; } /* * Release an object back to the cache * * If the object is the one that's under lock, the lock * is released. * * If there is no cached object, then the lock is obtained * and the object is placed in the cache. * */ internal void Release(Object obj) { if (obj == null) throw new ArgumentNullException("obj"); // if this reference owns the lock, release it if (_obj == obj) { _obj = null; _locked = 0; return; } // if no reference owns the lock, try to cache this reference if (_obj == null) { // try to obtain the lock if (0 == Interlocked.Exchange(ref _locked, 1)) { // if there's really no reference, cache this reference if (_ref == null) _ref = (RegexRunner)obj; // release the lock _locked = 0; return; } } } } /* * Used to cache a weak reference in a threadsafe way */ internal sealed class SharedReference { private WeakReference _ref = new WeakReference(null); private int _locked; /* * Return an object from a weakref, protected by a lock. * * If the exclusive lock can't be obtained, null is returned; * * Note that _ref.Target is referenced only under the protection * of the lock. (Is this necessary?) */ internal Object Get() { if (0 == Interlocked.Exchange(ref _locked, 1)) { Object obj = _ref.Target; _locked = 0; return obj; } return null; } /* * Suggest an object into a weakref, protected by a lock. * * Note that _ref.Target is referenced only under the protection * of the lock. (Is this necessary?) */ internal void Cache(Object obj) { if (0 == Interlocked.Exchange(ref _locked, 1)) { _ref.Target = obj; _locked = 0; } } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; // <auto-generated /> namespace NorthwindAccess { /// <summary> /// Strongly-typed collection for the Product class. /// </summary> [Serializable] public partial class ProductCollection : ActiveList<Product, ProductCollection> { public ProductCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>ProductCollection</returns> public ProductCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { Product o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the Products table. /// </summary> [Serializable] public partial class Product : ActiveRecord<Product>, IActiveRecord { #region .ctors and Default Settings public Product() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public Product(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public Product(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public Product(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("Products", TableType.Table, DataService.GetInstance("NorthwindAccess")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @""; //columns TableSchema.TableColumn colvarProductID = new TableSchema.TableColumn(schema); colvarProductID.ColumnName = "ProductID"; colvarProductID.DataType = DbType.Int32; colvarProductID.MaxLength = 0; colvarProductID.AutoIncrement = true; colvarProductID.IsNullable = false; colvarProductID.IsPrimaryKey = true; colvarProductID.IsForeignKey = false; colvarProductID.IsReadOnly = false; colvarProductID.DefaultSetting = @""; colvarProductID.ForeignKeyTableName = ""; schema.Columns.Add(colvarProductID); TableSchema.TableColumn colvarProductName = new TableSchema.TableColumn(schema); colvarProductName.ColumnName = "ProductName"; colvarProductName.DataType = DbType.String; colvarProductName.MaxLength = 40; colvarProductName.AutoIncrement = false; colvarProductName.IsNullable = false; colvarProductName.IsPrimaryKey = false; colvarProductName.IsForeignKey = false; colvarProductName.IsReadOnly = false; colvarProductName.DefaultSetting = @""; colvarProductName.ForeignKeyTableName = ""; schema.Columns.Add(colvarProductName); TableSchema.TableColumn colvarSupplierID = new TableSchema.TableColumn(schema); colvarSupplierID.ColumnName = "SupplierID"; colvarSupplierID.DataType = DbType.Int32; colvarSupplierID.MaxLength = 0; colvarSupplierID.AutoIncrement = false; colvarSupplierID.IsNullable = true; colvarSupplierID.IsPrimaryKey = false; colvarSupplierID.IsForeignKey = true; colvarSupplierID.IsReadOnly = false; colvarSupplierID.DefaultSetting = @""; colvarSupplierID.ForeignKeyTableName = "Suppliers"; schema.Columns.Add(colvarSupplierID); TableSchema.TableColumn colvarCategoryID = new TableSchema.TableColumn(schema); colvarCategoryID.ColumnName = "CategoryID"; colvarCategoryID.DataType = DbType.Int32; colvarCategoryID.MaxLength = 0; colvarCategoryID.AutoIncrement = false; colvarCategoryID.IsNullable = true; colvarCategoryID.IsPrimaryKey = false; colvarCategoryID.IsForeignKey = true; colvarCategoryID.IsReadOnly = false; colvarCategoryID.DefaultSetting = @""; colvarCategoryID.ForeignKeyTableName = "Categories"; schema.Columns.Add(colvarCategoryID); TableSchema.TableColumn colvarQuantityPerUnit = new TableSchema.TableColumn(schema); colvarQuantityPerUnit.ColumnName = "QuantityPerUnit"; colvarQuantityPerUnit.DataType = DbType.String; colvarQuantityPerUnit.MaxLength = 20; colvarQuantityPerUnit.AutoIncrement = false; colvarQuantityPerUnit.IsNullable = true; colvarQuantityPerUnit.IsPrimaryKey = false; colvarQuantityPerUnit.IsForeignKey = false; colvarQuantityPerUnit.IsReadOnly = false; colvarQuantityPerUnit.DefaultSetting = @""; colvarQuantityPerUnit.ForeignKeyTableName = ""; schema.Columns.Add(colvarQuantityPerUnit); TableSchema.TableColumn colvarUnitPrice = new TableSchema.TableColumn(schema); colvarUnitPrice.ColumnName = "UnitPrice"; colvarUnitPrice.DataType = DbType.Currency; colvarUnitPrice.MaxLength = 0; colvarUnitPrice.AutoIncrement = false; colvarUnitPrice.IsNullable = true; colvarUnitPrice.IsPrimaryKey = false; colvarUnitPrice.IsForeignKey = false; colvarUnitPrice.IsReadOnly = false; colvarUnitPrice.DefaultSetting = @"0"; colvarUnitPrice.ForeignKeyTableName = ""; schema.Columns.Add(colvarUnitPrice); TableSchema.TableColumn colvarUnitsInStock = new TableSchema.TableColumn(schema); colvarUnitsInStock.ColumnName = "UnitsInStock"; colvarUnitsInStock.DataType = DbType.Int16; colvarUnitsInStock.MaxLength = 0; colvarUnitsInStock.AutoIncrement = false; colvarUnitsInStock.IsNullable = true; colvarUnitsInStock.IsPrimaryKey = false; colvarUnitsInStock.IsForeignKey = false; colvarUnitsInStock.IsReadOnly = false; colvarUnitsInStock.DefaultSetting = @"0"; colvarUnitsInStock.ForeignKeyTableName = ""; schema.Columns.Add(colvarUnitsInStock); TableSchema.TableColumn colvarUnitsOnOrder = new TableSchema.TableColumn(schema); colvarUnitsOnOrder.ColumnName = "UnitsOnOrder"; colvarUnitsOnOrder.DataType = DbType.Int16; colvarUnitsOnOrder.MaxLength = 0; colvarUnitsOnOrder.AutoIncrement = false; colvarUnitsOnOrder.IsNullable = true; colvarUnitsOnOrder.IsPrimaryKey = false; colvarUnitsOnOrder.IsForeignKey = false; colvarUnitsOnOrder.IsReadOnly = false; colvarUnitsOnOrder.DefaultSetting = @"0"; colvarUnitsOnOrder.ForeignKeyTableName = ""; schema.Columns.Add(colvarUnitsOnOrder); TableSchema.TableColumn colvarReorderLevel = new TableSchema.TableColumn(schema); colvarReorderLevel.ColumnName = "ReorderLevel"; colvarReorderLevel.DataType = DbType.Int16; colvarReorderLevel.MaxLength = 0; colvarReorderLevel.AutoIncrement = false; colvarReorderLevel.IsNullable = true; colvarReorderLevel.IsPrimaryKey = false; colvarReorderLevel.IsForeignKey = false; colvarReorderLevel.IsReadOnly = false; colvarReorderLevel.DefaultSetting = @"0"; colvarReorderLevel.ForeignKeyTableName = ""; schema.Columns.Add(colvarReorderLevel); TableSchema.TableColumn colvarDiscontinued = new TableSchema.TableColumn(schema); colvarDiscontinued.ColumnName = "Discontinued"; colvarDiscontinued.DataType = DbType.Boolean; colvarDiscontinued.MaxLength = 2; colvarDiscontinued.AutoIncrement = false; colvarDiscontinued.IsNullable = false; colvarDiscontinued.IsPrimaryKey = false; colvarDiscontinued.IsForeignKey = false; colvarDiscontinued.IsReadOnly = false; colvarDiscontinued.DefaultSetting = @"=No"; colvarDiscontinued.ForeignKeyTableName = ""; schema.Columns.Add(colvarDiscontinued); TableSchema.TableColumn colvarAttributeXML = new TableSchema.TableColumn(schema); colvarAttributeXML.ColumnName = "AttributeXML"; colvarAttributeXML.DataType = DbType.String; colvarAttributeXML.MaxLength = 0; colvarAttributeXML.AutoIncrement = false; colvarAttributeXML.IsNullable = true; colvarAttributeXML.IsPrimaryKey = false; colvarAttributeXML.IsForeignKey = false; colvarAttributeXML.IsReadOnly = false; colvarAttributeXML.DefaultSetting = @""; colvarAttributeXML.ForeignKeyTableName = ""; schema.Columns.Add(colvarAttributeXML); TableSchema.TableColumn colvarDateCreated = new TableSchema.TableColumn(schema); colvarDateCreated.ColumnName = "DateCreated"; colvarDateCreated.DataType = DbType.DateTime; colvarDateCreated.MaxLength = 0; colvarDateCreated.AutoIncrement = false; colvarDateCreated.IsNullable = true; colvarDateCreated.IsPrimaryKey = false; colvarDateCreated.IsForeignKey = false; colvarDateCreated.IsReadOnly = false; colvarDateCreated.DefaultSetting = @"Date()"; colvarDateCreated.ForeignKeyTableName = ""; schema.Columns.Add(colvarDateCreated); TableSchema.TableColumn colvarProductGUID = new TableSchema.TableColumn(schema); colvarProductGUID.ColumnName = "ProductGUID"; colvarProductGUID.DataType = DbType.Guid; colvarProductGUID.MaxLength = 0; colvarProductGUID.AutoIncrement = false; colvarProductGUID.IsNullable = true; colvarProductGUID.IsPrimaryKey = false; colvarProductGUID.IsForeignKey = false; colvarProductGUID.IsReadOnly = false; colvarProductGUID.DefaultSetting = @""; colvarProductGUID.ForeignKeyTableName = ""; schema.Columns.Add(colvarProductGUID); TableSchema.TableColumn colvarCreatedOn = new TableSchema.TableColumn(schema); colvarCreatedOn.ColumnName = "CreatedOn"; colvarCreatedOn.DataType = DbType.DateTime; colvarCreatedOn.MaxLength = 0; colvarCreatedOn.AutoIncrement = false; colvarCreatedOn.IsNullable = false; colvarCreatedOn.IsPrimaryKey = false; colvarCreatedOn.IsForeignKey = false; colvarCreatedOn.IsReadOnly = false; colvarCreatedOn.DefaultSetting = @"Date()"; colvarCreatedOn.ForeignKeyTableName = ""; schema.Columns.Add(colvarCreatedOn); TableSchema.TableColumn colvarCreatedBy = new TableSchema.TableColumn(schema); colvarCreatedBy.ColumnName = "CreatedBy"; colvarCreatedBy.DataType = DbType.String; colvarCreatedBy.MaxLength = 50; colvarCreatedBy.AutoIncrement = false; colvarCreatedBy.IsNullable = true; colvarCreatedBy.IsPrimaryKey = false; colvarCreatedBy.IsForeignKey = false; colvarCreatedBy.IsReadOnly = false; colvarCreatedBy.DefaultSetting = @""; colvarCreatedBy.ForeignKeyTableName = ""; schema.Columns.Add(colvarCreatedBy); TableSchema.TableColumn colvarModifiedOn = new TableSchema.TableColumn(schema); colvarModifiedOn.ColumnName = "ModifiedOn"; colvarModifiedOn.DataType = DbType.DateTime; colvarModifiedOn.MaxLength = 0; colvarModifiedOn.AutoIncrement = false; colvarModifiedOn.IsNullable = false; colvarModifiedOn.IsPrimaryKey = false; colvarModifiedOn.IsForeignKey = false; colvarModifiedOn.IsReadOnly = false; colvarModifiedOn.DefaultSetting = @"Date()"; colvarModifiedOn.ForeignKeyTableName = ""; schema.Columns.Add(colvarModifiedOn); TableSchema.TableColumn colvarModifiedBy = new TableSchema.TableColumn(schema); colvarModifiedBy.ColumnName = "ModifiedBy"; colvarModifiedBy.DataType = DbType.String; colvarModifiedBy.MaxLength = 50; colvarModifiedBy.AutoIncrement = false; colvarModifiedBy.IsNullable = true; colvarModifiedBy.IsPrimaryKey = false; colvarModifiedBy.IsForeignKey = false; colvarModifiedBy.IsReadOnly = false; colvarModifiedBy.DefaultSetting = @""; colvarModifiedBy.ForeignKeyTableName = ""; schema.Columns.Add(colvarModifiedBy); TableSchema.TableColumn colvarDeleted = new TableSchema.TableColumn(schema); colvarDeleted.ColumnName = "Deleted"; colvarDeleted.DataType = DbType.Boolean; colvarDeleted.MaxLength = 2; colvarDeleted.AutoIncrement = false; colvarDeleted.IsNullable = false; colvarDeleted.IsPrimaryKey = false; colvarDeleted.IsForeignKey = false; colvarDeleted.IsReadOnly = false; colvarDeleted.DefaultSetting = @"False"; colvarDeleted.ForeignKeyTableName = ""; schema.Columns.Add(colvarDeleted); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["NorthwindAccess"].AddSchema("Products",schema); } } #endregion #region Props [XmlAttribute("ProductID")] [Bindable(true)] public int ProductID { get { return GetColumnValue<int>(Columns.ProductID); } set { SetColumnValue(Columns.ProductID, value); } } [XmlAttribute("ProductName")] [Bindable(true)] public string ProductName { get { return GetColumnValue<string>(Columns.ProductName); } set { SetColumnValue(Columns.ProductName, value); } } [XmlAttribute("SupplierID")] [Bindable(true)] public int? SupplierID { get { return GetColumnValue<int?>(Columns.SupplierID); } set { SetColumnValue(Columns.SupplierID, value); } } [XmlAttribute("CategoryID")] [Bindable(true)] public int? CategoryID { get { return GetColumnValue<int?>(Columns.CategoryID); } set { SetColumnValue(Columns.CategoryID, value); } } [XmlAttribute("QuantityPerUnit")] [Bindable(true)] public string QuantityPerUnit { get { return GetColumnValue<string>(Columns.QuantityPerUnit); } set { SetColumnValue(Columns.QuantityPerUnit, value); } } [XmlAttribute("UnitPrice")] [Bindable(true)] public decimal? UnitPrice { get { return GetColumnValue<decimal?>(Columns.UnitPrice); } set { SetColumnValue(Columns.UnitPrice, value); } } [XmlAttribute("UnitsInStock")] [Bindable(true)] public short? UnitsInStock { get { return GetColumnValue<short?>(Columns.UnitsInStock); } set { SetColumnValue(Columns.UnitsInStock, value); } } [XmlAttribute("UnitsOnOrder")] [Bindable(true)] public short? UnitsOnOrder { get { return GetColumnValue<short?>(Columns.UnitsOnOrder); } set { SetColumnValue(Columns.UnitsOnOrder, value); } } [XmlAttribute("ReorderLevel")] [Bindable(true)] public short? ReorderLevel { get { return GetColumnValue<short?>(Columns.ReorderLevel); } set { SetColumnValue(Columns.ReorderLevel, value); } } [XmlAttribute("Discontinued")] [Bindable(true)] public bool Discontinued { get { return GetColumnValue<bool>(Columns.Discontinued); } set { SetColumnValue(Columns.Discontinued, value); } } [XmlAttribute("AttributeXML")] [Bindable(true)] public string AttributeXML { get { return GetColumnValue<string>(Columns.AttributeXML); } set { SetColumnValue(Columns.AttributeXML, value); } } [XmlAttribute("DateCreated")] [Bindable(true)] public DateTime? DateCreated { get { return GetColumnValue<DateTime?>(Columns.DateCreated); } set { SetColumnValue(Columns.DateCreated, value); } } [XmlAttribute("ProductGUID")] [Bindable(true)] public Guid? ProductGUID { get { return GetColumnValue<Guid?>(Columns.ProductGUID); } set { SetColumnValue(Columns.ProductGUID, value); } } [XmlAttribute("CreatedOn")] [Bindable(true)] public DateTime CreatedOn { get { return GetColumnValue<DateTime>(Columns.CreatedOn); } set { SetColumnValue(Columns.CreatedOn, value); } } [XmlAttribute("CreatedBy")] [Bindable(true)] public string CreatedBy { get { return GetColumnValue<string>(Columns.CreatedBy); } set { SetColumnValue(Columns.CreatedBy, value); } } [XmlAttribute("ModifiedOn")] [Bindable(true)] public DateTime ModifiedOn { get { return GetColumnValue<DateTime>(Columns.ModifiedOn); } set { SetColumnValue(Columns.ModifiedOn, value); } } [XmlAttribute("ModifiedBy")] [Bindable(true)] public string ModifiedBy { get { return GetColumnValue<string>(Columns.ModifiedBy); } set { SetColumnValue(Columns.ModifiedBy, value); } } [XmlAttribute("Deleted")] [Bindable(true)] public bool Deleted { get { return GetColumnValue<bool>(Columns.Deleted); } set { SetColumnValue(Columns.Deleted, value); } } #endregion #region PrimaryKey Methods protected override void SetPrimaryKey(object oValue) { base.SetPrimaryKey(oValue); SetPKValues(); } public NorthwindAccess.OrderDetailCollection OrderDetails() { return new NorthwindAccess.OrderDetailCollection().Where(OrderDetail.Columns.ProductID, ProductID).Load(); } public NorthwindAccess.ProductCategoryMapCollection ProductCategoryMapRecords() { return new NorthwindAccess.ProductCategoryMapCollection().Where(ProductCategoryMap.Columns.ProductID, ProductID).Load(); } #endregion #region ForeignKey Properties /// <summary> /// Returns a Category ActiveRecord object related to this Product /// /// </summary> public NorthwindAccess.Category Category { get { return NorthwindAccess.Category.FetchByID(this.CategoryID); } set { SetColumnValue("CategoryID", value.CategoryID); } } /// <summary> /// Returns a Supplier ActiveRecord object related to this Product /// /// </summary> public NorthwindAccess.Supplier Supplier { get { return NorthwindAccess.Supplier.FetchByID(this.SupplierID); } set { SetColumnValue("SupplierID", value.SupplierID); } } #endregion #region Many To Many Helpers public NorthwindAccess.OrderCollection GetOrderCollection() { return Product.GetOrderCollection(this.ProductID); } public static NorthwindAccess.OrderCollection GetOrderCollection(int varProductID) { SubSonic.QueryCommand cmd = new SubSonic.QueryCommand("SELECT * FROM [Orders] INNER JOIN [Order Details] ON [Orders].[OrderID] = [Order Details].[OrderID] WHERE [Order Details].[ProductID] = PARM__ProductID", Product.Schema.Provider.Name); cmd.AddParameter("PARM__ProductID", varProductID, DbType.Int32); IDataReader rdr = SubSonic.DataService.GetReader(cmd); OrderCollection coll = new OrderCollection(); coll.LoadAndCloseReader(rdr); return coll; } public static void SaveOrderMap(int varProductID, OrderCollection items) { QueryCommandCollection coll = new SubSonic.QueryCommandCollection(); //delete out the existing QueryCommand cmdDel = new QueryCommand("DELETE FROM [Order Details] WHERE [Order Details].[ProductID] = PARM__ProductID", Product.Schema.Provider.Name); cmdDel.AddParameter("PARM__ProductID", varProductID, DbType.Int32); coll.Add(cmdDel); DataService.ExecuteTransaction(coll); foreach (Order item in items) { OrderDetail varOrderDetail = new OrderDetail(); varOrderDetail.SetColumnValue("ProductID", varProductID); varOrderDetail.SetColumnValue("OrderID", item.GetPrimaryKeyValue()); varOrderDetail.Save(); } } public static void SaveOrderMap(int varProductID, System.Web.UI.WebControls.ListItemCollection itemList) { QueryCommandCollection coll = new SubSonic.QueryCommandCollection(); //delete out the existing QueryCommand cmdDel = new QueryCommand("DELETE FROM [Order Details] WHERE [Order Details].[ProductID] = PARM__ProductID", Product.Schema.Provider.Name); cmdDel.AddParameter("PARM__ProductID", varProductID, DbType.Int32); coll.Add(cmdDel); DataService.ExecuteTransaction(coll); foreach (System.Web.UI.WebControls.ListItem l in itemList) { if (l.Selected) { OrderDetail varOrderDetail = new OrderDetail(); varOrderDetail.SetColumnValue("ProductID", varProductID); varOrderDetail.SetColumnValue("OrderID", l.Value); varOrderDetail.Save(); } } } public static void SaveOrderMap(int varProductID , int[] itemList) { QueryCommandCollection coll = new SubSonic.QueryCommandCollection(); //delete out the existing QueryCommand cmdDel = new QueryCommand("DELETE FROM [Order Details] WHERE [Order Details].[ProductID] = PARM__ProductID", Product.Schema.Provider.Name); cmdDel.AddParameter("PARM__ProductID", varProductID, DbType.Int32); coll.Add(cmdDel); DataService.ExecuteTransaction(coll); foreach (int item in itemList) { OrderDetail varOrderDetail = new OrderDetail(); varOrderDetail.SetColumnValue("ProductID", varProductID); varOrderDetail.SetColumnValue("OrderID", item); varOrderDetail.Save(); } } public static void DeleteOrderMap(int varProductID) { QueryCommand cmdDel = new QueryCommand("DELETE FROM [Order Details] WHERE [Order Details].[ProductID] = PARM__ProductID", Product.Schema.Provider.Name); cmdDel.AddParameter("PARM__ProductID", varProductID, DbType.Int32); DataService.ExecuteQuery(cmdDel); } public NorthwindAccess.CategoryCollection GetCategoryCollection() { return Product.GetCategoryCollection(this.ProductID); } public static NorthwindAccess.CategoryCollection GetCategoryCollection(int varProductID) { SubSonic.QueryCommand cmd = new SubSonic.QueryCommand("SELECT * FROM [Categories] INNER JOIN [Product_Category_Map] ON [Categories].[CategoryID] = [Product_Category_Map].[CategoryID] WHERE [Product_Category_Map].[ProductID] = PARM__ProductID", Product.Schema.Provider.Name); cmd.AddParameter("PARM__ProductID", varProductID, DbType.Int32); IDataReader rdr = SubSonic.DataService.GetReader(cmd); CategoryCollection coll = new CategoryCollection(); coll.LoadAndCloseReader(rdr); return coll; } public static void SaveCategoryMap(int varProductID, CategoryCollection items) { QueryCommandCollection coll = new SubSonic.QueryCommandCollection(); //delete out the existing QueryCommand cmdDel = new QueryCommand("DELETE FROM [Product_Category_Map] WHERE [Product_Category_Map].[ProductID] = PARM__ProductID", Product.Schema.Provider.Name); cmdDel.AddParameter("PARM__ProductID", varProductID, DbType.Int32); coll.Add(cmdDel); DataService.ExecuteTransaction(coll); foreach (Category item in items) { ProductCategoryMap varProductCategoryMap = new ProductCategoryMap(); varProductCategoryMap.SetColumnValue("ProductID", varProductID); varProductCategoryMap.SetColumnValue("CategoryID", item.GetPrimaryKeyValue()); varProductCategoryMap.Save(); } } public static void SaveCategoryMap(int varProductID, System.Web.UI.WebControls.ListItemCollection itemList) { QueryCommandCollection coll = new SubSonic.QueryCommandCollection(); //delete out the existing QueryCommand cmdDel = new QueryCommand("DELETE FROM [Product_Category_Map] WHERE [Product_Category_Map].[ProductID] = PARM__ProductID", Product.Schema.Provider.Name); cmdDel.AddParameter("PARM__ProductID", varProductID, DbType.Int32); coll.Add(cmdDel); DataService.ExecuteTransaction(coll); foreach (System.Web.UI.WebControls.ListItem l in itemList) { if (l.Selected) { ProductCategoryMap varProductCategoryMap = new ProductCategoryMap(); varProductCategoryMap.SetColumnValue("ProductID", varProductID); varProductCategoryMap.SetColumnValue("CategoryID", l.Value); varProductCategoryMap.Save(); } } } public static void SaveCategoryMap(int varProductID , int[] itemList) { QueryCommandCollection coll = new SubSonic.QueryCommandCollection(); //delete out the existing QueryCommand cmdDel = new QueryCommand("DELETE FROM [Product_Category_Map] WHERE [Product_Category_Map].[ProductID] = PARM__ProductID", Product.Schema.Provider.Name); cmdDel.AddParameter("PARM__ProductID", varProductID, DbType.Int32); coll.Add(cmdDel); DataService.ExecuteTransaction(coll); foreach (int item in itemList) { ProductCategoryMap varProductCategoryMap = new ProductCategoryMap(); varProductCategoryMap.SetColumnValue("ProductID", varProductID); varProductCategoryMap.SetColumnValue("CategoryID", item); varProductCategoryMap.Save(); } } public static void DeleteCategoryMap(int varProductID) { QueryCommand cmdDel = new QueryCommand("DELETE FROM [Product_Category_Map] WHERE [Product_Category_Map].[ProductID] = PARM__ProductID", Product.Schema.Provider.Name); cmdDel.AddParameter("PARM__ProductID", varProductID, DbType.Int32); DataService.ExecuteQuery(cmdDel); } #endregion #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(string varProductName,int? varSupplierID,int? varCategoryID,string varQuantityPerUnit,decimal? varUnitPrice,short? varUnitsInStock,short? varUnitsOnOrder,short? varReorderLevel,bool varDiscontinued,string varAttributeXML,DateTime? varDateCreated,Guid? varProductGUID,DateTime varCreatedOn,string varCreatedBy,DateTime varModifiedOn,string varModifiedBy,bool varDeleted) { Product item = new Product(); item.ProductName = varProductName; item.SupplierID = varSupplierID; item.CategoryID = varCategoryID; item.QuantityPerUnit = varQuantityPerUnit; item.UnitPrice = varUnitPrice; item.UnitsInStock = varUnitsInStock; item.UnitsOnOrder = varUnitsOnOrder; item.ReorderLevel = varReorderLevel; item.Discontinued = varDiscontinued; item.AttributeXML = varAttributeXML; item.DateCreated = varDateCreated; item.ProductGUID = varProductGUID; item.CreatedOn = varCreatedOn; item.CreatedBy = varCreatedBy; item.ModifiedOn = varModifiedOn; item.ModifiedBy = varModifiedBy; item.Deleted = varDeleted; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varProductID,string varProductName,int? varSupplierID,int? varCategoryID,string varQuantityPerUnit,decimal? varUnitPrice,short? varUnitsInStock,short? varUnitsOnOrder,short? varReorderLevel,bool varDiscontinued,string varAttributeXML,DateTime? varDateCreated,Guid? varProductGUID,DateTime varCreatedOn,string varCreatedBy,DateTime varModifiedOn,string varModifiedBy,bool varDeleted) { Product item = new Product(); item.ProductID = varProductID; item.ProductName = varProductName; item.SupplierID = varSupplierID; item.CategoryID = varCategoryID; item.QuantityPerUnit = varQuantityPerUnit; item.UnitPrice = varUnitPrice; item.UnitsInStock = varUnitsInStock; item.UnitsOnOrder = varUnitsOnOrder; item.ReorderLevel = varReorderLevel; item.Discontinued = varDiscontinued; item.AttributeXML = varAttributeXML; item.DateCreated = varDateCreated; item.ProductGUID = varProductGUID; item.CreatedOn = varCreatedOn; item.CreatedBy = varCreatedBy; item.ModifiedOn = varModifiedOn; item.ModifiedBy = varModifiedBy; item.Deleted = varDeleted; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn ProductIDColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn ProductNameColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn SupplierIDColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn CategoryIDColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn QuantityPerUnitColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn UnitPriceColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn UnitsInStockColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn UnitsOnOrderColumn { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn ReorderLevelColumn { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn DiscontinuedColumn { get { return Schema.Columns[9]; } } public static TableSchema.TableColumn AttributeXMLColumn { get { return Schema.Columns[10]; } } public static TableSchema.TableColumn DateCreatedColumn { get { return Schema.Columns[11]; } } public static TableSchema.TableColumn ProductGUIDColumn { get { return Schema.Columns[12]; } } public static TableSchema.TableColumn CreatedOnColumn { get { return Schema.Columns[13]; } } public static TableSchema.TableColumn CreatedByColumn { get { return Schema.Columns[14]; } } public static TableSchema.TableColumn ModifiedOnColumn { get { return Schema.Columns[15]; } } public static TableSchema.TableColumn ModifiedByColumn { get { return Schema.Columns[16]; } } public static TableSchema.TableColumn DeletedColumn { get { return Schema.Columns[17]; } } #endregion #region Columns Struct public struct Columns { public static string ProductID = @"ProductID"; public static string ProductName = @"ProductName"; public static string SupplierID = @"SupplierID"; public static string CategoryID = @"CategoryID"; public static string QuantityPerUnit = @"QuantityPerUnit"; public static string UnitPrice = @"UnitPrice"; public static string UnitsInStock = @"UnitsInStock"; public static string UnitsOnOrder = @"UnitsOnOrder"; public static string ReorderLevel = @"ReorderLevel"; public static string Discontinued = @"Discontinued"; public static string AttributeXML = @"AttributeXML"; public static string DateCreated = @"DateCreated"; public static string ProductGUID = @"ProductGUID"; public static string CreatedOn = @"CreatedOn"; public static string CreatedBy = @"CreatedBy"; public static string ModifiedOn = @"ModifiedOn"; public static string ModifiedBy = @"ModifiedBy"; public static string Deleted = @"Deleted"; } #endregion #region Update PK Collections public void SetPKValues() { } #endregion #region Deep Save public void DeepSave() { Save(); } #endregion } }
namespace android.content { [global::MonoJavaBridge.JavaClass(typeof(global::android.content.BroadcastReceiver_))] public abstract partial class BroadcastReceiver : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static BroadcastReceiver() { InitJNI(); } protected BroadcastReceiver(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _onReceive1085; public abstract void onReceive(android.content.Context arg0, android.content.Intent arg1); internal static global::MonoJavaBridge.MethodId _peekService1086; public virtual global::android.os.IBinder peekService(android.content.Context arg0, android.content.Intent arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.os.IBinder>(@__env.CallObjectMethod(this.JvmHandle, global::android.content.BroadcastReceiver._peekService1086, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.os.IBinder; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.os.IBinder>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.BroadcastReceiver.staticClass, global::android.content.BroadcastReceiver._peekService1086, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.os.IBinder; } internal static global::MonoJavaBridge.MethodId _setResultCode1087; public virtual void setResultCode(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.BroadcastReceiver._setResultCode1087, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.BroadcastReceiver.staticClass, global::android.content.BroadcastReceiver._setResultCode1087, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getResultCode1088; public virtual int getResultCode() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.content.BroadcastReceiver._getResultCode1088); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.BroadcastReceiver.staticClass, global::android.content.BroadcastReceiver._getResultCode1088); } internal static global::MonoJavaBridge.MethodId _setResultData1089; public virtual void setResultData(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.BroadcastReceiver._setResultData1089, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.BroadcastReceiver.staticClass, global::android.content.BroadcastReceiver._setResultData1089, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getResultData1090; public virtual global::java.lang.String getResultData() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.BroadcastReceiver._getResultData1090)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.BroadcastReceiver.staticClass, global::android.content.BroadcastReceiver._getResultData1090)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _setResultExtras1091; public virtual void setResultExtras(android.os.Bundle arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.BroadcastReceiver._setResultExtras1091, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.BroadcastReceiver.staticClass, global::android.content.BroadcastReceiver._setResultExtras1091, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getResultExtras1092; public virtual global::android.os.Bundle getResultExtras(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.BroadcastReceiver._getResultExtras1092, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.os.Bundle; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.BroadcastReceiver.staticClass, global::android.content.BroadcastReceiver._getResultExtras1092, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.os.Bundle; } internal static global::MonoJavaBridge.MethodId _setResult1093; public virtual void setResult(int arg0, java.lang.String arg1, android.os.Bundle arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.BroadcastReceiver._setResult1093, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.BroadcastReceiver.staticClass, global::android.content.BroadcastReceiver._setResult1093, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _getAbortBroadcast1094; public virtual bool getAbortBroadcast() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.content.BroadcastReceiver._getAbortBroadcast1094); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.content.BroadcastReceiver.staticClass, global::android.content.BroadcastReceiver._getAbortBroadcast1094); } internal static global::MonoJavaBridge.MethodId _abortBroadcast1095; public virtual void abortBroadcast() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.BroadcastReceiver._abortBroadcast1095); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.BroadcastReceiver.staticClass, global::android.content.BroadcastReceiver._abortBroadcast1095); } internal static global::MonoJavaBridge.MethodId _clearAbortBroadcast1096; public virtual void clearAbortBroadcast() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.BroadcastReceiver._clearAbortBroadcast1096); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.BroadcastReceiver.staticClass, global::android.content.BroadcastReceiver._clearAbortBroadcast1096); } internal static global::MonoJavaBridge.MethodId _isOrderedBroadcast1097; public virtual bool isOrderedBroadcast() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.content.BroadcastReceiver._isOrderedBroadcast1097); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.content.BroadcastReceiver.staticClass, global::android.content.BroadcastReceiver._isOrderedBroadcast1097); } internal static global::MonoJavaBridge.MethodId _isInitialStickyBroadcast1098; public virtual bool isInitialStickyBroadcast() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.content.BroadcastReceiver._isInitialStickyBroadcast1098); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.content.BroadcastReceiver.staticClass, global::android.content.BroadcastReceiver._isInitialStickyBroadcast1098); } internal static global::MonoJavaBridge.MethodId _setOrderedHint1099; public virtual void setOrderedHint(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.BroadcastReceiver._setOrderedHint1099, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.BroadcastReceiver.staticClass, global::android.content.BroadcastReceiver._setOrderedHint1099, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setDebugUnregister1100; public virtual void setDebugUnregister(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.BroadcastReceiver._setDebugUnregister1100, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.BroadcastReceiver.staticClass, global::android.content.BroadcastReceiver._setDebugUnregister1100, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getDebugUnregister1101; public virtual bool getDebugUnregister() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.content.BroadcastReceiver._getDebugUnregister1101); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.content.BroadcastReceiver.staticClass, global::android.content.BroadcastReceiver._getDebugUnregister1101); } internal static global::MonoJavaBridge.MethodId _BroadcastReceiver1102; public BroadcastReceiver() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.content.BroadcastReceiver.staticClass, global::android.content.BroadcastReceiver._BroadcastReceiver1102); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.content.BroadcastReceiver.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/content/BroadcastReceiver")); global::android.content.BroadcastReceiver._onReceive1085 = @__env.GetMethodIDNoThrow(global::android.content.BroadcastReceiver.staticClass, "onReceive", "(Landroid/content/Context;Landroid/content/Intent;)V"); global::android.content.BroadcastReceiver._peekService1086 = @__env.GetMethodIDNoThrow(global::android.content.BroadcastReceiver.staticClass, "peekService", "(Landroid/content/Context;Landroid/content/Intent;)Landroid/os/IBinder;"); global::android.content.BroadcastReceiver._setResultCode1087 = @__env.GetMethodIDNoThrow(global::android.content.BroadcastReceiver.staticClass, "setResultCode", "(I)V"); global::android.content.BroadcastReceiver._getResultCode1088 = @__env.GetMethodIDNoThrow(global::android.content.BroadcastReceiver.staticClass, "getResultCode", "()I"); global::android.content.BroadcastReceiver._setResultData1089 = @__env.GetMethodIDNoThrow(global::android.content.BroadcastReceiver.staticClass, "setResultData", "(Ljava/lang/String;)V"); global::android.content.BroadcastReceiver._getResultData1090 = @__env.GetMethodIDNoThrow(global::android.content.BroadcastReceiver.staticClass, "getResultData", "()Ljava/lang/String;"); global::android.content.BroadcastReceiver._setResultExtras1091 = @__env.GetMethodIDNoThrow(global::android.content.BroadcastReceiver.staticClass, "setResultExtras", "(Landroid/os/Bundle;)V"); global::android.content.BroadcastReceiver._getResultExtras1092 = @__env.GetMethodIDNoThrow(global::android.content.BroadcastReceiver.staticClass, "getResultExtras", "(Z)Landroid/os/Bundle;"); global::android.content.BroadcastReceiver._setResult1093 = @__env.GetMethodIDNoThrow(global::android.content.BroadcastReceiver.staticClass, "setResult", "(ILjava/lang/String;Landroid/os/Bundle;)V"); global::android.content.BroadcastReceiver._getAbortBroadcast1094 = @__env.GetMethodIDNoThrow(global::android.content.BroadcastReceiver.staticClass, "getAbortBroadcast", "()Z"); global::android.content.BroadcastReceiver._abortBroadcast1095 = @__env.GetMethodIDNoThrow(global::android.content.BroadcastReceiver.staticClass, "abortBroadcast", "()V"); global::android.content.BroadcastReceiver._clearAbortBroadcast1096 = @__env.GetMethodIDNoThrow(global::android.content.BroadcastReceiver.staticClass, "clearAbortBroadcast", "()V"); global::android.content.BroadcastReceiver._isOrderedBroadcast1097 = @__env.GetMethodIDNoThrow(global::android.content.BroadcastReceiver.staticClass, "isOrderedBroadcast", "()Z"); global::android.content.BroadcastReceiver._isInitialStickyBroadcast1098 = @__env.GetMethodIDNoThrow(global::android.content.BroadcastReceiver.staticClass, "isInitialStickyBroadcast", "()Z"); global::android.content.BroadcastReceiver._setOrderedHint1099 = @__env.GetMethodIDNoThrow(global::android.content.BroadcastReceiver.staticClass, "setOrderedHint", "(Z)V"); global::android.content.BroadcastReceiver._setDebugUnregister1100 = @__env.GetMethodIDNoThrow(global::android.content.BroadcastReceiver.staticClass, "setDebugUnregister", "(Z)V"); global::android.content.BroadcastReceiver._getDebugUnregister1101 = @__env.GetMethodIDNoThrow(global::android.content.BroadcastReceiver.staticClass, "getDebugUnregister", "()Z"); global::android.content.BroadcastReceiver._BroadcastReceiver1102 = @__env.GetMethodIDNoThrow(global::android.content.BroadcastReceiver.staticClass, "<init>", "()V"); } } [global::MonoJavaBridge.JavaProxy(typeof(global::android.content.BroadcastReceiver))] public sealed partial class BroadcastReceiver_ : android.content.BroadcastReceiver { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static BroadcastReceiver_() { InitJNI(); } internal BroadcastReceiver_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _onReceive1103; public override void onReceive(android.content.Context arg0, android.content.Intent arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.BroadcastReceiver_._onReceive1103, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.BroadcastReceiver_.staticClass, global::android.content.BroadcastReceiver_._onReceive1103, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.content.BroadcastReceiver_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/content/BroadcastReceiver")); global::android.content.BroadcastReceiver_._onReceive1103 = @__env.GetMethodIDNoThrow(global::android.content.BroadcastReceiver_.staticClass, "onReceive", "(Landroid/content/Context;Landroid/content/Intent;)V"); } } }
// 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. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Input; using System.Windows.Threading; using Microsoft.VisualStudioTools; namespace Microsoft.PythonTools.Analysis.Browser { public partial class MainWindow : Window { public static readonly ICommand CloseDatabaseCommand = new RoutedCommand(); public static readonly ICommand OpenDatabaseCommand = new RoutedCommand(); public static readonly ICommand BrowseSaveCommand = new RoutedCommand(); public static readonly ICommand BrowseFolderCommand = new RoutedCommand(); public static readonly ICommand GoToItemCommand = new RoutedCommand(); public static readonly IEnumerable<Version> SupportedVersions = new[] { new Version(2, 5), new Version(2, 6), new Version(2, 7), new Version(3, 0), new Version(3, 1), new Version(3, 2), new Version(3, 3), new Version(3, 4), }; public MainWindow() { InitializeComponent(); DatabaseDirectory.Text = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Python Tools" ); var path = Environment.GetCommandLineArgs().LastOrDefault(); try { if (Directory.Exists(path)) { Load(path); } } catch { } } internal AnalysisView Analysis { get { return (AnalysisView)GetValue(AnalysisProperty); } private set { SetValue(AnalysisPropertyKey, value); } } private static readonly DependencyPropertyKey AnalysisPropertyKey = DependencyProperty.RegisterReadOnly("Analysis", typeof(AnalysisView), typeof(MainWindow), new PropertyMetadata()); public static readonly DependencyProperty AnalysisProperty = AnalysisPropertyKey.DependencyProperty; public bool HasAnalysis { get { return (bool)GetValue(HasAnalysisProperty); } private set { SetValue(HasAnalysisPropertyKey, value); } } private static readonly DependencyPropertyKey HasAnalysisPropertyKey = DependencyProperty.RegisterReadOnly("HasAnalysis", typeof(bool), typeof(MainWindow), new PropertyMetadata(false)); public static readonly DependencyProperty HasAnalysisProperty = HasAnalysisPropertyKey.DependencyProperty; public bool Loading { get { return (bool)GetValue(LoadingProperty); } private set { SetValue(LoadingPropertyKey, value); } } private static readonly DependencyPropertyKey LoadingPropertyKey = DependencyProperty.RegisterReadOnly("Loading", typeof(bool), typeof(MainWindow), new PropertyMetadata(false)); public static readonly DependencyProperty LoadingProperty = LoadingPropertyKey.DependencyProperty; public Version Version { get { return (Version)GetValue(VersionProperty); } set { SetValue(VersionProperty, value); } } public static readonly DependencyProperty VersionProperty = DependencyProperty.Register("Version", typeof(Version), typeof(MainWindow), new PropertyMetadata(new Version(2, 7))); public bool LoadWithContention { get { return (bool)GetValue(LoadWithContentionProperty); } set { SetValue(LoadWithContentionProperty, value); } } public static readonly DependencyProperty LoadWithContentionProperty = DependencyProperty.Register("LoadWithContention", typeof(bool), typeof(MainWindow), new PropertyMetadata(false)); public bool LoadWithLowMemory { get { return (bool)GetValue(LoadWithLowMemoryProperty); } set { SetValue(LoadWithLowMemoryProperty, value); } } public static readonly DependencyProperty LoadWithLowMemoryProperty = DependencyProperty.Register("LoadWithLowMemory", typeof(bool), typeof(MainWindow), new PropertyMetadata(false)); public bool LoadRecursive { get { return (bool)GetValue(LoadRecursiveProperty); } set { SetValue(LoadRecursiveProperty, value); } } public static readonly DependencyProperty LoadRecursiveProperty = DependencyProperty.Register("LoadRecursive", typeof(bool), typeof(MainWindow), new PropertyMetadata(false)); private void Open_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = !Loading; } private void Open_Executed(object sender, ExecutedRoutedEventArgs e) { string path; var tb = e.Source as TextBox; if (tb == null || !Directory.Exists(path = tb.Text)) { using (var bfd = new Microsoft.WindowsAPICodePack.Dialogs.CommonOpenFileDialog()) { bfd.IsFolderPicker = true; bfd.RestoreDirectory = true; if (HasAnalysis) { path = Analysis.Path; } else { path = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Python Tools" ); } while (path.Length >= 4 && !Directory.Exists(path)) { path = Path.GetDirectoryName(path); } if (path.Length <= 3) { path = null; } bfd.InitialDirectory = path; if (bfd.ShowDialog() == WindowsAPICodePack.Dialogs.CommonFileDialogResult.Cancel) { return; } path = bfd.FileName; } } Load(path); } private void Load(string path) { HasAnalysis = false; Loading = true; Analysis = null; Cursor = Cursors.Wait; var version = Version; var withContention = LoadWithContention; var withLowMemory = LoadWithLowMemory; var withRecursion = LoadRecursive; var tcs = new TaskCompletionSource<object>(); tcs.SetResult(null); Task startTask = tcs.Task; if (withLowMemory) { startTask = Task.Factory.StartNew(() => { var bigBlocks = new LinkedList<byte[]>(); var rnd = new Random(); try { while (true) { var block = new byte[10 * 1024 * 1024]; rnd.NextBytes(block); bigBlocks.AddLast(block); } } catch (OutOfMemoryException) { // Leave 200MB of memory available for (int i = 0; i < 20 && bigBlocks.Any(); ++i) { bigBlocks.RemoveFirst(); } } return bigBlocks; }).ContinueWith(t => { Tag = t.Result; }, TaskScheduler.FromCurrentSynchronizationContext()); } var loadTask = startTask.ContinueWith<AnalysisView>(t => { return new AnalysisView(path, version, withContention, withRecursion); }, TaskContinuationOptions.LongRunning); loadTask.ContinueWith( t => { Tag = null; try { Analysis = t.Result; HasAnalysis = true; } catch (Exception ex) { HasAnalysis = false; MessageBox.Show(string.Format("Error occurred:{0}{0}{1}", Environment.NewLine, ex)); } Loading = false; Cursor = Cursors.Arrow; }, TaskScheduler.FromCurrentSynchronizationContext() ); } private void Export_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = HasAnalysis && !string.IsNullOrEmpty(ExportFilename.Text); if (e.Command == AnalysisView.ExportDiffableCommand) { // Not implemented yet e.CanExecute = false; } } private void Export_Executed(object sender, ExecutedRoutedEventArgs e) { e.Handled = true; var path = ExportFilename.Text; var filter = ExportFilter.Text; Cursor = Cursors.AppStarting; Task t = null; if (e.Command == AnalysisView.ExportTreeCommand) { t = Analysis.ExportTree(path, filter); } else if (e.Command == AnalysisView.ExportDiffableCommand) { t = Analysis.ExportDiffable(path, filter); } if (t != null) { t.ContinueWith(t2 => { Process.Start("explorer.exe", "/select,\"" + path + "\""); }, TaskContinuationOptions.OnlyOnRanToCompletion); t.ContinueWith(t2 => { Cursor = Cursors.Arrow; if (t2.Exception != null) { MessageBox.Show(string.Format("An error occurred while exporting:{0}{0}{1}", Environment.NewLine, t2.Exception)); } }, TaskScheduler.FromCurrentSynchronizationContext()); } } private void BrowseSave_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = e.Source is TextBox && e.Parameter is string; } private void BrowseSave_Executed(object sender, ExecutedRoutedEventArgs e) { using (var dialog = new System.Windows.Forms.SaveFileDialog()) { dialog.Filter = (string)e.Parameter; dialog.AutoUpgradeEnabled = true; var path = ((TextBox)e.Source).Text; try { dialog.FileName = path; dialog.InitialDirectory = Path.GetDirectoryName(path); } catch (ArgumentException) { dialog.FileName = string.Empty; dialog.InitialDirectory = Analysis.Path; } dialog.RestoreDirectory = true; if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.Cancel) { return; } ((TextBox)e.Source).SetCurrentValue(TextBox.TextProperty, dialog.FileName); } } private void BrowseFolder_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = e.Source is TextBox; } private void BrowseFolder_Executed(object sender, ExecutedRoutedEventArgs e) { using (var bfd = new Microsoft.WindowsAPICodePack.Dialogs.CommonOpenFileDialog()) { bfd.IsFolderPicker = true; bfd.RestoreDirectory = true; var path = ((TextBox)e.Source).Text; while (path.Length >= 4 && !Directory.Exists(path)) { path = Path.GetDirectoryName(path); } if (path.Length <= 3) { path = null; } bfd.InitialDirectory = path; if (bfd.ShowDialog() == WindowsAPICodePack.Dialogs.CommonFileDialogResult.Cancel) { return; } ((TextBox)e.Source).SetCurrentValue(TextBox.TextProperty, bfd.FileName); } } private void GoToItem_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = e.Parameter is IAnalysisItemView; } private static Stack<TreeViewItem> SelectChild(TreeViewItem root, object value) { if (root == null) { return null; } if (root.DataContext == value) { var lst = new Stack<TreeViewItem>(); lst.Push(root); return lst; } foreach (var child in root.Items .OfType<object>() .Select(i => (TreeViewItem)root.ItemContainerGenerator.ContainerFromItem(i))) { var lst = SelectChild(child, value); if (lst != null) { lst.Push(root); return lst; } } return null; } private static void SelectChild(TreeView tree, object value) { Stack<TreeViewItem> result = null; foreach (var item in tree.Items .OfType<object>() .Select(i => (TreeViewItem)tree.ItemContainerGenerator.ContainerFromItem(i))) { if ((result = SelectChild(item, value)) != null) { break; } } if (result != null) { while (result.Any()) { var item = result.Pop(); item.IsExpanded = true; item.Focus(); } } } private void GoToItem_Executed(object sender, ExecutedRoutedEventArgs e) { Cursor = Cursors.Wait; try { SelectChild(DatabaseTreeView, e.Parameter); } finally { Cursor = Cursors.Arrow; } } private void Close_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = true; } private void Close_Executed(object sender, ExecutedRoutedEventArgs e) { Close(); } private void CloseDatabase_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = HasAnalysis; } private void CloseDatabase_Executed(object sender, ExecutedRoutedEventArgs e) { Analysis = null; Loading = false; HasAnalysis = false; DatabaseDirectory.SelectAll(); } private void DatabaseDirectory_TextChanged(object sender, TextChangedEventArgs e) { var dir = DatabaseDirectory.Text; if (!Directory.Exists(dir)) { return; } foreach (var ver in SupportedVersions.Reverse()) { if (dir.Contains("\\" + ver.ToString())) { Version = ver; break; } } } private void NavigateTo_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = Directory.Exists(e.Parameter as string); e.Handled = true; } private void NavigateTo_Executed(object sender, ExecutedRoutedEventArgs e) { DatabaseDirectory.SetCurrentValue(TextBox.TextProperty, e.Parameter); DatabaseDirectory.Focus(); DatabaseDirectory.SelectAll(); e.Handled = true; } private void DatabaseDirectory_SubDirs_PreviewGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) { DatabaseDirectory.Focus(); e.Handled = true; } } class PropertyItemTemplateSelector : DataTemplateSelector { public DataTemplate Text { get; set; } public DataTemplate AnalysisItem { get; set; } public override DataTemplate SelectTemplate(object item, DependencyObject container) { if (item is string) { return Text; } else if (item is IAnalysisItemView) { return AnalysisItem; } return null; } } [ValueConversion(typeof(string), typeof(IEnumerable<string>))] class DirectoryList : IValueConverter { public bool IncludeParentDirectory { get; set; } public bool IncludeDirectories { get; set; } public bool IncludeFiles { get; set; } public bool NamesOnly { get; set; } private IEnumerable<string> GetParentDirectory(string dir) { if (!IncludeParentDirectory || ! CommonUtils.IsValidPath(dir)) { yield break; } var parentDir = Path.GetDirectoryName(dir); if (!string.IsNullOrEmpty(parentDir)) { yield return parentDir; } } private IEnumerable<string> GetFiles(string dir) { if (!IncludeFiles) { return Enumerable.Empty<string>(); } var files = Directory.EnumerateFiles(dir); if (NamesOnly) { files = files.Select(f => Path.GetFileName(f)); } return files.OrderBy(f => f); } private IEnumerable<string> GetDirectories(string dir) { if (!IncludeDirectories) { return Enumerable.Empty<string>(); } var dirs = Directory.EnumerateDirectories(dir); if (NamesOnly) { dirs = dirs.Select(d => Path.GetFileName(d)); } return dirs.OrderBy(d => d); } public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { var dir = value as string; if (!Directory.Exists(dir)) { return Enumerable.Empty<string>(); } return GetParentDirectory(dir).Concat(GetDirectories(dir)).Concat(GetFiles(dir)); } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Abp.Extensions; using Abp.Runtime.Session; using Abp.Utils.Etc; using Castle.Core; namespace Abp.Domain.Uow { /// <summary> /// Base for all Unit Of Work classes. /// </summary> public abstract class UnitOfWorkBase : IUnitOfWork { public string Id { get; } [DoNotWire] public IUnitOfWork Outer { get; set; } /// <inheritdoc/> public event EventHandler Completed; /// <inheritdoc/> public event EventHandler<UnitOfWorkFailedEventArgs> Failed; /// <inheritdoc/> public event EventHandler Disposed; /// <inheritdoc/> public UnitOfWorkOptions Options { get; private set; } /// <inheritdoc/> public IReadOnlyList<DataFilterConfiguration> Filters { get { return _filters.ToImmutableList(); } } private readonly List<DataFilterConfiguration> _filters; public Dictionary<string, object> Items { get; set; } /// <summary> /// Gets default UOW options. /// </summary> protected IUnitOfWorkDefaultOptions DefaultOptions { get; } /// <summary> /// Gets the connection string resolver. /// </summary> protected IConnectionStringResolver ConnectionStringResolver { get; } /// <summary> /// Gets a value indicates that this unit of work is disposed or not. /// </summary> public bool IsDisposed { get; private set; } /// <summary> /// Reference to current ABP session. /// </summary> public IAbpSession AbpSession { protected get; set; } protected IUnitOfWorkFilterExecuter FilterExecuter { get; } /// <summary> /// Is <see cref="Begin"/> method called before? /// </summary> private bool _isBeginCalledBefore; /// <summary> /// Is <see cref="Complete"/> method called before? /// </summary> private bool _isCompleteCalledBefore; /// <summary> /// Is this unit of work successfully completed. /// </summary> private bool _succeed; /// <summary> /// A reference to the exception if this unit of work failed. /// </summary> private Exception _exception; private int? _tenantId; /// <summary> /// Constructor. /// </summary> protected UnitOfWorkBase( IConnectionStringResolver connectionStringResolver, IUnitOfWorkDefaultOptions defaultOptions, IUnitOfWorkFilterExecuter filterExecuter) { FilterExecuter = filterExecuter; DefaultOptions = defaultOptions; ConnectionStringResolver = connectionStringResolver; Id = Guid.NewGuid().ToString("N"); _filters = defaultOptions.Filters.ToList(); AbpSession = NullAbpSession.Instance; Items = new Dictionary<string, object>(); } /// <inheritdoc/> public void Begin(UnitOfWorkOptions options) { Check.NotNull(options, nameof(options)); PreventMultipleBegin(); Options = options; //TODO: Do not set options like that, instead make a copy? SetFilters(options.FilterOverrides); SetTenantId(AbpSession.TenantId, false); BeginUow(); } /// <inheritdoc/> public abstract void SaveChanges(); /// <inheritdoc/> public abstract Task SaveChangesAsync(); /// <inheritdoc/> public IDisposable DisableFilter(params string[] filterNames) { //TODO: Check if filters exists? var disabledFilters = new List<string>(); foreach (var filterName in filterNames) { var filterIndex = GetFilterIndex(filterName); if (_filters[filterIndex].IsEnabled) { disabledFilters.Add(filterName); _filters[filterIndex] = new DataFilterConfiguration(_filters[filterIndex], false); } } disabledFilters.ForEach(ApplyDisableFilter); return new DisposeAction(() => EnableFilter(disabledFilters.ToArray())); } /// <inheritdoc/> public IDisposable EnableFilter(params string[] filterNames) { //TODO: Check if filters exists? var enabledFilters = new List<string>(); foreach (var filterName in filterNames) { var filterIndex = GetFilterIndex(filterName); if (!_filters[filterIndex].IsEnabled) { enabledFilters.Add(filterName); _filters[filterIndex] = new DataFilterConfiguration(_filters[filterIndex], true); } } enabledFilters.ForEach(ApplyEnableFilter); return new DisposeAction(() => DisableFilter(enabledFilters.ToArray())); } /// <inheritdoc/> public bool IsFilterEnabled(string filterName) { return GetFilter(filterName).IsEnabled; } /// <inheritdoc/> public IDisposable SetFilterParameter(string filterName, string parameterName, object value) { var filterIndex = GetFilterIndex(filterName); var newfilter = new DataFilterConfiguration(_filters[filterIndex]); //Store old value object oldValue = null; var hasOldValue = newfilter.FilterParameters.ContainsKey(parameterName); if (hasOldValue) { oldValue = newfilter.FilterParameters[parameterName]; } newfilter.FilterParameters[parameterName] = value; _filters[filterIndex] = newfilter; ApplyFilterParameterValue(filterName, parameterName, value); return new DisposeAction(() => { //Restore old value if (hasOldValue) { SetFilterParameter(filterName, parameterName, oldValue); } }); } public virtual IDisposable SetTenantId(int? tenantId) { return SetTenantId(tenantId, true); } public virtual IDisposable SetTenantId(int? tenantId, bool switchMustHaveTenantEnableDisable) { var oldTenantId = _tenantId; _tenantId = tenantId; IDisposable mustHaveTenantEnableChange; if (switchMustHaveTenantEnableDisable) { mustHaveTenantEnableChange = tenantId == null ? DisableFilter(AbpDataFilters.MustHaveTenant) : EnableFilter(AbpDataFilters.MustHaveTenant); } else { mustHaveTenantEnableChange = NullDisposable.Instance; } var mayHaveTenantChange = SetFilterParameter(AbpDataFilters.MayHaveTenant, AbpDataFilters.Parameters.TenantId, tenantId); var mustHaveTenantChange = SetFilterParameter(AbpDataFilters.MustHaveTenant, AbpDataFilters.Parameters.TenantId, tenantId ?? 0); return new DisposeAction(() => { mayHaveTenantChange.Dispose(); mustHaveTenantChange.Dispose(); mustHaveTenantEnableChange.Dispose(); _tenantId = oldTenantId; }); } public int? GetTenantId() { return _tenantId; } /// <inheritdoc/> public void Complete() { PreventMultipleComplete(); try { CompleteUow(); _succeed = true; OnCompleted(); } catch (Exception ex) { _exception = ex; throw; } } /// <inheritdoc/> public async Task CompleteAsync() { PreventMultipleComplete(); try { await CompleteUowAsync(); _succeed = true; OnCompleted(); } catch (Exception ex) { _exception = ex; throw; } } /// <inheritdoc/> public void Dispose() { if (!_isBeginCalledBefore || IsDisposed) { return; } IsDisposed = true; if (!_succeed) { OnFailed(_exception); } DisposeUow(); OnDisposed(); } /// <summary> /// Can be implemented by derived classes to start UOW. /// </summary> protected virtual void BeginUow() { } /// <summary> /// Should be implemented by derived classes to complete UOW. /// </summary> protected abstract void CompleteUow(); /// <summary> /// Should be implemented by derived classes to complete UOW. /// </summary> protected abstract Task CompleteUowAsync(); /// <summary> /// Should be implemented by derived classes to dispose UOW. /// </summary> protected abstract void DisposeUow(); protected virtual void ApplyDisableFilter(string filterName) { FilterExecuter.ApplyDisableFilter(this, filterName); } protected virtual void ApplyEnableFilter(string filterName) { FilterExecuter.ApplyEnableFilter(this, filterName); } protected virtual void ApplyFilterParameterValue(string filterName, string parameterName, object value) { FilterExecuter.ApplyFilterParameterValue(this, filterName, parameterName, value); } protected virtual string ResolveConnectionString(ConnectionStringResolveArgs args) { return ConnectionStringResolver.GetNameOrConnectionString(args); } /// <summary> /// Called to trigger <see cref="Completed"/> event. /// </summary> protected virtual void OnCompleted() { Completed.InvokeSafely(this); } /// <summary> /// Called to trigger <see cref="Failed"/> event. /// </summary> /// <param name="exception">Exception that cause failure</param> protected virtual void OnFailed(Exception exception) { Failed.InvokeSafely(this, new UnitOfWorkFailedEventArgs(exception)); } /// <summary> /// Called to trigger <see cref="Disposed"/> event. /// </summary> protected virtual void OnDisposed() { Disposed.InvokeSafely(this); } private void PreventMultipleBegin() { if (_isBeginCalledBefore) { throw new AbpException("This unit of work has started before. Can not call Start method more than once."); } _isBeginCalledBefore = true; } private void PreventMultipleComplete() { if (_isCompleteCalledBefore) { throw new AbpException("Complete is called before!"); } _isCompleteCalledBefore = true; } private void SetFilters(List<DataFilterConfiguration> filterOverrides) { for (var i = 0; i < _filters.Count; i++) { var filterOverride = filterOverrides.FirstOrDefault(f => f.FilterName == _filters[i].FilterName); if (filterOverride != null) { _filters[i] = filterOverride; } } if (AbpSession.TenantId == null) { ChangeFilterIsEnabledIfNotOverrided(filterOverrides, AbpDataFilters.MustHaveTenant, false); } } private void ChangeFilterIsEnabledIfNotOverrided(List<DataFilterConfiguration> filterOverrides, string filterName, bool isEnabled) { if (filterOverrides.Any(f => f.FilterName == filterName)) { return; } var index = _filters.FindIndex(f => f.FilterName == filterName); if (index < 0) { return; } if (_filters[index].IsEnabled == isEnabled) { return; } _filters[index] = new DataFilterConfiguration(filterName, isEnabled); } private DataFilterConfiguration GetFilter(string filterName) { var filter = _filters.FirstOrDefault(f => f.FilterName == filterName); if (filter == null) { throw new AbpException("Unknown filter name: " + filterName + ". Be sure this filter is registered before."); } return filter; } private int GetFilterIndex(string filterName) { var filterIndex = _filters.FindIndex(f => f.FilterName == filterName); if (filterIndex < 0) { throw new AbpException("Unknown filter name: " + filterName + ". Be sure this filter is registered before."); } return filterIndex; } public override string ToString() { return $"[UnitOfWork {Id}]"; } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the RisLugarRealizacion class. /// </summary> [Serializable] public partial class RisLugarRealizacionCollection : ActiveList<RisLugarRealizacion, RisLugarRealizacionCollection> { public RisLugarRealizacionCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>RisLugarRealizacionCollection</returns> public RisLugarRealizacionCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { RisLugarRealizacion o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the RIS_LugarRealizacion table. /// </summary> [Serializable] public partial class RisLugarRealizacion : ActiveRecord<RisLugarRealizacion>, IActiveRecord { #region .ctors and Default Settings public RisLugarRealizacion() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public RisLugarRealizacion(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public RisLugarRealizacion(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public RisLugarRealizacion(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("RIS_LugarRealizacion", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdLugarRealizacion = new TableSchema.TableColumn(schema); colvarIdLugarRealizacion.ColumnName = "idLugarRealizacion"; colvarIdLugarRealizacion.DataType = DbType.Int32; colvarIdLugarRealizacion.MaxLength = 0; colvarIdLugarRealizacion.AutoIncrement = true; colvarIdLugarRealizacion.IsNullable = false; colvarIdLugarRealizacion.IsPrimaryKey = true; colvarIdLugarRealizacion.IsForeignKey = false; colvarIdLugarRealizacion.IsReadOnly = false; colvarIdLugarRealizacion.DefaultSetting = @""; colvarIdLugarRealizacion.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdLugarRealizacion); TableSchema.TableColumn colvarIdEstudio = new TableSchema.TableColumn(schema); colvarIdEstudio.ColumnName = "idEstudio"; colvarIdEstudio.DataType = DbType.Int32; colvarIdEstudio.MaxLength = 0; colvarIdEstudio.AutoIncrement = false; colvarIdEstudio.IsNullable = false; colvarIdEstudio.IsPrimaryKey = false; colvarIdEstudio.IsForeignKey = false; colvarIdEstudio.IsReadOnly = false; colvarIdEstudio.DefaultSetting = @""; colvarIdEstudio.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdEstudio); TableSchema.TableColumn colvarDescripcion = new TableSchema.TableColumn(schema); colvarDescripcion.ColumnName = "descripcion"; colvarDescripcion.DataType = DbType.AnsiString; colvarDescripcion.MaxLength = 100; colvarDescripcion.AutoIncrement = false; colvarDescripcion.IsNullable = false; colvarDescripcion.IsPrimaryKey = false; colvarDescripcion.IsForeignKey = false; colvarDescripcion.IsReadOnly = false; colvarDescripcion.DefaultSetting = @""; colvarDescripcion.ForeignKeyTableName = ""; schema.Columns.Add(colvarDescripcion); TableSchema.TableColumn colvarAmbito = new TableSchema.TableColumn(schema); colvarAmbito.ColumnName = "ambito"; colvarAmbito.DataType = DbType.AnsiString; colvarAmbito.MaxLength = 100; colvarAmbito.AutoIncrement = false; colvarAmbito.IsNullable = false; colvarAmbito.IsPrimaryKey = false; colvarAmbito.IsForeignKey = false; colvarAmbito.IsReadOnly = false; colvarAmbito.DefaultSetting = @""; colvarAmbito.ForeignKeyTableName = ""; schema.Columns.Add(colvarAmbito); TableSchema.TableColumn colvarDomicilio = new TableSchema.TableColumn(schema); colvarDomicilio.ColumnName = "domicilio"; colvarDomicilio.DataType = DbType.AnsiString; colvarDomicilio.MaxLength = 100; colvarDomicilio.AutoIncrement = false; colvarDomicilio.IsNullable = false; colvarDomicilio.IsPrimaryKey = false; colvarDomicilio.IsForeignKey = false; colvarDomicilio.IsReadOnly = false; colvarDomicilio.DefaultSetting = @""; colvarDomicilio.ForeignKeyTableName = ""; schema.Columns.Add(colvarDomicilio); TableSchema.TableColumn colvarCp = new TableSchema.TableColumn(schema); colvarCp.ColumnName = "cp"; colvarCp.DataType = DbType.AnsiString; colvarCp.MaxLength = 100; colvarCp.AutoIncrement = false; colvarCp.IsNullable = false; colvarCp.IsPrimaryKey = false; colvarCp.IsForeignKey = false; colvarCp.IsReadOnly = false; colvarCp.DefaultSetting = @""; colvarCp.ForeignKeyTableName = ""; schema.Columns.Add(colvarCp); TableSchema.TableColumn colvarCiudad = new TableSchema.TableColumn(schema); colvarCiudad.ColumnName = "ciudad"; colvarCiudad.DataType = DbType.AnsiString; colvarCiudad.MaxLength = 100; colvarCiudad.AutoIncrement = false; colvarCiudad.IsNullable = false; colvarCiudad.IsPrimaryKey = false; colvarCiudad.IsForeignKey = false; colvarCiudad.IsReadOnly = false; colvarCiudad.DefaultSetting = @""; colvarCiudad.ForeignKeyTableName = ""; schema.Columns.Add(colvarCiudad); TableSchema.TableColumn colvarEmail = new TableSchema.TableColumn(schema); colvarEmail.ColumnName = "email"; colvarEmail.DataType = DbType.AnsiString; colvarEmail.MaxLength = 100; colvarEmail.AutoIncrement = false; colvarEmail.IsNullable = false; colvarEmail.IsPrimaryKey = false; colvarEmail.IsForeignKey = false; colvarEmail.IsReadOnly = false; colvarEmail.DefaultSetting = @""; colvarEmail.ForeignKeyTableName = ""; schema.Columns.Add(colvarEmail); TableSchema.TableColumn colvarResponsable = new TableSchema.TableColumn(schema); colvarResponsable.ColumnName = "responsable"; colvarResponsable.DataType = DbType.AnsiString; colvarResponsable.MaxLength = 100; colvarResponsable.AutoIncrement = false; colvarResponsable.IsNullable = false; colvarResponsable.IsPrimaryKey = false; colvarResponsable.IsForeignKey = false; colvarResponsable.IsReadOnly = false; colvarResponsable.DefaultSetting = @""; colvarResponsable.ForeignKeyTableName = ""; schema.Columns.Add(colvarResponsable); TableSchema.TableColumn colvarCargo = new TableSchema.TableColumn(schema); colvarCargo.ColumnName = "cargo"; colvarCargo.DataType = DbType.AnsiString; colvarCargo.MaxLength = 100; colvarCargo.AutoIncrement = false; colvarCargo.IsNullable = false; colvarCargo.IsPrimaryKey = false; colvarCargo.IsForeignKey = false; colvarCargo.IsReadOnly = false; colvarCargo.DefaultSetting = @""; colvarCargo.ForeignKeyTableName = ""; schema.Columns.Add(colvarCargo); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("RIS_LugarRealizacion",schema); } } #endregion #region Props [XmlAttribute("IdLugarRealizacion")] [Bindable(true)] public int IdLugarRealizacion { get { return GetColumnValue<int>(Columns.IdLugarRealizacion); } set { SetColumnValue(Columns.IdLugarRealizacion, value); } } [XmlAttribute("IdEstudio")] [Bindable(true)] public int IdEstudio { get { return GetColumnValue<int>(Columns.IdEstudio); } set { SetColumnValue(Columns.IdEstudio, value); } } [XmlAttribute("Descripcion")] [Bindable(true)] public string Descripcion { get { return GetColumnValue<string>(Columns.Descripcion); } set { SetColumnValue(Columns.Descripcion, value); } } [XmlAttribute("Ambito")] [Bindable(true)] public string Ambito { get { return GetColumnValue<string>(Columns.Ambito); } set { SetColumnValue(Columns.Ambito, value); } } [XmlAttribute("Domicilio")] [Bindable(true)] public string Domicilio { get { return GetColumnValue<string>(Columns.Domicilio); } set { SetColumnValue(Columns.Domicilio, value); } } [XmlAttribute("Cp")] [Bindable(true)] public string Cp { get { return GetColumnValue<string>(Columns.Cp); } set { SetColumnValue(Columns.Cp, value); } } [XmlAttribute("Ciudad")] [Bindable(true)] public string Ciudad { get { return GetColumnValue<string>(Columns.Ciudad); } set { SetColumnValue(Columns.Ciudad, value); } } [XmlAttribute("Email")] [Bindable(true)] public string Email { get { return GetColumnValue<string>(Columns.Email); } set { SetColumnValue(Columns.Email, value); } } [XmlAttribute("Responsable")] [Bindable(true)] public string Responsable { get { return GetColumnValue<string>(Columns.Responsable); } set { SetColumnValue(Columns.Responsable, value); } } [XmlAttribute("Cargo")] [Bindable(true)] public string Cargo { get { return GetColumnValue<string>(Columns.Cargo); } set { SetColumnValue(Columns.Cargo, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varIdEstudio,string varDescripcion,string varAmbito,string varDomicilio,string varCp,string varCiudad,string varEmail,string varResponsable,string varCargo) { RisLugarRealizacion item = new RisLugarRealizacion(); item.IdEstudio = varIdEstudio; item.Descripcion = varDescripcion; item.Ambito = varAmbito; item.Domicilio = varDomicilio; item.Cp = varCp; item.Ciudad = varCiudad; item.Email = varEmail; item.Responsable = varResponsable; item.Cargo = varCargo; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdLugarRealizacion,int varIdEstudio,string varDescripcion,string varAmbito,string varDomicilio,string varCp,string varCiudad,string varEmail,string varResponsable,string varCargo) { RisLugarRealizacion item = new RisLugarRealizacion(); item.IdLugarRealizacion = varIdLugarRealizacion; item.IdEstudio = varIdEstudio; item.Descripcion = varDescripcion; item.Ambito = varAmbito; item.Domicilio = varDomicilio; item.Cp = varCp; item.Ciudad = varCiudad; item.Email = varEmail; item.Responsable = varResponsable; item.Cargo = varCargo; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdLugarRealizacionColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdEstudioColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn DescripcionColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn AmbitoColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn DomicilioColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn CpColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn CiudadColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn EmailColumn { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn ResponsableColumn { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn CargoColumn { get { return Schema.Columns[9]; } } #endregion #region Columns Struct public struct Columns { public static string IdLugarRealizacion = @"idLugarRealizacion"; public static string IdEstudio = @"idEstudio"; public static string Descripcion = @"descripcion"; public static string Ambito = @"ambito"; public static string Domicilio = @"domicilio"; public static string Cp = @"cp"; public static string Ciudad = @"ciudad"; public static string Email = @"email"; public static string Responsable = @"responsable"; public static string Cargo = @"cargo"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
using Orleans.Serialization.Serializers; using Orleans.Serialization.Utilities; using Microsoft.Extensions.ObjectPool; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Net; using System.Reflection; using System.Threading; using Orleans.Serialization.Invocation; namespace Orleans.Serialization.Cloning { public interface IDeepCopierProvider { IDeepCopier<T> GetDeepCopier<T>(); IDeepCopier<T> TryGetDeepCopier<T>(); IDeepCopier<object> GetDeepCopier(Type type); IDeepCopier<object> TryGetDeepCopier(Type type); IBaseCopier<T> GetBaseCopier<T>() where T : class; } public interface IDeepCopier { } public interface IDeepCopier<T> : IDeepCopier { T DeepCopy(T input, CopyContext context); } public interface IBaseCopier { } public interface IBaseCopier<T> : IBaseCopier where T : class { void DeepCopy(T input, T output, CopyContext context); } /// <summary> /// Indicates that an IDeepCopier implementation generalizes over all sub-types. /// </summary> public interface IDerivedTypeCopier { } public interface IGeneralizedCopier : IDeepCopier<object> { bool IsSupportedType(Type type); } public interface ISpecializableCopier { bool IsSupportedType(Type type); IDeepCopier GetSpecializedCodec(Type type); } public sealed class CopyContext : IDisposable { private readonly Dictionary<object, object> _copies = new(ReferenceEqualsComparer.Default); private readonly CodecProvider _copierProvider; private readonly Action<CopyContext> _onDisposed; public CopyContext(CodecProvider codecProvider, Action<CopyContext> onDisposed) { _copierProvider = codecProvider; _onDisposed = onDisposed; } public bool TryGetCopy<T>(object original, out T result) where T : class { if (original is null) { result = null; return true; } if (_copies.TryGetValue(original, out var existing)) { result = existing as T; return true; } result = null; return false; } public void RecordCopy(object original, object copy) { _copies[original] = copy; } public void Reset() => _copies.Clear(); public T Copy<T>(T value) { if (!typeof(T).IsValueType) { if (value is null) return default; } var copier = _copierProvider.GetDeepCopier(value.GetType()); return (T)copier.DeepCopy(value, this); } public void Dispose() => _onDisposed?.Invoke(this); } internal static class ShallowCopyableTypes { private static readonly ConcurrentDictionary<Type, bool> Types = new() { [typeof(decimal)] = true, [typeof(DateTime)] = true, [typeof(DateTimeOffset)] = true, [typeof(TimeSpan)] = true, [typeof(IPAddress)] = true, [typeof(IPEndPoint)] = true, [typeof(string)] = true, [typeof(CancellationToken)] = true, [typeof(Guid)] = true, }; public static bool Contains(Type type) { if (Types.TryGetValue(type, out var result)) { return result; } return Types.GetOrAdd(type, IsShallowCopyableInternal(type)); } private static bool IsShallowCopyableInternal(Type type) { if (type.IsPrimitive || type.IsEnum) { return true; } if (type.IsDefined(typeof(ImmutableAttribute), false)) { return true; } if (type.IsConstructedGenericType) { var def = type.GetGenericTypeDefinition(); if (def == typeof(Nullable<>) || def == typeof(Tuple<>) || def == typeof(Tuple<,>) || def == typeof(Tuple<,,>) || def == typeof(Tuple<,,,>) || def == typeof(Tuple<,,,,>) || def == typeof(Tuple<,,,,,>) || def == typeof(Tuple<,,,,,,>) || def == typeof(Tuple<,,,,,,,>)) { return Array.TrueForAll(type.GenericTypeArguments, a => Contains(a)); } } if (type.IsValueType && !type.IsGenericTypeDefinition) { return Array.TrueForAll(type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic), f => Contains(f.FieldType)); } if (typeof(Exception).IsAssignableFrom(type)) { return true; } return false; } } /// <summary>throw new NotImplementedException(); /// Methods for adapting typed and untyped copiers. /// </summary> internal static class CopierAdapter { /// <summary> /// Converts a strongly-typed copier into an untyped copier. /// </summary> public static IDeepCopier<object> CreateUntypedFromTyped<T, TCopier>(TCopier typedCodec) where TCopier : IDeepCopier<T> => new TypedCopierWrapper<T, TCopier>(typedCodec); /// <summary> /// Converts an untyped codec into a strongly-typed codec. /// </summary> public static IDeepCopier<T> CreateTypedFromUntyped<T>(IDeepCopier<object> untypedCodec) => new UntypedCopierWrapper<T>(untypedCodec); private sealed class TypedCopierWrapper<T, TCopier> : IDeepCopier<object>, IWrappedCodec where TCopier : IDeepCopier<T> { private readonly TCopier _copier; public TypedCopierWrapper(TCopier codec) { _copier = codec; } object IDeepCopier<object>.DeepCopy(object original, CopyContext context) => _copier.DeepCopy((T)original, context); public object Inner => _copier; } private sealed class UntypedCopierWrapper<T> : IWrappedCodec, IDeepCopier<T> { private readonly IDeepCopier<object> _codec; public UntypedCopierWrapper(IDeepCopier<object> codec) { _codec = codec; } public object Inner => _codec; T IDeepCopier<T>.DeepCopy(T original, CopyContext context) => (T)_codec.DeepCopy(original, context); } } public sealed class ShallowCopyableTypeCopier<T> : IDeepCopier<T> { public T DeepCopy(T input, CopyContext context) => input; } public sealed class CopyContextPool { private readonly ConcurrentObjectPool<CopyContext, PoolPolicy> _pool; public CopyContextPool(CodecProvider codecProvider) { var sessionPoolPolicy = new PoolPolicy(codecProvider, Return); _pool = new ConcurrentObjectPool<CopyContext, PoolPolicy>(sessionPoolPolicy); } public CopyContext GetContext() => _pool.Get(); private void Return(CopyContext session) => _pool.Return(session); private readonly struct PoolPolicy : IPooledObjectPolicy<CopyContext> { private readonly CodecProvider _codecProvider; private readonly Action<CopyContext> _onDisposed; public PoolPolicy(CodecProvider codecProvider, Action<CopyContext> onDisposed) { _codecProvider = codecProvider; _onDisposed = onDisposed; } public CopyContext Create() => new(_codecProvider, _onDisposed); public bool Return(CopyContext obj) { obj.Reset(); return true; } } } }
// // PersistentColumnController.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2008 Novell, Inc. // // 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.Collections.Generic; using Hyena.Data; using Hyena.Data.Gui; using Banshee.Sources; using Banshee.Configuration; namespace Banshee.Collection.Gui { public class PersistentColumnController : ColumnController { private string root_namespace; private bool loaded = false; private bool pending_changes; private uint timer_id = 0; private string source_id, unique_source_id; private Source source; public Source Source { get { return source; } set { if (source == value) { return; } if (source != null) { Save (); } source = value; source_id = unique_source_id = null; if (source != null) { // If we have a parent, use their UniqueId so all children of a parent persist the same columns source_id = source.ParentConfigurationId; unique_source_id = source.ConfigurationId; Load (); } } } public PersistentColumnController (string rootNamespace) : base () { if (String.IsNullOrEmpty (rootNamespace)) { throw new ArgumentException ("Argument must not be null or empty", "rootNamespace"); } root_namespace = rootNamespace; } public void Load () { lock (this) { if (source == null) { return; } loaded = false; int i = 0; foreach (Column column in this) { if (column.Id != null) { string @namespace = MakeNamespace (column.Id); column.Visible = ConfigurationClient.Get<bool> (@namespace, "visible", column.Visible); column.Width = ConfigurationClient.Get<double> (@namespace, "width", column.Width); column.OrderHint = ConfigurationClient.Get<int> (@namespace, "order", i); } else { column.OrderHint = -1; } i++; } Columns.Sort ((a, b) => a.OrderHint.CompareTo (b.OrderHint)); string sort_ns = String.Format ("{0}.{1}.{2}", root_namespace, unique_source_id, "sort"); string sort_column_id = ConfigurationClient.Get<string> (sort_ns, "column", null); if (sort_column_id != null) { ISortableColumn sort_column = null; foreach (Column column in this) { if (column.Id == sort_column_id) { sort_column = column as ISortableColumn; break; } } if (sort_column != null) { int sort_dir = ConfigurationClient.Get<int> (sort_ns, "direction", 0); SortType sort_type = sort_dir == 0 ? SortType.None : sort_dir == 1 ? SortType.Ascending : SortType.Descending; sort_column.SortType = sort_type; base.SortColumn = sort_column; } } else { base.SortColumn = null; } loaded = true; } OnUpdated (); } public override ISortableColumn SortColumn { set { base.SortColumn = value; Save (); } } public void Save () { if (timer_id == 0) { timer_id = GLib.Timeout.Add (500, OnTimeout); } else { pending_changes = true; } } private bool OnTimeout () { if (pending_changes) { pending_changes = false; return true; } else { SaveCore (); timer_id = 0; return false; } } private void SaveCore () { lock (this) { if (source == null) { return; } for (int i = 0; i < Count; i++) { if (Columns[i].Id != null) { Save (Columns[i], i); } } if (SortColumn != null) { string ns = String.Format ("{0}.{1}.{2}", root_namespace, unique_source_id, "sort"); ConfigurationClient.Set<string> (ns, "column", SortColumn.Id); ConfigurationClient.Set<int> (ns, "direction", (int)SortColumn.SortType); } } } private void Save (Column column, int index) { string @namespace = MakeNamespace (column.Id); ConfigurationClient.Set<int> (@namespace, "order", index); ConfigurationClient.Set<bool> (@namespace, "visible", column.Visible); ConfigurationClient.Set<double> (@namespace, "width", column.Width); } protected override void OnWidthsChanged () { if (loaded) { Save (); } base.OnWidthsChanged (); } private string MakeNamespace (string name) { return String.Format ("{0}.{1}.{2}", root_namespace, source_id, name); } public override bool EnableColumnMenu { get { return true; } } } }
// // Copyright (C) Microsoft. All rights reserved. // namespace Microsoft.PowerShell.Commands { using System; using System.Collections.Generic; using System.IO; using System.Threading; using System.Reflection; using System.Management.Automation; using System.Management.Automation.Internal; using Microsoft.PowerShell.Commands.Internal.Format; internal class OutWindowProxy : IDisposable { private const string OutGridViewWindowClassName = "Microsoft.Management.UI.Internal.OutGridViewWindow"; private const string OriginalTypePropertyName = "OriginalType"; internal const string OriginalObjectPropertyName = "OutGridViewOriginalObject"; private const string ToStringValuePropertyName = "ToStringValue"; private const string IndexPropertyName = "IndexValue"; private int _index; /// <summary> Columns definition of the underlying Management List</summary> private HeaderInfo _headerInfo; private bool _isWindowStarted; private string _title; private OutputModeOption _outputMode; private AutoResetEvent _closedEvent; private OutGridViewCommand _parentCmdlet; private GraphicalHostReflectionWrapper _graphicalHostReflectionWrapper; /// <summary> /// Initializes a new instance of the OutWindowProxy class. /// </summary> internal OutWindowProxy(string title, OutputModeOption outPutMode, OutGridViewCommand parentCmdlet) { _title = title; _outputMode = outPutMode; _parentCmdlet = parentCmdlet; _graphicalHostReflectionWrapper = GraphicalHostReflectionWrapper.GetGraphicalHostReflectionWrapper(parentCmdlet, OutWindowProxy.OutGridViewWindowClassName); } /// <summary> /// Adds columns to the output window. /// </summary> /// <param name="propertyNames">An array of property names to add.</param> /// <param name="displayNames">An array of display names to add.</param> /// <param name="types">An array of types to add.</param> internal void AddColumns(string[] propertyNames, string[] displayNames, Type[] types) { if (null == propertyNames) { throw new ArgumentNullException("propertyNames"); } if (null == displayNames) { throw new ArgumentNullException("displayNames"); } if (null == types) { throw new ArgumentNullException("types"); } try { _graphicalHostReflectionWrapper.CallMethod("AddColumns", propertyNames, displayNames, types); } catch (TargetInvocationException ex) { // Verify if this is an error loading the System.Core dll. FileNotFoundException fileNotFoundEx = ex.InnerException as FileNotFoundException; if (fileNotFoundEx != null && fileNotFoundEx.FileName.Contains("System.Core")) { _parentCmdlet.ThrowTerminatingError( new ErrorRecord(new InvalidOperationException( StringUtil.Format(FormatAndOut_out_gridview.RestartPowerShell, _parentCmdlet.CommandInfo.Name), ex.InnerException), "ErrorLoadingAssembly", ErrorCategory.ObjectNotFound, null)); } else { // Let PowerShell take care of this problem. throw; } } } // Types that are not defined in the database and are not scalar. internal void AddColumnsAndItem(PSObject liveObject, TableView tableView) { // Create a header using only the input object's properties. _headerInfo = tableView.GenerateHeaderInfo(liveObject, _parentCmdlet); AddColumnsAndItemEnd(liveObject); } // Database defined types. internal void AddColumnsAndItem(PSObject liveObject, TableView tableView, TableControlBody tableBody) { _headerInfo = tableView.GenerateHeaderInfo(liveObject, tableBody, _parentCmdlet); AddColumnsAndItemEnd(liveObject); } // Scalar types. internal void AddColumnsAndItem(PSObject liveObject) { _headerInfo = new HeaderInfo(); // On scalar types the type name is used as a column name. _headerInfo.AddColumn(new ScalarTypeColumnInfo(liveObject.BaseObject.GetType())); AddColumnsAndItemEnd(liveObject); } private void AddColumnsAndItemEnd(PSObject liveObject) { // Add columns to the underlying Management list and as a byproduct get a stale PSObject. PSObject staleObject = _headerInfo.AddColumnsToWindow(this, liveObject); // Add 3 extra properties, so that the stale PSObject has meaningful info in the Hetero-type header view. AddExtraProperties(staleObject, liveObject); // Add the stale PSObject to the underlying Management list. _graphicalHostReflectionWrapper.CallMethod("AddItem", staleObject); } // Hetero types. internal void AddHeteroViewColumnsAndItem(PSObject liveObject) { _headerInfo = new HeaderInfo(); _headerInfo.AddColumn(new IndexColumnInfo(OutWindowProxy.IndexPropertyName, StringUtil.Format(FormatAndOut_out_gridview.IndexColumnName), _index)); _headerInfo.AddColumn(new ToStringColumnInfo(OutWindowProxy.ToStringValuePropertyName, StringUtil.Format(FormatAndOut_out_gridview.ValueColumnName), _parentCmdlet)); _headerInfo.AddColumn(new TypeNameColumnInfo(OutWindowProxy.OriginalTypePropertyName, StringUtil.Format(FormatAndOut_out_gridview.TypeColumnName))); // Add columns to the underlying Management list and as a byproduct get a stale PSObject. PSObject staleObject = _headerInfo.AddColumnsToWindow(this, liveObject); // Add the stale PSObject to the underlying Management list. _graphicalHostReflectionWrapper.CallMethod("AddItem", staleObject); } private void AddExtraProperties(PSObject staleObject, PSObject liveObject) { // Add 3 extra properties, so that the stale PSObject has meaningful info in the Hetero-type header view. staleObject.Properties.Add(new PSNoteProperty(OutWindowProxy.IndexPropertyName, _index++)); staleObject.Properties.Add(new PSNoteProperty(OutWindowProxy.OriginalTypePropertyName, liveObject.BaseObject.GetType().FullName)); staleObject.Properties.Add(new PSNoteProperty(OutWindowProxy.OriginalObjectPropertyName, liveObject)); // Convert the LivePSObject to a string preserving PowerShell formatting. staleObject.Properties.Add(new PSNoteProperty(OutWindowProxy.ToStringValuePropertyName, _parentCmdlet.ConvertToString(liveObject))); } /// <summary> /// Adds an item to the out window. /// </summary> /// <param name="livePSObject"> /// The item to add. /// </param> internal void AddItem(PSObject livePSObject) { if (null == livePSObject) { throw new ArgumentNullException("livePSObject"); } if (_headerInfo == null) { throw new InvalidOperationException(); } PSObject stalePSObject = _headerInfo.CreateStalePSObject(livePSObject); // Add 3 extra properties, so that the stale PSObject has meaningful info in the Hetero-type header view. AddExtraProperties(stalePSObject, livePSObject); _graphicalHostReflectionWrapper.CallMethod("AddItem", stalePSObject); } /// <summary> /// Adds an item to the out window. /// </summary> /// <param name="livePSObject"> /// The item to add. /// </param> internal void AddHeteroViewItem(PSObject livePSObject) { if (null == livePSObject) { throw new ArgumentNullException("livePSObject"); } if (_headerInfo == null) { throw new InvalidOperationException(); } PSObject stalePSObject = _headerInfo.CreateStalePSObject(livePSObject); _graphicalHostReflectionWrapper.CallMethod("AddItem", stalePSObject); } /// <summary> /// Shows the out window if it has not already been displayed. /// </summary> internal void ShowWindow() { if (!_isWindowStarted) { _closedEvent = new AutoResetEvent(false); _graphicalHostReflectionWrapper.CallMethod("StartWindow", _title, _outputMode.ToString(), _closedEvent); _isWindowStarted = true; } } internal void BlockUntillClosed() { if (_closedEvent != null) { _closedEvent.WaitOne(); } } /// <summary> /// Implements IDisposable logic /// </summary> /// <param name="isDisposing">true if being called from Dispose</param> private void Dispose(bool isDisposing) { if (isDisposing) { if (_closedEvent != null) { _closedEvent.Dispose(); _closedEvent = null; } } } /// <summary> /// Dispose method in IDisposable /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Close the window if it has already been displayed. /// </summary> internal void CloseWindow() { if (_isWindowStarted) { _graphicalHostReflectionWrapper.CallMethod("CloseWindow"); _isWindowStarted = false; } } /// <summary> /// Gets a value indicating whether the out window is closed. /// </summary> /// <returns> /// True if the out window is closed, false otherwise. /// </returns> internal bool IsWindowClosed() { return (bool)_graphicalHostReflectionWrapper.CallMethod("GetWindowClosedStatus"); } /// <summary>Returns any exception that has been thrown by previous method calls.</summary> /// <returns>The thrown and caught exception. It returns null if no exceptions were thrown by any previous method calls.</returns> internal Exception GetLastException() { return (Exception)_graphicalHostReflectionWrapper.CallMethod("GetLastException"); } /// <summary> /// Return the selected item of the OutGridView. /// </summary> /// <returns> /// The selected item /// </returns> internal List<PSObject> GetSelectedItems() { return (List<PSObject>)_graphicalHostReflectionWrapper.CallMethod("SelectedItems"); } } }
using System; using System.Linq; using System.Threading.Tasks; using Android.Views; using Xamarin.Forms.Internals; using AButton = Android.Widget.Button; using AView = Android.Views.View; using AndroidAnimation = Android.Animation; namespace Xamarin.Forms.Platform.Android { public class NavigationRenderer : VisualElementRenderer<NavigationPage> { static ViewPropertyAnimator s_currentAnimation; Page _current; bool _disposed; public NavigationRenderer() { AutoPackage = false; } public Task<bool> PopToRootAsync(Page page, bool animated = true) { return OnPopToRootAsync(page, animated); } public Task<bool> PopViewAsync(Page page, bool animated = true) { return OnPopViewAsync(page, animated); } public Task<bool> PushViewAsync(Page page, bool animated = true) { return OnPushAsync(page, animated); } IPageController PageController => Element as IPageController; protected override void Dispose(bool disposing) { if (disposing && !_disposed) { _disposed = true; if (Element != null) { foreach (Element element in PageController.InternalChildren) { var child = (VisualElement)element; if (child == null) { continue; } IVisualElementRenderer renderer = Platform.GetRenderer(child); renderer?.Dispose(); } var navController = (INavigationPageController)Element; navController.PushRequested -= OnPushed; navController.PopRequested -= OnPopped; navController.PopToRootRequested -= OnPoppedToRoot; navController.InsertPageBeforeRequested -= OnInsertPageBeforeRequested; navController.RemovePageRequested -= OnRemovePageRequested; } } base.Dispose(disposing); } protected override void OnAttachedToWindow() { base.OnAttachedToWindow(); PageController?.SendAppearing(); } protected override void OnDetachedFromWindow() { base.OnDetachedFromWindow(); PageController?.SendDisappearing(); } protected override void OnElementChanged(ElementChangedEventArgs<NavigationPage> e) { base.OnElementChanged(e); if (e.OldElement != null) { var oldNavController = (INavigationPageController)e.OldElement; oldNavController.PushRequested -= OnPushed; oldNavController.PopRequested -= OnPopped; oldNavController.PopToRootRequested -= OnPoppedToRoot; oldNavController.InsertPageBeforeRequested -= OnInsertPageBeforeRequested; oldNavController.RemovePageRequested -= OnRemovePageRequested; RemoveAllViews(); } var newNavController = (INavigationPageController)e.NewElement; newNavController.PushRequested += OnPushed; newNavController.PopRequested += OnPopped; newNavController.PopToRootRequested += OnPoppedToRoot; newNavController.InsertPageBeforeRequested += OnInsertPageBeforeRequested; newNavController.RemovePageRequested += OnRemovePageRequested; // If there is already stuff on the stack we need to push it foreach(Page page in newNavController.StackCopy.Reverse()) { PushViewAsync(page, false); } } protected override void OnLayout(bool changed, int l, int t, int r, int b) { base.OnLayout(changed, l, t, r, b); for (var i = 0; i < ChildCount; i++) GetChildAt(i).Layout(0, 0, r - l, b - t); } protected virtual Task<bool> OnPopToRootAsync(Page page, bool animated) { return SwitchContentAsync(page, animated, true); } protected virtual Task<bool> OnPopViewAsync(Page page, bool animated) { Page pageToShow = ((INavigationPageController)Element).StackCopy.Skip(1).FirstOrDefault(); if (pageToShow == null) return Task.FromResult(false); return SwitchContentAsync(pageToShow, animated, true); } protected virtual Task<bool> OnPushAsync(Page view, bool animated) { return SwitchContentAsync(view, animated); } void InsertPageBefore(Page page, Page before) { int index = PageController.InternalChildren.IndexOf(before); if (index == -1) throw new InvalidOperationException("This should never happen, please file a bug"); Device.StartTimer(TimeSpan.FromMilliseconds(0), () => { ((Platform)Element.Platform).UpdateNavigationTitleBar(); return false; }); } void OnInsertPageBeforeRequested(object sender, NavigationRequestedEventArgs e) { InsertPageBefore(e.Page, e.BeforePage); } void OnPopped(object sender, NavigationRequestedEventArgs e) { e.Task = PopViewAsync(e.Page, e.Animated); } void OnPoppedToRoot(object sender, NavigationRequestedEventArgs e) { e.Task = PopToRootAsync(e.Page, e.Animated); } void OnPushed(object sender, NavigationRequestedEventArgs e) { e.Task = PushViewAsync(e.Page, e.Animated); } void OnRemovePageRequested(object sender, NavigationRequestedEventArgs e) { RemovePage(e.Page); } void RemovePage(Page page) { IVisualElementRenderer rendererToRemove = Platform.GetRenderer(page); PageContainer containerToRemove = rendererToRemove == null ? null : (PageContainer)rendererToRemove.ViewGroup.Parent; containerToRemove.RemoveFromParent(); if (rendererToRemove != null) { rendererToRemove.ViewGroup.RemoveFromParent(); rendererToRemove.Dispose(); } containerToRemove?.Dispose(); Device.StartTimer(TimeSpan.FromMilliseconds(0), () => { ((Platform)Element.Platform).UpdateNavigationTitleBar(); return false; }); } Task<bool> SwitchContentAsync(Page view, bool animated, bool removed = false) { Context.HideKeyboard(this); IVisualElementRenderer rendererToAdd = Platform.GetRenderer(view); bool existing = rendererToAdd != null; if (!existing) Platform.SetRenderer(view, rendererToAdd = Platform.CreateRenderer(view)); Page pageToRemove = _current; IVisualElementRenderer rendererToRemove = pageToRemove == null ? null : Platform.GetRenderer(pageToRemove); PageContainer containerToRemove = rendererToRemove == null ? null : (PageContainer)rendererToRemove.ViewGroup.Parent; PageContainer containerToAdd = (PageContainer)rendererToAdd.ViewGroup.Parent ?? new PageContainer(Context, rendererToAdd); containerToAdd.SetWindowBackground(); _current = view; ((Platform)Element.Platform).NavAnimationInProgress = true; var tcs = new TaskCompletionSource<bool>(); if (animated) { if (s_currentAnimation != null) s_currentAnimation.Cancel(); if (removed) { // animate out if (containerToAdd.Parent != this) AddView(containerToAdd, ((IElementController)Element).LogicalChildren.IndexOf(rendererToAdd.Element)); else ((IPageController)rendererToAdd.Element).SendAppearing(); containerToAdd.Visibility = ViewStates.Visible; if (containerToRemove != null) { Action<AndroidAnimation.Animator> done = a => { containerToRemove.Visibility = ViewStates.Gone; containerToRemove.Alpha = 1; containerToRemove.ScaleX = 1; containerToRemove.ScaleY = 1; RemoveView(containerToRemove); tcs.TrySetResult(true); ((Platform)Element.Platform).NavAnimationInProgress = false; VisualElement removedElement = rendererToRemove.Element; rendererToRemove.Dispose(); if (removedElement != null) Platform.SetRenderer(removedElement, null); }; // should always happen s_currentAnimation = containerToRemove.Animate().Alpha(0).ScaleX(0.8f).ScaleY(0.8f).SetDuration(250).SetListener(new GenericAnimatorListener { OnEnd = a => { s_currentAnimation = null; done(a); }, OnCancel = done }); } } else { bool containerAlreadyAdded = containerToAdd.Parent == this; // animate in if (!containerAlreadyAdded) AddView(containerToAdd); else ((IPageController)rendererToAdd.Element).SendAppearing(); if (existing) Element.ForceLayout(); containerToAdd.Alpha = 0; containerToAdd.ScaleX = containerToAdd.ScaleY = 0.8f; containerToAdd.Visibility = ViewStates.Visible; s_currentAnimation = containerToAdd.Animate().Alpha(1).ScaleX(1).ScaleY(1).SetDuration(250).SetListener(new GenericAnimatorListener { OnEnd = a => { if (containerToRemove != null && containerToRemove.Handle != IntPtr.Zero) { containerToRemove.Visibility = ViewStates.Gone; ((IPageController)pageToRemove)?.SendDisappearing(); } s_currentAnimation = null; tcs.TrySetResult(true); ((Platform)Element.Platform).NavAnimationInProgress = false; } }); } } else { // just do it fast if (containerToRemove != null) { if (removed) RemoveView(containerToRemove); else containerToRemove.Visibility = ViewStates.Gone; } if (containerToAdd.Parent != this) AddView(containerToAdd); else ((IPageController)rendererToAdd.Element).SendAppearing(); if (containerToRemove != null && !removed) ((IPageController)pageToRemove).SendDisappearing(); if (existing) Element.ForceLayout(); containerToAdd.Visibility = ViewStates.Visible; tcs.SetResult(true); ((Platform)Element.Platform).NavAnimationInProgress = false; } return tcs.Task; } } }
/* * 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 log4net; using Nini.Config; using OpenMetaverse; using Mono.Addins; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Connectors.Hypergrid; using GridRegion = OpenSim.Services.Interfaces.GridRegion; namespace OpenSim.Region.CoreModules.Avatar.Lure { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "HGLureModule")] public class HGLureModule : ISharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private readonly List<Scene> m_scenes = new List<Scene>(); private IMessageTransferModule m_TransferModule = null; private bool m_Enabled = false; private string m_ThisGridURL; private ExpiringCache<UUID, GridInstantMessage> m_PendingLures = new ExpiringCache<UUID, GridInstantMessage>(); public void Initialise(IConfigSource config) { if (config.Configs["Messaging"] != null) { if (config.Configs["Messaging"].GetString("LureModule", string.Empty) == "HGLureModule") { m_Enabled = true; m_ThisGridURL = Util.GetConfigVarFromSections<string>(config, "GatekeeperURI", new string[] { "Startup", "Hypergrid", "Messaging" }, String.Empty); // Legacy. Remove soon! m_ThisGridURL = config.Configs["Messaging"].GetString("Gatekeeper", m_ThisGridURL); m_log.DebugFormat("[LURE MODULE]: {0} enabled", Name); } } } public void AddRegion(Scene scene) { if (!m_Enabled) return; lock (m_scenes) { m_scenes.Add(scene); scene.EventManager.OnIncomingInstantMessage += OnIncomingInstantMessage; scene.EventManager.OnNewClient += OnNewClient; } } public void RegionLoaded(Scene scene) { if (!m_Enabled) return; if (m_TransferModule == null) { m_TransferModule = scene.RequestModuleInterface<IMessageTransferModule>(); if (m_TransferModule == null) { m_log.Error("[LURE MODULE]: No message transfer module, lures will not work!"); m_Enabled = false; m_scenes.Clear(); scene.EventManager.OnNewClient -= OnNewClient; scene.EventManager.OnIncomingInstantMessage -= OnIncomingInstantMessage; } } } public void RemoveRegion(Scene scene) { if (!m_Enabled) return; lock (m_scenes) { m_scenes.Remove(scene); scene.EventManager.OnNewClient -= OnNewClient; scene.EventManager.OnIncomingInstantMessage -= OnIncomingInstantMessage; } } void OnNewClient(IClientAPI client) { client.OnInstantMessage += OnInstantMessage; client.OnStartLure += OnStartLure; client.OnTeleportLureRequest += OnTeleportLureRequest; } public void PostInitialise() { } public void Close() { } public string Name { get { return "HGLureModule"; } } public Type ReplaceableInterface { get { return null; } } void OnInstantMessage(IClientAPI client, GridInstantMessage im) { } void OnIncomingInstantMessage(GridInstantMessage im) { if (im.dialog == (byte)InstantMessageDialog.RequestTeleport || im.dialog == (byte)InstantMessageDialog.GodLikeRequestTeleport) { UUID sessionID = new UUID(im.imSessionID); if (!m_PendingLures.Contains(sessionID)) { m_log.DebugFormat("[HG LURE MODULE]: RequestTeleport sessionID={0}, regionID={1}, message={2}", im.imSessionID, im.RegionID, im.message); m_PendingLures.Add(sessionID, im, 7200); // 2 hours } // Forward. We do this, because the IM module explicitly rejects // IMs of this type if (m_TransferModule != null) m_TransferModule.SendInstantMessage(im, delegate(bool success) { }); } } public void OnStartLure(byte lureType, string message, UUID targetid, IClientAPI client) { if (!(client.Scene is Scene)) return; Scene scene = (Scene)(client.Scene); ScenePresence presence = scene.GetScenePresence(client.AgentId); message += "@" + m_ThisGridURL; m_log.DebugFormat("[HG LURE MODULE]: TP invite with message {0}", message); UUID sessionID = UUID.Random(); GridInstantMessage m = new GridInstantMessage(scene, client.AgentId, client.FirstName+" "+client.LastName, targetid, (byte)InstantMessageDialog.RequestTeleport, false, message, sessionID, false, presence.AbsolutePosition, new Byte[0], true); m.RegionID = client.Scene.RegionInfo.RegionID.Guid; m_log.DebugFormat("[HG LURE MODULE]: RequestTeleport sessionID={0}, regionID={1}, message={2}", m.imSessionID, m.RegionID, m.message); m_PendingLures.Add(sessionID, m, 7200); // 2 hours if (m_TransferModule != null) { m_TransferModule.SendInstantMessage(m, delegate(bool success) { }); } } public void OnTeleportLureRequest(UUID lureID, uint teleportFlags, IClientAPI client) { if (!(client.Scene is Scene)) return; // Scene scene = (Scene)(client.Scene); GridInstantMessage im = null; if (m_PendingLures.TryGetValue(lureID, out im)) { m_PendingLures.Remove(lureID); Lure(client, teleportFlags, im); } else m_log.DebugFormat("[HG LURE MODULE]: pending lure {0} not found", lureID); } private void Lure(IClientAPI client, uint teleportflags, GridInstantMessage im) { Scene scene = (Scene)(client.Scene); GridRegion region = scene.GridService.GetRegionByUUID(scene.RegionInfo.ScopeID, new UUID(im.RegionID)); if (region != null) scene.RequestTeleportLocation(client, region.RegionHandle, im.Position + new Vector3(0.5f, 0.5f, 0f), Vector3.UnitX, teleportflags); else // we don't have that region here. Check if it's HG { string[] parts = im.message.Split(new char[] { '@' }); if (parts.Length > 1) { string url = parts[parts.Length - 1]; // the last part if (url.Trim(new char[] {'/'}) != m_ThisGridURL.Trim(new char[] {'/'})) { m_log.DebugFormat("[HG LURE MODULE]: Luring agent to grid {0} region {1} position {2}", url, im.RegionID, im.Position); GatekeeperServiceConnector gConn = new GatekeeperServiceConnector(); GridRegion gatekeeper = new GridRegion(); gatekeeper.ServerURI = url; string homeURI = scene.GetAgentHomeURI(client.AgentId); string message; GridRegion finalDestination = gConn.GetHyperlinkRegion(gatekeeper, new UUID(im.RegionID), client.AgentId, homeURI, out message); if (finalDestination != null) { ScenePresence sp = scene.GetScenePresence(client.AgentId); IEntityTransferModule transferMod = scene.RequestModuleInterface<IEntityTransferModule>(); if (transferMod != null && sp != null) { if (message != null) sp.ControllingClient.SendAgentAlertMessage(message, true); transferMod.DoTeleport( sp, gatekeeper, finalDestination, im.Position + new Vector3(0.5f, 0.5f, 0f), Vector3.UnitX, teleportflags); } } else { m_log.InfoFormat("[HG LURE MODULE]: Lure failed: {0}", message); client.SendAgentAlertMessage(message, true); } } } } } } }
// MIT License // // Copyright (c) 2009-2017 Luca Piccioni // // 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. // // This file is automatically generated #pragma warning disable 649, 1572, 1573 // ReSharper disable RedundantUsingDirective using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Text; using Khronos; // ReSharper disable CheckNamespace // ReSharper disable InconsistentNaming // ReSharper disable JoinDeclarationAndInitializer namespace OpenGL { public partial class Glx { /// <summary> /// [GLX] Value of GLX_VIDEO_OUT_COLOR_NV symbol. /// </summary> [RequiredByFeature("GLX_NV_video_out")] public const int VIDEO_OUT_COLOR_NV = 0x20C3; /// <summary> /// [GLX] Value of GLX_VIDEO_OUT_ALPHA_NV symbol. /// </summary> [RequiredByFeature("GLX_NV_video_out")] public const int VIDEO_OUT_ALPHA_NV = 0x20C4; /// <summary> /// [GLX] Value of GLX_VIDEO_OUT_DEPTH_NV symbol. /// </summary> [RequiredByFeature("GLX_NV_video_out")] public const int VIDEO_OUT_DEPTH_NV = 0x20C5; /// <summary> /// [GLX] Value of GLX_VIDEO_OUT_COLOR_AND_ALPHA_NV symbol. /// </summary> [RequiredByFeature("GLX_NV_video_out")] public const int VIDEO_OUT_COLOR_AND_ALPHA_NV = 0x20C6; /// <summary> /// [GLX] Value of GLX_VIDEO_OUT_COLOR_AND_DEPTH_NV symbol. /// </summary> [RequiredByFeature("GLX_NV_video_out")] public const int VIDEO_OUT_COLOR_AND_DEPTH_NV = 0x20C7; /// <summary> /// [GLX] Value of GLX_VIDEO_OUT_FRAME_NV symbol. /// </summary> [RequiredByFeature("GLX_NV_video_out")] public const int VIDEO_OUT_FRAME_NV = 0x20C8; /// <summary> /// [GLX] Value of GLX_VIDEO_OUT_FIELD_1_NV symbol. /// </summary> [RequiredByFeature("GLX_NV_video_out")] public const int VIDEO_OUT_FIELD_1_NV = 0x20C9; /// <summary> /// [GLX] Value of GLX_VIDEO_OUT_FIELD_2_NV symbol. /// </summary> [RequiredByFeature("GLX_NV_video_out")] public const int VIDEO_OUT_FIELD_2_NV = 0x20CA; /// <summary> /// [GLX] Value of GLX_VIDEO_OUT_STACKED_FIELDS_1_2_NV symbol. /// </summary> [RequiredByFeature("GLX_NV_video_out")] public const int VIDEO_OUT_STACKED_FIELDS_1_2_NV = 0x20CB; /// <summary> /// [GLX] Value of GLX_VIDEO_OUT_STACKED_FIELDS_2_1_NV symbol. /// </summary> [RequiredByFeature("GLX_NV_video_out")] public const int VIDEO_OUT_STACKED_FIELDS_2_1_NV = 0x20CC; /// <summary> /// [GLX] glXGetVideoDeviceNV: Binding for glXGetVideoDeviceNV. /// </summary> /// <param name="dpy"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="screen"> /// A <see cref="T:int"/>. /// </param> /// <param name="numVideoDevices"> /// A <see cref="T:int"/>. /// </param> /// <param name="pVideoDevice"> /// A <see cref="T:IntPtr"/>. /// </param> [RequiredByFeature("GLX_NV_video_out")] public static int GetVideoDeviceNV(IntPtr dpy, int screen, int numVideoDevices, IntPtr pVideoDevice) { int retValue; Debug.Assert(Delegates.pglXGetVideoDeviceNV != null, "pglXGetVideoDeviceNV not implemented"); retValue = Delegates.pglXGetVideoDeviceNV(dpy, screen, numVideoDevices, pVideoDevice); LogCommand("glXGetVideoDeviceNV", retValue, dpy, screen, numVideoDevices, pVideoDevice ); DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [GLX] glXReleaseVideoDeviceNV: Binding for glXReleaseVideoDeviceNV. /// </summary> /// <param name="dpy"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="screen"> /// A <see cref="T:int"/>. /// </param> /// <param name="VideoDevice"> /// A <see cref="T:IntPtr"/>. /// </param> [RequiredByFeature("GLX_NV_video_out")] public static int ReleaseVideoDeviceNV(IntPtr dpy, int screen, IntPtr VideoDevice) { int retValue; Debug.Assert(Delegates.pglXReleaseVideoDeviceNV != null, "pglXReleaseVideoDeviceNV not implemented"); retValue = Delegates.pglXReleaseVideoDeviceNV(dpy, screen, VideoDevice); LogCommand("glXReleaseVideoDeviceNV", retValue, dpy, screen, VideoDevice ); DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [GLX] glXBindVideoImageNV: Binding for glXBindVideoImageNV. /// </summary> /// <param name="dpy"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="VideoDevice"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="pbuf"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="iVideoBuffer"> /// A <see cref="T:int"/>. /// </param> [RequiredByFeature("GLX_NV_video_out")] public static int BindVideoImageNV(IntPtr dpy, IntPtr VideoDevice, IntPtr pbuf, int iVideoBuffer) { int retValue; Debug.Assert(Delegates.pglXBindVideoImageNV != null, "pglXBindVideoImageNV not implemented"); retValue = Delegates.pglXBindVideoImageNV(dpy, VideoDevice, pbuf, iVideoBuffer); LogCommand("glXBindVideoImageNV", retValue, dpy, VideoDevice, pbuf, iVideoBuffer ); DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [GLX] glXReleaseVideoImageNV: Binding for glXReleaseVideoImageNV. /// </summary> /// <param name="dpy"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="pbuf"> /// A <see cref="T:IntPtr"/>. /// </param> [RequiredByFeature("GLX_NV_video_out")] public static int ReleaseVideoImageNV(IntPtr dpy, IntPtr pbuf) { int retValue; Debug.Assert(Delegates.pglXReleaseVideoImageNV != null, "pglXReleaseVideoImageNV not implemented"); retValue = Delegates.pglXReleaseVideoImageNV(dpy, pbuf); LogCommand("glXReleaseVideoImageNV", retValue, dpy, pbuf ); DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [GLX] glXSendPbufferToVideoNV: Binding for glXSendPbufferToVideoNV. /// </summary> /// <param name="dpy"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="pbuf"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="iBufferType"> /// A <see cref="T:int"/>. /// </param> /// <param name="pulCounterPbuffer"> /// A <see cref="T:uint[]"/>. /// </param> /// <param name="bBlock"> /// A <see cref="T:bool"/>. /// </param> [RequiredByFeature("GLX_NV_video_out")] public static int SendPbufferToVideoNV(IntPtr dpy, IntPtr pbuf, int iBufferType, uint[] pulCounterPbuffer, bool bBlock) { int retValue; unsafe { fixed (uint* p_pulCounterPbuffer = pulCounterPbuffer) { Debug.Assert(Delegates.pglXSendPbufferToVideoNV != null, "pglXSendPbufferToVideoNV not implemented"); retValue = Delegates.pglXSendPbufferToVideoNV(dpy, pbuf, iBufferType, p_pulCounterPbuffer, bBlock); LogCommand("glXSendPbufferToVideoNV", retValue, dpy, pbuf, iBufferType, pulCounterPbuffer, bBlock ); } } DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [GLX] glXGetVideoInfoNV: Binding for glXGetVideoInfoNV. /// </summary> /// <param name="dpy"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="screen"> /// A <see cref="T:int"/>. /// </param> /// <param name="VideoDevice"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="pulCounterOutputPbuffer"> /// A <see cref="T:uint[]"/>. /// </param> /// <param name="pulCounterOutputVideo"> /// A <see cref="T:uint[]"/>. /// </param> [RequiredByFeature("GLX_NV_video_out")] public static int GetVideoInfoNV(IntPtr dpy, int screen, IntPtr VideoDevice, [Out] uint[] pulCounterOutputPbuffer, [Out] uint[] pulCounterOutputVideo) { int retValue; unsafe { fixed (uint* p_pulCounterOutputPbuffer = pulCounterOutputPbuffer) fixed (uint* p_pulCounterOutputVideo = pulCounterOutputVideo) { Debug.Assert(Delegates.pglXGetVideoInfoNV != null, "pglXGetVideoInfoNV not implemented"); retValue = Delegates.pglXGetVideoInfoNV(dpy, screen, VideoDevice, p_pulCounterOutputPbuffer, p_pulCounterOutputVideo); LogCommand("glXGetVideoInfoNV", retValue, dpy, screen, VideoDevice, pulCounterOutputPbuffer, pulCounterOutputVideo ); } } DebugCheckErrors(retValue); return (retValue); } internal static unsafe partial class Delegates { [RequiredByFeature("GLX_NV_video_out")] [SuppressUnmanagedCodeSecurity] internal delegate int glXGetVideoDeviceNV(IntPtr dpy, int screen, int numVideoDevices, IntPtr pVideoDevice); [RequiredByFeature("GLX_NV_video_out")] internal static glXGetVideoDeviceNV pglXGetVideoDeviceNV; [RequiredByFeature("GLX_NV_video_out")] [SuppressUnmanagedCodeSecurity] internal delegate int glXReleaseVideoDeviceNV(IntPtr dpy, int screen, IntPtr VideoDevice); [RequiredByFeature("GLX_NV_video_out")] internal static glXReleaseVideoDeviceNV pglXReleaseVideoDeviceNV; [RequiredByFeature("GLX_NV_video_out")] [SuppressUnmanagedCodeSecurity] internal delegate int glXBindVideoImageNV(IntPtr dpy, IntPtr VideoDevice, IntPtr pbuf, int iVideoBuffer); [RequiredByFeature("GLX_NV_video_out")] internal static glXBindVideoImageNV pglXBindVideoImageNV; [RequiredByFeature("GLX_NV_video_out")] [SuppressUnmanagedCodeSecurity] internal delegate int glXReleaseVideoImageNV(IntPtr dpy, IntPtr pbuf); [RequiredByFeature("GLX_NV_video_out")] internal static glXReleaseVideoImageNV pglXReleaseVideoImageNV; [RequiredByFeature("GLX_NV_video_out")] [SuppressUnmanagedCodeSecurity] internal delegate int glXSendPbufferToVideoNV(IntPtr dpy, IntPtr pbuf, int iBufferType, uint* pulCounterPbuffer, [MarshalAs(UnmanagedType.I1)] bool bBlock); [RequiredByFeature("GLX_NV_video_out")] internal static glXSendPbufferToVideoNV pglXSendPbufferToVideoNV; [RequiredByFeature("GLX_NV_video_out")] [SuppressUnmanagedCodeSecurity] internal delegate int glXGetVideoInfoNV(IntPtr dpy, int screen, IntPtr VideoDevice, uint* pulCounterOutputPbuffer, uint* pulCounterOutputVideo); [RequiredByFeature("GLX_NV_video_out")] internal static glXGetVideoInfoNV pglXGetVideoInfoNV; } } }
/* Copyright (c) 2017 Marcin Szeniak (https://github.com/Klocman/) Apache License Version 2.0 */ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using Klocman.Extensions; using Klocman.Native; using Klocman.Tools; using Microsoft.Win32; using UninstallTools.Properties; namespace UninstallTools.Startup.Normal { internal sealed class OldStartupDisable : IStartupDisable { /// <summary> /// Extension used for link backup of the disabled entry /// (it is appended to the end of the filename, after the original extension). /// </summary> private static readonly string BackupExtension = ".Startup"; /// <summary> /// Path used to store link backups of disabled entries /// </summary> private static readonly string DriveDisableBackupPath = Path.Combine(WindowsTools.GetEnvironmentPath(CSIDL.CSIDL_WINDOWS), "pss"); /// <summary> /// Registry key used to store information about disabled links /// </summary> private static readonly StartupPointData DriveDisabledKey = new StartupPointData( true, false, false, false, string.Empty, @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Shared Tools\MSConfig\startupfolder"); /// <summary> /// Registry key used to store information about disabled registry values /// </summary> private static readonly StartupPointData RegistryDisabledKey = new StartupPointData( true, true, false, false, string.Empty, @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Shared Tools\MSConfig\startupreg"); /// <summary> /// Look for entries in the disabled startup backup store. /// </summary> public IEnumerable<StartupEntry> AddDisableInfo(IList<StartupEntry> existingEntries) { foreach (var entry in existingEntries) yield return entry; using (var regDisKey = RegistryTools.CreateSubKeyRecursively(RegistryDisabledKey.Path)) { var badLocations = new List<string>(); foreach (var subKeyName in regDisKey.GetSubKeyNames()) { using (var subKey = regDisKey.OpenSubKey(subKeyName)) { if (subKey == null) continue; var key = subKey.GetStringSafe("key"); var hkey = subKey.GetStringSafe("hkey"); var item = subKey.GetStringSafe("item"); var command = subKey.GetStringSafe("command"); if (string.IsNullOrEmpty(key) || string.IsNullOrEmpty(hkey) || string.IsNullOrEmpty(item) || string.IsNullOrEmpty(command)) continue; string location; try { location = Path.Combine(RegistryTools.GetKeyRoot(hkey, false), key); } catch (ArgumentException) { continue; } if (string.IsNullOrEmpty(location.Trim())) continue; var runLocation = StartupEntryFactory.RunLocations .FirstOrDefault(x => PathTools.PathsEqual(location, x.Path)); if (runLocation != null) { StartupEntry startupEntry; try { startupEntry = new StartupEntry(runLocation, item, command) { DisabledStore = true }; } catch { badLocations.Add(location); continue; } yield return startupEntry; } else { badLocations.Add(location); } } } if (badLocations.Any()) { var errorString = Localisation.Error_InvalidRegKeys + "\n" + string.Join("\n", badLocations.Distinct().OrderBy(x => x).ToArray()); #if DEBUG Debug.Fail(errorString); #else Console.WriteLine(errorString); #endif } } using (var hddDisKey = RegistryTools.CreateSubKeyRecursively(DriveDisabledKey.Path)) { foreach (var subKeyName in hddDisKey.GetSubKeyNames()) { using (var subKey = hddDisKey.OpenSubKey(subKeyName)) { if (subKey == null) continue; var path = subKey.GetStringSafe("path"); var location = subKey.GetStringSafe("location"); var backup = subKey.GetStringSafe("backup"); var command = subKey.GetStringSafe("command"); if (backup == null || location == null || path == null || command == null) continue; var runLocation = StartupEntryFactory.RunLocations .FirstOrDefault(x => PathTools.PathsEqual(x.Path, location)); if (runLocation == null) continue; yield return new StartupEntry(runLocation, Path.GetFileName(path), command) { BackupPath = backup, DisabledStore = true }; } } } } public void Disable(StartupEntry startupEntry) { if (startupEntry.DisabledStore) return; var newPath = CreateDisabledEntryPath(startupEntry); // Remove the startup entry / move the file to the backup folder if (startupEntry.IsRegKey) { try { startupEntry.Delete(); } catch { // Key doesn't exist } } else { if (File.Exists(startupEntry.FullLongName)) { File.Delete(newPath); Directory.CreateDirectory(DriveDisableBackupPath); File.Move(startupEntry.FullLongName, newPath); startupEntry.BackupPath = newPath; } else throw new InvalidOperationException(Localisation.StartupManager_FailedEnable_FileNotFound + "\n\n" + startupEntry.FullLongName); } CreateDisabledEntry(startupEntry, newPath); startupEntry.DisabledStore = true; } public void Enable(StartupEntry startupEntry) { if (!startupEntry.DisabledStore) return; // Reconstruct the startup entry if (!startupEntry.IsRegKey) { // Move the backup file back to its original location var oldPath = GetDisabledEntryPath(startupEntry); if (File.Exists(oldPath)) { File.Delete(startupEntry.FullLongName); File.Move(oldPath, startupEntry.FullLongName); } else throw new InvalidOperationException(Localisation.StartupManager_FailedEnable_FileNotFound + "\n\n" + oldPath); } else { // Recreate the registry key StartupEntryManager.CreateRegValue(startupEntry); } Delete(startupEntry); startupEntry.BackupPath = string.Empty; // Entry is no longer disabled startupEntry.DisabledStore = false; } /// <summary> /// Create backup store path for the link. The backup extension is appended as well. /// Works only for links, returns garbage for registry values. /// </summary> public string GetDisabledEntryPath(StartupEntry startupEntry) { return string.IsNullOrEmpty(startupEntry.BackupPath) ? CreateDisabledEntryPath(startupEntry) : startupEntry.BackupPath; } public bool StillExists(StartupEntry startupEntry) { try { using (var key = RegistryTools.OpenRegistryKey( startupEntry.IsRegKey ? RegistryDisabledKey.Path : DriveDisabledKey.Path)) { var disabledSubKeyName = startupEntry.IsRegKey ? startupEntry.EntryLongName : startupEntry.FullLongName.Replace('\\', '^'); return key.GetSubKeyNames() .Any(x => disabledSubKeyName.Equals(x, StringComparison.InvariantCultureIgnoreCase)); } } catch { return false; } } public void Delete(StartupEntry startupEntry) { RemoveDisabledRegEntry(startupEntry); // Remove the backup file if (!startupEntry.IsRegKey) File.Delete(GetDisabledEntryPath(startupEntry)); } /// <summary> /// Create a new record in the appropriate disabled entry store. If the entry already exists it is overwritten. /// </summary> /// <param name="startupEntry">Startup entry to create the record for</param> /// <param name="newEntryPath">Full path to the new backup file</param> private static void CreateDisabledEntry(StartupEntry startupEntry, string newEntryPath) { using (var disabledStartupEntryStore = RegistryTools.CreateSubKeyRecursively( startupEntry.IsRegKey ? RegistryDisabledKey.Path : DriveDisabledKey.Path)) { var disabledSubKeyName = startupEntry.IsRegKey ? startupEntry.EntryLongName : startupEntry.FullLongName.Replace('\\', '^'); var disabledSubkeyKey = disabledStartupEntryStore.GetSubKeyNames() .FirstOrDefault(x => disabledSubKeyName.Equals(x, StringComparison.InvariantCultureIgnoreCase)); // Clean up old disabled entry if any if (!string.IsNullOrEmpty(disabledSubkeyKey)) { disabledStartupEntryStore.DeleteSubKey(disabledSubkeyKey); } using ( var storeSubkey = disabledStartupEntryStore.CreateSubKey(disabledSubKeyName, RegistryKeyPermissionCheck.ReadWriteSubTree)) { if (storeSubkey == null) return; if (startupEntry.IsRegKey) { storeSubkey.SetValue("key", RegistryTools.StripKeyRoot(startupEntry.ParentLongName), RegistryValueKind.String); storeSubkey.SetValue("item", startupEntry.EntryLongName, RegistryValueKind.String); storeSubkey.SetValue("hkey", RegistryTools.GetKeyRoot(startupEntry.ParentLongName, true), RegistryValueKind.String); storeSubkey.SetValue("inimapping", 0, RegistryValueKind.String); } else { storeSubkey.SetValue("item", Path.GetFileNameWithoutExtension(startupEntry.EntryLongName) ?? string.Empty, RegistryValueKind.String); storeSubkey.SetValue("path", startupEntry.FullLongName, RegistryValueKind.String); storeSubkey.SetValue("location", startupEntry.ParentLongName, RegistryValueKind.String); storeSubkey.SetValue("backup", newEntryPath, RegistryValueKind.String); storeSubkey.SetValue("backupExtension", BackupExtension, RegistryValueKind.String); } // Command stays the same for both storeSubkey.SetValue("command", startupEntry.Command, RegistryValueKind.String); // Set the disable date var now = DateTime.Now; storeSubkey.SetValue("YEAR", now.Year, RegistryValueKind.DWord); storeSubkey.SetValue("MONTH", now.Month, RegistryValueKind.DWord); storeSubkey.SetValue("DAY", now.Day, RegistryValueKind.DWord); storeSubkey.SetValue("HOUR", now.Hour, RegistryValueKind.DWord); storeSubkey.SetValue("MINUTE", now.Minute, RegistryValueKind.DWord); storeSubkey.SetValue("SECOND", now.Second, RegistryValueKind.DWord); } } } private static string CreateDisabledEntryPath(StartupEntryBase startupEntry) { return Path.Combine(DriveDisableBackupPath, startupEntry.EntryLongName + BackupExtension); } /// <summary> /// Remove registry key of a disabled startup entry. Link file is not touched if it exists. /// </summary> private static void RemoveDisabledRegEntry(StartupEntry startupEntry) { using (var disabledStartupEntryStore = RegistryTools.OpenRegistryKey( startupEntry.IsRegKey ? RegistryDisabledKey.Path : DriveDisabledKey.Path, true)) { var disabledSubKeyName = startupEntry.IsRegKey ? startupEntry.EntryLongName : startupEntry.FullLongName.Replace('\\', '^'); var disabledSubkeyKey = disabledStartupEntryStore.GetSubKeyNames() .FirstOrDefault(x => disabledSubKeyName.Equals(x, StringComparison.InvariantCultureIgnoreCase)); if (!string.IsNullOrEmpty(disabledSubkeyKey)) { disabledStartupEntryStore.DeleteSubKey(disabledSubkeyKey); } } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. /* * This is the source code for the tool 'TypeCatalogGen.exe', which has been checked in %SDXROOT%\tools\managed\v4.0\TypeCatalogGen. * The tool 'TypeCatalogGen.exe' is used when building 'Microsoft.PowerShell.CoreCLR.AssemblyLoadContext.dll' for OneCore powershell * to generate the CoreCLR type catalog initialization code, which will then be compiled into the same DLL. * * See files 'makefile.inc' and 'sources' under directory 'PSAssemblyLoadContext' to learn how the tool and the auto-generated CSharp * file is used. * * Compilation Note: * .NET Fx Version - 4.5 * Special Dependency - System.Reflection.Metadata.dll, System.Collections.Immutable.dll (Available as nuget package: https://www.nuget.org/packages/System.Reflection.Metadata) * To compile the code, create a VS project and get the 'System.Reflection.Metadata' package from nuget. Then add this file to the VS * project and compile it. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Security.Cryptography; using System.Text; namespace Microsoft.PowerShell.CoreCLR { public class TypeCatalogGen { // Help messages private const string Param_TargetCSharpFilePath = "TargetCSharpFilePath"; private const string Param_ReferenceListPath = "ReferenceListPath"; private const string Param_PrintDebugMessage = "-debug"; private const string HelpMessage = @" Usage: TypeCatalogGen.exe <{0}> <{1}> [{2}] - {0}: Path of the target C# source file to generate. - {1}: Path of the file containing all reference assembly paths, separated by semicolons. - [{2}]: Write out debug messages. Optional. "; // Error messages private const string TargetSourceDirNotFound = "Cannot find the target source directory. The path '{0}' doesn't exist."; private const string ReferenceListFileNotFound = "Cannot find the file that contains the reference list. The path '{0}' doesn't exist."; private const string RefAssemblyNotFound = "Reference assembly '{0}' is declared in the reference list file '{1}', but the assembly doesn't exist."; private const string UnexpectedFileExtension = "Cannot process '{0}' because its extension is neither '.DLL' nor '.METADATA_DLL'. Please make sure the file is an reference assembly."; // Format strings for constructing type names private const string Format_RegularType = "{0}.{1}"; private const string Format_SingleLevelNestedType = "{0}.{1}+{2}"; private const string Format_MultiLevelNestedType = "{0}+{1}"; /* * Go through all reference assemblies of .NET Core and generate the type catalog -> Dictionary<NamespaceQualifiedTypeName, TPAStrongName> * Then auto-generate the partial class 'PowerShellAssemblyLoadContext' that has the code to initialize the type catalog cache. * * In CoreCLR, there is no way to get all loaded TPA assemblies (.NET Framework Assemblies). In order to get type based on type name, powershell needs to know what .NET * types are available and in which TPA assemblies. So we have to generate the type catalog based on the reference assemblies of .NET Core. */ public static void Main(string[] args) { if (args.Length < 2 || args.Length > 3) { string message = string.Format(CultureInfo.CurrentCulture, HelpMessage, Param_TargetCSharpFilePath, Param_ReferenceListPath, Param_PrintDebugMessage); Console.WriteLine(message); return; } bool printDebugMessage = args.Length == 3 && string.Equals(Param_PrintDebugMessage, args[2], StringComparison.OrdinalIgnoreCase); string targetFilePath = ResolveTargetFilePath(args[0]); List<string> refAssemblyFiles = ResolveReferenceAssemblies(args[1]); Dictionary<string, TypeMetadata> typeNameToAssemblyMap = new Dictionary<string, TypeMetadata>(StringComparer.OrdinalIgnoreCase); // mscorlib.metadata_dll doesn't contain any type definition. foreach (string filePath in refAssemblyFiles) { if (!filePath.EndsWith(".METADATA_DLL", StringComparison.OrdinalIgnoreCase) && !filePath.EndsWith(".DLL", StringComparison.OrdinalIgnoreCase)) { string message = string.Format(CultureInfo.CurrentCulture, UnexpectedFileExtension, filePath); throw new InvalidOperationException(message); } using (Stream stream = File.OpenRead(filePath)) using (PEReader peReader = new PEReader(stream)) { MetadataReader metadataReader = peReader.GetMetadataReader(); string strongAssemblyName = GetAssemblyStrongName(metadataReader); foreach (TypeDefinitionHandle typeHandle in metadataReader.TypeDefinitions) { // We only care about public types TypeDefinition typeDefinition = metadataReader.GetTypeDefinition(typeHandle); // The visibility mask is used to mask out the bits that contain the visibility. // The visibilities are not combineable, e.g. you can't be both public and private, which is why these aren't independent powers of two. TypeAttributes visibilityBits = typeDefinition.Attributes & TypeAttributes.VisibilityMask; if (visibilityBits != TypeAttributes.Public && visibilityBits != TypeAttributes.NestedPublic) { continue; } string fullName = GetTypeFullName(metadataReader, typeDefinition); bool isTypeObsolete = IsTypeObsolete(metadataReader, typeDefinition); if (!typeNameToAssemblyMap.ContainsKey(fullName)) { // Add unique type. typeNameToAssemblyMap.Add(fullName, new TypeMetadata(strongAssemblyName, isTypeObsolete)); } else if (typeNameToAssemblyMap[fullName].IsObsolete && !isTypeObsolete) { // Duplicate types found defined in different assemblies, but the previous one is obsolete while the current one is not. // Replace the existing type with the current one. if (printDebugMessage) { var existingTypeMetadata = typeNameToAssemblyMap[fullName]; Console.WriteLine($@" REPLACE '{fullName}' from '{existingTypeMetadata.AssemblyName}' (IsObsolete? {existingTypeMetadata.IsObsolete}) WITH '{strongAssemblyName}' (IsObsolete? {isTypeObsolete})"); } typeNameToAssemblyMap[fullName] = new TypeMetadata(strongAssemblyName, isTypeObsolete); } else if (printDebugMessage) { // Duplicate types found defined in different assemblies, and fall into one of the following conditions: // - both are obsolete // - both are not obsolete // - the existing type is not obsolete while the new one is obsolete var existingTypeMetadata = typeNameToAssemblyMap[fullName]; Console.WriteLine($@" DUPLICATE key '{fullName}' from '{strongAssemblyName}' (IsObsolete? {isTypeObsolete}). -- Already exist in '{existingTypeMetadata.AssemblyName}' (IsObsolete? {existingTypeMetadata.IsObsolete})"); } } } } WritePowerShellAssemblyLoadContextPartialClass(targetFilePath, typeNameToAssemblyMap); } /// <summary> /// Check if the type is obsolete. /// </summary> private static bool IsTypeObsolete(MetadataReader reader, TypeDefinition typeDefinition) { const string obsoleteFullTypeName = "System.ObsoleteAttribute"; foreach (var customAttributeHandle in typeDefinition.GetCustomAttributes()) { var customAttribute = reader.GetCustomAttribute(customAttributeHandle); if (IsAttributeOfType(reader, customAttribute, obsoleteFullTypeName)) { return true; } } return false; } /// <summary> /// Check if the attribute type name is what we expected. /// </summary> private static bool IsAttributeOfType(MetadataReader reader, CustomAttribute customAttribute, string expectedTypeName) { string attributeFullName = null; switch (customAttribute.Constructor.Kind) { case HandleKind.MethodDefinition: // Attribute is defined in the same module MethodDefinition methodDef = reader.GetMethodDefinition((MethodDefinitionHandle)customAttribute.Constructor); TypeDefinitionHandle declaringTypeDefHandle = methodDef.GetDeclaringType(); if (declaringTypeDefHandle.IsNil) { /* Global method */ return false; } TypeDefinition declaringTypeDef = reader.GetTypeDefinition(declaringTypeDefHandle); attributeFullName = GetTypeFullName(reader, declaringTypeDef); break; case HandleKind.MemberReference: MemberReference memberRef = reader.GetMemberReference((MemberReferenceHandle)customAttribute.Constructor); switch (memberRef.Parent.Kind) { case HandleKind.TypeReference: TypeReference typeRef = reader.GetTypeReference((TypeReferenceHandle)memberRef.Parent); attributeFullName = GetTypeFullName(reader, typeRef); break; case HandleKind.TypeDefinition: TypeDefinition typeDef = reader.GetTypeDefinition((TypeDefinitionHandle)memberRef.Parent); attributeFullName = GetTypeFullName(reader, typeDef); break; default: // constructor is global method, vararg method, or from a generic type. return false; } break; default: throw new BadImageFormatException("Invalid custom attribute."); } return string.Equals(attributeFullName, expectedTypeName, StringComparison.Ordinal); } /// <summary> /// Get the strong name of a reference assembly represented by the 'metadataReader' /// </summary> private static string GetAssemblyStrongName(MetadataReader metadataReader) { AssemblyDefinition assemblyDefinition = metadataReader.GetAssemblyDefinition(); string asmName = metadataReader.GetString(assemblyDefinition.Name); string asmVersion = assemblyDefinition.Version.ToString(); string asmCulture = metadataReader.GetString(assemblyDefinition.Culture); asmCulture = (asmCulture == string.Empty) ? "neutral" : asmCulture; AssemblyHashAlgorithm hashAlgorithm = assemblyDefinition.HashAlgorithm; BlobHandle blobHandle = assemblyDefinition.PublicKey; BlobReader blobReader = metadataReader.GetBlobReader(blobHandle); byte[] publickey = blobReader.ReadBytes(blobReader.Length); HashAlgorithm hashImpl = null; switch (hashAlgorithm) { case AssemblyHashAlgorithm.Sha1: hashImpl = SHA1.Create(); break; case AssemblyHashAlgorithm.MD5: hashImpl = MD5.Create(); break; case AssemblyHashAlgorithm.Sha256: hashImpl = SHA256.Create(); break; case AssemblyHashAlgorithm.Sha384: hashImpl = SHA384.Create(); break; case AssemblyHashAlgorithm.Sha512: hashImpl = SHA512.Create(); break; default: throw new NotSupportedException(); } byte[] publicKeyHash = hashImpl.ComputeHash(publickey); byte[] publicKeyTokenBytes = new byte[8]; // Note that, the low 8 bytes of the hash of public key in reverse order is the public key tokens. for (int i = 1; i <= 8; i++) { publicKeyTokenBytes[i - 1] = publicKeyHash[publicKeyHash.Length - i]; } // Convert bytes to hex format strings in lower case. string publicKeyTokenString = BitConverter.ToString(publicKeyTokenBytes).Replace("-", string.Empty).ToLowerInvariant(); string strongAssemblyName = string.Format(CultureInfo.InvariantCulture, "{0}, Version={1}, Culture={2}, PublicKeyToken={3}", asmName, asmVersion, asmCulture, publicKeyTokenString); return strongAssemblyName; } /// <summary> /// Get the full name of a Type reference. /// </summary> private static string GetTypeFullName(MetadataReader metadataReader, TypeReference typeReference) { string fullName; string typeName = metadataReader.GetString(typeReference.Name); string nsName = metadataReader.GetString(typeReference.Namespace); EntityHandle resolutionScope = typeReference.ResolutionScope; if (resolutionScope.IsNil || resolutionScope.Kind != HandleKind.TypeReference) { fullName = string.Format(CultureInfo.InvariantCulture, Format_RegularType, nsName, typeName); } else { // It's a nested type. fullName = typeName; while (!resolutionScope.IsNil && resolutionScope.Kind == HandleKind.TypeReference) { TypeReference declaringTypeRef = metadataReader.GetTypeReference((TypeReferenceHandle)resolutionScope); resolutionScope = declaringTypeRef.ResolutionScope; if (resolutionScope.IsNil || resolutionScope.Kind != HandleKind.TypeReference) { fullName = string.Format(CultureInfo.InvariantCulture, Format_SingleLevelNestedType, metadataReader.GetString(declaringTypeRef.Namespace), metadataReader.GetString(declaringTypeRef.Name), fullName); } else { fullName = string.Format(CultureInfo.InvariantCulture, Format_MultiLevelNestedType, metadataReader.GetString(declaringTypeRef.Name), fullName); } } } return fullName; } /// <summary> /// Get the full name of a Type definition. /// </summary> private static string GetTypeFullName(MetadataReader metadataReader, TypeDefinition typeDefinition) { string fullName; string typeName = metadataReader.GetString(typeDefinition.Name); string nsName = metadataReader.GetString(typeDefinition.Namespace); // Get the enclosing type if the type is nested TypeDefinitionHandle declaringTypeHandle = typeDefinition.GetDeclaringType(); if (declaringTypeHandle.IsNil) { fullName = string.Format(CultureInfo.InvariantCulture, Format_RegularType, nsName, typeName); } else { fullName = typeName; while (!declaringTypeHandle.IsNil) { TypeDefinition declaringTypeDef = metadataReader.GetTypeDefinition(declaringTypeHandle); declaringTypeHandle = declaringTypeDef.GetDeclaringType(); if (declaringTypeHandle.IsNil) { fullName = string.Format(CultureInfo.InvariantCulture, Format_SingleLevelNestedType, metadataReader.GetString(declaringTypeDef.Namespace), metadataReader.GetString(declaringTypeDef.Name), fullName); } else { fullName = string.Format(CultureInfo.InvariantCulture, Format_MultiLevelNestedType, metadataReader.GetString(declaringTypeDef.Name), fullName); } } } return fullName; } /// <summary> /// Resolve the target file path. /// </summary> private static string ResolveTargetFilePath(string path) { if (string.IsNullOrWhiteSpace(path)) { throw new ArgumentNullException(Param_TargetCSharpFilePath); } string targetPath = Path.GetFullPath(path); string targetParentFolder = Path.GetDirectoryName(targetPath); if (!Directory.Exists(targetParentFolder)) { string message = string.Format(CultureInfo.CurrentCulture, TargetSourceDirNotFound, targetParentFolder ?? "null"); throw new ArgumentException(message); } return targetPath; } /// <summary> /// Resolve the reference assembly file paths. /// </summary> private static List<string> ResolveReferenceAssemblies(string path) { if (string.IsNullOrWhiteSpace(path)) { throw new ArgumentNullException(Param_ReferenceListPath); } string referenceListPath = Path.GetFullPath(path); if (!File.Exists(referenceListPath)) { string message = string.Format(CultureInfo.CurrentCulture, ReferenceListFileNotFound, referenceListPath ?? "null"); throw new ArgumentException(message); } string allText = File.ReadAllText(referenceListPath); string[] references = allText.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); List<string> refAssemblyFiles = new List<string>(120); for (int i = 0; i < references.Length; i++) { // Ignore entries that only contain white spaces if (string.IsNullOrWhiteSpace(references[i])) { continue; } string refAssemblyPath = references[i].Trim(); if (File.Exists(refAssemblyPath)) { refAssemblyFiles.Add(refAssemblyPath); } else { string message = string.Format(CultureInfo.CurrentCulture, RefAssemblyNotFound, refAssemblyPath, referenceListPath); throw new InvalidDataException(message); } } return refAssemblyFiles; } /// <summary> /// Generate the CSharp source code that initialize the type catalog. /// </summary> private static void WritePowerShellAssemblyLoadContextPartialClass(string targetFilePath, Dictionary<string, TypeMetadata> typeNameToAssemblyMap) { const string SourceFormat = " typeCatalog[\"{0}\"] = \"{1}\";"; const string SourceHead = @"// // This file is auto-generated by TypeCatalogGen.exe during build of Microsoft.PowerShell.CoreCLR.AssemblyLoadContext.dll. // This file will be compiled into Microsoft.PowerShell.CoreCLR.AssemblyLoadContext.dll. // // In CoreCLR, there is no way to get all loaded TPA assemblies (.NET Framework Assemblies). In order to get type based on type // name, powershell needs to know what .NET types are available and in which TPA assemblies. So we have to generate this type // catalog based on the reference assemblies of .NET Core. // using System.Collections.Generic; using System.Runtime.Loader; namespace System.Management.Automation {{ internal partial class PowerShellAssemblyLoadContext {{ private Dictionary<string, string> InitializeTypeCatalog() {{ Dictionary<string, string> typeCatalog = new Dictionary<string, string>({0}, StringComparer.OrdinalIgnoreCase); "; const string SourceEnd = @" return typeCatalog; } } } "; StringBuilder sourceCode = new StringBuilder(string.Format(CultureInfo.InvariantCulture, SourceHead, typeNameToAssemblyMap.Count)); foreach (KeyValuePair<string, TypeMetadata> pair in typeNameToAssemblyMap) { sourceCode.AppendLine(string.Format(CultureInfo.InvariantCulture, SourceFormat, pair.Key, pair.Value.AssemblyName)); } sourceCode.Append(SourceEnd); using (FileStream stream = new FileStream(targetFilePath, FileMode.Create, FileAccess.Write)) using (StreamWriter writer = new StreamWriter(stream, Encoding.ASCII)) { writer.Write(sourceCode.ToString()); } } /// <summary> /// Helper class to keep the metadata of a type. /// </summary> private class TypeMetadata { internal readonly string AssemblyName; internal readonly bool IsObsolete; internal TypeMetadata(string assemblyName, bool isTypeObsolete) { this.AssemblyName = assemblyName; this.IsObsolete = isTypeObsolete; } } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using Mapsui.Fetcher; using Mapsui.Logging; using Mapsui.Rendering; namespace Mapsui.Layers { public class RasterizingLayer : BaseLayer, IAsyncDataFetcher { private readonly ConcurrentStack<RasterFeature> _cache; private readonly ILayer _layer; private readonly bool _onlyRerasterizeIfOutsideOverscan; private readonly double _overscan; private readonly double _renderResolutionMultiplier; private readonly float _pixelDensity; private readonly object _syncLock = new(); private bool _busy; private Viewport? _currentViewport; private bool _modified; private IEnumerable<IFeature>? _previousFeatures; private readonly IRenderer _rasterizer = DefaultRendererFactory.Create(); private FetchInfo? _fetchInfo; public Delayer Delayer { get; } = new(); private readonly Delayer _rasterizeDelayer = new(); /// <summary> /// Creates a RasterizingLayer which rasterizes a layer for performance /// </summary> /// <param name="layer">The Layer to be rasterized</param> /// <param name="delayBeforeRasterize">Delay after viewport change to start re-rasterizing</param> /// <param name="renderResolutionMultiplier"></param> /// <param name="rasterizer">Rasterizer to use. null will use the default</param> /// <param name="overscanRatio">The ratio of the size of the rasterized output to the current viewport</param> /// <param name="onlyRerasterizeIfOutsideOverscan"> /// Set the rasterization policy. false will trigger a rasterization on /// every viewport change. true will trigger a re-rasterization only if the viewport moves outside the existing /// rasterization. /// </param> /// <param name="pixelDensity"></param> public RasterizingLayer( ILayer layer, int delayBeforeRasterize = 1000, double renderResolutionMultiplier = 1, IRenderer? rasterizer = null, double overscanRatio = 1, bool onlyRerasterizeIfOutsideOverscan = false, float pixelDensity = 1) { if (overscanRatio < 1) throw new ArgumentException($"{nameof(overscanRatio)} must be >= 1", nameof(overscanRatio)); _layer = layer; Name = layer.Name; _renderResolutionMultiplier = renderResolutionMultiplier; if (rasterizer != null) _rasterizer = rasterizer; _cache = new ConcurrentStack<RasterFeature>(); _overscan = overscanRatio; _onlyRerasterizeIfOutsideOverscan = onlyRerasterizeIfOutsideOverscan; _pixelDensity = pixelDensity; _layer.DataChanged += LayerOnDataChanged; Delayer.StartWithDelay = true; Delayer.MillisecondsToWait = delayBeforeRasterize; } public override MRect? Extent => _layer.Extent; public ILayer ChildLayer => _layer; private void LayerOnDataChanged(object sender, DataChangedEventArgs dataChangedEventArgs) { if (!Enabled) return; if (_fetchInfo == null) return; if (MinVisible > _fetchInfo.Resolution) return; if (MaxVisible < _fetchInfo.Resolution) return; if (_busy) return; _modified = true; // Will start immediately if it is not currently waiting. This well be in most cases. _rasterizeDelayer.ExecuteDelayed(Rasterize); } private void Rasterize() { if (!Enabled) return; if (_busy) return; _busy = true; _modified = false; lock (_syncLock) { try { if (_fetchInfo == null) return; if (double.IsNaN(_fetchInfo.Resolution) || _fetchInfo.Resolution <= 0) return; if (_fetchInfo.Extent == null || _fetchInfo.Extent?.Width <= 0 || _fetchInfo.Extent?.Height <= 0) return; var viewport = CreateViewport(_fetchInfo.Extent!, _fetchInfo.Resolution, _renderResolutionMultiplier, _overscan); _currentViewport = viewport; using var bitmapStream = _rasterizer.RenderToBitmapStream(viewport, new[] { _layer }, pixelDensity: _pixelDensity); RemoveExistingFeatures(); if (bitmapStream != null) { _cache.Clear(); var features = new RasterFeature[1]; features[0] = new RasterFeature(new MRaster(bitmapStream.ToArray(), viewport.Extent)); _cache.PushRange(features); #if DEBUG Logger.Log(LogLevel.Debug, $"Memory after rasterizing layer {GC.GetTotalMemory(true):N0}"); #endif OnDataChanged(new DataChangedEventArgs()); } if (_modified) Delayer.ExecuteDelayed(() => _layer.RefreshData(_fetchInfo)); } finally { _busy = false; } } } private void RemoveExistingFeatures() { var features = _cache.ToArray(); _cache.Clear(); // clear before dispose to prevent possible null disposed exception on render // Disposing previous and storing current in the previous field to prevent dispose during rendering. if (_previousFeatures != null) DisposeRenderedGeometries(_previousFeatures); _previousFeatures = features; } private static void DisposeRenderedGeometries(IEnumerable<IFeature> features) { foreach (var feature in features.Cast<RasterFeature>()) { foreach (var key in feature.RenderedGeometry.Keys) { var disposable = feature.RenderedGeometry[key] as IDisposable; disposable?.Dispose(); } } } public static double SymbolSize { get; set; } = 64; public override IEnumerable<IFeature> GetFeatures(MRect box, double resolution) { if (box == null) throw new ArgumentNullException(nameof(box)); var features = _cache.ToArray(); // Use a larger extent so that symbols partially outside of the extent are included var biggerBox = box.Grow(resolution * SymbolSize * 0.5); return features.Where(f => f.Raster != null && f.Raster.Intersects(biggerBox)).ToList(); } public void AbortFetch() { if (_layer is IAsyncDataFetcher asyncLayer) asyncLayer.AbortFetch(); } public override void RefreshData(FetchInfo fetchInfo) { if (fetchInfo.Extent == null) return; var newViewport = CreateViewport(fetchInfo.Extent, fetchInfo.Resolution, _renderResolutionMultiplier, 1); if (!Enabled) return; if (MinVisible > fetchInfo.Resolution) return; if (MaxVisible < fetchInfo.Resolution) return; if (!_onlyRerasterizeIfOutsideOverscan || (_currentViewport == null) || (_currentViewport.Resolution != newViewport.Resolution) || !_currentViewport.Extent.Contains(newViewport.Extent)) { // Explicitly set the change type to discrete for rasterization _fetchInfo = new FetchInfo(fetchInfo.Extent, fetchInfo.Resolution, fetchInfo.CRS); if (_layer is IAsyncDataFetcher) Delayer.ExecuteDelayed(() => _layer.RefreshData(_fetchInfo)); else Delayer.ExecuteDelayed(Rasterize); } } public void ClearCache() { if (_layer is IAsyncDataFetcher asyncLayer) asyncLayer.ClearCache(); } private static Viewport CreateViewport(MRect extent, double resolution, double renderResolutionMultiplier, double overscan) { var renderResolution = resolution / renderResolutionMultiplier; return new Viewport { Resolution = renderResolution, CenterX = extent.Centroid.X, CenterY = extent.Centroid.Y, Width = extent.Width * overscan / renderResolution, Height = extent.Height * overscan / renderResolution }; } } }
using System; using System.Collections.Generic; namespace Parse.Infrastructure.Utilities { /// <summary> /// A reimplementation of Xamarin's PreserveAttribute. /// This allows us to support AOT and linking for Xamarin platforms. /// </summary> [AttributeUsage(AttributeTargets.All)] internal class PreserveAttribute : Attribute { public bool AllMembers; public bool Conditional; } [AttributeUsage(AttributeTargets.All)] internal class LinkerSafeAttribute : Attribute { public LinkerSafeAttribute() { } } [Preserve(AllMembers = true)] internal class PreserveWrapperTypes { /// <summary> /// Exists to ensure that generic types are AOT-compiled for the conversions we support. /// Any new value types that we add support for will need to be registered here. /// The method itself is never called, but by virtue of the Preserve attribute being set /// on the class, these types will be AOT-compiled. /// /// This also applies to Unity. /// </summary> static List<object> AOTPreservations => new List<object> { typeof(FlexibleListWrapper<object, object>), typeof(FlexibleListWrapper<object, bool>), typeof(FlexibleListWrapper<object, byte>), typeof(FlexibleListWrapper<object, sbyte>), typeof(FlexibleListWrapper<object, short>), typeof(FlexibleListWrapper<object, ushort>), typeof(FlexibleListWrapper<object, int>), typeof(FlexibleListWrapper<object, uint>), typeof(FlexibleListWrapper<object, long>), typeof(FlexibleListWrapper<object, ulong>), typeof(FlexibleListWrapper<object, char>), typeof(FlexibleListWrapper<object, double>), typeof(FlexibleListWrapper<object, float>), typeof(FlexibleListWrapper<bool, object>), typeof(FlexibleListWrapper<bool, bool>), typeof(FlexibleListWrapper<bool, byte>), typeof(FlexibleListWrapper<bool, sbyte>), typeof(FlexibleListWrapper<bool, short>), typeof(FlexibleListWrapper<bool, ushort>), typeof(FlexibleListWrapper<bool, int>), typeof(FlexibleListWrapper<bool, uint>), typeof(FlexibleListWrapper<bool, long>), typeof(FlexibleListWrapper<bool, ulong>), typeof(FlexibleListWrapper<bool, char>), typeof(FlexibleListWrapper<bool, double>), typeof(FlexibleListWrapper<bool, float>), typeof(FlexibleListWrapper<byte, object>), typeof(FlexibleListWrapper<byte, bool>), typeof(FlexibleListWrapper<byte, byte>), typeof(FlexibleListWrapper<byte, sbyte>), typeof(FlexibleListWrapper<byte, short>), typeof(FlexibleListWrapper<byte, ushort>), typeof(FlexibleListWrapper<byte, int>), typeof(FlexibleListWrapper<byte, uint>), typeof(FlexibleListWrapper<byte, long>), typeof(FlexibleListWrapper<byte, ulong>), typeof(FlexibleListWrapper<byte, char>), typeof(FlexibleListWrapper<byte, double>), typeof(FlexibleListWrapper<byte, float>), typeof(FlexibleListWrapper<sbyte, object>), typeof(FlexibleListWrapper<sbyte, bool>), typeof(FlexibleListWrapper<sbyte, byte>), typeof(FlexibleListWrapper<sbyte, sbyte>), typeof(FlexibleListWrapper<sbyte, short>), typeof(FlexibleListWrapper<sbyte, ushort>), typeof(FlexibleListWrapper<sbyte, int>), typeof(FlexibleListWrapper<sbyte, uint>), typeof(FlexibleListWrapper<sbyte, long>), typeof(FlexibleListWrapper<sbyte, ulong>), typeof(FlexibleListWrapper<sbyte, char>), typeof(FlexibleListWrapper<sbyte, double>), typeof(FlexibleListWrapper<sbyte, float>), typeof(FlexibleListWrapper<short, object>), typeof(FlexibleListWrapper<short, bool>), typeof(FlexibleListWrapper<short, byte>), typeof(FlexibleListWrapper<short, sbyte>), typeof(FlexibleListWrapper<short, short>), typeof(FlexibleListWrapper<short, ushort>), typeof(FlexibleListWrapper<short, int>), typeof(FlexibleListWrapper<short, uint>), typeof(FlexibleListWrapper<short, long>), typeof(FlexibleListWrapper<short, ulong>), typeof(FlexibleListWrapper<short, char>), typeof(FlexibleListWrapper<short, double>), typeof(FlexibleListWrapper<short, float>), typeof(FlexibleListWrapper<ushort, object>), typeof(FlexibleListWrapper<ushort, bool>), typeof(FlexibleListWrapper<ushort, byte>), typeof(FlexibleListWrapper<ushort, sbyte>), typeof(FlexibleListWrapper<ushort, short>), typeof(FlexibleListWrapper<ushort, ushort>), typeof(FlexibleListWrapper<ushort, int>), typeof(FlexibleListWrapper<ushort, uint>), typeof(FlexibleListWrapper<ushort, long>), typeof(FlexibleListWrapper<ushort, ulong>), typeof(FlexibleListWrapper<ushort, char>), typeof(FlexibleListWrapper<ushort, double>), typeof(FlexibleListWrapper<ushort, float>), typeof(FlexibleListWrapper<int, object>), typeof(FlexibleListWrapper<int, bool>), typeof(FlexibleListWrapper<int, byte>), typeof(FlexibleListWrapper<int, sbyte>), typeof(FlexibleListWrapper<int, short>), typeof(FlexibleListWrapper<int, ushort>), typeof(FlexibleListWrapper<int, int>), typeof(FlexibleListWrapper<int, uint>), typeof(FlexibleListWrapper<int, long>), typeof(FlexibleListWrapper<int, ulong>), typeof(FlexibleListWrapper<int, char>), typeof(FlexibleListWrapper<int, double>), typeof(FlexibleListWrapper<int, float>), typeof(FlexibleListWrapper<uint, object>), typeof(FlexibleListWrapper<uint, bool>), typeof(FlexibleListWrapper<uint, byte>), typeof(FlexibleListWrapper<uint, sbyte>), typeof(FlexibleListWrapper<uint, short>), typeof(FlexibleListWrapper<uint, ushort>), typeof(FlexibleListWrapper<uint, int>), typeof(FlexibleListWrapper<uint, uint>), typeof(FlexibleListWrapper<uint, long>), typeof(FlexibleListWrapper<uint, ulong>), typeof(FlexibleListWrapper<uint, char>), typeof(FlexibleListWrapper<uint, double>), typeof(FlexibleListWrapper<uint, float>), typeof(FlexibleListWrapper<long, object>), typeof(FlexibleListWrapper<long, bool>), typeof(FlexibleListWrapper<long, byte>), typeof(FlexibleListWrapper<long, sbyte>), typeof(FlexibleListWrapper<long, short>), typeof(FlexibleListWrapper<long, ushort>), typeof(FlexibleListWrapper<long, int>), typeof(FlexibleListWrapper<long, uint>), typeof(FlexibleListWrapper<long, long>), typeof(FlexibleListWrapper<long, ulong>), typeof(FlexibleListWrapper<long, char>), typeof(FlexibleListWrapper<long, double>), typeof(FlexibleListWrapper<long, float>), typeof(FlexibleListWrapper<ulong, object>), typeof(FlexibleListWrapper<ulong, bool>), typeof(FlexibleListWrapper<ulong, byte>), typeof(FlexibleListWrapper<ulong, sbyte>), typeof(FlexibleListWrapper<ulong, short>), typeof(FlexibleListWrapper<ulong, ushort>), typeof(FlexibleListWrapper<ulong, int>), typeof(FlexibleListWrapper<ulong, uint>), typeof(FlexibleListWrapper<ulong, long>), typeof(FlexibleListWrapper<ulong, ulong>), typeof(FlexibleListWrapper<ulong, char>), typeof(FlexibleListWrapper<ulong, double>), typeof(FlexibleListWrapper<ulong, float>), typeof(FlexibleListWrapper<char, object>), typeof(FlexibleListWrapper<char, bool>), typeof(FlexibleListWrapper<char, byte>), typeof(FlexibleListWrapper<char, sbyte>), typeof(FlexibleListWrapper<char, short>), typeof(FlexibleListWrapper<char, ushort>), typeof(FlexibleListWrapper<char, int>), typeof(FlexibleListWrapper<char, uint>), typeof(FlexibleListWrapper<char, long>), typeof(FlexibleListWrapper<char, ulong>), typeof(FlexibleListWrapper<char, char>), typeof(FlexibleListWrapper<char, double>), typeof(FlexibleListWrapper<char, float>), typeof(FlexibleListWrapper<double, object>), typeof(FlexibleListWrapper<double, bool>), typeof(FlexibleListWrapper<double, byte>), typeof(FlexibleListWrapper<double, sbyte>), typeof(FlexibleListWrapper<double, short>), typeof(FlexibleListWrapper<double, ushort>), typeof(FlexibleListWrapper<double, int>), typeof(FlexibleListWrapper<double, uint>), typeof(FlexibleListWrapper<double, long>), typeof(FlexibleListWrapper<double, ulong>), typeof(FlexibleListWrapper<double, char>), typeof(FlexibleListWrapper<double, double>), typeof(FlexibleListWrapper<double, float>), typeof(FlexibleListWrapper<float, object>), typeof(FlexibleListWrapper<float, bool>), typeof(FlexibleListWrapper<float, byte>), typeof(FlexibleListWrapper<float, sbyte>), typeof(FlexibleListWrapper<float, short>), typeof(FlexibleListWrapper<float, ushort>), typeof(FlexibleListWrapper<float, int>), typeof(FlexibleListWrapper<float, uint>), typeof(FlexibleListWrapper<float, long>), typeof(FlexibleListWrapper<float, ulong>), typeof(FlexibleListWrapper<float, char>), typeof(FlexibleListWrapper<float, double>), typeof(FlexibleListWrapper<float, float>), typeof(FlexibleListWrapper<object, DateTime>), typeof(FlexibleListWrapper<DateTime, object>), typeof(FlexibleDictionaryWrapper<object, object>), typeof(FlexibleDictionaryWrapper<object, bool>), typeof(FlexibleDictionaryWrapper<object, byte>), typeof(FlexibleDictionaryWrapper<object, sbyte>), typeof(FlexibleDictionaryWrapper<object, short>), typeof(FlexibleDictionaryWrapper<object, ushort>), typeof(FlexibleDictionaryWrapper<object, int>), typeof(FlexibleDictionaryWrapper<object, uint>), typeof(FlexibleDictionaryWrapper<object, long>), typeof(FlexibleDictionaryWrapper<object, ulong>), typeof(FlexibleDictionaryWrapper<object, char>), typeof(FlexibleDictionaryWrapper<object, double>), typeof(FlexibleDictionaryWrapper<object, float>), typeof(FlexibleDictionaryWrapper<bool, object>), typeof(FlexibleDictionaryWrapper<bool, bool>), typeof(FlexibleDictionaryWrapper<bool, byte>), typeof(FlexibleDictionaryWrapper<bool, sbyte>), typeof(FlexibleDictionaryWrapper<bool, short>), typeof(FlexibleDictionaryWrapper<bool, ushort>), typeof(FlexibleDictionaryWrapper<bool, int>), typeof(FlexibleDictionaryWrapper<bool, uint>), typeof(FlexibleDictionaryWrapper<bool, long>), typeof(FlexibleDictionaryWrapper<bool, ulong>), typeof(FlexibleDictionaryWrapper<bool, char>), typeof(FlexibleDictionaryWrapper<bool, double>), typeof(FlexibleDictionaryWrapper<bool, float>), typeof(FlexibleDictionaryWrapper<byte, object>), typeof(FlexibleDictionaryWrapper<byte, bool>), typeof(FlexibleDictionaryWrapper<byte, byte>), typeof(FlexibleDictionaryWrapper<byte, sbyte>), typeof(FlexibleDictionaryWrapper<byte, short>), typeof(FlexibleDictionaryWrapper<byte, ushort>), typeof(FlexibleDictionaryWrapper<byte, int>), typeof(FlexibleDictionaryWrapper<byte, uint>), typeof(FlexibleDictionaryWrapper<byte, long>), typeof(FlexibleDictionaryWrapper<byte, ulong>), typeof(FlexibleDictionaryWrapper<byte, char>), typeof(FlexibleDictionaryWrapper<byte, double>), typeof(FlexibleDictionaryWrapper<byte, float>), typeof(FlexibleDictionaryWrapper<sbyte, object>), typeof(FlexibleDictionaryWrapper<sbyte, bool>), typeof(FlexibleDictionaryWrapper<sbyte, byte>), typeof(FlexibleDictionaryWrapper<sbyte, sbyte>), typeof(FlexibleDictionaryWrapper<sbyte, short>), typeof(FlexibleDictionaryWrapper<sbyte, ushort>), typeof(FlexibleDictionaryWrapper<sbyte, int>), typeof(FlexibleDictionaryWrapper<sbyte, uint>), typeof(FlexibleDictionaryWrapper<sbyte, long>), typeof(FlexibleDictionaryWrapper<sbyte, ulong>), typeof(FlexibleDictionaryWrapper<sbyte, char>), typeof(FlexibleDictionaryWrapper<sbyte, double>), typeof(FlexibleDictionaryWrapper<sbyte, float>), typeof(FlexibleDictionaryWrapper<short, object>), typeof(FlexibleDictionaryWrapper<short, bool>), typeof(FlexibleDictionaryWrapper<short, byte>), typeof(FlexibleDictionaryWrapper<short, sbyte>), typeof(FlexibleDictionaryWrapper<short, short>), typeof(FlexibleDictionaryWrapper<short, ushort>), typeof(FlexibleDictionaryWrapper<short, int>), typeof(FlexibleDictionaryWrapper<short, uint>), typeof(FlexibleDictionaryWrapper<short, long>), typeof(FlexibleDictionaryWrapper<short, ulong>), typeof(FlexibleDictionaryWrapper<short, char>), typeof(FlexibleDictionaryWrapper<short, double>), typeof(FlexibleDictionaryWrapper<short, float>), typeof(FlexibleDictionaryWrapper<ushort, object>), typeof(FlexibleDictionaryWrapper<ushort, bool>), typeof(FlexibleDictionaryWrapper<ushort, byte>), typeof(FlexibleDictionaryWrapper<ushort, sbyte>), typeof(FlexibleDictionaryWrapper<ushort, short>), typeof(FlexibleDictionaryWrapper<ushort, ushort>), typeof(FlexibleDictionaryWrapper<ushort, int>), typeof(FlexibleDictionaryWrapper<ushort, uint>), typeof(FlexibleDictionaryWrapper<ushort, long>), typeof(FlexibleDictionaryWrapper<ushort, ulong>), typeof(FlexibleDictionaryWrapper<ushort, char>), typeof(FlexibleDictionaryWrapper<ushort, double>), typeof(FlexibleDictionaryWrapper<ushort, float>), typeof(FlexibleDictionaryWrapper<int, object>), typeof(FlexibleDictionaryWrapper<int, bool>), typeof(FlexibleDictionaryWrapper<int, byte>), typeof(FlexibleDictionaryWrapper<int, sbyte>), typeof(FlexibleDictionaryWrapper<int, short>), typeof(FlexibleDictionaryWrapper<int, ushort>), typeof(FlexibleDictionaryWrapper<int, int>), typeof(FlexibleDictionaryWrapper<int, uint>), typeof(FlexibleDictionaryWrapper<int, long>), typeof(FlexibleDictionaryWrapper<int, ulong>), typeof(FlexibleDictionaryWrapper<int, char>), typeof(FlexibleDictionaryWrapper<int, double>), typeof(FlexibleDictionaryWrapper<int, float>), typeof(FlexibleDictionaryWrapper<uint, object>), typeof(FlexibleDictionaryWrapper<uint, bool>), typeof(FlexibleDictionaryWrapper<uint, byte>), typeof(FlexibleDictionaryWrapper<uint, sbyte>), typeof(FlexibleDictionaryWrapper<uint, short>), typeof(FlexibleDictionaryWrapper<uint, ushort>), typeof(FlexibleDictionaryWrapper<uint, int>), typeof(FlexibleDictionaryWrapper<uint, uint>), typeof(FlexibleDictionaryWrapper<uint, long>), typeof(FlexibleDictionaryWrapper<uint, ulong>), typeof(FlexibleDictionaryWrapper<uint, char>), typeof(FlexibleDictionaryWrapper<uint, double>), typeof(FlexibleDictionaryWrapper<uint, float>), typeof(FlexibleDictionaryWrapper<long, object>), typeof(FlexibleDictionaryWrapper<long, bool>), typeof(FlexibleDictionaryWrapper<long, byte>), typeof(FlexibleDictionaryWrapper<long, sbyte>), typeof(FlexibleDictionaryWrapper<long, short>), typeof(FlexibleDictionaryWrapper<long, ushort>), typeof(FlexibleDictionaryWrapper<long, int>), typeof(FlexibleDictionaryWrapper<long, uint>), typeof(FlexibleDictionaryWrapper<long, long>), typeof(FlexibleDictionaryWrapper<long, ulong>), typeof(FlexibleDictionaryWrapper<long, char>), typeof(FlexibleDictionaryWrapper<long, double>), typeof(FlexibleDictionaryWrapper<long, float>), typeof(FlexibleDictionaryWrapper<ulong, object>), typeof(FlexibleDictionaryWrapper<ulong, bool>), typeof(FlexibleDictionaryWrapper<ulong, byte>), typeof(FlexibleDictionaryWrapper<ulong, sbyte>), typeof(FlexibleDictionaryWrapper<ulong, short>), typeof(FlexibleDictionaryWrapper<ulong, ushort>), typeof(FlexibleDictionaryWrapper<ulong, int>), typeof(FlexibleDictionaryWrapper<ulong, uint>), typeof(FlexibleDictionaryWrapper<ulong, long>), typeof(FlexibleDictionaryWrapper<ulong, ulong>), typeof(FlexibleDictionaryWrapper<ulong, char>), typeof(FlexibleDictionaryWrapper<ulong, double>), typeof(FlexibleDictionaryWrapper<ulong, float>), typeof(FlexibleDictionaryWrapper<char, object>), typeof(FlexibleDictionaryWrapper<char, bool>), typeof(FlexibleDictionaryWrapper<char, byte>), typeof(FlexibleDictionaryWrapper<char, sbyte>), typeof(FlexibleDictionaryWrapper<char, short>), typeof(FlexibleDictionaryWrapper<char, ushort>), typeof(FlexibleDictionaryWrapper<char, int>), typeof(FlexibleDictionaryWrapper<char, uint>), typeof(FlexibleDictionaryWrapper<char, long>), typeof(FlexibleDictionaryWrapper<char, ulong>), typeof(FlexibleDictionaryWrapper<char, char>), typeof(FlexibleDictionaryWrapper<char, double>), typeof(FlexibleDictionaryWrapper<char, float>), typeof(FlexibleDictionaryWrapper<double, object>), typeof(FlexibleDictionaryWrapper<double, bool>), typeof(FlexibleDictionaryWrapper<double, byte>), typeof(FlexibleDictionaryWrapper<double, sbyte>), typeof(FlexibleDictionaryWrapper<double, short>), typeof(FlexibleDictionaryWrapper<double, ushort>), typeof(FlexibleDictionaryWrapper<double, int>), typeof(FlexibleDictionaryWrapper<double, uint>), typeof(FlexibleDictionaryWrapper<double, long>), typeof(FlexibleDictionaryWrapper<double, ulong>), typeof(FlexibleDictionaryWrapper<double, char>), typeof(FlexibleDictionaryWrapper<double, double>), typeof(FlexibleDictionaryWrapper<double, float>), typeof(FlexibleDictionaryWrapper<float, object>), typeof(FlexibleDictionaryWrapper<float, bool>), typeof(FlexibleDictionaryWrapper<float, byte>), typeof(FlexibleDictionaryWrapper<float, sbyte>), typeof(FlexibleDictionaryWrapper<float, short>), typeof(FlexibleDictionaryWrapper<float, ushort>), typeof(FlexibleDictionaryWrapper<float, int>), typeof(FlexibleDictionaryWrapper<float, uint>), typeof(FlexibleDictionaryWrapper<float, long>), typeof(FlexibleDictionaryWrapper<float, ulong>), typeof(FlexibleDictionaryWrapper<float, char>), typeof(FlexibleDictionaryWrapper<float, double>), typeof(FlexibleDictionaryWrapper<float, float>), typeof(FlexibleDictionaryWrapper<object, DateTime>), typeof(FlexibleDictionaryWrapper<DateTime, object>) }; } }
// // Copyright (C) 2010 Jackson Harper (jackson@manosdemono.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // using System; using System.Collections.Generic; using System.IO; using System.Text; namespace Manos.Templates { public class Token { public Token(int line, int col, TokenType type, string value) { Line = line; Column = col; Type = type; Value = value; } public Token(int line, int col, TokenType type, string value, object tok_value) : this(line, col, type, value) { TokenizedValue = tok_value; } public int Line { get; private set; } public int Column { get; private set; } public TokenType Type { get; private set; } public string Value { get; private set; } public object TokenizedValue { get; private set; } } public class TemplateTokenizer { private static readonly string idchars = "_"; private static readonly string numstartchars = "-"; private static readonly string numchars = "."; private readonly StringBuilder builder; private readonly TemplateEnvironment environment; private readonly TextReader reader; private readonly TokenOperators token_ops; private int col; private Token current; private bool have_unget; private bool in_code_block; private int line; private int position; private string source; private int unget_value; public TemplateTokenizer(TemplateEnvironment env, TextReader reader) { environment = env; this.reader = reader; builder = new StringBuilder(); token_ops = new TokenOperators(environment); } public Token Current { get { return current; } } public int Line { get { return line; } } public int Column { get { return col; } } public Token GetNextToken() { current = _GetNextToken(); return current; } private Token _GetNextToken() { int c; Token tok = null; TokenType tok_type; builder.Length = 0; while ((c = ReadChar()) != -1) { if (in_code_block && (c == '\'' || c == '\"')) { string str = ReadQuotedString(c); Console.WriteLine("READ QUOTED STRING: {0}", str); if (str == null) return new Token(line, col, TokenType.TOKEN_EOF, String.Empty); tok = new Token(line, col, TokenType.TOKEN_QUOTED_STRING, str); return tok; } int d = reader.Peek(); if (in_code_block && IsNumberStartChar(c) && IsNumberChar(d)) { object number = ReadNumber(c, d, out tok_type); tok = new Token(line, col, tok_type, number.ToString(), number); return tok; } string two_chars = String.Concat((char) c, (char) d); if (token_ops.DoubleCharOps.TryGetValue(two_chars, out tok_type)) { tok = new Token(line, col, tok_type, two_chars); reader.Read(); UpdateInCodeBlock(tok_type); return tok; } if (token_ops.SingleCharOps.TryGetValue(c, out tok_type)) { tok = new Token(line, col, tok_type, "" + (char) c); return tok; } if (in_code_block) { if (Char.IsWhiteSpace((char) c)) { tok = new Token(line, col, TokenType.TOKEN_WHITESPACE, "" + (char) c); return tok; } if (IsNameStartChar(c)) { do { builder.Append((char) c); c = ReadChar(); } while (IsNameChar(c)); PutbackChar(c); tok = new Token(line, col, TokenType.TOKEN_NAME, builder.ToString()); return tok; } } tok = new Token(line, col, TokenType.TOKEN_DATA, "" + (char) c); return tok; } return new Token(line, col, TokenType.TOKEN_EOF, ""); } private void PutbackChar(int c) { have_unget = true; unget_value = c; } private int ReadChar() { int c; if (have_unget) { c = unget_value; have_unget = false; } else { c = reader.Read(); } if (c == '\r' && reader.Peek() == '\n') { c = reader.Read(); position++; } if (c == '\n') { col = -1; line++; } if (c != -1) { col++; position++; } return c; } private void UpdateInCodeBlock(TokenType tok_type) { switch (tok_type) { case TokenType.TOKEN_BLOCK_END: case TokenType.TOKEN_VARIABLE_END: in_code_block = false; break; case TokenType.TOKEN_BLOCK_BEGIN: case TokenType.TOKEN_VARIABLE_BEGIN: in_code_block = true; break; default: break; } } private string ReadQuotedString(int c) { int quote_char = c; do { builder.Append((char) c); c = ReadChar(); } while (c != quote_char && c != -1); if (c == -1) return null; builder.Append((char) c); return builder.ToString(); } private static bool IsNameStartChar(int ch) { return (Char.IsLetter((char) ch) || (idchars.IndexOf((char) ch) != -1)); } private static bool IsNameChar(int ch) { return (Char.IsLetterOrDigit((char) ch) || (idchars.IndexOf((char) ch) != -1)); } private static bool IsNumberStartChar(int c) { return (Char.IsDigit((char) c) || (numstartchars.IndexOf((char) c) != -1)); } private static bool IsNumberChar(int c) { return (Char.IsDigit((char) c) || (numchars.IndexOf((char) c) != -1)); } private object ReadNumber(int c, int d, out TokenType tok_type) { var builder = new StringBuilder(); bool is_double = false; object number; builder.Append((char) c); c = ReadChar(); while (IsNumberChar(c)) { if (c == '.') is_double = true; builder.Append((char) c); c = ReadChar(); } if (is_double) { tok_type = TokenType.TOKEN_DOUBLE; number = Double.Parse(builder.ToString()); } else { tok_type = TokenType.TOKEN_INTEGER; number = Int32.Parse(builder.ToString()); } PutbackChar(c); return number; } } public enum TokenType { TOKEN_ADD, TOKEN_ASSIGN, TOKEN_COLON, TOKEN_COMMA, TOKEN_DIV, TOKEN_DOT, TOKEN_DOUBLE, TOKEN_EQ, TOKEN_FLOORDIV, TOKEN_GT, TOKEN_GTEQ, TOKEN_LBRACE, TOKEN_LBRACKET, TOKEN_LPAREN, TOKEN_LT, TOKEN_LTEQ, TOKEN_MOD, TOKEN_MUL, TOKEN_NE, TOKEN_PIPE, TOKEN_POW, TOKEN_RBRACE, TOKEN_RBRACKET, TOKEN_RPAREN, TOKEN_SEMICOLON, TOKEN_SUB, TOKEN_TILDE, TOKEN_WHITESPACE, TOKEN_INTEGER, TOKEN_NAME, TOKEN_STRING, TOKEN_QUOTED_STRING, TOKEN_OPERATOR, TOKEN_BLOCK_BEGIN, TOKEN_BLOCK_END, TOKEN_VARIABLE_BEGIN, TOKEN_VARIABLE_END, TOKEN_RAW_BEGIN, TOKEN_RAW_END, TOKEN_COMMENT_BEGIN, TOKEN_COMMENT_END, TOKEN_COMMENT, TOKEN_DATA, TOKEN_INITIAL, TOKEN_EOF, } public class TokenOperators { private readonly Dictionary<string, TokenType> double_char_ops = new Dictionary<string, TokenType>(); private readonly Dictionary<int, TokenType> single_char_ops = new Dictionary<int, TokenType>(); public TokenOperators(TemplateEnvironment env) { single_char_ops.Add('+', TokenType.TOKEN_ADD); single_char_ops.Add('-', TokenType.TOKEN_SUB); single_char_ops.Add('/', TokenType.TOKEN_DIV); single_char_ops.Add('*', TokenType.TOKEN_MUL); single_char_ops.Add('%', TokenType.TOKEN_MOD); single_char_ops.Add('~', TokenType.TOKEN_TILDE); single_char_ops.Add('[', TokenType.TOKEN_LBRACKET); single_char_ops.Add(']', TokenType.TOKEN_RBRACKET); single_char_ops.Add('(', TokenType.TOKEN_LPAREN); single_char_ops.Add(')', TokenType.TOKEN_RPAREN); single_char_ops.Add('{', TokenType.TOKEN_LBRACE); single_char_ops.Add('}', TokenType.TOKEN_RBRACE); single_char_ops.Add('>', TokenType.TOKEN_GT); single_char_ops.Add('<', TokenType.TOKEN_LT); single_char_ops.Add('=', TokenType.TOKEN_ASSIGN); single_char_ops.Add('.', TokenType.TOKEN_DOT); single_char_ops.Add(':', TokenType.TOKEN_COLON); single_char_ops.Add('|', TokenType.TOKEN_PIPE); single_char_ops.Add(',', TokenType.TOKEN_COMMA); single_char_ops.Add(';', TokenType.TOKEN_SEMICOLON); double_char_ops.Add("//", TokenType.TOKEN_FLOORDIV); double_char_ops.Add("**", TokenType.TOKEN_POW); double_char_ops.Add("==", TokenType.TOKEN_EQ); double_char_ops.Add("!=", TokenType.TOKEN_NE); double_char_ops.Add(">=", TokenType.TOKEN_GTEQ); double_char_ops.Add("<=", TokenType.TOKEN_LTEQ); // These should be environment dependendant double_char_ops.Add(env.BlockStartString, TokenType.TOKEN_BLOCK_BEGIN); double_char_ops.Add(env.BlockEndString, TokenType.TOKEN_BLOCK_END); double_char_ops.Add(env.VariableStartString, TokenType.TOKEN_VARIABLE_BEGIN); double_char_ops.Add(env.VariableEndString, TokenType.TOKEN_VARIABLE_END); double_char_ops.Add(env.CommentStartString, TokenType.TOKEN_COMMENT_BEGIN); double_char_ops.Add(env.CommentEndString, TokenType.TOKEN_COMMENT_END); } public Dictionary<int, TokenType> SingleCharOps { get { return single_char_ops; } } public Dictionary<string, TokenType> DoubleCharOps { get { return double_char_ops; } } } }
namespace gView.Framework.Carto.Rendering.UI { partial class PropertyForm_SimpleLabelRenderer { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form 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() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PropertyForm_SimpleLabelRenderer)); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.btnExpression = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.cmbFields = new System.Windows.Forms.ComboBox(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.btnSymbol = new System.Windows.Forms.Button(); this.panelPreview = new System.Windows.Forms.Panel(); this.btnRotation = new System.Windows.Forms.Button(); this.panel1 = new System.Windows.Forms.Panel(); this.gbOrientation = new System.Windows.Forms.GroupBox(); this.btnOrientation = new System.Windows.Forms.Button(); this.groupBox5 = new System.Windows.Forms.GroupBox(); this.radioButton5 = new System.Windows.Forms.RadioButton(); this.radioButton3 = new System.Windows.Forms.RadioButton(); this.radioButton9 = new System.Windows.Forms.RadioButton(); this.radioButton4 = new System.Windows.Forms.RadioButton(); this.radioButton2 = new System.Windows.Forms.RadioButton(); this.radioButton8 = new System.Windows.Forms.RadioButton(); this.radioButton1 = new System.Windows.Forms.RadioButton(); this.radioButton6 = new System.Windows.Forms.RadioButton(); this.radioButton7 = new System.Windows.Forms.RadioButton(); this.groupBox3 = new System.Windows.Forms.GroupBox(); this.cmbLabelPriority = new System.Windows.Forms.ComboBox(); this.label3 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.cmbHowManyLabels = new System.Windows.Forms.ComboBox(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.panel1.SuspendLayout(); this.gbOrientation.SuspendLayout(); this.groupBox5.SuspendLayout(); this.groupBox3.SuspendLayout(); this.SuspendLayout(); // // groupBox1 // this.groupBox1.Controls.Add(this.btnExpression); this.groupBox1.Controls.Add(this.label1); this.groupBox1.Controls.Add(this.cmbFields); resources.ApplyResources(this.groupBox1, "groupBox1"); this.groupBox1.Name = "groupBox1"; this.groupBox1.TabStop = false; // // btnExpression // resources.ApplyResources(this.btnExpression, "btnExpression"); this.btnExpression.Name = "btnExpression"; this.btnExpression.UseVisualStyleBackColor = true; this.btnExpression.Click += new System.EventHandler(this.btnExpression_Click); // // label1 // resources.ApplyResources(this.label1, "label1"); this.label1.Name = "label1"; // // cmbFields // this.cmbFields.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbFields.FormattingEnabled = true; resources.ApplyResources(this.cmbFields, "cmbFields"); this.cmbFields.Name = "cmbFields"; this.cmbFields.SelectedIndexChanged += new System.EventHandler(this.cmbFields_SelectedIndexChanged); // // groupBox2 // this.groupBox2.Controls.Add(this.btnSymbol); this.groupBox2.Controls.Add(this.panelPreview); this.groupBox2.Controls.Add(this.btnRotation); resources.ApplyResources(this.groupBox2, "groupBox2"); this.groupBox2.Name = "groupBox2"; this.groupBox2.TabStop = false; // // btnSymbol // resources.ApplyResources(this.btnSymbol, "btnSymbol"); this.btnSymbol.Name = "btnSymbol"; this.btnSymbol.UseVisualStyleBackColor = true; this.btnSymbol.Click += new System.EventHandler(this.btnSymbol_Click); // // panelPreview // this.panelPreview.BackColor = System.Drawing.Color.White; resources.ApplyResources(this.panelPreview, "panelPreview"); this.panelPreview.Name = "panelPreview"; this.panelPreview.Paint += new System.Windows.Forms.PaintEventHandler(this.panelPreview_Paint); // // btnRotation // resources.ApplyResources(this.btnRotation, "btnRotation"); this.btnRotation.Name = "btnRotation"; this.btnRotation.UseVisualStyleBackColor = true; this.btnRotation.Click += new System.EventHandler(this.btnRotation_Click); // // panel1 // this.panel1.Controls.Add(this.gbOrientation); this.panel1.Controls.Add(this.groupBox5); this.panel1.Controls.Add(this.groupBox3); this.panel1.Controls.Add(this.groupBox1); this.panel1.Controls.Add(this.groupBox2); resources.ApplyResources(this.panel1, "panel1"); this.panel1.Name = "panel1"; // // gbOrientation // this.gbOrientation.Controls.Add(this.btnOrientation); resources.ApplyResources(this.gbOrientation, "gbOrientation"); this.gbOrientation.Name = "gbOrientation"; this.gbOrientation.TabStop = false; // // btnOrientation // resources.ApplyResources(this.btnOrientation, "btnOrientation"); this.btnOrientation.Name = "btnOrientation"; this.btnOrientation.UseVisualStyleBackColor = true; this.btnOrientation.Click += new System.EventHandler(this.btnOrientation_Click); // // groupBox5 // this.groupBox5.Controls.Add(this.radioButton5); this.groupBox5.Controls.Add(this.radioButton3); this.groupBox5.Controls.Add(this.radioButton9); this.groupBox5.Controls.Add(this.radioButton4); this.groupBox5.Controls.Add(this.radioButton2); this.groupBox5.Controls.Add(this.radioButton8); this.groupBox5.Controls.Add(this.radioButton1); this.groupBox5.Controls.Add(this.radioButton6); this.groupBox5.Controls.Add(this.radioButton7); resources.ApplyResources(this.groupBox5, "groupBox5"); this.groupBox5.Name = "groupBox5"; this.groupBox5.TabStop = false; // // radioButton5 // resources.ApplyResources(this.radioButton5, "radioButton5"); this.radioButton5.Name = "radioButton5"; this.radioButton5.TabStop = true; this.radioButton5.UseVisualStyleBackColor = true; this.radioButton5.CheckedChanged += new System.EventHandler(this.radioButton5_CheckedChanged); // // radioButton3 // resources.ApplyResources(this.radioButton3, "radioButton3"); this.radioButton3.Name = "radioButton3"; this.radioButton3.TabStop = true; this.radioButton3.UseVisualStyleBackColor = true; this.radioButton3.CheckedChanged += new System.EventHandler(this.radioButton3_CheckedChanged); // // radioButton9 // resources.ApplyResources(this.radioButton9, "radioButton9"); this.radioButton9.Name = "radioButton9"; this.radioButton9.TabStop = true; this.radioButton9.UseVisualStyleBackColor = true; this.radioButton9.CheckedChanged += new System.EventHandler(this.radioButton9_CheckedChanged); // // radioButton4 // resources.ApplyResources(this.radioButton4, "radioButton4"); this.radioButton4.Name = "radioButton4"; this.radioButton4.TabStop = true; this.radioButton4.UseVisualStyleBackColor = true; this.radioButton4.CheckedChanged += new System.EventHandler(this.radioButton4_CheckedChanged); // // radioButton2 // resources.ApplyResources(this.radioButton2, "radioButton2"); this.radioButton2.Name = "radioButton2"; this.radioButton2.TabStop = true; this.radioButton2.UseVisualStyleBackColor = true; this.radioButton2.CheckedChanged += new System.EventHandler(this.radioButton2_CheckedChanged); // // radioButton8 // resources.ApplyResources(this.radioButton8, "radioButton8"); this.radioButton8.Name = "radioButton8"; this.radioButton8.TabStop = true; this.radioButton8.UseVisualStyleBackColor = true; this.radioButton8.CheckedChanged += new System.EventHandler(this.radioButton8_CheckedChanged); // // radioButton1 // resources.ApplyResources(this.radioButton1, "radioButton1"); this.radioButton1.Name = "radioButton1"; this.radioButton1.TabStop = true; this.radioButton1.UseVisualStyleBackColor = true; this.radioButton1.CheckedChanged += new System.EventHandler(this.radioButton1_CheckedChanged); // // radioButton6 // resources.ApplyResources(this.radioButton6, "radioButton6"); this.radioButton6.Name = "radioButton6"; this.radioButton6.TabStop = true; this.radioButton6.UseVisualStyleBackColor = true; this.radioButton6.CheckedChanged += new System.EventHandler(this.radioButton6_CheckedChanged); // // radioButton7 // resources.ApplyResources(this.radioButton7, "radioButton7"); this.radioButton7.Name = "radioButton7"; this.radioButton7.TabStop = true; this.radioButton7.UseVisualStyleBackColor = true; this.radioButton7.CheckedChanged += new System.EventHandler(this.radioButton7_CheckedChanged); // // groupBox3 // this.groupBox3.Controls.Add(this.cmbLabelPriority); this.groupBox3.Controls.Add(this.label3); this.groupBox3.Controls.Add(this.label2); this.groupBox3.Controls.Add(this.cmbHowManyLabels); resources.ApplyResources(this.groupBox3, "groupBox3"); this.groupBox3.Name = "groupBox3"; this.groupBox3.TabStop = false; // // cmbLabelPriority // this.cmbLabelPriority.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbLabelPriority.FormattingEnabled = true; this.cmbLabelPriority.Items.AddRange(new object[] { resources.GetString("cmbLabelPriority.Items"), resources.GetString("cmbLabelPriority.Items1"), resources.GetString("cmbLabelPriority.Items2"), resources.GetString("cmbLabelPriority.Items3")}); resources.ApplyResources(this.cmbLabelPriority, "cmbLabelPriority"); this.cmbLabelPriority.Name = "cmbLabelPriority"; this.cmbLabelPriority.SelectedIndexChanged += new System.EventHandler(this.cmbLabelPriority_SelectedIndexChanged); // // label3 // resources.ApplyResources(this.label3, "label3"); this.label3.Name = "label3"; // // label2 // resources.ApplyResources(this.label2, "label2"); this.label2.Name = "label2"; // // cmbHowManyLabels // this.cmbHowManyLabels.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbHowManyLabels.FormattingEnabled = true; this.cmbHowManyLabels.Items.AddRange(new object[] { resources.GetString("cmbHowManyLabels.Items"), resources.GetString("cmbHowManyLabels.Items1"), resources.GetString("cmbHowManyLabels.Items2")}); resources.ApplyResources(this.cmbHowManyLabels, "cmbHowManyLabels"); this.cmbHowManyLabels.Name = "cmbHowManyLabels"; this.cmbHowManyLabels.SelectedIndexChanged += new System.EventHandler(this.cmbHowManyLabels_SelectedIndexChanged); // // PropertyForm_SimpleLabelRenderer // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.panel1); this.Name = "PropertyForm_SimpleLabelRenderer"; this.Load += new System.EventHandler(this.PropertyForm_SimpleLabelRenderer_Load); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.groupBox2.ResumeLayout(false); this.panel1.ResumeLayout(false); this.gbOrientation.ResumeLayout(false); this.groupBox5.ResumeLayout(false); this.groupBox5.PerformLayout(); this.groupBox3.ResumeLayout(false); this.groupBox3.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Button btnExpression; private System.Windows.Forms.ComboBox cmbFields; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.Button btnSymbol; public System.Windows.Forms.Panel panel1; private System.Windows.Forms.Panel panelPreview; private System.Windows.Forms.Label label1; private System.Windows.Forms.GroupBox groupBox3; private System.Windows.Forms.ComboBox cmbLabelPriority; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label2; private System.Windows.Forms.ComboBox cmbHowManyLabels; private System.Windows.Forms.Button btnRotation; private System.Windows.Forms.GroupBox gbOrientation; private System.Windows.Forms.Button btnOrientation; private System.Windows.Forms.GroupBox groupBox5; private System.Windows.Forms.RadioButton radioButton5; private System.Windows.Forms.RadioButton radioButton3; private System.Windows.Forms.RadioButton radioButton9; private System.Windows.Forms.RadioButton radioButton4; private System.Windows.Forms.RadioButton radioButton2; private System.Windows.Forms.RadioButton radioButton8; private System.Windows.Forms.RadioButton radioButton1; private System.Windows.Forms.RadioButton radioButton6; private System.Windows.Forms.RadioButton radioButton7; } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; using System.Xml; using Orleans.Runtime; using Orleans.Runtime.Configuration; namespace Orleans.Providers { /// <summary> /// Providers configuration and loading error semantics: /// 1) We will only load the providers that were specified in the config. /// If a provider is not specified in the config, we will not attempt to load it. /// Specificaly, it means both storage and streaming providers are loaded only if configured. /// 2) If a provider is specified in the config, but was not loaded (no type found, or constructor failed, or Init failed), the silo will fail to start. /// /// Loading providers workflow and error handling implementation: /// 1) Load ProviderCategoryConfiguration. /// a) If CategoryConfiguration not found - it is not an error, continue. /// 2) Go over all assemblies and load all found providers and instantiate them via ProviderTypeManager. /// a) If a certain found provider type failed to get instantiated, it is not an error, continue. /// 3) Validate all providers were loaded: go over all provider config and check that we could indeed load and instantiate all of them. /// a) If failed to load or instantiate at least one configured provider, fail the silo start. /// 4) InitProviders: call Init on all loaded providers. /// a) Failure to init a provider wil result in silo failing to start. /// </summary> /// <typeparam name="TProvider"></typeparam> internal class ProviderLoader<TProvider> where TProvider : IProvider { private readonly Dictionary<string, TProvider> providers; private IDictionary<string, IProviderConfiguration> providerConfigs; private readonly Logger logger; public ProviderLoader() { logger = LogManager.GetLogger("ProviderLoader/" + typeof(TProvider).Name, LoggerType.Runtime); providers = new Dictionary<string, TProvider>(); } public void LoadProviders(IDictionary<string, IProviderConfiguration> configs, IProviderManager providerManager) { providerConfigs = configs ?? new Dictionary<string, IProviderConfiguration>(); foreach (IProviderConfiguration providerConfig in providerConfigs.Values) ((ProviderConfiguration)providerConfig).SetProviderManager(providerManager); // Load providers ProviderTypeLoader.AddProviderTypeManager(t => typeof(TProvider).IsAssignableFrom(t), RegisterProviderType); ValidateProviders(); } private void ValidateProviders() { foreach (IProviderConfiguration providerConfig in providerConfigs.Values) { TProvider provider; ProviderConfiguration fullConfig = (ProviderConfiguration) providerConfig; if (providers.TryGetValue(providerConfig.Name, out provider)) { logger.Verbose(ErrorCode.Provider_ProviderLoadedOk, "Provider of type {0} name {1} located ok.", fullConfig.Type, fullConfig.Name); continue; } string msg = string.Format("Provider of type {0} name {1} was not loaded." + "Please check that you deployed the assembly in which the provider class is defined to the execution folder.", fullConfig.Type, fullConfig.Name); logger.Error(ErrorCode.Provider_ConfiguredProviderNotLoaded, msg); throw new OrleansException(msg); } } public async Task InitProviders(IProviderRuntime providerRuntime) { Dictionary<string, TProvider> copy; lock (providers) { copy = providers.ToDictionary(p => p.Key, p => p.Value); } foreach (var provider in copy) { string name = provider.Key; try { await provider.Value.Init(provider.Key, providerRuntime, providerConfigs[name]); } catch (Exception exc) { logger.Error(ErrorCode.Provider_ErrorFromInit, string.Format("Exception initializing provider Name={0} Type={1}", name, provider), exc); throw; } } } // used only for testing internal void AddProvider(string name, TProvider provider, IProviderConfiguration config) { lock (providers) { providers.Add(name, provider); } } internal int GetNumLoadedProviders() { lock (providers) { return providers.Count; } } public TProvider GetProvider(string name, bool caseInsensitive = false) { TProvider provider; if (!TryGetProvider(name, out provider, caseInsensitive)) { throw new KeyNotFoundException(string.Format("Cannot find provider of type {0} with Name={1}", typeof(TProvider).FullName, name)); } return provider; } public bool TryGetProvider(string name, out TProvider provider, bool caseInsensitive = false) { lock (providers) { if (providers.TryGetValue(name, out provider)) return provider != null; if (!caseInsensitive) return provider != null; // Try all lower case if (!providers.TryGetValue(name.ToLowerInvariant(), out provider)) { // Try all upper case providers.TryGetValue(name.ToUpperInvariant(), out provider); } } return provider != null; } public IList<TProvider> GetProviders() { lock (providers) { return providers.Values.ToList(); } } public TProvider GetDefaultProvider(string defaultProviderName) { lock (providers) { TProvider provider; // Use provider named "Default" if present if (!providers.TryGetValue(defaultProviderName, out provider)) { // Otherwise, if there is only a single provider listed, use that if (providers.Count == 1) provider = providers.First().Value; } if (provider != null) return provider; string errMsg = "Cannot find default provider for " + typeof(TProvider); logger.Error(ErrorCode.Provider_NoDefaultProvider, errMsg); throw new InvalidOperationException(errMsg); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private void RegisterProviderType(Type t) { // First, figure out the provider type name var typeName = TypeUtils.GetFullName(t); // Now see if we have any config entries for that type // If there's no config entry, then we don't load the type Type[] constructorBindingTypes = new[] { typeof(string), typeof(XmlElement) }; foreach (var entry in providerConfigs.Values) { var fullConfig = (ProviderConfiguration) entry; if (fullConfig.Type != typeName) continue; // Found one! Now look for an appropriate constructor; try TProvider(string, Dictionary<string,string>) first var constructor = t.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, constructorBindingTypes, null); var parms = new object[] { typeName, entry.Properties }; if (constructor == null) { // See if there's a default constructor to use, if there's no two-parameter constructor constructor = t.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null); parms = new object[0]; } if (constructor == null) continue; TProvider instance; try { instance = (TProvider)constructor.Invoke(parms); } catch (Exception ex) { logger.Warn(ErrorCode.Provider_InstanceConstructionError1, "Error constructing an instance of a " + typeName + " provider using type " + t.Name + " for provider with name " + fullConfig.Name, ex); return; } lock (providers) { providers[fullConfig.Name] = instance; } logger.Info(ErrorCode.Provider_Loaded, "Loaded provider of type {0} Name={1}", typeName, fullConfig.Name); } } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using log4net; namespace DataMigration { /// <summary> /// SqlFeedStager has the responsiblity /// for staging a DataTable input to a staging SQL table, as described in the Plan. In /// addition to the Plan, which drive the Properties of this object, it uses the App.Config /// to get a Sql connection string. /// </summary> public class SqlDataStager : IFeedStager { static readonly ILog log = LogManager.GetLogger(typeof(SqlDataStager)); const string TdsVersionForSqlServerEnvironmentVariable = "TDSVER"; bool useBulkCopy; // This is property-driven, if true, uses Threading.Task for inserting rows one at a time. // This only comes into play if useBulkCopy is false. bool useTaskLibrary; // If useTaskLibrary is on, sometime it crushes the Sql Server, or the net connection. // Using a delay can help. This is driven from properties in the Descriptor, but // it defaults here. int taskDelayMilliseconds = 10; readonly string connectionString; public SqlDataStager() { connectionString = ConfigurationManager.AppSettings["ConnectionString"]; } #region IFeedStager implementation /// <summary> /// Gets or sets the Properties for this FeedStager. This is a set of key-value pairs, /// described in the DataSourcePlan, that have scalar values specific to this /// implementation. /// </summary> /// <value>The properties.</value> public IEnumerable<DescriptorProperty> Properties { get; set; } public string Location { get; set; } public string BadRowsLocation { get; set; } public string WarnRowsLocation { get; set; } /// <summary> /// This is the number of rows at a time the FeedStager will need to process. This /// should be set before calling BulkLoad(), and the DataTable passed to BulkLoad() /// should have this many rows in it. /// </summary> /// <value>The size of the batch.</value> public int BatchSize { get; set; } public int SecondsTimeout { get; set; } /// <summary> /// Gets the load number. This is used by the DataProcessor when building the DataTable /// that gets passed to this FeedStager in BulkLoad, and is used to disambiguate one /// load from another in the staged results. /// </summary> /// <returns>The load number.</returns> public int GetLoadNumber() { try { using (var conn = new SqlConnection(connectionString)) { using (var cmd = new SqlCommand()) { cmd.CommandText = "up_DM_GetLoadNum"; cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = conn; conn.Open(); var loadNum = (decimal)cmd.ExecuteScalar(); return Decimal.ToInt32(loadNum); } } } catch (Exception ex) { throw new Exception(String.Format("GetLoadNumber - error {0}", ex.Message), ex); } } /// <summary> /// This entry point loads the data in the datatable argument into staging. Depending /// on the Properties set for this object (which are driven from the Plan) it will /// either use SqlBulkCopy, or insert rows one at a time into Sql. /// </summary> /// <param name="dataTable">The DataTable with a batch of Data to insert</param> /// <param name="badRowsDataTable">The DataTable with a batch of Bad Rows to insert. /// </param> /// <param name="warnRowsDataTable">The DataTable with a batch of warning rows to /// insert.</param> public void BulkLoad(DataTable dataTable, DataTable badRowsDataTable, DataTable warnRowsDataTable) { if (String.IsNullOrEmpty(connectionString) || String.IsNullOrEmpty(Location)) { throw new InvalidOperationException( String.Format("Cannot perform BulkLoad until Location property set")); } var useBulkCopyString = Utilities.GetProperty("useBulkCopy", Properties, false); if (!bool.TryParse(useBulkCopyString, out useBulkCopy)) { useBulkCopy = false; } // Disabling bulkCopy on mono for now; it works with NAMG, but there's a problem // with freebcp bulk copying to the StageLoadMemberApi table; this is low priority // to fix, since the row-by-row insert works fine. var runtimeType = Type.GetType ("Mono.Runtime"); if (runtimeType != null) { useBulkCopy = false; } if (useBulkCopy) { DoBulkCopy(dataTable, Location); DoBulkCopy(badRowsDataTable, BadRowsLocation); DoBulkCopy(warnRowsDataTable, WarnRowsLocation); } else { // Grovel through the Properties collection, looking for properties that // qualify how the Row By Row insertion is to be done. // Check and see if we're to use the TPL. var useTaskLibraryString = Utilities.GetProperty("useTaskLibrary", Properties, false); if (!String.IsNullOrEmpty(useTaskLibraryString) && !bool.TryParse(useTaskLibraryString, out useTaskLibrary)) { useTaskLibrary = false; } // Check to see if we want to add a millisecond-based delay on each task. // This is sometimes necessary on slow connections or the Database is slow. var taskDelayMillisecondsString = Utilities.GetProperty("taskDelayMilliseconds", Properties, false); if (!String.IsNullOrEmpty(taskDelayMillisecondsString)) { int.TryParse(taskDelayMillisecondsString, out taskDelayMilliseconds); } InsertRowByRow(dataTable, Location); InsertRowByRow(badRowsDataTable, BadRowsLocation); } } #endregion /// <summary> /// Inserts an entire datatabe, one row at a time. This is a fallback method; driven /// by the Plan; we're using it until we can get a version of Mono with the SqlBulkCopy /// fixed. /// </summary> /// <param name="dataTable"> The DataTable with the data to insert.</param> /// <param name="tableName"> The name of the Sql table to insert to. </param> void InsertRowByRow(DataTable dataTable, string tableName) { if (dataTable.Rows.Count == 0) { return; } var rowNum = 0; var colNames = new List<String>(); // Due to some vagary of the DataColumnCollection class, you can't use the 'var' // implicit typing construct here; it won't compile. It's not an IEnumerable // either, so you can't Select to get the column names out. var firstBuilder = new StringBuilder("insert into " + tableName + "("); foreach (DataColumn col in dataTable.Columns) { if (col.ColumnName.Equals(FeedProcessor.IdString, StringComparison.OrdinalIgnoreCase)) { continue; // Do not add the Id column to the insert statement. } colNames.Add(col.ColumnName); } firstBuilder.Append(String.Join(",", colNames) + ") VALUES("); var commandPrefix = firstBuilder.ToString(); if (useTaskLibrary) { try { var taskArray = new Task[dataTable.Rows.Count]; foreach (DataRow dr in dataTable.Rows) { var cmdStr = FormSqlCmdString(commandPrefix, dataTable, dr); taskArray[rowNum] = Task.Factory.StartNew(() => TaskWorker(cmdStr, true)); rowNum++; } Task.WaitAll(taskArray); } catch (AggregateException aggregateException) { var flattenedException = aggregateException.Flatten(); var message = String.Join(",", flattenedException.InnerExceptions. Select(innerEx => innerEx.Message).ToArray()); throw new Exception(String.Format("InsertRowByRow -aggregateExceptions " + "caught, errors = {0}", message), flattenedException); } } else { // We're not using multiple tasks to do this. foreach (DataRow dr in dataTable.Rows) { var cmdStr = FormSqlCmdString(commandPrefix, dataTable, dr); TaskWorker(cmdStr); rowNum++; } } log.DebugFormat("Successfully inserted {0} rows to staging table {1}", rowNum, tableName); } /// <summary> /// This is just a delegate for the TPL to use. When we're not using the TPL, it's /// called sequentially in a loop. /// </summary> /// <param name="commandString">Sql command string.</param> /// <param name="delay">If set to <c>true</c> delay by 'taskDelayMilliseconds'.</param> void TaskWorker(String commandString, bool delay = false) { using (var conn = new SqlConnection(connectionString)) { conn.Open(); //log.Debug (cmdStr); ExecuteSingleInsert(commandString, conn); } if (delay && taskDelayMilliseconds > 0) { System.Threading.Thread.Sleep(taskDelayMilliseconds); } } /// <summary> /// Uses SqlBulkCopy (bcp) to blow an entire datatable (a single batch of data rows) /// into the Sql table. /// </summary> /// <param name="dataTable">The Datatable to copy into staging.</param> /// <param name="tableName">The SQL table that holds the staging data.</param> void DoBulkCopy(DataTable dataTable, string tableName) { if (dataTable.Rows.Count == 0 || String.IsNullOrWhiteSpace(tableName)) { return; } // This is a hack, but I believe it is an acceptable hack to workaround the bug // in Mono's implementation of SqlBulkCopy until they get around to fixing it; I // submitted it to Mono's Bugzilla database April 4, 2014. var runtimeType = Type.GetType ("Mono.Runtime"); if (runtimeType == null) { // We're running on Windows, so we can use the SqlBulkCopy class. try { using (var conn = new SqlConnection(connectionString)) { conn.Open(); using (var bc = new SqlBulkCopy(conn) { BatchSize = BatchSize, BulkCopyTimeout = SecondsTimeout, DestinationTableName = tableName }) { bc.WriteToServer(dataTable); log.DebugFormat("Successfully bulk copied {0} rows to {1}", dataTable.Rows.Count, tableName); } } } catch (Exception ex) { throw new Exception(String.Format("BulkLoad - error = {0}", ex.Message), ex); } } else { // we're on Mono - use freebcp. var bcpFileFullPath = WriteOutBcpFile(dataTable); UseFreeBcpToBulkCopyIntoSql(bcpFileFullPath, tableName); try { if (File.Exists(bcpFileFullPath)) { File.Delete(bcpFileFullPath); } } catch (Exception ex) { log.WarnFormat("Error deleting bcp file, continuing on, error = {0}", ex.Message); } } } /// <summary> /// Builds the Sql text command to insert a single row into the staging db table. /// </summary> /// <returns>The sql cmd string.</returns> /// <param name="cmdStart">This string has the first reusable part of the insert /// command, i.e. 'Insert Into foo(col1, col2, etc)VALUES('. It's this method's /// responsibility to add the actual scalar values, and close the parentheses. /// </param> /// <param name="dt">The DataTable which describes the columns.</param> /// <param name="dr">The DataRow with the values.</param> static string FormSqlCmdString(string cmdStart, DataTable dt, DataRow dr) { var sb = new StringBuilder(cmdStart); var valList = new List<string>(); foreach (DataColumn col in dt.Columns) { if (col.ColumnName.Equals(FeedProcessor.IdString, StringComparison.OrdinalIgnoreCase)) { continue; // Do not add the Id column to the insert statement. } var oVal = dr[col.ColumnName]; var isNull = oVal == DBNull.Value; var sVal = isNull ? "null" : oVal.ToString(); if (col.DataType == typeof(String) || col.DataType == typeof(DateTime)) { if (!isNull) { sVal = sVal.Replace("'", "''"); valList.Add("'" + sVal + "'"); } else { valList.Add("null"); } } else { if (col.DataType == typeof(bool)) { sVal = String.Equals(sVal, "True", StringComparison.OrdinalIgnoreCase) ? "1" : "0"; } valList.Add(sVal); } } sb.Append(String.Join(",", valList) + ")"); return sb.ToString(); } /// <summary> /// Given a fully formed sql command, and an open connection, executes the insert. /// </summary> /// <param name="command">The insertion command.</param> /// <param name="conn">An open Sql Connection.</param> static void ExecuteSingleInsert(string command, SqlConnection conn) { try { using (var cmd = new SqlCommand(command, conn)) { cmd.ExecuteNonQuery(); } } catch (Exception ex) { throw new Exception( String.Format( "ExecuteSingleInsert - error executing statement {0} err = {1}", command, ex.Message), ex); } } /// <summary> /// On Linux/Mono, we need to write out a bcp file to disk, then spawn freebcp to run /// it. This function just writes it to a tempfileName. /// </summary> /// <returns>The temporary bcp file written to disk. Callers are responsible for /// cleaning this file up (i.e. deleting it when done).</returns> /// <param name="dataTable">The datatable with the data to write to the file.</param> string WriteOutBcpFile(DataTable dataTable) { var bcpFileFullPath = Path.GetTempFileName(); try { using (var bcpFileWriter = File.CreateText(bcpFileFullPath)) { foreach (DataRow dataRow in dataTable.Rows) { var rowText = new List<string>(); // Can't use 'var' syntax here, the DataColumn objects come out as // typeless objects that way. foreach (DataColumn column in dataTable.Columns) { var dataObject = dataRow[column.ColumnName]; if (column.ColumnName.Equals("id", StringComparison.OrdinalIgnoreCase)) { rowText.Add("1"); } else if (DBNull.Value == dataObject) { rowText.Add(String.Empty); } else { if (column.DataType == typeof(bool)) { rowText.Add((bool) dataObject ? "1" : "0"); } else if (column.DataType == typeof(DateTime)) { rowText.Add(((DateTime) dataObject) .ToString("yyyy-MM-dd HH:mm:ss.fff")); } else { rowText.Add(dataObject.ToString()); } } } // Write out the row, tab-separated, and then write a new line. bcpFileWriter.Write(String.Join("\t", rowText.ToArray())); bcpFileWriter.Write("\t"); bcpFileWriter.WriteLine(); } } } catch (Exception ex) { throw new Exception(String.Format("WriteOutBcpFile - error writing file {0}" + " error = {1}", bcpFileFullPath, ex.Message), ex); } return bcpFileFullPath; } /// <summary> /// Uses freebcp, a utility from freetds package, to copy from a bcp file we've put /// on the file system into Sql Server. /// </summary> /// <param name="bcpFileFullPath">Bcp file full path.</param> /// <param name="tableName">Table name to copy to.</param> void UseFreeBcpToBulkCopyIntoSql(string bcpFileFullPath, string tableName) { SetTdsVersionEnvironmentVariable(); var tokens = connectionString.Split(';'); var databaseName = ExtractConnectionStringValue(tokens, "database"); var databaseTableName = databaseName + ".dbo." + tableName; var serverName = ExtractConnectionStringValue(tokens, "server"); // This is on Linux that this code runs, so we can assume Sql Server Authentication // rather than Trusted Authentication, so we need a username and password from the // connection string. var userName = ExtractConnectionStringValue(tokens, "user"); var password = ExtractConnectionStringValue(tokens, "password"); var process = new Process { StartInfo = { FileName = "freebcp", Arguments = String.Format("{0} in {1} -S {2} -U {3} -P {4} -c", databaseTableName, bcpFileFullPath, serverName, userName, password), UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true } }; process.OutputDataReceived += StdoutHandler; process.ErrorDataReceived += StderrHandler; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); while (!process.HasExited) { process.WaitForExit(1000); } // Need to make this additional call to make sure stdout and stderr are flushed. process.WaitForExit(); if (0 != process.ExitCode) { throw new Exception(String.Format("UseFreeBcpToBulkCopyIntoSql - freebcp " + "process returned exit code {0}", process.ExitCode)); } } /// <summary> /// Print stdout to the debug log. /// </summary> private void StdoutHandler(object sender, DataReceivedEventArgs e) { if (e.Data == null) return; var message = e.Data as string; if (String.IsNullOrEmpty(message)) return; log.Debug(message); } /// <summary> /// Prints stderr to the debug log. /// </summary> private void StderrHandler(object sender, DataReceivedEventArgs e) { if (e.Data == null) return; var error = e.Data as string; if (String.IsNullOrEmpty(error)) return; log.Error(error); } /// <summary> /// Extracts a value from the connection string. We parse the connection string /// instead of providing properties for the SqlDataStager in the plan because we want /// to allow the same plan to work on different configs, when the database name is /// different (e.g. 'cpms_test2', instead of just 'cpms'), and using different logons /// and so forth. This function only gets called when we're on Mono/Linux, and so /// we have to use Sql Server Authentication (rather than Trusted), and therefore the /// relevant information is in the connection string. /// </summary> /// <returns>A value from the connection string.</returns> /// <param name="tokens">The connection string, broken into tokens.</param> /// <param name="key">The key we're looking for.</param> string ExtractConnectionStringValue(string[] tokens, string key) { var matchingToken = tokens.SingleOrDefault(token => token.StartsWith(key, StringComparison.OrdinalIgnoreCase)); if (String.IsNullOrEmpty(matchingToken)) { throw new Exception(String.Format("ExtractConnectionStringValue-cannot parse" + " out {0} value from connectionString = '{1}', this is needed for freebcp", key, connectionString)); } if (!matchingToken.Contains("=")) { throw new Exception(String.Format("ExtractConnectionStringValue - found {0} " + "token '{0}' but no '=', so don't know what to make of it", matchingToken)); } tokens = matchingToken.Split('='); return tokens[1]; } /// <summary> /// OpenBcp requires us to set an enviroment variable to talk to SQL Server. This is /// the equivalent of doing 'export TDSVER=7.0' from the bash shell. We're driving /// the value from the properties for the SqlDataStager in the Plan, instead of hard- /// coding the '7.0' value. /// </summary> void SetTdsVersionEnvironmentVariable() { var versionString = Utilities.GetRequiredProperty("TdsVersionForSqlServer", Properties); // It appears to be necessary to let freebcp know that it's Sql Server it's talking // to. Environment.SetEnvironmentVariable(TdsVersionForSqlServerEnvironmentVariable, versionString); } } }
// // Copyright (c) Microsoft and contributors. 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 // // 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. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Common.Internals; using Microsoft.WindowsAzure.Management.ExpressRoute; using Microsoft.WindowsAzure.Management.ExpressRoute.Models; namespace Microsoft.WindowsAzure.Management.ExpressRoute { internal partial class BorderGatewayProtocolPeeringOperations : IServiceOperations<ExpressRouteManagementClient>, Microsoft.WindowsAzure.Management.ExpressRoute.IBorderGatewayProtocolPeeringOperations { /// <summary> /// Initializes a new instance of the /// BorderGatewayProtocolPeeringOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal BorderGatewayProtocolPeeringOperations(ExpressRouteManagementClient client) { this._client = client; } private ExpressRouteManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.ExpressRoute.ExpressRouteManagementClient. /// </summary> public ExpressRouteManagementClient Client { get { return this._client; } } /// <summary> /// The New Border Gateway Protocol Peering operation creates a new /// Border Gateway Protocol Peering /// </summary> /// <param name='serviceKey'> /// Required. The service key representing the relationship between /// Azure and the customer. /// </param> /// <param name='accessType'> /// Required. Whether the peering is private or public. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the New Border Gateway Protocol /// Peering operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.ExpressRoute.Models.ExpressRouteOperationResponse> BeginNewAsync(string serviceKey, BgpPeeringAccessType accessType, BorderGatewayProtocolPeeringNewParameters parameters, CancellationToken cancellationToken) { // Validate if (serviceKey == null) { throw new ArgumentNullException("serviceKey"); } if (serviceKey.Length > 36) { throw new ArgumentOutOfRangeException("serviceKey"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.PrimaryPeerSubnet == null) { throw new ArgumentNullException("parameters.PrimaryPeerSubnet"); } if (parameters.PrimaryPeerSubnet.Length > 18) { throw new ArgumentOutOfRangeException("parameters.PrimaryPeerSubnet"); } if (parameters.SecondaryPeerSubnet == null) { throw new ArgumentNullException("parameters.SecondaryPeerSubnet"); } if (parameters.SecondaryPeerSubnet.Length > 18) { throw new ArgumentOutOfRangeException("parameters.SecondaryPeerSubnet"); } if (parameters.SharedKey != null && parameters.SharedKey.Length < 6) { throw new ArgumentOutOfRangeException("parameters.SharedKey"); } if (parameters.SharedKey != null && parameters.SharedKey.Length > 24) { throw new ArgumentOutOfRangeException("parameters.SharedKey"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceKey", serviceKey); tracingParameters.Add("accessType", accessType); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "BeginNewAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/networking/dedicatedcircuits/" + serviceKey.Trim() + "/bgppeerings/" + accessType + "?api-version=1.0"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2011-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement createBgpPeeringElement = new XElement(XName.Get("CreateBgpPeering", "http://schemas.microsoft.com/windowsazure")); requestDoc.Add(createBgpPeeringElement); XElement peerAsnElement = new XElement(XName.Get("PeerAsn", "http://schemas.microsoft.com/windowsazure")); peerAsnElement.Value = parameters.PeerAutonomousSystemNumber.ToString(); createBgpPeeringElement.Add(peerAsnElement); XElement primaryPeerSubnetElement = new XElement(XName.Get("PrimaryPeerSubnet", "http://schemas.microsoft.com/windowsazure")); primaryPeerSubnetElement.Value = parameters.PrimaryPeerSubnet; createBgpPeeringElement.Add(primaryPeerSubnetElement); XElement secondaryPeerSubnetElement = new XElement(XName.Get("SecondaryPeerSubnet", "http://schemas.microsoft.com/windowsazure")); secondaryPeerSubnetElement.Value = parameters.SecondaryPeerSubnet; createBgpPeeringElement.Add(secondaryPeerSubnetElement); if (parameters.SharedKey != null) { XElement sharedKeyElement = new XElement(XName.Get("SharedKey", "http://schemas.microsoft.com/windowsazure")); sharedKeyElement.Value = parameters.SharedKey; createBgpPeeringElement.Add(sharedKeyElement); } XElement vlanIdElement = new XElement(XName.Get("VlanId", "http://schemas.microsoft.com/windowsazure")); vlanIdElement.Value = parameters.VirtualLanId.ToString(); createBgpPeeringElement.Add(vlanIdElement); requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result ExpressRouteOperationResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ExpressRouteOperationResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement gatewayOperationAsyncResponseElement = responseDoc.Element(XName.Get("GatewayOperationAsyncResponse", "http://schemas.microsoft.com/windowsazure")); if (gatewayOperationAsyncResponseElement != null) { XElement idElement = gatewayOperationAsyncResponseElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure")); if (idElement != null) { string idInstance = idElement.Value; result.OperationId = idInstance; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Remove Border Gateway Protocol Peering operation deletes an /// existing border gateway protocol peering. /// </summary> /// <param name='serviceKey'> /// Required. Service Key representing the border gateway protocol /// peering to be deleted. /// </param> /// <param name='accessType'> /// Required. Whether the peering is private or public. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.ExpressRoute.Models.ExpressRouteOperationResponse> BeginRemoveAsync(string serviceKey, BgpPeeringAccessType accessType, CancellationToken cancellationToken) { // Validate if (serviceKey == null) { throw new ArgumentNullException("serviceKey"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceKey", serviceKey); tracingParameters.Add("accessType", accessType); Tracing.Enter(invocationId, this, "BeginRemoveAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/networking/dedicatedcircuits/" + serviceKey.Trim() + "/bgppeerings/" + accessType + "?api-version=1.0"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2011-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result ExpressRouteOperationResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ExpressRouteOperationResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement gatewayOperationAsyncResponseElement = responseDoc.Element(XName.Get("GatewayOperationAsyncResponse", "http://schemas.microsoft.com/windowsazure")); if (gatewayOperationAsyncResponseElement != null) { XElement idElement = gatewayOperationAsyncResponseElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure")); if (idElement != null) { string idInstance = idElement.Value; result.OperationId = idInstance; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Update Border Gateway Protocol Peering operation updates an /// existing bgp peering. /// </summary> /// <param name='serviceKey'> /// Required. The service key representing the relationship between /// Azure and the customer. /// </param> /// <param name='accessType'> /// Required. Whether the peering is private or public. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Update Border Gateway Protocol /// Peering operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.ExpressRoute.Models.ExpressRouteOperationResponse> BeginUpdateAsync(string serviceKey, BgpPeeringAccessType accessType, BorderGatewayProtocolPeeringUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (serviceKey == null) { throw new ArgumentNullException("serviceKey"); } if (serviceKey.Length > 36) { throw new ArgumentOutOfRangeException("serviceKey"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.PrimaryPeerSubnet != null && parameters.PrimaryPeerSubnet.Length > 18) { throw new ArgumentOutOfRangeException("parameters.PrimaryPeerSubnet"); } if (parameters.SecondaryPeerSubnet != null && parameters.SecondaryPeerSubnet.Length > 18) { throw new ArgumentOutOfRangeException("parameters.SecondaryPeerSubnet"); } if (parameters.SharedKey != null && parameters.SharedKey.Length < 6) { throw new ArgumentOutOfRangeException("parameters.SharedKey"); } if (parameters.SharedKey != null && parameters.SharedKey.Length > 24) { throw new ArgumentOutOfRangeException("parameters.SharedKey"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceKey", serviceKey); tracingParameters.Add("accessType", accessType); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "BeginUpdateAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/networking/dedicatedcircuits/" + serviceKey.Trim() + "/bgppeerings/" + accessType + "?api-version=1.0"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2011-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement updateBgpPeeringElement = new XElement(XName.Get("UpdateBgpPeering", "http://schemas.microsoft.com/windowsazure")); requestDoc.Add(updateBgpPeeringElement); XElement peerAsnElement = new XElement(XName.Get("PeerAsn", "http://schemas.microsoft.com/windowsazure")); peerAsnElement.Value = parameters.PeerAutonomousSystemNumber.ToString(); updateBgpPeeringElement.Add(peerAsnElement); if (parameters.PrimaryPeerSubnet != null) { XElement primaryPeerSubnetElement = new XElement(XName.Get("PrimaryPeerSubnet", "http://schemas.microsoft.com/windowsazure")); primaryPeerSubnetElement.Value = parameters.PrimaryPeerSubnet; updateBgpPeeringElement.Add(primaryPeerSubnetElement); } if (parameters.SecondaryPeerSubnet != null) { XElement secondaryPeerSubnetElement = new XElement(XName.Get("SecondaryPeerSubnet", "http://schemas.microsoft.com/windowsazure")); secondaryPeerSubnetElement.Value = parameters.SecondaryPeerSubnet; updateBgpPeeringElement.Add(secondaryPeerSubnetElement); } if (parameters.SharedKey != null) { XElement sharedKeyElement = new XElement(XName.Get("SharedKey", "http://schemas.microsoft.com/windowsazure")); sharedKeyElement.Value = parameters.SharedKey; updateBgpPeeringElement.Add(sharedKeyElement); } XElement vlanIdElement = new XElement(XName.Get("VlanId", "http://schemas.microsoft.com/windowsazure")); vlanIdElement.Value = parameters.VirtualLanId.ToString(); updateBgpPeeringElement.Add(vlanIdElement); requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result ExpressRouteOperationResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ExpressRouteOperationResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement gatewayOperationAsyncResponseElement = responseDoc.Element(XName.Get("GatewayOperationAsyncResponse", "http://schemas.microsoft.com/windowsazure")); if (gatewayOperationAsyncResponseElement != null) { XElement idElement = gatewayOperationAsyncResponseElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure")); if (idElement != null) { string idInstance = idElement.Value; result.OperationId = idInstance; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Get Border Gateway Protocol Peering operation retrieves the bgp /// peering for the dedicated circuit with the specified service key. /// </summary> /// <param name='serviceKey'> /// Required. The servicee key representing the dedicated circuit. /// </param> /// <param name='accessType'> /// Required. Whether the peering is private or public. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Get Border Gateway Protocol Peering Operation Response. /// </returns> public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.ExpressRoute.Models.BorderGatewayProtocolPeeringGetResponse> GetAsync(string serviceKey, BgpPeeringAccessType accessType, CancellationToken cancellationToken) { // Validate if (serviceKey == null) { throw new ArgumentNullException("serviceKey"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceKey", serviceKey); tracingParameters.Add("accessType", accessType); Tracing.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/networking/dedicatedcircuits/" + serviceKey.Trim() + "/bgppeerings/" + accessType + "?api-version=1.0"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2011-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result BorderGatewayProtocolPeeringGetResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new BorderGatewayProtocolPeeringGetResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement bgpPeeringElement = responseDoc.Element(XName.Get("BgpPeering", "http://schemas.microsoft.com/windowsazure")); if (bgpPeeringElement != null) { AzureBgpPeering bgpPeeringInstance = new AzureBgpPeering(); result.BgpPeering = bgpPeeringInstance; XElement azureAsnElement = bgpPeeringElement.Element(XName.Get("AzureAsn", "http://schemas.microsoft.com/windowsazure")); if (azureAsnElement != null) { uint azureAsnInstance = uint.Parse(azureAsnElement.Value, CultureInfo.InvariantCulture); bgpPeeringInstance.AzureAsn = azureAsnInstance; } XElement peerAsnElement = bgpPeeringElement.Element(XName.Get("PeerAsn", "http://schemas.microsoft.com/windowsazure")); if (peerAsnElement != null) { uint peerAsnInstance = uint.Parse(peerAsnElement.Value, CultureInfo.InvariantCulture); bgpPeeringInstance.PeerAsn = peerAsnInstance; } XElement primaryAzurePortElement = bgpPeeringElement.Element(XName.Get("PrimaryAzurePort", "http://schemas.microsoft.com/windowsazure")); if (primaryAzurePortElement != null) { string primaryAzurePortInstance = primaryAzurePortElement.Value; bgpPeeringInstance.PrimaryAzurePort = primaryAzurePortInstance; } XElement primaryPeerSubnetElement = bgpPeeringElement.Element(XName.Get("PrimaryPeerSubnet", "http://schemas.microsoft.com/windowsazure")); if (primaryPeerSubnetElement != null) { string primaryPeerSubnetInstance = primaryPeerSubnetElement.Value; bgpPeeringInstance.PrimaryPeerSubnet = primaryPeerSubnetInstance; } XElement secondaryAzurePortElement = bgpPeeringElement.Element(XName.Get("SecondaryAzurePort", "http://schemas.microsoft.com/windowsazure")); if (secondaryAzurePortElement != null) { string secondaryAzurePortInstance = secondaryAzurePortElement.Value; bgpPeeringInstance.SecondaryAzurePort = secondaryAzurePortInstance; } XElement secondaryPeerSubnetElement = bgpPeeringElement.Element(XName.Get("SecondaryPeerSubnet", "http://schemas.microsoft.com/windowsazure")); if (secondaryPeerSubnetElement != null) { string secondaryPeerSubnetInstance = secondaryPeerSubnetElement.Value; bgpPeeringInstance.SecondaryPeerSubnet = secondaryPeerSubnetInstance; } XElement stateElement = bgpPeeringElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure")); if (stateElement != null) { BgpPeeringState stateInstance = ((BgpPeeringState)Enum.Parse(typeof(BgpPeeringState), stateElement.Value, true)); bgpPeeringInstance.State = stateInstance; } XElement vlanIdElement = bgpPeeringElement.Element(XName.Get("VlanId", "http://schemas.microsoft.com/windowsazure")); if (vlanIdElement != null) { uint vlanIdInstance = uint.Parse(vlanIdElement.Value, CultureInfo.InvariantCulture); bgpPeeringInstance.VlanId = vlanIdInstance; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The New Border Gateway Protocol Peering operation creates a new /// border gateway protocol peering associated with the dedicated /// circuit specified by the service key provided. /// </summary> /// <param name='serviceKey'> /// Required. The service key representing the relationship between /// Azure and the customer. /// </param> /// <param name='accessType'> /// Required. Whether the peering is private or public. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the New Bgp Peering operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Get Border Gateway Protocol Peering Operation Response. /// </returns> public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.ExpressRoute.Models.BorderGatewayProtocolPeeringGetResponse> NewAsync(string serviceKey, BgpPeeringAccessType accessType, BorderGatewayProtocolPeeringNewParameters parameters, CancellationToken cancellationToken) { // Validate if (serviceKey == null) { throw new ArgumentNullException("serviceKey"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.PrimaryPeerSubnet == null) { throw new ArgumentNullException("parameters.PrimaryPeerSubnet"); } if (parameters.PrimaryPeerSubnet.Length > 18) { throw new ArgumentOutOfRangeException("parameters.PrimaryPeerSubnet"); } if (parameters.SecondaryPeerSubnet == null) { throw new ArgumentNullException("parameters.SecondaryPeerSubnet"); } if (parameters.SecondaryPeerSubnet.Length > 18) { throw new ArgumentOutOfRangeException("parameters.SecondaryPeerSubnet"); } if (parameters.SharedKey != null && parameters.SharedKey.Length < 6) { throw new ArgumentOutOfRangeException("parameters.SharedKey"); } if (parameters.SharedKey != null && parameters.SharedKey.Length > 24) { throw new ArgumentOutOfRangeException("parameters.SharedKey"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceKey", serviceKey); tracingParameters.Add("accessType", accessType); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "NewAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/networking/dedicatedcircuits/" + serviceKey.Trim() + "/bgppeerings/" + accessType + "?api-version=1.0"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode >= HttpStatusCode.BadRequest) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result BorderGatewayProtocolPeeringGetResponse result = null; result = new BorderGatewayProtocolPeeringGetResponse(); result.StatusCode = statusCode; if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Remove Border Gateway Protocol Peering operation deletes an /// existing border gateway protocol peering. /// </summary> /// <param name='serviceKey'> /// Required. Service key associated with the border gateway protocol /// peering to be deleted. /// </param> /// <param name='accessType'> /// Required. Whether the peering is private or public. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.ExpressRoute.Models.ExpressRouteOperationStatusResponse> RemoveAsync(string serviceKey, BgpPeeringAccessType accessType, CancellationToken cancellationToken) { // Validate if (serviceKey == null) { throw new ArgumentNullException("serviceKey"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceKey", serviceKey); tracingParameters.Add("accessType", accessType); Tracing.Enter(invocationId, this, "RemoveAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/networking/dedicatedcircuits/" + serviceKey.Trim() + "/bgppeerings/" + accessType + "?api-version=1.0"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode >= HttpStatusCode.BadRequest) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result ExpressRouteOperationStatusResponse result = null; result = new ExpressRouteOperationStatusResponse(); result.StatusCode = statusCode; if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Update Border Gateway Protocol Peering operation updates an /// existing border gateway protocol peering or creates a new one if /// one doesn't exist. /// </summary> /// <param name='serviceKey'> /// Required. The service key representing the relationship between /// Azure and the customer. /// </param> /// <param name='accessType'> /// Required. Whether the peering is private or public. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Update Border Gateway Protocol /// Peering operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Get Border Gateway Protocol Peering Operation Response. /// </returns> public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.ExpressRoute.Models.BorderGatewayProtocolPeeringGetResponse> UpdateAsync(string serviceKey, BgpPeeringAccessType accessType, BorderGatewayProtocolPeeringUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (serviceKey == null) { throw new ArgumentNullException("serviceKey"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.PrimaryPeerSubnet != null && parameters.PrimaryPeerSubnet.Length > 18) { throw new ArgumentOutOfRangeException("parameters.PrimaryPeerSubnet"); } if (parameters.SecondaryPeerSubnet != null && parameters.SecondaryPeerSubnet.Length > 18) { throw new ArgumentOutOfRangeException("parameters.SecondaryPeerSubnet"); } if (parameters.SharedKey != null && parameters.SharedKey.Length < 6) { throw new ArgumentOutOfRangeException("parameters.SharedKey"); } if (parameters.SharedKey != null && parameters.SharedKey.Length > 24) { throw new ArgumentOutOfRangeException("parameters.SharedKey"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceKey", serviceKey); tracingParameters.Add("accessType", accessType); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "UpdateAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/networking/dedicatedcircuits/" + serviceKey.Trim() + "/bgppeering?api-version=1.0"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode >= HttpStatusCode.BadRequest) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result BorderGatewayProtocolPeeringGetResponse result = null; result = new BorderGatewayProtocolPeeringGetResponse(); result.StatusCode = statusCode; if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
/* * 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.IO; using System.Reflection; using System.Threading; using System.Xml; using log4net; using Nini.Config; using OpenSim.Framework; namespace OpenSim { /// <summary> /// Loads the Configuration files into nIni /// </summary> public class ConfigurationLoader { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Various Config settings the region needs to start /// Physics Engine, Mesh Engine, GridMode, PhysicsPrim allowed, Neighbor, /// StorageDLL, Storage Connection String, Estate connection String, Client Stack /// Standalone settings. /// </summary> protected ConfigSettings m_configSettings; /// <summary> /// A source of Configuration data /// </summary> protected OpenSimConfigSource m_config; /// <summary> /// Grid Service Information. This refers to classes and addresses of the grid service /// </summary> protected NetworkServersInfo m_networkServersInfo; /// <summary> /// Loads the region configuration /// </summary> /// <param name="argvSource">Parameters passed into the process when started</param> /// <param name="configSettings"></param> /// <param name="networkInfo"></param> /// <returns>A configuration that gets passed to modules</returns> public OpenSimConfigSource LoadConfigSettings( IConfigSource argvSource, out ConfigSettings configSettings, out NetworkServersInfo networkInfo) { m_configSettings = configSettings = new ConfigSettings(); m_networkServersInfo = networkInfo = new NetworkServersInfo(); bool iniFileExists = false; IConfig startupConfig = argvSource.Configs["Startup"]; List<string> sources = new List<string>(); string masterFileName = startupConfig.GetString("inimaster", "OpenSimDefaults.ini"); if (masterFileName == "none") masterFileName = String.Empty; if (IsUri(masterFileName)) { if (!sources.Contains(masterFileName)) sources.Add(masterFileName); } else { string masterFilePath = Path.GetFullPath( Path.Combine(Util.configDir(), masterFileName)); if (masterFileName != String.Empty) { if (File.Exists(masterFilePath)) { if (!sources.Contains(masterFilePath)) sources.Add(masterFilePath); } else { m_log.ErrorFormat("Master ini file {0} not found", masterFilePath); Environment.Exit(1); } } } string iniFileName = startupConfig.GetString("inifile", "OpenSim.ini"); if (IsUri(iniFileName)) { if (!sources.Contains(iniFileName)) sources.Add(iniFileName); Application.iniFilePath = iniFileName; } else { Application.iniFilePath = Path.GetFullPath( Path.Combine(Util.configDir(), iniFileName)); if (!File.Exists(Application.iniFilePath)) { iniFileName = "OpenSim.xml"; Application.iniFilePath = Path.GetFullPath( Path.Combine(Util.configDir(), iniFileName)); } if (File.Exists(Application.iniFilePath)) { if (!sources.Contains(Application.iniFilePath)) sources.Add(Application.iniFilePath); } } string iniDirName = startupConfig.GetString("inidirectory", "config"); string iniDirPath = Path.Combine(Util.configDir(), iniDirName); if (Directory.Exists(iniDirPath)) { m_log.InfoFormat("Searching folder {0} for config ini files", iniDirPath); string[] fileEntries = Directory.GetFiles(iniDirName); foreach (string filePath in fileEntries) { if (Path.GetExtension(filePath).ToLower() == ".ini") { if (!sources.Contains(Path.GetFullPath(filePath))) sources.Add(Path.GetFullPath(filePath)); } } } m_config = new OpenSimConfigSource(); m_config.Source = new IniConfigSource(); m_config.Source.Merge(DefaultConfig()); m_log.Info("[CONFIG]: Reading configuration settings"); if (sources.Count == 0) { m_log.FatalFormat("[CONFIG]: Could not load any configuration"); m_log.FatalFormat("[CONFIG]: Did you copy the OpenSimDefaults.ini.example file to OpenSimDefaults.ini?"); Environment.Exit(1); } for (int i = 0 ; i < sources.Count ; i++) { if (ReadConfig(sources[i])) { iniFileExists = true; AddIncludes(sources); } } if (!iniFileExists) { m_log.FatalFormat("[CONFIG]: Could not load any configuration"); m_log.FatalFormat("[CONFIG]: Configuration exists, but there was an error loading it!"); Environment.Exit(1); } // Make sure command line options take precedence m_config.Source.Merge(argvSource); ReadConfigSettings(); return m_config; } /// <summary> /// Adds the included files as ini configuration files /// </summary> /// <param name="sources">List of URL strings or filename strings</param> private void AddIncludes(List<string> sources) { //loop over config sources foreach (IConfig config in m_config.Source.Configs) { // Look for Include-* in the key name string[] keys = config.GetKeys(); foreach (string k in keys) { if (k.StartsWith("Include-")) { // read the config file to be included. string file = config.GetString(k); if (IsUri(file)) { if (!sources.Contains(file)) sources.Add(file); } else { string basepath = Path.GetFullPath(Util.configDir()); // Resolve relative paths with wildcards string chunkWithoutWildcards = file; string chunkWithWildcards = string.Empty; int wildcardIndex = file.IndexOfAny(new char[] { '*', '?' }); if (wildcardIndex != -1) { chunkWithoutWildcards = file.Substring(0, wildcardIndex); chunkWithWildcards = file.Substring(wildcardIndex); } string path = Path.Combine(basepath, chunkWithoutWildcards); path = Path.GetFullPath(path) + chunkWithWildcards; string[] paths = Util.Glob(path); // If the include path contains no wildcards, then warn the user that it wasn't found. if (wildcardIndex == -1 && paths.Length == 0) { m_log.WarnFormat("[CONFIG]: Could not find include file {0}", path); } else { foreach (string p in paths) { if (!sources.Contains(p)) sources.Add(p); } } } } } } } /// <summary> /// Check if we can convert the string to a URI /// </summary> /// <param name="file">String uri to the remote resource</param> /// <returns>true if we can convert the string to a Uri object</returns> bool IsUri(string file) { Uri configUri; return Uri.TryCreate(file, UriKind.Absolute, out configUri) && configUri.Scheme == Uri.UriSchemeHttp; } /// <summary> /// Provide same ini loader functionality for standard ini and master ini - file system or XML over http /// </summary> /// <param name="iniPath">Full path to the ini</param> /// <returns></returns> private bool ReadConfig(string iniPath) { bool success = false; if (!IsUri(iniPath)) { m_log.InfoFormat("[CONFIG]: Reading configuration file {0}", Path.GetFullPath(iniPath)); m_config.Source.Merge(new IniConfigSource(iniPath)); success = true; } else { m_log.InfoFormat("[CONFIG]: {0} is a http:// URI, fetching ...", iniPath); // The ini file path is a http URI // Try to read it try { XmlReader r = XmlReader.Create(iniPath); XmlConfigSource cs = new XmlConfigSource(r); m_config.Source.Merge(cs); success = true; } catch (Exception e) { m_log.FatalFormat("[CONFIG]: Exception reading config from URI {0}\n" + e.ToString(), iniPath); Environment.Exit(1); } } return success; } /// <summary> /// Setup a default config values in case they aren't present in the ini file /// </summary> /// <returns>A Configuration source containing the default configuration</returns> private static IConfigSource DefaultConfig() { IConfigSource defaultConfig = new IniConfigSource(); { IConfig config = defaultConfig.Configs["Startup"]; if (null == config) config = defaultConfig.AddConfig("Startup"); config.Set("region_info_source", "filesystem"); config.Set("physics", "OpenDynamicsEngine"); config.Set("meshing", "Meshmerizer"); config.Set("physical_prim", true); config.Set("see_into_this_sim_from_neighbor", true); config.Set("serverside_object_permissions", false); config.Set("storage_plugin", "OpenSim.Data.SQLite.dll"); config.Set("storage_connection_string", "URI=file:OpenSim.db,version=3"); config.Set("storage_prim_inventories", true); config.Set("startup_console_commands_file", String.Empty); config.Set("shutdown_console_commands_file", String.Empty); config.Set("DefaultScriptEngine", "XEngine"); config.Set("clientstack_plugin", "OpenSim.Region.ClientStack.LindenUDP.dll"); // life doesn't really work without this config.Set("EventQueue", true); } { IConfig config = defaultConfig.Configs["Network"]; if (null == config) config = defaultConfig.AddConfig("Network"); config.Set("http_listener_port", ConfigSettings.DefaultRegionHttpPort); } return defaultConfig; } /// <summary> /// Read initial region settings from the ConfigSource /// </summary> protected virtual void ReadConfigSettings() { IConfig startupConfig = m_config.Source.Configs["Startup"]; if (startupConfig != null) { m_configSettings.PhysicsEngine = startupConfig.GetString("physics"); m_configSettings.MeshEngineName = startupConfig.GetString("meshing"); m_configSettings.PhysicalPrim = startupConfig.GetBoolean("physical_prim", true); m_configSettings.See_into_region_from_neighbor = startupConfig.GetBoolean("see_into_this_sim_from_neighbor", true); m_configSettings.StorageDll = startupConfig.GetString("storage_plugin"); m_configSettings.ClientstackDll = startupConfig.GetString("clientstack_plugin", "OpenSim.Region.ClientStack.LindenUDP.dll"); } IConfig standaloneConfig = m_config.Source.Configs["StandAlone"]; if (standaloneConfig != null) { m_configSettings.StandaloneAuthenticate = standaloneConfig.GetBoolean("accounts_authenticate", true); m_configSettings.StandaloneWelcomeMessage = standaloneConfig.GetString("welcome_message"); m_configSettings.StandaloneInventoryPlugin = standaloneConfig.GetString("inventory_plugin"); m_configSettings.StandaloneInventorySource = standaloneConfig.GetString("inventory_source"); m_configSettings.StandaloneUserPlugin = standaloneConfig.GetString("userDatabase_plugin"); m_configSettings.StandaloneUserSource = standaloneConfig.GetString("user_source"); m_configSettings.LibrariesXMLFile = standaloneConfig.GetString("LibrariesXMLFile"); } m_networkServersInfo.loadFromConfiguration(m_config.Source); } } }
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; using Elastic.Clients.Elasticsearch; using Elastic.Clients.Elasticsearch.Helpers; using Elastic.Clients.Elasticsearch.IndexManagement; using Elastic.Transport; using Tests.Core.Client; using Tests.Domain; namespace Tests.Core.ManagedElasticsearch.NodeSeeders { public class DefaultSeeder { public const string CommitsAliasFilter = "commits-only"; public const string ProjectsAliasFilter = "projects-only"; public const string ProjectsAliasName = "projects-alias"; public const string TestsIndexTemplateName = "elasticsearch_client_tests"; public const string RemoteClusterName = "remote-cluster"; public const string PipelineName = "elasticsearch-client-pipeline"; private readonly IndexSettings _defaultIndexSettings = new() { NumberOfShards = 2, NumberOfReplicas = 0, }; public DefaultSeeder(IElasticsearchClient client, IndexSettings indexSettings) { Client = client; IndexSettings = indexSettings ?? _defaultIndexSettings; } public DefaultSeeder(IElasticsearchClient client) : this(client, null) { } private IElasticsearchClient Client { get; } private IndexSettings IndexSettings { get; } public void SeedNode() { var alreadySeeded = false; if (!TestClient.Configuration.ForceReseed && (alreadySeeded = AlreadySeeded())) return; var t = Task.Run(async () => await SeedNodeAsync(alreadySeeded).ConfigureAwait(false)); t.Wait(TimeSpan.FromSeconds(40)); } public void SeedNodeNoData() { var alreadySeeded = false; if (!TestClient.Configuration.ForceReseed && (alreadySeeded = AlreadySeeded())) return; var t = Task.Run(async () => await SeedNodeNoDataAsync(alreadySeeded).ConfigureAwait(false)); t.Wait(TimeSpan.FromSeconds(40)); } // Sometimes we run against an manually started Elasticsearch when // writing tests to cut down on cluster startup times. // If raw_fields exists assume this cluster is already seeded. private bool AlreadySeeded() { var response = Client.Transport.Request<BytesResponse>(HttpMethod.HEAD, $"_template/{TestsIndexTemplateName}"); return response.HttpStatusCode == 200; } private async Task SeedNodeAsync(bool alreadySeeded) { await CleanupCluster(alreadySeeded).ConfigureAwait(false); await PutPipeline().ConfigureAwait(false); await CreateIndicesAndSeedIndexDataAsync().ConfigureAwait(false); } private async Task SeedNodeNoDataAsync(bool alreadySeeded) { await CleanupCluster(alreadySeeded).ConfigureAwait(false); await CreateIndicesAsync().ConfigureAwait(false); } /// <summary> /// Ensure a clean slate by deleting everything regardless of whether they may already exist /// </summary> private async Task CleanupCluster(bool alreadySeeded) { await DeleteIndicesAndTemplatesAsync(alreadySeeded).ConfigureAwait(false); await ClusterSettingsAsync().ConfigureAwait(false); } public async Task ClusterSettingsAsync() { var clusterConfiguration = new Dictionary<string, object>() { { "cluster.routing.use_adaptive_replica_selection", true } }; //if (TestConfiguration.Instance.InRange(">=6.5.0")) //clusterConfiguration += new RemoteClusterConfiguration // { // { RemoteClusterName, "127.0.0.1:9300" } // }; var req = new { transient = clusterConfiguration }; _ = await Client.Transport.RequestAsync<BytesResponse>(HttpMethod.PUT, $"_cluster/settings", PostData.Serializable(req)); //var putSettingsResponse = await Client.Cluster.PutSettingsAsync(new ClusterPutSettingsRequest //{ // Transient = clusterConfiguration //}).ConfigureAwait(false); //putSettingsResponse.ShouldBeValid(); } public async Task PutPipeline() { //// TODO: Resume fluent version //var putProcessors = await Client.Ingest.PutPipelineAsync(PipelineName, pi => pi // .Description("A pipeline registered by the NEST test framework") // .Processors(new[] { new ProcessorContainer(new SetProcessor { Field = "metadata", Value = new { x = "y" } }) }) //).ConfigureAwait(false); //putProcessors.ShouldBeValid(); var req = new { description = "A pipeline registered by the NEST test framework", processors = new object[] { new Dictionary<string, object> { { "set", new { field = "metadata", value= new { x = "y" } } } } } }; _ = await Client.Transport.RequestAsync<BytesResponse>(HttpMethod.PUT, $"_ingest/pipeline/{PipelineName}", PostData.Serializable(req)); } public async Task DeleteIndicesAndTemplatesAsync(bool alreadySeeded) { var tasks = new List<Task> { Client.IndexManagement.DeleteAsync(typeof(Project)), Client.IndexManagement.DeleteAsync(typeof(Developer)), Client.IndexManagement.DeleteAsync(typeof(ProjectPercolation)) }; if (alreadySeeded) { tasks.Add(Client.Transport.RequestAsync<BytesResponse>(HttpMethod.DELETE, $"_template/{TestsIndexTemplateName}", PostData.Empty)); } await Task.WhenAll(tasks.ToArray()).ConfigureAwait(false); } private async Task CreateIndicesAndSeedIndexDataAsync() { await CreateIndicesAsync().ConfigureAwait(false); await SeedTimeSeriesDataAsync().ConfigureAwait(false); //await SeedIndexDataAsync().ConfigureAwait(false); } public static readonly string IndicesWildCard = "customlogs-*"; public async Task SeedTimeSeriesDataAsync() { var transport = Client.Transport; var req = new { mapping = new { properties = new Dictionary<string, object> { { "timestamp", new { type = "date" } } } }, index_patterns = new[] { IndicesWildCard }, settings = new Dictionary<string, object> { { "index.number_of_replicas", 0 }, { "index.number_of_shards", 1 } } }; _ = await transport.RequestAsync<BytesResponse>(HttpMethod.PUT, $"_template/customlogs-template", PostData.Serializable(req)).ConfigureAwait(false); var logs = Log.Generator.GenerateLazy(100_000); var sw = Stopwatch.StartNew(); var dropped = new List<Log>(); var bulkAll = Client.BulkAll(new BulkAllRequest<Log>(logs) { Size = 10_000, MaxDegreeOfParallelism = 10, RefreshOnCompleted = true, RefreshIndices = IndicesWildCard, DroppedDocumentCallback = (d, l) => dropped.Add(l), BufferToBulk = (b, buffer) => b.IndexMany(buffer, (i, l) => i.Index($"customlogs-{l.Timestamp:yyyy-MM-dd}")) }); bulkAll.Wait(TimeSpan.FromMinutes(1), x => { }); Console.WriteLine($"Completed in {sw.Elapsed} with {dropped.Count} dropped logs"); var countResult = Client.Count<Log>(s => s.Index(IndicesWildCard)); Console.WriteLine($"Stored {countResult.Count} in {IndicesWildCard} indices"); } public async Task CreateIndicesAsync() { var transport = Client.Transport; var req = new { index_patterns = new[] { "*" }, settings = new Dictionary<string, object> { { "index.number_of_replicas", 0 }, { "index.number_of_shards", 1 } } }; _ = await transport.RequestAsync<BytesResponse>(HttpMethod.PUT, $"_template/{TestsIndexTemplateName}", PostData.Serializable(req)); var requestData = new { aliases = new Dictionary<string, object> { { "projects-alias", new { } }, { "projects-only", new { filter = new { term = new { join = new { value = "project" }}}} } }, mappings = new { _routing = new { required = true }, properties = new Dictionary<string, object> { { "locationPoint", new { type = "geo_point" } }, { "name", new { type = "keyword", store = true, fields = new { suggest = new { type = "completion" }, standard = new { analyzer = "standard", type = "text" } } } }, { "numberOfCommits", new { type = "integer", store = true } }, { "state", new { type = "keyword" } }, { "startedOn", new { type = "date", store = true } }, { "tags", new { type = "nested", properties = new { added = new { type = "date" }, name = new { type = "keyword", fields = new { vectors = new { term_vector = "with_positions_offsets_payloads", type = "text" } } } } } } } }, settings = new { // TODO } }; _ = await transport.RequestAsync<BytesResponse>(HttpMethod.PUT, "project", PostData.Serializable(requestData)); var requestDataDeveloper = new { mappings = new { _routing = new { required = true }, properties = new Dictionary<string, object> { { "onlineHandle", new { type = "keyword" } } } }, settings = new { // TODO } }; _ = await transport.RequestAsync<BytesResponse>(HttpMethod.PUT, "devs", PostData.Serializable(requestDataDeveloper)); var tasks = new[] { SeedIndexDataAsync(), //CreateDeveloperIndexAsync() }; await Task.WhenAll(tasks) .ContinueWith(t => { //foreach (var r in t.Result) // r.ShouldBeValid(); }).ConfigureAwait(false); } //private async Task<CreateIndexResponse> CreateProjectIndexAsync() //{ // //var properties = new Properties // //{ // // { Infer.Property(Infer.Field<Project>(p => p.Name).Name), new KeywordProperty() } // //}; // var request = new CreateIndexRequest(IndexName.From<Project>()) // { // Mappings = new TypeMapping // { // //Properties = properties // }, // Aliases = new Dictionary<Name, Alias> // { // { // ProjectsAliasFilter, // new Alias() // { // //Filter = new TermQuery() // //{ // // Field = Infer.Field<Project>(f => f.Join) // //} // } // } // } // }; // //return await Client.IndexManagement.CreateIndexAsync(request); //} //=> Client.IndexManagement.CreateIndexAsync<Project>(IndexName.From<Project>(), i => i.Settings(s => s.NumberOfShards(1).NumberOfReplicas(0))); //.Settings(settings => settings.Analysis(ProjectAnalysisSettings)) // this uses obsolete overload somewhat on purpose to make sure it works just as the rest // TODO 8.0 remove with once the overloads are gone too //.Mappings(ProjectMappings) //.Aliases(aliases => aliases // .Alias(ProjectsAliasName) // .Alias(ProjectsAliasFilter, a => a // .Filter<Project>(f => f.Term(p => p.Join, Infer.Relation<Project>())) // ) // .Alias(CommitsAliasFilter, a => a // .Filter<CommitActivity>(f => f.Term(p => p.Join, Infer.Relation<CommitActivity>())) // ) //) //); //public static ITypeMapping ProjectMappings(MappingsDescriptor map) => map // .Map<Project>(ProjectTypeMappings); //public static ITypeMapping ProjectTypeMappings(TypeMappingDescriptor<Project> mapping) //{ // mapping // .RoutingField(r => r.Required()) // .AutoMap() // .Properties(ProjectProperties) // .Properties<CommitActivity>(props => props // .Object<Developer>(o => o // .AutoMap() // .Name(p => p.Committer) // .Properties(DeveloperProperties) // .Dynamic() // ) // .Text(t => t // .Name(p => p.ProjectName) // .Index(false) // ) // ) // .RuntimeFields<ProjectRuntimeFields>(rf => rf // .RuntimeField(r => r.StartedOnDayOfWeek, FieldType.Keyword, rtf => rtf // .Script("if (doc['startedOn'].size() != 0) {emit(doc['startedOn'].value.dayOfWeekEnum.getDisplayName(TextStyle.FULL, Locale.ROOT))}")) // .RuntimeField(r => r.ThirtyDaysFromStarted, FieldType.Date, rtf => rtf // .Script("if (doc['startedOn'].size() != 0) {emit(doc['startedOn'].value.plusDays(30).toEpochMilli())}"))); // return mapping; //} //private async Task<IndexPutIndexTemplateResponse> CreateIndexTemplateAsync() //{ // var req = new // { // IndexPatterns = new[] { "*" }, // Settings = new Dictionary<string, object> // { // { "index.number_of_replicas", 0 }, // { "index.number_of_shards", 0 } // } // }; // _ = await Client.Transport.RequestAsync<BytesResponse>(HttpMethod.PUT, "_template/nest_tests", PostData.Serializable(req)); //} //public async Task CreateIndicesAsync() //{ // var indexTemplateResponse = await CreateIndexTemplateAsync().ConfigureAwait(false); // indexTemplateResponse.ShouldBeValid(); // var tasks = new[] // { // CreateProjectIndexAsync(), // CreateDeveloperIndexAsync(), // CreatePercolatorIndexAsync(), // }; // await Task.WhenAll(tasks) // .ContinueWith(t => // { // foreach (var r in t.Result) // r.ShouldBeValid(); // }).ConfigureAwait(false); //} private async Task SeedIndexDataAsync() { var tasks = new Task[] { Client.IndexManyAsync(Project.Projects) }; await Task.WhenAll(tasks).ConfigureAwait(false); await Client.IndexManagement.RefreshAsync(new RefreshRequest(Indices.Index(typeof(Project)))).ConfigureAwait(false); } // private Task<PutIndexTemplateResponse> CreateIndexTemplateAsync() => Client.Indices.PutTemplateAsync( // new PutIndexTemplateRequest(TestsIndexTemplateName) // { // IndexPatterns = new[] { "*" }, // Settings = IndexSettings // }); //private Task<CreateIndexResponse> CreateDeveloperIndexAsync() => Client.IndexManagement.CreateIndexAsync(Infer.Index<Developer>()); //.Map<Developer>(m => m // .AutoMap() // .Properties(DeveloperProperties) //) //); //#pragma warning disable 618 // private Task<CreateIndexResponse> CreateProjectIndexAsync() => Client.Indices.CreateAsync(typeof(Project), c => c // .Settings(settings => settings.Analysis(ProjectAnalysisSettings)) // // this uses obsolete overload somewhat on purpose to make sure it works just as the rest // // TODO 8.0 remove with once the overloads are gone too // .Mappings(ProjectMappings) // .Aliases(aliases => aliases // .Alias(ProjectsAliasName) // .Alias(ProjectsAliasFilter, a => a // .Filter<Project>(f => f.Term(p => p.Join, Infer.Relation<Project>())) // ) // .Alias(CommitsAliasFilter, a => a // .Filter<CommitActivity>(f => f.Term(p => p.Join, Infer.Relation<CommitActivity>())) // ) // ) // ); //#pragma warning restore 618 //#pragma warning disable 618 // public static ITypeMapping ProjectMappings(MappingsDescriptor map) => map // .Map<Project>(ProjectTypeMappings); //#pragma warning restore 618 // public static ITypeMapping ProjectTypeMappings(TypeMappingDescriptor<Project> mapping) // { // mapping // .RoutingField(r => r.Required()) // .AutoMap() // .Properties(ProjectProperties) // .Properties<CommitActivity>(props => props // .Object<Developer>(o => o // .AutoMap() // .Name(p => p.Committer) // .Properties(DeveloperProperties) // .Dynamic() // ) // .Text(t => t // .Name(p => p.ProjectName) // .Index(false) // ) // ); // // runtime fields are a new feature added in 7.11.0 // if (TestConfiguration.Instance.InRange(">=7.11.0")) // { // mapping.RuntimeFields<ProjectRuntimeFields>(rf => rf // .RuntimeField(r => r.StartedOnDayOfWeek, FieldType.Keyword, rtf => rtf // .Script("if (doc['startedOn'].size() != 0) {emit(doc['startedOn'].value.dayOfWeekEnum.getDisplayName(TextStyle.FULL, Locale.ROOT))}")) // .RuntimeField(r => r.ThirtyDaysFromStarted, FieldType.Date, rtf => rtf // .Script("if (doc['startedOn'].size() != 0) {emit(doc['startedOn'].value.plusDays(30).toEpochMilli())}"))); // } // return mapping; // } public static IndexSettingsAnalysisDescriptor ProjectAnalysisSettings(IndexSettingsAnalysisDescriptor analysis) => analysis; //{ // //analysis // // .TokenFilters(tokenFilters => tokenFilters // // .Shingle("shingle", shingle => shingle // // .MinShingleSize(2) // // .MaxShingleSize(4) // // ) // // ) // // .Analyzers(analyzers => analyzers // // .Custom("shingle", shingle => shingle // // .Filters("shingle") // // .Tokenizer("standard") // // ) // // ); // //var filters = new TokenFilters // //{ // // { "shingle", new ShingleTokenFilter { MinShingleSize = 2, MaxShingleSize = 4 } } // //}; // //analysis.TokenFilters(tokenFilters => tokenFilters.Shingle("shingle", shingle => shingle.MinShingleSize(2))); // //analysis.Filter(f => f.Add("shingle", new ShingleTokenFilter { MinShingleSize = 2, MaxShingleSize = 4 })); // ////normalizers are a new feature since 5.2.0 // //if (TestConfiguration.Instance.InRange(">=5.2.0")) // // analysis.Normalizers(analyzers => analyzers // // .Custom("my_normalizer", n => n // // .Filters("lowercase", "asciifolding") // // ) // //// ); // return analysis; //} // private Task<CreateIndexResponse> CreatePercolatorIndexAsync() => Client.Indices.CreateAsync(typeof(ProjectPercolation), c => c // .Settings(s => s // .AutoExpandReplicas("0-all") // .Analysis(ProjectAnalysisSettings) // ) // .Map<ProjectPercolation>(m => m // .AutoMap() // .Properties(PercolatedQueryProperties) // ) // ); // public static PropertiesDescriptor<TProject> ProjectProperties<TProject>(PropertiesDescriptor<TProject> props) // where TProject : Project // { // props // .Join(j => j // .Name(n => n.Join) // .Relations(r => r // .Join<Project, CommitActivity>() // ) // ) // .Keyword(d => d.Name(p => p.Type)) // .Keyword(s => s // .Name(p => p.Name) // .Store() // .Fields(fs => fs // .Text(ss => ss // .Name("standard") // .Analyzer("standard") // ) // .Completion(cm => cm // .Name("suggest") // ) // ) // ) // .Text(s => s // .Name(p => p.Description) // .Fielddata() // .Fields(f => f // .Text(t => t // .Name("shingle") // .Analyzer("shingle") // ) // ) // ) // .Date(d => d // .Store() // .Name(p => p.StartedOn) // ) // .Text(d => d // .Store() // .Name(p => p.DateString) // ) // .Keyword(d => d // .Name(p => p.State) // .Fields(fs => fs // .Text(st => st // .Name("offsets") // .IndexOptions(IndexOptions.Offsets) // ) // .Keyword(sk => sk // .Name("keyword") // ) // ) // ) // .Nested<Tag>(mo => mo // .AutoMap() // .Name(p => p.Tags) // .Properties(TagProperties) // ) // .Object<Developer>(o => o // .AutoMap() // .Name(p => p.LeadDeveloper) // .Properties(DeveloperProperties) // ) // .GeoPoint(g => g // .Name(p => p.LocationPoint) // ) // .GeoShape(g => g // .Name(p => p.LocationShape) // ) // .Shape(g => g // .Name(p => p.ArbitraryShape) // ) // .Completion(cm => cm // .Name(p => p.Suggest) // .Contexts(cx => cx // .Category(c => c // .Name("color") // ) // .GeoLocation(c => c // .Name("geo") // .Precision(1) // ) // ) // ) // .Scalar(p => p.NumberOfCommits, n => n.Store()) // .Scalar(p => p.NumberOfContributors, n => n.Store()) // .Object<Dictionary<string, Metadata>>(o => o // .Name(p => p.Metadata) // ) // .RankFeature(rf => rf // .Name(p => p.Rank) // .PositiveScoreImpact() // ); // if (TestConfiguration.Instance.InRange(">=7.3.0")) // props.Flattened(f => f // .Name(p => p.Labels) // ); // else // props.Object<Labels>(f => f // .Name(p => p.Labels) // .Enabled(false) // ); // if (TestConfiguration.Instance.InRange(">=7.7.0")) // props.ConstantKeyword(f => f // .Name(p => p.VersionControl) // ); // else // props.Keyword(f => f // .Name(p => p.VersionControl) // ); // return props; // } // private static PropertiesDescriptor<Tag> TagProperties(PropertiesDescriptor<Tag> props) => props // .Keyword(s => s // .Name(p => p.Name) // .Fields(f => f // .Text(st => st // .Name("vectors") // .TermVector(TermVectorOption.WithPositionsOffsetsPayloads) // ) // ) // ); // public static PropertiesDescriptor<Developer> DeveloperProperties(PropertiesDescriptor<Developer> props) => props // .Keyword(s => s // .Name(p => p.OnlineHandle) // ) // .Keyword(s => s // .Name(p => p.Gender) // ) // .Text(s => s // .Name(p => p.FirstName) // .TermVector(TermVectorOption.WithPositionsOffsetsPayloads) // ) // .Ip(s => s // .Name(p => p.IpAddress) // ) // .GeoPoint(g => g // .Name(p => p.Location) // ) // .Object<GeoIp>(o => o // .Name(p => p.GeoIp) // ); // public static PropertiesDescriptor<ProjectPercolation> PercolatedQueryProperties(PropertiesDescriptor<ProjectPercolation> props) => // ProjectProperties(props.Percolator(pp => pp.Name(n => n.Query))); } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using TimeManagment.WebApp.Areas.HelpPage.ModelDescriptions; using TimeManagment.WebApp.Areas.HelpPage.Models; namespace TimeManagment.WebApp.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Nick Berard, http://www.coderjournal.com // // 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. // #endregion [assembly: Elmah.Scc("$Id: MySqlErrorLog.cs 925 2011-12-23 22:46:09Z azizatif $")] namespace Elmah { #region Imports using System; using System.Collections.Generic; using System.Data; using MySql.Data.MySqlClient; using IDictionary = System.Collections.IDictionary; #endregion /// <summary> /// An <see cref="ErrorLog"/> implementation that uses /// <a href="http://www.mysql.com/">MySQL</a> as its backing store. /// </summary> public class MySqlErrorLog : ErrorLog { private readonly string _connectionString; private const int _maxAppNameLength = 60; /// <summary> /// Initializes a new instance of the <see cref="SqlErrorLog"/> class /// using a dictionary of configured settings. /// </summary> public MySqlErrorLog(IDictionary config) { if (config == null) throw new ArgumentNullException("config"); var connectionString = ConnectionStringHelper.GetConnectionString(config); // // If there is no connection string to use then throw an // exception to abort construction. // if (connectionString.Length == 0) throw new ApplicationException("Connection string is missing for the SQL error log."); _connectionString = connectionString; // // Set the application name as this implementation provides // per-application isolation over a single store. // var appName = config.Find("applicationName", string.Empty); if (appName.Length > _maxAppNameLength) { throw new ApplicationException(string.Format( "Application name is too long. Maximum length allowed is {0} characters.", _maxAppNameLength.ToString("N0"))); } ApplicationName = appName; } /// <summary> /// Initializes a new instance of the <see cref="SqlErrorLog"/> class /// to use a specific connection string for connecting to the database. /// </summary> public MySqlErrorLog(string connectionString) { if (connectionString == null) throw new ArgumentNullException("connectionString"); if (connectionString.Length == 0) throw new ArgumentException(null, "connectionString"); _connectionString = connectionString; } /// <summary> /// Gets the name of this error log implementation. /// </summary> public override string Name { get { return "MySQL Server Error Log"; } } /// <summary> /// Gets the connection string used by the log to connect to the database. /// </summary> public virtual string ConnectionString { get { return _connectionString; } } /// <summary> /// Logs an error to the database. /// </summary> /// <remarks> /// Use the stored procedure called by this implementation to set a /// policy on how long errors are kept in the log. The default /// implementation stores all errors for an indefinite time. /// </remarks> public override string Log(Error error) { if (error == null) throw new ArgumentNullException("error"); var errorXml = ErrorXml.EncodeString(error); var id = Guid.NewGuid(); using (var connection = new MySqlConnection(ConnectionString)) using (var command = Commands.LogError( id, ApplicationName, error.HostName, error.Type, error.Source, error.Message, error.User, error.StatusCode, error.Time.ToUniversalTime(), errorXml)) { command.Connection = connection; connection.Open(); command.ExecuteNonQuery(); return id.ToString(); } } /// <summary> /// Returns a page of errors from the databse in descending order /// of logged time. /// </summary> public override int GetErrors(int pageIndex, int pageSize, ICollection<ErrorLogEntry> errorEntryList) { if (pageIndex < 0) throw new ArgumentOutOfRangeException("pageIndex", pageIndex, null); if (pageSize < 0) throw new ArgumentOutOfRangeException("pageSize", pageSize, null); using (var connection = new MySqlConnection(ConnectionString)) using (var command = Commands.GetErrorsXml(ApplicationName, pageIndex, pageSize)) { command.Connection = connection; connection.Open(); using (var reader = command.ExecuteReader()) { Debug.Assert(reader != null); if (errorEntryList != null) { while (reader.Read()) { var error = new Error(); error.ApplicationName = reader["Application"].ToString(); error.HostName = reader["Host"].ToString(); error.Type = reader["Type"].ToString(); error.Source = reader["Source"].ToString(); error.Message = reader["Message"].ToString(); error.User = reader["User"].ToString(); error.StatusCode = Convert.ToInt32(reader["StatusCode"]); error.Time = Convert.ToDateTime(reader.GetString("TimeUtc")).ToLocalTime(); errorEntryList.Add(new ErrorLogEntry(this, reader["ErrorId"].ToString(), error)); } } reader.Close(); } return (int)command.Parameters["TotalCount"].Value; } } /// <summary> /// Returns the specified error from the database, or null /// if it does not exist. /// </summary> public override ErrorLogEntry GetError(string id) { if (id == null) throw new ArgumentNullException("id"); if (id.Length == 0) throw new ArgumentException(null, "id"); Guid errorGuid; try { errorGuid = new Guid(id); } catch (FormatException e) { throw new ArgumentException(e.Message, "id", e); } string errorXml = null; using (var connection = new MySqlConnection(ConnectionString)) using (var command = Commands.GetErrorXml(ApplicationName, errorGuid)) { command.Connection = connection; connection.Open(); using (var reader = command.ExecuteReader()) { Debug.Assert(reader != null); while (reader.Read()) { errorXml = reader.GetString("AllXml"); } reader.Close(); } } if (errorXml == null) return null; var error = ErrorXml.DecodeString(errorXml); return new ErrorLogEntry(this, id, error); } private static class Commands { public static MySqlCommand LogError( Guid id, string appName, string hostName, string typeName, string source, string message, string user, int statusCode, DateTime time, string xml) { var command = new MySqlCommand("elmah_LogError"); command.CommandType = CommandType.StoredProcedure; var parameters = command.Parameters; parameters.Add("ErrorId", MySqlDbType.String, 36).Value = id.ToString(); parameters.Add("Application", MySqlDbType.VarChar, _maxAppNameLength).Value = appName.Substring(0, Math.Min(_maxAppNameLength, appName.Length)); parameters.Add("Host", MySqlDbType.VarChar, 30).Value = hostName.Substring(0, Math.Min(30, hostName.Length)); parameters.Add("Type", MySqlDbType.VarChar, 100).Value = typeName.Substring(0, Math.Min(100, typeName.Length)); parameters.Add("Source", MySqlDbType.VarChar, 60).Value = source.Substring(0, Math.Min(60, source.Length)); parameters.Add("Message", MySqlDbType.VarChar, 500).Value = message.Substring(0, Math.Min(500, message.Length)); parameters.Add("User", MySqlDbType.VarChar, 50).Value = user.Substring(0, Math.Min(50, user.Length)); parameters.Add("AllXml", MySqlDbType.Text).Value = xml; parameters.Add("StatusCode", MySqlDbType.Int32).Value = statusCode; parameters.Add("TimeUtc", MySqlDbType.Datetime).Value = time; return command; } public static MySqlCommand GetErrorXml(string appName, Guid id) { var command = new MySqlCommand("elmah_GetErrorXml"); command.CommandType = CommandType.StoredProcedure; var parameters = command.Parameters; parameters.Add("Id", MySqlDbType.String, 36).Value = id.ToString(); parameters.Add("App", MySqlDbType.VarChar, _maxAppNameLength).Value = appName.Substring(0, Math.Min(_maxAppNameLength, appName.Length)); return command; } public static MySqlCommand GetErrorsXml(string appName, int pageIndex, int pageSize) { var command = new MySqlCommand("elmah_GetErrorsXml"); command.CommandType = CommandType.StoredProcedure; var parameters = command.Parameters; parameters.Add("App", MySqlDbType.VarChar, _maxAppNameLength).Value = appName.Substring(0, Math.Min(_maxAppNameLength, appName.Length)); parameters.Add("PageIndex", MySqlDbType.Int32).Value = pageIndex; parameters.Add("PageSize", MySqlDbType.Int32).Value = pageSize; parameters.Add("TotalCount", MySqlDbType.Int32).Direction = ParameterDirection.Output; return command; } public static void GetErrorsXmlOutputs(MySqlCommand command, out int totalCount) { Debug.Assert(command != null); totalCount = (int)command.Parameters["TotalCount"].Value; } } } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.Threading; /// <summary> /// Game Jolt Trophy. Inherit from <see cref="GJObject"/>. /// </summary> public class GJTrophy : GJObject { /// <summary> /// Trophy difficulty enumeration. /// </summary> public enum TrophyDifficulty { Undefined, Bronze, Silver, Gold, Platinium }; /// <summary> /// Initializes a new instance of the <see cref="GJTrophy"/> class. /// </summary> public GJTrophy () { } /// <summary> /// Initializes a new instance of the <see cref="GJTrophy"/> class. /// </summary> /// <param name='id'> /// The trophy identifier. /// </param> /// <param name='title'> /// The trophy name. /// </param> /// <param name='difficulty'> /// The trophy difficulty. See <see cref="GJTrophy.TrophyDifficulty"/>. /// </param> /// <param name='achieved'> /// Is the trophy achieved. /// </param> /// <param name='description'> /// The trophy description. Default empty. /// </param> /// <param name='imageURL'> /// The URL to the trophy's thumbnail. Default empty. /// </param> public GJTrophy (uint id, string title, TrophyDifficulty difficulty, bool achieved, string description = "", string imageURL = "") { this.AddProperty ("id", id.ToString ()); this.AddProperty ("title", title); this.AddProperty ("difficulty", difficulty.ToString ()); this.AddProperty ("achieved", achieved.ToString ()); this.AddProperty ("description", description); this.AddProperty ("image_url", imageURL); } /// <summary> /// Initializes a new instance of the <see cref="GJTrophy"/> class. /// </summary> /// <param name='properties'> /// Properties to add to the <see cref="GJTrophy"/>. /// </param> public GJTrophy (Dictionary<string,string> properties) { this.AddProperties (properties); } /// <summary> /// Gets or sets the trophy identifier. /// </summary> /// <value> /// The trophy identifier. /// </value> public uint Id { get { if (this.properties.ContainsKey ("id")) { if (this.properties ["id"] == string.Empty) { Debug.Log ("Trophy ID is empty. Returning 0."); return 0; } try { return Convert.ToUInt32 (this.properties ["id"]); } catch (Exception e) { Debug.LogError ("Error converting Trophy ID to uint. Returning 0. " + e.Message); return 0; } } else { return 0; } } set { this.properties ["id"] = value.ToString (); } } /// <summary> /// Gets or sets the trophy name. /// </summary> /// <value> /// The trophy name. /// </value> public string Title { get { return this.properties.ContainsKey ("title") ? this.properties ["title"] : string.Empty; } set { this.properties ["title"] = value; } } /// <summary> /// Gets or sets the description. /// </summary> /// <value> /// The description. /// </value> public string Description { get { return this.properties.ContainsKey ("description") ? this.properties ["description"] : string.Empty; } set { this.properties ["description"] = value; } } /// <summary> /// Gets or sets the trophy difficulty. See <see cref="GJTrophy.TrophyDifficulty"/>. /// </summary> /// <value> /// The trophy difficulty. See <see cref="GJTrophy.TrophyDifficulty"/>. /// </value> public TrophyDifficulty Difficulty { get { if (this.properties.ContainsKey ("difficulty")) { try { return (TrophyDifficulty) Enum.Parse (typeof (TrophyDifficulty), this.properties ["difficulty"]); } catch (Exception e) { Debug.LogError ("Error converting Trophy Difficulty to TrophyDifficulty. Returning Undefined. " + e.Message); return TrophyDifficulty.Undefined; } } else { return TrophyDifficulty.Undefined; } } set { this.properties ["difficulty"] = value.ToString ();} } /// <summary> /// Gets or sets a value indicating whether this <see cref="GJTrophy"/> is achieved. /// </summary> /// <value> /// <c>true</c> if achieved; otherwise, <c>false</c>. /// </value> public bool Achieved { get { if (this.properties.ContainsKey ("achieved") && !(this.properties ["achieved"] == "false")) { return true; } return false; } set { this.properties ["achieved"] = value.ToString (); } } /// <summary> /// Gets or sets when the trophy was achieved. /// </summary> /// <value> /// When the trophy was achieved. /// </value> public string AchievedTime { get { if (this.properties.ContainsKey ("achieved") && !(this.properties ["achieved"] == "false")) { return this.properties ["achieved"]; } return "NA"; } set { this.properties ["achieved"] = value; } } /// <summary> /// Gets or sets the URL of the trophy's thumbnail. /// </summary> /// <value> /// The URL of the trophy's thumbnail. /// </value> public string ImageURL { get { return this.properties.ContainsKey ("image_url") ? this.properties ["image_url"] : string.Empty; } set { this.properties ["image_url"] = 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. using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using Xunit; namespace System.Security.Cryptography.X509Certificates.Tests { public static class FindTests { private static void RunTest(Action<X509Certificate2Collection> test) { RunTest((msCer, pfxCer, col1) => test(col1)); } private static void RunTest(Action<X509Certificate2, X509Certificate2, X509Certificate2Collection> test) { using (var msCer = new X509Certificate2(TestData.MsCertificate)) using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) { X509Certificate2Collection col1 = new X509Certificate2Collection(new[] { msCer, pfxCer }); test(msCer, pfxCer, col1); } } private static void RunExceptionTest<TException>(X509FindType findType, object findValue) where TException : Exception { RunTest( (msCer, pfxCer, col1) => { Assert.Throws<TException>(() => col1.Find(findType, findValue, validOnly: false)); }); } private static void RunZeroMatchTest(X509FindType findType, object findValue) { RunTest( (msCer, pfxCer, col1) => { X509Certificate2Collection col2 = col1.Find(findType, findValue, validOnly: false); using (new ImportedCollection(col2)) { Assert.Equal(0, col2.Count); } }); } private static void RunSingleMatchTest_MsCer(X509FindType findType, object findValue) { RunTest( (msCer, pfxCer, col1) => { EvaluateSingleMatch(msCer, col1, findType, findValue); }); } private static void RunSingleMatchTest_PfxCer(X509FindType findType, object findValue) { RunTest( (msCer, pfxCer, col1) => { EvaluateSingleMatch(pfxCer, col1, findType, findValue); }); } private static void EvaluateSingleMatch( X509Certificate2 expected, X509Certificate2Collection col1, X509FindType findType, object findValue) { X509Certificate2Collection col2 = col1.Find(findType, findValue, validOnly: false); using (new ImportedCollection(col2)) { Assert.Equal(1, col2.Count); byte[] serialNumber; using (X509Certificate2 match = col2[0]) { Assert.Equal(expected, match); Assert.NotSame(expected, match); // FriendlyName is Windows-only. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { // Verify that the find result and original are linked, not just equal. match.FriendlyName = "HAHA"; Assert.Equal("HAHA", expected.FriendlyName); } serialNumber = match.GetSerialNumber(); } // Check that disposing match didn't dispose expected Assert.Equal(serialNumber, expected.GetSerialNumber()); } } [Theory] [MemberData(nameof(GenerateInvalidInputs))] public static void FindWithWrongTypeValue(X509FindType findType, Type badValueType) { object badValue; if (badValueType == typeof(object)) { badValue = new object(); } else if (badValueType == typeof(DateTime)) { badValue = DateTime.Now; } else if (badValueType == typeof(byte[])) { badValue = Array.Empty<byte>(); } else if (badValueType == typeof(string)) { badValue = "Hello, world"; } else { throw new InvalidOperationException("No creator exists for type " + badValueType); } RunExceptionTest<CryptographicException>(findType, badValue); } [Theory] [MemberData(nameof(GenerateInvalidOidInputs))] public static void FindWithBadOids(X509FindType findType, string badOid) { RunExceptionTest<ArgumentException>(findType, badOid); } [Fact] public static void FindByNullName() { RunExceptionTest<ArgumentNullException>(X509FindType.FindBySubjectName, null); } [Fact] public static void FindByInvalidThumbprint() { RunZeroMatchTest(X509FindType.FindByThumbprint, "Nothing"); } [Fact] public static void FindByInvalidThumbprint_RightLength() { RunZeroMatchTest(X509FindType.FindByThumbprint, "ffffffffffffffffffffffffffffffffffffffff"); } [Fact] public static void FindByValidThumbprint() { RunTest( (msCer, pfxCer, col1) => { EvaluateSingleMatch( pfxCer, col1, X509FindType.FindByThumbprint, pfxCer.Thumbprint); }); } [Theory] [InlineData(false)] [InlineData(true)] public static void FindByValidThumbprint_ValidOnly(bool validOnly) { using (var msCer = new X509Certificate2(TestData.MsCertificate)) { var col1 = new X509Certificate2Collection(msCer); X509Certificate2Collection col2 = col1.Find(X509FindType.FindByThumbprint, msCer.Thumbprint, validOnly); using (new ImportedCollection(col2)) { // The certificate is expired. Unless we invent time travel // (or roll the computer clock back significantly), the validOnly // criteria should filter it out. // // This test runs both ways to make sure that the precondition of // "would match otherwise" is met (in the validOnly=false case it is // effectively the same as FindByValidThumbprint, but does less inspection) int expectedMatchCount = validOnly ? 0 : 1; Assert.Equal(expectedMatchCount, col2.Count); if (!validOnly) { // Double check that turning on validOnly doesn't prevent the cloning // behavior of Find. using (X509Certificate2 match = col2[0]) { Assert.Equal(msCer, match); Assert.NotSame(msCer, match); } } } } } [Fact] [ActiveIssue(19260, TestPlatforms.OSX)] public static void FindByValidThumbprint_RootCert() { using (X509Store machineRoot = new X509Store(StoreName.Root, StoreLocation.LocalMachine)) { machineRoot.Open(OpenFlags.ReadOnly); using (var watchedStoreCerts = new ImportedCollection(machineRoot.Certificates)) { X509Certificate2Collection storeCerts = watchedStoreCerts.Collection; X509Certificate2 rootCert = null; TimeSpan tolerance = TimeSpan.FromHours(12); // These APIs use local time, so use DateTime.Now, not DateTime.UtcNow. DateTime notBefore = DateTime.Now; DateTime notAfter = DateTime.Now.Subtract(tolerance); foreach (X509Certificate2 cert in storeCerts) { if (cert.NotBefore < notBefore && cert.NotAfter > notAfter) { X509KeyUsageExtension keyUsageExtension = null; foreach (X509Extension extension in cert.Extensions) { keyUsageExtension = extension as X509KeyUsageExtension; if (keyUsageExtension != null) { break; } } // Some tool is putting the com.apple.systemdefault utility cert in the // LM\Root store on OSX machines; but it gets rejected by OpenSSL as an // invalid root for not having the Certificate Signing key usage value. // // While the real problem seems to be with whatever tool is putting it // in the bundle; we can work around it here. const X509KeyUsageFlags RequiredFlags = X509KeyUsageFlags.KeyCertSign; // No key usage extension means "good for all usages" if (keyUsageExtension == null || (keyUsageExtension.KeyUsages & RequiredFlags) == RequiredFlags) { rootCert = cert; break; } } } // Just in case someone has a system with no valid trusted root certs whatsoever. if (rootCert != null) { X509Certificate2Collection matches = storeCerts.Find(X509FindType.FindByThumbprint, rootCert.Thumbprint, true); using (new ImportedCollection(matches)) { // Improve the debuggability, since the root cert found on each // machine might be different if (matches.Count == 0) { Assert.True( false, $"Root certificate '{rootCert.Subject}' ({rootCert.NotBefore} - {rootCert.NotAfter}) is findable with thumbprint '{rootCert.Thumbprint}' and validOnly=true"); } Assert.NotSame(rootCert, matches[0]); Assert.Equal(rootCert, matches[0]); } } } } } [Theory] [InlineData("Nothing")] [InlineData("US, Redmond, Microsoft Corporation, MOPR, Microsoft Corporation")] public static void TestSubjectName_NoMatch(string subjectQualifier) { RunZeroMatchTest(X509FindType.FindBySubjectName, subjectQualifier); } [Theory] [InlineData("Microsoft Corporation")] [InlineData("MOPR")] [InlineData("Redmond")] [InlineData("Washington")] [InlineData("US")] [InlineData("US, Washington")] [InlineData("Washington, Redmond")] [InlineData("US, Washington, Redmond, Microsoft Corporation, MOPR, Microsoft Corporation")] [InlineData("us, washington, redmond, microsoft corporation, mopr, microsoft corporation")] public static void TestSubjectName_Match(string subjectQualifier) { RunSingleMatchTest_MsCer(X509FindType.FindBySubjectName, subjectQualifier); } [Theory] [InlineData("")] [InlineData("Nothing")] [InlineData("ou=mopr, o=microsoft corporation")] [InlineData("CN=Microsoft Corporation")] [InlineData("CN=Microsoft Corporation, OU=MOPR, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] [InlineData("CN=Microsoft Corporation, OU=MOPR, O=Microsoft Corporation, L=Redmond, S=Washington, C=US ")] [InlineData(" CN=Microsoft Corporation, OU=MOPR, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] public static void TestDistinguishedSubjectName_NoMatch(string distinguishedSubjectName) { RunZeroMatchTest(X509FindType.FindBySubjectDistinguishedName, distinguishedSubjectName); } [Theory] [InlineData("CN=Microsoft Corporation, OU=MOPR, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] [InlineData("CN=microsoft corporation, OU=MOPR, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] [InlineData("cn=microsoft corporation, ou=mopr, o=microsoft corporation, l=redmond, s=washington, c=us")] public static void TestDistinguishedSubjectName_Match(string distinguishedSubjectName) { RunSingleMatchTest_MsCer(X509FindType.FindBySubjectDistinguishedName, distinguishedSubjectName); } [Fact] public static void TestIssuerName_NoMatch() { RunZeroMatchTest(X509FindType.FindByIssuerName, "Nothing"); } [Theory] [InlineData("Microsoft Code Signing PCA")] [InlineData("Microsoft Corporation")] [InlineData("Redmond")] [InlineData("Washington")] [InlineData("US")] [InlineData("US, Washington")] [InlineData("Washington, Redmond")] [InlineData("US, Washington, Redmond, Microsoft Corporation, Microsoft Code Signing PCA")] [InlineData("us, washington, redmond, microsoft corporation, microsoft code signing pca")] public static void TestIssuerName_Match(string issuerQualifier) { RunSingleMatchTest_MsCer(X509FindType.FindByIssuerName, issuerQualifier); } [Theory] [InlineData("")] [InlineData("Nothing")] [InlineData("CN=Microsoft Code Signing PCA")] [InlineData("CN=Microsoft Code Signing PCA, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] [InlineData("CN=Microsoft Code Signing PCA, O=Microsoft Corporation, L=Redmond, S=Washington, C=US ")] [InlineData(" CN=Microsoft Code Signing PCA, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] public static void TestDistinguishedIssuerName_NoMatch(string issuerDistinguishedName) { RunZeroMatchTest(X509FindType.FindByIssuerDistinguishedName, issuerDistinguishedName); } [Theory] [InlineData("CN=Microsoft Code Signing PCA, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] [InlineData("CN=microsoft Code signing pca, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] [InlineData("cn=microsoft code signing pca, o=microsoft corporation, l=redmond, s=washington, c=us")] public static void TestDistinguishedIssuerName_Match(string issuerDistinguishedName) { RunSingleMatchTest_MsCer(X509FindType.FindByIssuerDistinguishedName, issuerDistinguishedName); } [Fact] public static void TestByTimeValid_Before() { RunTest( (msCer, pfxCer, col1) => { DateTime earliest = new[] { msCer.NotBefore, pfxCer.NotBefore }.Min(); X509Certificate2Collection col2 = col1.Find( X509FindType.FindByTimeValid, earliest - TimeSpan.FromSeconds(1), validOnly: false); using (new ImportedCollection(col2)) { Assert.Equal(0, col2.Count); } }); } [Fact] public static void TestByTimeValid_After() { RunTest( (msCer, pfxCer, col1) => { DateTime latest = new[] { msCer.NotAfter, pfxCer.NotAfter }.Max(); X509Certificate2Collection col2 = col1.Find( X509FindType.FindByTimeValid, latest + TimeSpan.FromSeconds(1), validOnly: false); using (new ImportedCollection(col2)) { Assert.Equal(0, col2.Count); } }); } [Fact] public static void TestByTimeValid_Between() { RunTest( (msCer, pfxCer, col1) => { DateTime earliestNotAfter = new[] { msCer.NotAfter, pfxCer.NotAfter }.Min(); DateTime latestNotBefore = new[] { msCer.NotBefore, pfxCer.NotBefore }.Max(); TimeSpan gap = latestNotBefore - earliestNotAfter; // If this assert fails it means our test data was rebuilt and the constraint // can no longer be satisfied Assert.True(gap > TimeSpan.FromSeconds(1)); DateTime noMatchTime = earliestNotAfter + TimeSpan.FromSeconds(1); X509Certificate2Collection col2 = col1.Find( X509FindType.FindByTimeValid, noMatchTime, validOnly: false); using (new ImportedCollection(col2)) { Assert.Equal(0, col2.Count); } }); } [Fact] public static void TestByTimeValid_Match() { RunTest( (msCer, pfxCer, col1) => { EvaluateSingleMatch( msCer, col1, X509FindType.FindByTimeValid, msCer.NotBefore + TimeSpan.FromSeconds(1)); }); } [Fact] public static void TestFindByTimeNotYetValid_Match() { RunTest( (msCer, pfxCer, col1) => { DateTime earliestNotAfter = new[] { msCer.NotAfter, pfxCer.NotAfter }.Min(); DateTime latestNotBefore = new[] { msCer.NotBefore, pfxCer.NotBefore }.Max(); TimeSpan gap = latestNotBefore - earliestNotAfter; // If this assert fails it means our test data was rebuilt and the constraint // can no longer be satisfied Assert.True(gap > TimeSpan.FromSeconds(1)); // One second before the latest NotBefore, so one is valid, the other is not yet valid. DateTime matchTime = latestNotBefore - TimeSpan.FromSeconds(1); X509Certificate2Collection col2 = col1.Find( X509FindType.FindByTimeNotYetValid, matchTime, validOnly: false); using (new ImportedCollection(col2)) { Assert.Equal(1, col2.Count); } }); } [Fact] public static void TestFindByTimeNotYetValid_NoMatch() { RunTest( (msCer, pfxCer, col1) => { DateTime earliestNotAfter = new[] { msCer.NotAfter, pfxCer.NotAfter }.Min(); DateTime latestNotBefore = new[] { msCer.NotBefore, pfxCer.NotBefore }.Max(); TimeSpan gap = latestNotBefore - earliestNotAfter; // If this assert fails it means our test data was rebuilt and the constraint // can no longer be satisfied Assert.True(gap > TimeSpan.FromSeconds(1)); // One second after the latest NotBefore, both certificates are time-valid DateTime noMatchTime = latestNotBefore + TimeSpan.FromSeconds(1); X509Certificate2Collection col2 = col1.Find( X509FindType.FindByTimeNotYetValid, noMatchTime, validOnly: false); using (new ImportedCollection(col2)) { Assert.Equal(0, col2.Count); } }); } [Fact] public static void TestFindByTimeExpired_Match() { RunTest( (msCer, pfxCer, col1) => { DateTime earliestNotAfter = new[] { msCer.NotAfter, pfxCer.NotAfter }.Min(); DateTime latestNotBefore = new[] { msCer.NotBefore, pfxCer.NotBefore }.Max(); TimeSpan gap = latestNotBefore - earliestNotAfter; // If this assert fails it means our test data was rebuilt and the constraint // can no longer be satisfied Assert.True(gap > TimeSpan.FromSeconds(1)); // One second after the earliest NotAfter, so one is valid, the other is no longer valid. DateTime matchTime = earliestNotAfter + TimeSpan.FromSeconds(1); X509Certificate2Collection col2 = col1.Find( X509FindType.FindByTimeExpired, matchTime, validOnly: false); using (new ImportedCollection(col2)) { Assert.Equal(1, col2.Count); } }); } [Fact] public static void TestFindByTimeExpired_NoMatch() { RunTest( (msCer, pfxCer, col1) => { DateTime earliestNotAfter = new[] { msCer.NotAfter, pfxCer.NotAfter }.Min(); DateTime latestNotBefore = new[] { msCer.NotBefore, pfxCer.NotBefore }.Max(); TimeSpan gap = latestNotBefore - earliestNotAfter; // If this assert fails it means our test data was rebuilt and the constraint // can no longer be satisfied Assert.True(gap > TimeSpan.FromSeconds(1)); // One second before the earliest NotAfter, so both certificates are valid DateTime noMatchTime = earliestNotAfter - TimeSpan.FromSeconds(1); X509Certificate2Collection col2 = col1.Find( X509FindType.FindByTimeExpired, noMatchTime, validOnly: false); using (new ImportedCollection(col2)) { Assert.Equal(0, col2.Count); } }); } [Fact] public static void TestBySerialNumber_Decimal() { // Decimal string is an allowed input format. RunSingleMatchTest_PfxCer( X509FindType.FindBySerialNumber, "284069184166497622998429950103047369500"); } [Fact] public static void TestBySerialNumber_DecimalLeadingZeros() { // Checking that leading zeros are ignored. RunSingleMatchTest_PfxCer( X509FindType.FindBySerialNumber, "000" + "284069184166497622998429950103047369500"); } [Theory] [InlineData("1137338006039264696476027508428304567989436592")] // Leading zeroes are fine/ignored [InlineData("0001137338006039264696476027508428304567989436592")] // Compat: Minus signs are ignored [InlineData("-1137338006039264696476027508428304567989436592")] public static void TestBySerialNumber_Decimal_CertB(string serialNumber) { RunSingleMatchTest_MsCer(X509FindType.FindBySerialNumber, serialNumber); } [Fact] public static void TestBySerialNumber_Hex() { // Hex string is also an allowed input format. RunSingleMatchTest_PfxCer( X509FindType.FindBySerialNumber, "D5B5BC1C458A558845BFF51CB4DFF31C"); } [Fact] public static void TestBySerialNumber_HexIgnoreCase() { // Hex string is also an allowed input format and case-blind RunSingleMatchTest_PfxCer( X509FindType.FindBySerialNumber, "d5b5bc1c458a558845bff51cb4dff31c"); } [Fact] public static void TestBySerialNumber_HexLeadingZeros() { // Checking that leading zeros are ignored. RunSingleMatchTest_PfxCer( X509FindType.FindBySerialNumber, "0000" + "D5B5BC1C458A558845BFF51CB4DFF31C"); } [Fact] public static void TestBySerialNumber_NoMatch() { RunZeroMatchTest( X509FindType.FindBySerialNumber, "23000000B011AF0A8BD03B9FDD0001000000B0"); } [Theory] [MemberData(nameof(GenerateWorkingFauxSerialNumbers))] public static void TestBySerialNumber_Match_NonDecimalInput(string input) { RunSingleMatchTest_MsCer(X509FindType.FindBySerialNumber, input); } [Fact] public static void TestByExtension_FriendlyName() { // Cannot just say "Enhanced Key Usage" here because the extension name is localized. // Instead, look it up via the OID. RunSingleMatchTest_MsCer(X509FindType.FindByExtension, new Oid("2.5.29.37").FriendlyName); } [Fact] public static void TestByExtension_OidValue() { RunSingleMatchTest_MsCer(X509FindType.FindByExtension, "2.5.29.37"); } [Fact] // Compat: Non-ASCII digits don't throw, but don't match. public static void TestByExtension_OidValue_ArabicNumericChar() { // This uses the same OID as TestByExtension_OidValue, but uses "Arabic-Indic Digit Two" instead // of "Digit Two" in the third segment. This value can't possibly ever match, but it doesn't throw // as an illegal OID value. RunZeroMatchTest(X509FindType.FindByExtension, "2.5.\u06629.37"); } [Fact] public static void TestByExtension_UnknownFriendlyName() { RunExceptionTest<ArgumentException>(X509FindType.FindByExtension, "BOGUS"); } [Fact] public static void TestByExtension_NoMatch() { RunZeroMatchTest(X509FindType.FindByExtension, "2.9"); } [Fact] public static void TestBySubjectKeyIdentifier_UsingFallback() { RunSingleMatchTest_PfxCer( X509FindType.FindBySubjectKeyIdentifier, "B4D738B2D4978AFF290A0B02987BABD114FEE9C7"); } [Theory] [InlineData("5971A65A334DDA980780FF841EBE87F9723241F2")] // Whitespace is allowed [InlineData("59 71\tA6 5A 33 4D DA 98 07 80 FF 84 1E BE 87 F9 72 32 41 F2")] // Lots of kinds of whitespace (does not include \u000b or \u000c, because those // produce a build warning (which becomes an error): // EXEC : warning : '(not included here)', hexadecimal value 0x0C, is an invalid character. [InlineData( "59\u000971\u000aA6\u30005A\u205f33\u000d4D\u0020DA\u008598\u00a007\u1680" + "80\u2000FF\u200184\u20021E\u2003BE\u200487\u2005F9\u200672\u200732\u2008" + "4\u20091\u200aF\u20282\u2029\u202f")] // Non-byte-aligned whitespace is allowed [InlineData("597 1A6 5A3 34D DA9 807 80F F84 1EB E87 F97 232 41F 2")] // Non-symmetric whitespace is allowed [InlineData(" 5971A65 A334DDA980780FF84 1EBE87F97 23241F 2")] public static void TestBySubjectKeyIdentifier_ExtensionPresent(string subjectKeyIdentifier) { RunSingleMatchTest_MsCer(X509FindType.FindBySubjectKeyIdentifier, subjectKeyIdentifier); } [Theory] // Compat: Lone trailing nybbles are ignored [InlineData("59 71 A6 5A 33 4D DA 98 07 80 FF 84 1E BE 87 F9 72 32 41 F2 3")] // Compat: Lone trailing nybbles are ignored, even if not hex [InlineData("59 71 A6 5A 33 4D DA 98 07 80 FF 84 1E BE 87 F9 72 32 41 F2 p")] // Compat: A non-hex character as the high nybble makes that nybble be F [InlineData("59 71 A6 5A 33 4D DA 98 07 80 FF 84 1E BE 87 p9 72 32 41 F2")] // Compat: A non-hex character as the low nybble makes the whole byte FF. [InlineData("59 71 A6 5A 33 4D DA 98 07 80 0p 84 1E BE 87 F9 72 32 41 F2")] public static void TestBySubjectKeyIdentifier_Compat(string subjectKeyIdentifier) { RunSingleMatchTest_MsCer(X509FindType.FindBySubjectKeyIdentifier, subjectKeyIdentifier); } [Fact] public static void TestBySubjectKeyIdentifier_NoMatch() { RunZeroMatchTest(X509FindType.FindBySubjectKeyIdentifier, ""); } [Fact] public static void TestBySubjectKeyIdentifier_NoMatch_RightLength() { RunZeroMatchTest( X509FindType.FindBySubjectKeyIdentifier, "5971A65A334DDA980780FF841EBE87F9723241F0"); } [Fact] public static void TestByApplicationPolicy_MatchAll() { RunTest( (msCer, pfxCer, col1) => { X509Certificate2Collection results = col1.Find(X509FindType.FindByApplicationPolicy, "1.3.6.1.5.5.7.3.3", false); using (new ImportedCollection(results)) { Assert.Equal(2, results.Count); Assert.True(results.Contains(msCer)); Assert.True(results.Contains(pfxCer)); } }); } [Fact] public static void TestByApplicationPolicy_NoPolicyAlwaysMatches() { // PfxCer doesn't have any application policies which means it's good for all usages (even nonsensical ones.) RunSingleMatchTest_PfxCer(X509FindType.FindByApplicationPolicy, "2.2"); } [Fact] public static void TestByApplicationPolicy_NoMatch() { RunTest( (msCer, pfxCer, col1) => { // Per TestByApplicationPolicy_NoPolicyAlwaysMatches we know that pfxCer will match, so remove it. col1.Remove(pfxCer); X509Certificate2Collection results = col1.Find(X509FindType.FindByApplicationPolicy, "2.2", false); using (new ImportedCollection(results)) { Assert.Equal(0, results.Count); } }); } [Fact] public static void TestByCertificatePolicies_MatchA() { using (var policyCert = new X509Certificate2(TestData.CertWithPolicies)) { EvaluateSingleMatch( policyCert, new X509Certificate2Collection(policyCert), X509FindType.FindByCertificatePolicy, "2.18.19"); } } [Fact] public static void TestByCertificatePolicies_MatchB() { using (var policyCert = new X509Certificate2(TestData.CertWithPolicies)) { EvaluateSingleMatch( policyCert, new X509Certificate2Collection(policyCert), X509FindType.FindByCertificatePolicy, "2.32.33"); } } [Fact] public static void TestByCertificatePolicies_NoMatch() { using (var policyCert = new X509Certificate2(TestData.CertWithPolicies)) { X509Certificate2Collection col1 = new X509Certificate2Collection(policyCert); X509Certificate2Collection results = col1.Find(X509FindType.FindByCertificatePolicy, "2.999", false); using (new ImportedCollection(results)) { Assert.Equal(0, results.Count); } } } [Fact] public static void TestByTemplate_MatchA() { using (var templatedCert = new X509Certificate2(TestData.CertWithTemplateData)) { EvaluateSingleMatch( templatedCert, new X509Certificate2Collection(templatedCert), X509FindType.FindByTemplateName, "Hello"); } } [Fact] public static void TestByTemplate_MatchB() { using (var templatedCert = new X509Certificate2(TestData.CertWithTemplateData)) { EvaluateSingleMatch( templatedCert, new X509Certificate2Collection(templatedCert), X509FindType.FindByTemplateName, "2.7.8.9"); } } [Fact] public static void TestByTemplate_NoMatch() { using (var templatedCert = new X509Certificate2(TestData.CertWithTemplateData)) { X509Certificate2Collection col1 = new X509Certificate2Collection(templatedCert); X509Certificate2Collection results = col1.Find(X509FindType.FindByTemplateName, "2.999", false); using (new ImportedCollection(results)) { Assert.Equal(0, results.Count); } } } [Theory] [InlineData((int)0x80)] [InlineData((uint)0x80)] [InlineData(X509KeyUsageFlags.DigitalSignature)] [InlineData("DigitalSignature")] [InlineData("digitalSignature")] public static void TestFindByKeyUsage_Match(object matchCriteria) { TestFindByKeyUsage(true, matchCriteria); } [Theory] [InlineData((int)0x20)] [InlineData((uint)0x20)] [InlineData(X509KeyUsageFlags.KeyEncipherment)] [InlineData("KeyEncipherment")] [InlineData("KEYEncipherment")] public static void TestFindByKeyUsage_NoMatch(object matchCriteria) { TestFindByKeyUsage(false, matchCriteria); } private static void TestFindByKeyUsage(bool shouldMatch, object matchCriteria) { using (var noKeyUsages = new X509Certificate2(TestData.MsCertificate)) using (var noKeyUsages2 = new X509Certificate2(Path.Combine("TestData", "test.cer"))) using (var keyUsages = new X509Certificate2(Path.Combine("TestData", "microsoft.cer"))) { var coll = new X509Certificate2Collection { noKeyUsages, noKeyUsages2, keyUsages, }; X509Certificate2Collection results = coll.Find(X509FindType.FindByKeyUsage, matchCriteria, false); using (new ImportedCollection(results)) { // The two certificates with no KeyUsages extension will always match, // the real question is about the third. int matchCount = shouldMatch ? 3 : 2; Assert.Equal(matchCount, results.Count); if (shouldMatch) { bool found = false; foreach (X509Certificate2 cert in results) { if (keyUsages.Equals(cert)) { Assert.NotSame(cert, keyUsages); found = true; break; } } Assert.True(found, "Certificate with key usages was found in the collection"); } else { Assert.False( results.Contains(keyUsages), "KeyUsages certificate is not present in the collection"); } } } } public static IEnumerable<object[]> GenerateWorkingFauxSerialNumbers { get { const string seedDec = "1137338006039264696476027508428304567989436592"; string[] nonHexWords = { "wow", "its", "tough", "using", "only", "high", "lttr", "vlus" }; string gluedTogether = string.Join("", nonHexWords); string withSpaces = string.Join(" ", nonHexWords); yield return new object[] { gluedTogether + seedDec }; yield return new object[] { seedDec + gluedTogether }; yield return new object[] { withSpaces + seedDec }; yield return new object[] { seedDec + withSpaces }; StringBuilder builderDec = new StringBuilder(512); int offsetDec = 0; for (int i = 0; i < nonHexWords.Length; i++) { if (offsetDec < seedDec.Length) { int appendLen = Math.Max(1, seedDec.Length / nonHexWords.Length); appendLen = Math.Min(appendLen, seedDec.Length - offsetDec); builderDec.Append(seedDec, offsetDec, appendLen); offsetDec += appendLen; } builderDec.Append(nonHexWords[i]); } builderDec.Append(seedDec, offsetDec, seedDec.Length - offsetDec); yield return new object[] { builderDec.ToString() }; builderDec.Length = 0; offsetDec = 0; for (int i = 0; i < nonHexWords.Length; i++) { if (offsetDec < seedDec.Length) { int appendLen = Math.Max(1, seedDec.Length / nonHexWords.Length); appendLen = Math.Min(appendLen, seedDec.Length - offsetDec); builderDec.Append(seedDec, offsetDec, appendLen); offsetDec += appendLen; builderDec.Append(' '); } builderDec.Append(nonHexWords[i]); builderDec.Append(' '); } builderDec.Append(seedDec, offsetDec, seedDec.Length - offsetDec); yield return new object[] { builderDec.ToString() }; } } public static IEnumerable<object[]> GenerateInvalidOidInputs { get { X509FindType[] oidTypes = { X509FindType.FindByApplicationPolicy, }; string[] invalidOids = { "", "This Is Not An Oid", "1", "95.22", ".1", "1..1", "1.", "1.2.", }; List<object[]> combinations = new List<object[]>(oidTypes.Length * invalidOids.Length); for (int findTypeIndex = 0; findTypeIndex < oidTypes.Length; findTypeIndex++) { for (int oidIndex = 0; oidIndex < invalidOids.Length; oidIndex++) { combinations.Add(new object[] { oidTypes[findTypeIndex], invalidOids[oidIndex] }); } } return combinations; } } public static IEnumerable<object[]> GenerateInvalidInputs { get { Type[] allTypes = { typeof(object), typeof(DateTime), typeof(byte[]), typeof(string), }; Tuple<X509FindType, Type>[] legalInputs = { Tuple.Create(X509FindType.FindByThumbprint, typeof(string)), Tuple.Create(X509FindType.FindBySubjectName, typeof(string)), Tuple.Create(X509FindType.FindBySubjectDistinguishedName, typeof(string)), Tuple.Create(X509FindType.FindByIssuerName, typeof(string)), Tuple.Create(X509FindType.FindByIssuerDistinguishedName, typeof(string)), Tuple.Create(X509FindType.FindBySerialNumber, typeof(string)), Tuple.Create(X509FindType.FindByTimeValid, typeof(DateTime)), Tuple.Create(X509FindType.FindByTimeNotYetValid, typeof(DateTime)), Tuple.Create(X509FindType.FindByTimeExpired, typeof(DateTime)), Tuple.Create(X509FindType.FindByTemplateName, typeof(string)), Tuple.Create(X509FindType.FindByApplicationPolicy, typeof(string)), Tuple.Create(X509FindType.FindByCertificatePolicy, typeof(string)), Tuple.Create(X509FindType.FindByExtension, typeof(string)), // KeyUsage supports int/uint/KeyUsage/string, but only one of those is in allTypes. Tuple.Create(X509FindType.FindByKeyUsage, typeof(string)), Tuple.Create(X509FindType.FindBySubjectKeyIdentifier, typeof(string)), }; List<object[]> invalidCombinations = new List<object[]>(); for (int findTypesIndex = 0; findTypesIndex < legalInputs.Length; findTypesIndex++) { Tuple<X509FindType, Type> tuple = legalInputs[findTypesIndex]; for (int typeIndex = 0; typeIndex < allTypes.Length; typeIndex++) { Type t = allTypes[typeIndex]; if (t != tuple.Item2) { invalidCombinations.Add(new object[] { tuple.Item1, t }); } } } return invalidCombinations; } } } }
/* * 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 System.Collections.Generic; using System.IO; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; using System.Runtime.Serialization.Formatters; namespace Apache.Geode.Client.FwkClient { using Apache.Geode.DUnitFramework; class ClientProcess { public static IChannel clientChannel = null; public static string bbUrl; public static string logFile = null; static void Main(string[] args) { string myId = "0"; try { int myNum; string driverUrl; object clientPort; ParseArguments(args, out driverUrl, out bbUrl, out clientPort, out myId, out myNum, out logFile); // NOTE: This is required so that remote client receive custom exceptions RemotingConfiguration.CustomErrorsMode = CustomErrorsModes.Off; BinaryServerFormatterSinkProvider serverProvider = new BinaryServerFormatterSinkProvider(); serverProvider.TypeFilterLevel = TypeFilterLevel.Full; BinaryClientFormatterSinkProvider clientProvider = new BinaryClientFormatterSinkProvider(); Dictionary<string, string> properties; #region Create the communication channel to receive commands from server properties = new Dictionary<string, string>(); properties["port"] = clientPort.ToString(); clientChannel = new TcpChannel(properties, clientProvider, serverProvider); //Util.Log("Registering TCP channel: " + clientPort); ChannelServices.RegisterChannel(clientChannel, false); RemotingConfiguration.RegisterWellKnownServiceType(typeof(ClientComm), CommConstants.ClientService, WellKnownObjectMode.SingleCall); #endregion Util.ClientId = myId; Util.ClientNum = myNum; Util.LogFile = logFile; Util.DriverComm = ServerConnection<IDriverComm>.Connect(driverUrl); Util.BBComm = ServerConnection<IBBComm>.Connect(bbUrl); Util.ClientListening(); } catch (Exception ex) { Util.Log("FATAL: Client {0}, Exception caught: {1}", myId, ex); } System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite); } private static void ShowUsage(string[] args) { if (args != null) { Util.Log("Args: "); foreach (string arg in args) { Util.Log("\t{0}", arg); } } string procName = Util.ProcessName; Util.Log("Usage: " + procName + " [OPTION] <client port>"); Util.Log("Options are:"); Util.Log(" --id=ID \t\t ID of the client; process ID is used when not provided"); Util.Log(" --driver=URL \t The URL (e.g. tcp://<host>:<port>/<service>) of the Driver"); Util.Log(" --bbServer=URL \t The URL (e.g. tcp://<host>:<port>/<service>) of the BlackBoard server"); Util.Log(" --num=NUM \t\t An optional number for the process"); Util.Log(" --log=LOGFILE \t The name of the logfile; standard output is used when not provided"); Util.Log(" --env:VAR=VALUE \t Set environment variable VAR with given VALUE"); Util.Log(" \t If VAR is the PATH variable then it is prepended to the existing PATH"); Util.Log(" --startdir=DIR \t Start in the given directory"); Util.Log(" --bg \t Start in background"); Environment.Exit(1); } private static void ParseArguments(string[] args, out string driverUrl, out string bbUrl, out object clientPort, out string myId, out int myNum, out string logFile) { if (args == null) { ShowUsage(args); } string IDOption = "--id="; string DriverOption = "--driver="; string BBServerOption = "--bbServer="; string NumOption = "--num="; string LogOption = "--log="; string EnvOption = "--env:"; string StartDirOption = "--startdir="; string BGOption = "--bg"; myId = Util.PID.ToString(); driverUrl = null; bbUrl = null; myNum = 0; logFile = null; int argIndx = 0; while (argIndx <= (args.Length - 1) && args[argIndx].StartsWith("--")) { string arg = args[argIndx]; if (arg.StartsWith(IDOption)) { myId = arg.Substring(IDOption.Length); } else if (arg.StartsWith(DriverOption)) { driverUrl = arg.Substring(DriverOption.Length); } else if (arg.StartsWith(BBServerOption)) { bbUrl = arg.Substring(BBServerOption.Length); } else if (arg.StartsWith(NumOption)) { try { myNum = int.Parse(arg.Substring(NumOption.Length)); } catch (Exception ex) { Util.Log("Exception while reading --num: {0}", ex.Message); ShowUsage(args); } } else if (arg.StartsWith(LogOption)) { logFile = arg.Substring(LogOption.Length); } else if (arg.StartsWith(EnvOption)) { string[] envVarValue = arg.Substring(EnvOption.Length).Split('='); if (envVarValue.Length != 2) { ShowUsage(args); } string envVar = envVarValue[0]; string envValue = envVarValue[1]; int lastIndx = envVar.Length - 1; if (envVar[lastIndx] == '+') { envVar = envVar.Substring(0, lastIndx); envValue = envValue + Util.GetEnvironmentVariable(envVar); } Util.SetEnvironmentVariable(envVar, envValue); } else if (arg.StartsWith(StartDirOption)) { string startDir = arg.Substring(StartDirOption.Length); if (startDir.Length > 0) { Environment.CurrentDirectory = startDir; } } else if (arg == BGOption) { string procArgs = string.Empty; foreach (string newArg in args) { if (newArg != BGOption) { procArgs += '"' + newArg + "\" "; } } procArgs = procArgs.Trim(); System.Diagnostics.Process bgProc; if (!Util.StartProcess(Environment.GetCommandLineArgs()[0], procArgs, false, null, false, false, false, out bgProc)) { Util.Log("Failed to start background process with args: {0}", procArgs); Environment.Exit(1); } Environment.Exit(0); } else { Util.Log("Unknown option: {0}", arg); ShowUsage(args); } argIndx++; } if (driverUrl == null || driverUrl.Length == 0 || bbUrl == null || bbUrl.Length == 0) { ShowUsage(args); } if (args.Length != (argIndx + 1)) { Util.Log("Incorrect number of arguments: {0}", (args.Length - argIndx)); ShowUsage(args); } try { clientPort = int.Parse(args[argIndx]); } catch { clientPort = args[argIndx]; } } } public class CreateBBServerConnection : MarshalByRefObject { public void OpenBBServerConnection(string urlPath) { Util.BBComm = ServerConnection<IBBComm>.Connect(urlPath); } public void SetLogFile(string logfile) { Util.LogFile = logfile; } } }
// 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.Diagnostics; namespace System.Collections.ObjectModel { [Serializable] [DebuggerTypeProxy(typeof(ICollectionDebugView<>))] [DebuggerDisplay("Count = {Count}")] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class ReadOnlyCollection<T> : IList<T>, IList, IReadOnlyList<T> { private IList<T> list; // Do not rename (binary serialization) public ReadOnlyCollection(IList<T> list) { if (list == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.list); } this.list = list; } public int Count { get { return list.Count; } } public T this[int index] { get { return list[index]; } } public bool Contains(T value) { return list.Contains(value); } public void CopyTo(T[] array, int index) { list.CopyTo(array, index); } public IEnumerator<T> GetEnumerator() { return list.GetEnumerator(); } public int IndexOf(T value) { return list.IndexOf(value); } protected IList<T> Items { get { return list; } } bool ICollection<T>.IsReadOnly { get { return true; } } T IList<T>.this[int index] { get { return list[index]; } set { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } } void ICollection<T>.Add(T value) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } void ICollection<T>.Clear() { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } void IList<T>.Insert(int index, T value) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } bool ICollection<T>.Remove(T value) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); return false; } void IList<T>.RemoveAt(int index) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)list).GetEnumerator(); } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return (list is ICollection coll) ? coll.SyncRoot : this; } } void ICollection.CopyTo(Array array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (array.Rank != 1) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } if (array.GetLowerBound(0) != 0) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); } if (index < 0) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (array.Length - index < Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } if (array is T[] items) { list.CopyTo(items, index); } else { // // Catch the obvious case assignment will fail. // We can't find all possible problems by doing the check though. // For example, if the element type of the Array is derived from T, // we can't figure out if we can successfully copy the element beforehand. // Type targetType = array.GetType().GetElementType(); Type sourceType = typeof(T); if (!(targetType.IsAssignableFrom(sourceType) || sourceType.IsAssignableFrom(targetType))) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } // // We can't cast array of value type to object[], so we don't support // widening of primitive types here. // object[] objects = array as object[]; if (objects == null) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } int count = list.Count; try { for (int i = 0; i < count; i++) { objects[index++] = list[i]; } } catch (ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } } } bool IList.IsFixedSize { get { return true; } } bool IList.IsReadOnly { get { return true; } } object IList.this[int index] { get { return list[index]; } set { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } } int IList.Add(object value) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); return -1; } void IList.Clear() { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } private static bool IsCompatibleObject(object value) { // Non-null values are fine. Only accept nulls if T is a class or Nullable<U>. // Note that default(T) is not equal to null for value types except when T is Nullable<U>. return ((value is T) || (value == null && default(T) == null)); } bool IList.Contains(object value) { if (IsCompatibleObject(value)) { return Contains((T)value); } return false; } int IList.IndexOf(object value) { if (IsCompatibleObject(value)) { return IndexOf((T)value); } return -1; } void IList.Insert(int index, object value) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } void IList.Remove(object value) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } void IList.RemoveAt(int index) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } } }
// 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.Reflection; using System.Runtime.Remoting; using System.Runtime.Serialization; using System.Globalization; using System.Diagnostics.Contracts; namespace System { [Serializable] internal sealed class DelegateSerializationHolder : IObjectReference, ISerializable { #region Static Members internal static DelegateEntry GetDelegateSerializationInfo( SerializationInfo info, Type delegateType, Object target, MethodInfo method, int targetIndex) { // Used for MulticastDelegate if (method == null) throw new ArgumentNullException(nameof(method)); Contract.EndContractBlock(); Type c = delegateType.BaseType; if (c == null || (c != typeof(Delegate) && c != typeof(MulticastDelegate))) throw new ArgumentException(SR.Arg_MustBeDelegate, "type"); if (method.DeclaringType == null) throw new NotSupportedException(SR.NotSupported_GlobalMethodSerialization); DelegateEntry de = new DelegateEntry(delegateType.FullName, delegateType.Module.Assembly.FullName, target, method.ReflectedType.Module.Assembly.FullName, method.ReflectedType.FullName, method.Name); if (info.MemberCount == 0) { info.SetType(typeof(DelegateSerializationHolder)); info.AddValue("Delegate", de, typeof(DelegateEntry)); } // target can be an object so it needs to be added to the info, or else a fixup is needed // when deserializing, and the fixup will occur too late. If it is added directly to the // info then the rules of deserialization will guarantee that it will be available when // needed if (target != null) { String targetName = "target" + targetIndex; info.AddValue(targetName, de.target); de.target = targetName; } // Due to a number of additions (delegate signature binding relaxation, delegates with open this or closed over the // first parameter and delegates over generic methods) we need to send a deal more information than previously. We can // get this by serializing the target MethodInfo. We still need to send the same information as before though (the // DelegateEntry above) for backwards compatibility. And we want to send the MethodInfo (which is serialized via an // ISerializable holder) as a top-level child of the info for the same reason as the target above -- we wouldn't have an // order of deserialization guarantee otherwise. String methodInfoName = "method" + targetIndex; info.AddValue(methodInfoName, method); return de; } #endregion #region Definitions [Serializable] internal class DelegateEntry { #region Internal Data Members internal String type; internal String assembly; internal Object target; internal String targetTypeAssembly; internal String targetTypeName; internal String methodName; internal DelegateEntry delegateEntry; #endregion #region Constructor internal DelegateEntry( String type, String assembly, Object target, String targetTypeAssembly, String targetTypeName, String methodName) { this.type = type; this.assembly = assembly; this.target = target; this.targetTypeAssembly = targetTypeAssembly; this.targetTypeName = targetTypeName; this.methodName = methodName; } #endregion #region Internal Members internal DelegateEntry Entry { get { return delegateEntry; } set { delegateEntry = value; } } #endregion } #endregion #region Private Data Members private DelegateEntry m_delegateEntry; private MethodInfo[] m_methods; #endregion #region Constructor private DelegateSerializationHolder(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); bool bNewWire = true; try { m_delegateEntry = (DelegateEntry)info.GetValue("Delegate", typeof(DelegateEntry)); } catch { // Old wire format m_delegateEntry = OldDelegateWireFormat(info, context); bNewWire = false; } if (bNewWire) { // retrieve the targets DelegateEntry deiter = m_delegateEntry; int count = 0; while (deiter != null) { if (deiter.target != null) { string stringTarget = deiter.target as string; //need test to pass older wire format if (stringTarget != null) deiter.target = info.GetValue(stringTarget, typeof(Object)); } count++; deiter = deiter.delegateEntry; } // If the sender is as recent as us they'll have provided MethodInfos for each delegate. Look for these and pack // them into an ordered array if present. MethodInfo[] methods = new MethodInfo[count]; int i; for (i = 0; i < count; i++) { String methodInfoName = "method" + i; methods[i] = (MethodInfo)info.GetValueNoThrow(methodInfoName, typeof(MethodInfo)); if (methods[i] == null) break; } // If we got the info then make the array available for deserialization. if (i == count) m_methods = methods; } } #endregion #region Private Members private void ThrowInsufficientState(string field) { throw new SerializationException( SR.Format(SR.Serialization_InsufficientDeserializationState, field)); } private DelegateEntry OldDelegateWireFormat(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); String delegateType = info.GetString("DelegateType"); String delegateAssembly = info.GetString("DelegateAssembly"); Object target = info.GetValue("Target", typeof(Object)); String targetTypeAssembly = info.GetString("TargetTypeAssembly"); String targetTypeName = info.GetString("TargetTypeName"); String methodName = info.GetString("MethodName"); return new DelegateEntry(delegateType, delegateAssembly, target, targetTypeAssembly, targetTypeName, methodName); } private Delegate GetDelegate(DelegateEntry de, int index) { Delegate d; try { if (de.methodName == null || de.methodName.Length == 0) ThrowInsufficientState("MethodName"); if (de.assembly == null || de.assembly.Length == 0) ThrowInsufficientState("DelegateAssembly"); if (de.targetTypeName == null || de.targetTypeName.Length == 0) ThrowInsufficientState("TargetTypeName"); // We cannot use Type.GetType directly, because of AppCompat - assembly names starting with '[' would fail to load. RuntimeType type = (RuntimeType)Assembly.GetType_Compat(de.assembly, de.type); // {de.targetTypeAssembly, de.targetTypeName} do not actually refer to the type of the target, but the reflected // type of the method. Those types may be the same when the method is on the target's type or on a type in its // inheritance chain, but those types may not be the same when the method is an extension method for the // target's type or a type in its inheritance chain. // If we received the new style delegate encoding we already have the target MethodInfo in hand. if (m_methods != null) { // The method info is serialized, so the target type info is redundant. The desktop framework does no // additional verification on the target type info. d = Delegate.CreateDelegateNoSecurityCheck(type, de.target, m_methods[index]); } else { if (de.target != null) { // For consistency with the desktop framework, when the method info is not serialized for a closed // delegate, the method is assumed to be on the target's type or in its inheritance chain. An extension // method would not work on this path for the above reason and also because the delegate binds to // instance methods only. The desktop framework does no additional verification on the target type info. d = Delegate.CreateDelegate(type, de.target, de.methodName); } else { RuntimeType targetType = (RuntimeType)Assembly.GetType_Compat(de.targetTypeAssembly, de.targetTypeName); d = Delegate.CreateDelegate(type, targetType, de.methodName); } } } catch (Exception e) { if (e is SerializationException) throw e; throw new SerializationException(e.Message, e); } return d; } #endregion #region IObjectReference public Object GetRealObject(StreamingContext context) { int count = 0; for (DelegateEntry de = m_delegateEntry; de != null; de = de.Entry) count++; int maxindex = count - 1; if (count == 1) { return GetDelegate(m_delegateEntry, 0); } else { object[] invocationList = new object[count]; for (DelegateEntry de = m_delegateEntry; de != null; de = de.Entry) { // Be careful to match the index we pass to GetDelegate (used to look up extra information for each delegate) to // the order we process the entries: we're actually looking at them in reverse order. --count; invocationList[count] = GetDelegate(de, maxindex - count); } return ((MulticastDelegate)invocationList[0]).NewMulticastDelegate(invocationList, invocationList.Length); } } #endregion #region ISerializable public void GetObjectData(SerializationInfo info, StreamingContext context) { throw new NotSupportedException(SR.NotSupported_DelegateSerHolderSerial); } #endregion } }
// PendingBuffer.cs // // Copyright (C) 2001 Mike Krueger // Copyright (C) 2004 John Reilly // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 2001 Free Software Foundation, Inc. // // 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. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; namespace ICSharpCode.SharpZipLib.Zip.Compression { /// <summary> /// This class is general purpose class for writing data to a buffer. /// /// It allows you to write bits as well as bytes /// Based on DeflaterPending.java /// /// author of the original java version : Jochen Hoenicke /// </summary> internal class PendingBuffer { #region Instance Fields /// <summary> /// Internal work buffer /// </summary> byte[] buffer_; int start; int end; uint bits; int bitCount; #endregion #region Constructors /// <summary> /// construct instance using default buffer size of 4096 /// </summary> public PendingBuffer() : this( 4096 ) { } /// <summary> /// construct instance using specified buffer size /// </summary> /// <param name="bufferSize"> /// size to use for internal buffer /// </param> public PendingBuffer(int bufferSize) { buffer_ = new byte[bufferSize]; } #endregion /// <summary> /// Clear internal state/buffers /// </summary> public void Reset() { start = end = bitCount = 0; } /// <summary> /// Write a byte to buffer /// </summary> /// <param name="value"> /// The value to write /// </param> public void WriteByte(int value) { #if DebugDeflation if (DeflaterConstants.DEBUGGING && (start != 0) ) { throw new SharpZipBaseException("Debug check: start != 0"); } #endif buffer_[end++] = unchecked((byte) value); } /// <summary> /// Write a short value to buffer LSB first /// </summary> /// <param name="value"> /// The value to write. /// </param> public void WriteShort(int value) { #if DebugDeflation if (DeflaterConstants.DEBUGGING && (start != 0) ) { throw new SharpZipBaseException("Debug check: start != 0"); } #endif buffer_[end++] = unchecked((byte) value); buffer_[end++] = unchecked((byte) (value >> 8)); } /// <summary> /// write an integer LSB first /// </summary> /// <param name="value">The value to write.</param> public void WriteInt(int value) { #if DebugDeflation if (DeflaterConstants.DEBUGGING && (start != 0) ) { throw new SharpZipBaseException("Debug check: start != 0"); } #endif buffer_[end++] = unchecked((byte) value); buffer_[end++] = unchecked((byte) (value >> 8)); buffer_[end++] = unchecked((byte) (value >> 16)); buffer_[end++] = unchecked((byte) (value >> 24)); } /// <summary> /// Write a block of data to buffer /// </summary> /// <param name="block">data to write</param> /// <param name="offset">offset of first byte to write</param> /// <param name="length">number of bytes to write</param> public void WriteBlock(byte[] block, int offset, int length) { #if DebugDeflation if (DeflaterConstants.DEBUGGING && (start != 0) ) { throw new SharpZipBaseException("Debug check: start != 0"); } #endif System.Array.Copy(block, offset, buffer_, end, length); end += length; } /// <summary> /// The number of bits written to the buffer /// </summary> public int BitCount { get { return bitCount; } } /// <summary> /// Align internal buffer on a byte boundary /// </summary> public void AlignToByte() { #if DebugDeflation if (DeflaterConstants.DEBUGGING && (start != 0) ) { throw new SharpZipBaseException("Debug check: start != 0"); } #endif if (bitCount > 0) { buffer_[end++] = unchecked((byte) bits); if (bitCount > 8) { buffer_[end++] = unchecked((byte) (bits >> 8)); } } bits = 0; bitCount = 0; } /// <summary> /// Write bits to internal buffer /// </summary> /// <param name="b">source of bits</param> /// <param name="count">number of bits to write</param> public void WriteBits(int b, int count) { #if DebugDeflation if (DeflaterConstants.DEBUGGING && (start != 0) ) { throw new SharpZipBaseException("Debug check: start != 0"); } // if (DeflaterConstants.DEBUGGING) { // //Console.WriteLine("writeBits("+b+","+count+")"); // } #endif bits |= (uint)(b << bitCount); bitCount += count; if (bitCount >= 16) { buffer_[end++] = unchecked((byte) bits); buffer_[end++] = unchecked((byte) (bits >> 8)); bits >>= 16; bitCount -= 16; } } /// <summary> /// Write a short value to internal buffer most significant byte first /// </summary> /// <param name="s">value to write</param> public void WriteShortMSB(int s) { #if DebugDeflation if (DeflaterConstants.DEBUGGING && (start != 0) ) { throw new SharpZipBaseException("Debug check: start != 0"); } #endif buffer_[end++] = unchecked((byte) (s >> 8)); buffer_[end++] = unchecked((byte) s); } /// <summary> /// Indicates if buffer has been flushed /// </summary> public bool IsFlushed { get { return end == 0; } } /// <summary> /// Flushes the pending buffer into the given output array. If the /// output array is to small, only a partial flush is done. /// </summary> /// <param name="output">The output array.</param> /// <param name="offset">The offset into output array.</param> /// <param name="length">The maximum number of bytes to store.</param> /// <returns>The number of bytes flushed.</returns> public int Flush(byte[] output, int offset, int length) { if (bitCount >= 8) { buffer_[end++] = unchecked((byte) bits); bits >>= 8; bitCount -= 8; } if (length > end - start) { length = end - start; System.Array.Copy(buffer_, start, output, offset, length); start = 0; end = 0; } else { System.Array.Copy(buffer_, start, output, offset, length); start += length; } return length; } /// <summary> /// Convert internal buffer to byte array. /// Buffer is empty on completion /// </summary> /// <returns> /// The internal buffer contents converted to a byte array. /// </returns> public byte[] ToByteArray() { byte[] result = new byte[end - start]; System.Array.Copy(buffer_, start, result, 0, result.Length); start = 0; end = 0; return result; } } }
// 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.Xml; using System.Xml.XPath; namespace MS.Internal.Xml.Cache { /// <summary> /// Although the XPath data model does not differentiate between text and whitespace, Managed Xml 1.0 /// does. Therefore, when building from an XmlReader, we must preserve these designations in order /// to remain backwards-compatible. /// </summary> internal enum TextBlockType { None = 0, Text = XPathNodeType.Text, SignificantWhitespace = XPathNodeType.SignificantWhitespace, Whitespace = XPathNodeType.Whitespace, }; /// <summary> /// Implementation of XmlRawWriter that builds nodes in an XPathDocument. /// </summary> internal sealed class XPathDocumentBuilder : XmlRawWriter { private NodePageFactory _nodePageFact; // Creates non-namespace node pages private NodePageFactory _nmspPageFact; // Creates namespace node pages private TextBlockBuilder _textBldr; // Concatenates adjacent text blocks private Stack<XPathNodeRef> _stkNmsp; // In-scope namespaces private XPathNodeInfoTable _infoTable; // Atomization table for shared node information private XPathDocument _doc; // Currently building document private IXmlLineInfo _lineInfo; // Line information provider private XmlNameTable _nameTable; // Atomization table for all names in the document private bool _atomizeNames; // True if all names should be atomized (false if they are pre-atomized) private XPathNode[] _pageNmsp; // Page of last in-scope namespace node private int _idxNmsp; // Page index of last in-scope namespace node private XPathNode[] _pageParent; // Page of last parent-type node (Element or Root) private int _idxParent; // Page index of last parent-type node (Element or Root) private XPathNode[] _pageSibling; // Page of previous sibling node (may be null if no previous sibling) private int _idxSibling; // Page index of previous sibling node private int _lineNumBase; // Line number from which offsets are computed private int _linePosBase; // Line position from which offsets are computed private XPathNodeRef[] _elemNameIndex; // Elements with the same name are linked together so that they can be searched quickly private const int ElementIndexSize = 64; /// <summary> /// Create a new XPathDocumentBuilder which creates nodes in "doc". /// </summary> public XPathDocumentBuilder(XPathDocument doc, IXmlLineInfo lineInfo, string baseUri, XPathDocument.LoadFlags flags) { // Allocate the initial node (for non-namespaces) page, and the initial namespace page _nodePageFact.Init(256); _nmspPageFact.Init(16); _stkNmsp = new Stack<XPathNodeRef>(); Initialize(doc, lineInfo, baseUri, flags); } /// <summary> /// Start construction of a new document. This must be called before any other methods are called. /// It may also be called after Close(), in order to build further documents. /// </summary> public void Initialize(XPathDocument doc, IXmlLineInfo lineInfo, string baseUri, XPathDocument.LoadFlags flags) { XPathNode[] page; int idx; _doc = doc; _nameTable = doc.NameTable; _atomizeNames = (flags & XPathDocument.LoadFlags.AtomizeNames) != 0; _idxParent = _idxSibling = 0; _elemNameIndex = new XPathNodeRef[ElementIndexSize]; // Prepare line number information _textBldr.Initialize(lineInfo); _lineInfo = lineInfo; _lineNumBase = 0; _linePosBase = 0; // Allocate the atomization table _infoTable = new XPathNodeInfoTable(); // Allocate singleton collapsed text node idx = NewNode(out page, XPathNodeType.Text, string.Empty, string.Empty, string.Empty, string.Empty); _doc.SetCollapsedTextNode(page, idx); // Allocate xmlns:xml namespace node _idxNmsp = NewNamespaceNode(out _pageNmsp, _nameTable.Add("xml"), _nameTable.Add(XmlConst.ReservedNsXml), null, 0); _doc.SetXmlNamespaceNode(_pageNmsp, _idxNmsp); if ((flags & XPathDocument.LoadFlags.Fragment) == 0) { // This tree has a document root node _idxParent = NewNode(out _pageParent, XPathNodeType.Root, string.Empty, string.Empty, string.Empty, baseUri); _doc.SetRootNode(_pageParent, _idxParent); } else { // This tree is an XQuery fragment (no document root node), so root will be next node in the current page _doc.SetRootNode(_nodePageFact.NextNodePage, _nodePageFact.NextNodeIndex); } } //----------------------------------------------- // XmlWriter interface //----------------------------------------------- /// <summary> /// XPathDocument ignores the DocType information. /// </summary> public override void WriteDocType(string name, string pubid, string sysid, string subset) { } /// <summary> /// Shortcut for calling WriteStartElement with elemType == null. /// </summary> public override void WriteStartElement(string prefix, string localName, string ns) { this.WriteStartElement(prefix, localName, ns, string.Empty); } /// <summary> /// Build an element node and attach it to its parent, if one exists. Make the element the new parent node. /// </summary> public void WriteStartElement(string prefix, string localName, string ns, string baseUri) { int hash; Debug.Assert(prefix != null && localName != null && ns != null && localName.Length != 0 && baseUri != null); if (_atomizeNames) { prefix = _nameTable.Add(prefix); localName = _nameTable.Add(localName); ns = _nameTable.Add(ns); } AddSibling(XPathNodeType.Element, localName, ns, prefix, baseUri); _pageParent = _pageSibling; _idxParent = _idxSibling; _idxSibling = 0; // Link elements with the same name together hash = (_pageParent[_idxParent].LocalNameHashCode & (ElementIndexSize - 1)); _elemNameIndex[hash] = LinkSimilarElements(_elemNameIndex[hash].Page, _elemNameIndex[hash].Index, _pageParent, _idxParent); } /// <summary> /// Must be called when an element node's children have been fully enumerated. /// </summary> public override void WriteEndElement() { WriteEndElement(true); } /// <summary> /// Must be called when an element node's children have been fully enumerated. /// </summary> public override void WriteFullEndElement() { WriteEndElement(false); } /// <summary> /// Must be called when an element node's children have been fully enumerated. /// </summary> internal override void WriteEndElement(string prefix, string localName, string namespaceName) { WriteEndElement(true); } /// <summary> /// Must be called when an element node's children have been fully enumerated. /// </summary> internal override void WriteFullEndElement(string prefix, string localName, string namespaceName) { WriteEndElement(false); } /// <summary> /// Must be called when an element node's children have been fully enumerated. /// </summary> public void WriteEndElement(bool allowShortcutTag) { XPathNodeRef nodeRef; Debug.Assert(_pageParent[_idxParent].NodeType == XPathNodeType.Element); // If element has no content-typed children except for the one about to be added, then // its value is the same as its only text child's. if (!_pageParent[_idxParent].HasContentChild) { switch (_textBldr.TextType) { case TextBlockType.Text: // Collapsed text node can be created if text line number information can be encoded efficiently in parent node if (_lineInfo != null) { // If collapsed text node is not on same line as parent, don't collapse text if (_textBldr.LineNumber != _pageParent[_idxParent].LineNumber) goto case TextBlockType.Whitespace; // If position is not within 256 of parent, don't collapse text int posDiff = _textBldr.LinePosition - _pageParent[_idxParent].LinePosition; if (posDiff < 0 || posDiff > XPathNode.MaxCollapsedPositionOffset) goto case TextBlockType.Whitespace; // Set collapsed node line position offset _pageParent[_idxParent].SetCollapsedLineInfoOffset(posDiff); } // Set collapsed node text _pageParent[_idxParent].SetCollapsedValue(_textBldr.ReadText()); break; case TextBlockType.SignificantWhitespace: case TextBlockType.Whitespace: // Create separate whitespace node CachedTextNode(); _pageParent[_idxParent].SetValue(_pageSibling[_idxSibling].Value); break; default: // Empty value, so don't create collapsed text node _pageParent[_idxParent].SetEmptyValue(allowShortcutTag); break; } } else { if (_textBldr.HasText) { // Element's last child (one of several) is a text or whitespace node CachedTextNode(); } } // If namespaces were added to this element, if (_pageParent[_idxParent].HasNamespaceDecls) { // Add it to the document's element --> namespace mapping _doc.AddNamespace(_pageParent, _idxParent, _pageNmsp, _idxNmsp); // Restore the previous namespace chain nodeRef = _stkNmsp.Pop(); _pageNmsp = nodeRef.Page; _idxNmsp = nodeRef.Index; } // Make parent of this element the current element _pageSibling = _pageParent; _idxSibling = _idxParent; _idxParent = _pageParent[_idxParent].GetParent(out _pageParent); } /// <summary> /// Shortcut for calling WriteStartAttribute with attrfType == null. /// </summary> public override void WriteStartAttribute(string prefix, string localName, string namespaceName) { Debug.Assert(!prefix.Equals("xmlns")); Debug.Assert(_idxParent == 0 || _pageParent[_idxParent].NodeType == XPathNodeType.Element); Debug.Assert(_idxSibling == 0 || _pageSibling[_idxSibling].NodeType == XPathNodeType.Attribute); if (_atomizeNames) { prefix = _nameTable.Add(prefix); localName = _nameTable.Add(localName); namespaceName = _nameTable.Add(namespaceName); } AddSibling(XPathNodeType.Attribute, localName, namespaceName, prefix, string.Empty); } /// <summary> /// Attach the attribute's text or typed value to the previously constructed attribute node. /// </summary> public override void WriteEndAttribute() { Debug.Assert(_pageSibling[_idxSibling].NodeType == XPathNodeType.Attribute); _pageSibling[_idxSibling].SetValue(_textBldr.ReadText()); } /// <summary> /// Map CData text into regular text. /// </summary> public override void WriteCData(string text) { WriteString(text, TextBlockType.Text); } /// <summary> /// Construct comment node. /// </summary> public override void WriteComment(string text) { AddSibling(XPathNodeType.Comment, string.Empty, string.Empty, string.Empty, string.Empty); _pageSibling[_idxSibling].SetValue(text); } /// <summary> /// Shortcut for calling WriteProcessingInstruction with baseUri = string.Empty. /// </summary> public override void WriteProcessingInstruction(string name, string text) { this.WriteProcessingInstruction(name, text, string.Empty); } /// <summary> /// Construct pi node. /// </summary> public void WriteProcessingInstruction(string name, string text, string baseUri) { if (_atomizeNames) name = _nameTable.Add(name); AddSibling(XPathNodeType.ProcessingInstruction, name, string.Empty, string.Empty, baseUri); _pageSibling[_idxSibling].SetValue(text); } /// <summary> /// Write a whitespace text block. /// </summary> public override void WriteWhitespace(string ws) { WriteString(ws, TextBlockType.Whitespace); } /// <summary> /// Write an attribute or element text block. /// </summary> public override void WriteString(string text) { WriteString(text, TextBlockType.Text); } public override void WriteChars(char[] buffer, int index, int count) { WriteString(new string(buffer, index, count), TextBlockType.Text); } /// <summary> /// Map RawText to Text. This will lose entitization and won't roundtrip. /// </summary> public override void WriteRaw(string data) { WriteString(data, TextBlockType.Text); } public override void WriteRaw(char[] buffer, int index, int count) { WriteString(new string(buffer, index, count), TextBlockType.Text); } /// <summary> /// Write an element text block with the specified text type (whitespace, significant whitespace, or text). /// </summary> public void WriteString(string text, TextBlockType textType) { _textBldr.WriteTextBlock(text, textType); } /// <summary> /// Cache does not handle entity references. /// </summary> public override void WriteEntityRef(string name) { throw NotImplemented.ByDesign; } /// <summary> /// Don't entitize, since the cache cannot represent character entities. /// </summary> public override void WriteCharEntity(char ch) { WriteString(new string(ch, 1), TextBlockType.Text); } /// <summary> /// Don't entitize, since the cache cannot represent character entities. /// </summary> public override void WriteSurrogateCharEntity(char lowChar, char highChar) { char[] chars = { highChar, lowChar }; WriteString(new string(chars), TextBlockType.Text); } /// <summary> /// Signals the end of tree construction. /// </summary> internal void CloseWithoutDisposing() { XPathNode[] page; int idx; // If cached text exists, then create a text node at the top-level if (_textBldr.HasText) CachedTextNode(); // If document does not yet contain nodes, then an empty text node must have been created idx = _doc.GetRootNode(out page); if (idx == _nodePageFact.NextNodeIndex && page == _nodePageFact.NextNodePage) { AddSibling(XPathNodeType.Text, string.Empty, string.Empty, string.Empty, string.Empty); _pageSibling[_idxSibling].SetValue(string.Empty); } } /// <summary> /// Since output is not forwarded to another object, this does nothing. /// </summary> public override void Flush() { } //----------------------------------------------- // XmlRawWriter interface //----------------------------------------------- /// <summary> /// Write the xml declaration. This must be the first call after Open. /// </summary> internal override void WriteXmlDeclaration(XmlStandalone standalone) { // Ignore the xml declaration when building the cache } internal override void WriteXmlDeclaration(string xmldecl) { // Ignore the xml declaration when building the cache } /// <summary> /// Called as element node's children are about to be enumerated. /// </summary> internal override void StartElementContent() { Debug.Assert(_pageParent[_idxParent].NodeType == XPathNodeType.Element); } /// <summary> /// Build a namespace declaration node. Attach it to an element parent, if one was previously constructed. /// All namespace declarations are linked together in an in-scope namespace tree. /// </summary> internal override void WriteNamespaceDeclaration(string prefix, string namespaceName) { XPathNode[] pageTemp, pageOverride, pageNew, pageOrig, pageCopy; int idxTemp, idxOverride, idxNew, idxOrig, idxCopy; Debug.Assert(_idxSibling == 0 || _pageSibling[_idxSibling].NodeType == XPathNodeType.Attribute); Debug.Assert(!prefix.Equals("xmlns") && !namespaceName.Equals(XmlConst.ReservedNsXmlNs)); Debug.Assert(_idxParent == 0 || _idxNmsp != 0); Debug.Assert(_idxParent == 0 || _pageParent[_idxParent].NodeType == XPathNodeType.Element); if (_atomizeNames) prefix = _nameTable.Add(prefix); namespaceName = _nameTable.Add(namespaceName); // Does the new namespace override a previous namespace node? pageOverride = _pageNmsp; idxOverride = _idxNmsp; while (idxOverride != 0) { if ((object)pageOverride[idxOverride].LocalName == (object)prefix) { // Need to clone all namespaces up until the overridden node in order to bypass it break; } idxOverride = pageOverride[idxOverride].GetSibling(out pageOverride); } // Create new namespace node and add it to front of namespace list idxNew = NewNamespaceNode(out pageNew, prefix, namespaceName, _pageParent, _idxParent); if (idxOverride != 0) { // Bypass overridden node by cloning nodes in list leading to it pageOrig = _pageNmsp; idxOrig = _idxNmsp; pageCopy = pageNew; idxCopy = idxNew; while (idxOrig != idxOverride || pageOrig != pageOverride) { // Make a copy of the original namespace node idxTemp = pageOrig[idxOrig].GetParent(out pageTemp); idxTemp = NewNamespaceNode(out pageTemp, pageOrig[idxOrig].LocalName, pageOrig[idxOrig].Value, pageTemp, idxTemp); // Attach copy to chain of copied nodes pageCopy[idxCopy].SetSibling(_infoTable, pageTemp, idxTemp); // Position on the new copy pageCopy = pageTemp; idxCopy = idxTemp; // Get next original sibling idxOrig = pageOrig[idxOrig].GetSibling(out pageOrig); } // Link farther up in the original chain, just past the last overridden node idxOverride = pageOverride[idxOverride].GetSibling(out pageOverride); if (idxOverride != 0) pageCopy[idxCopy].SetSibling(_infoTable, pageOverride, idxOverride); else Debug.Assert(prefix.Equals("xml"), "xmlns:xml namespace declaration should always be present in the list."); } else if (_idxParent != 0) { // Link new node directly to last in-scope namespace. No overrides necessary. pageNew[idxNew].SetSibling(_infoTable, _pageNmsp, _idxNmsp); } else { // Floating namespace, so make this the root of the tree _doc.SetRootNode(pageNew, idxNew); } if (_idxParent != 0) { // If this is the first namespace on the current element, if (!_pageParent[_idxParent].HasNamespaceDecls) { // Then save the last in-scope namespace on a stack so that EndElementNode can restore it. _stkNmsp.Push(new XPathNodeRef(_pageNmsp, _idxNmsp)); // Mark element parent as having namespace nodes declared on it _pageParent[_idxParent].HasNamespaceDecls = true; } // New namespace is now last in-scope namespace _pageNmsp = pageNew; _idxNmsp = idxNew; } } //----------------------------------------------- // Custom Build Helper Methods //----------------------------------------------- /// <summary> /// Link "prev" element with "next" element, which has a "similar" name. This increases the performance of searches by element name. /// </summary> private XPathNodeRef LinkSimilarElements(XPathNode[] pagePrev, int idxPrev, XPathNode[] pageNext, int idxNext) { // Set link on previous element if (pagePrev != null) pagePrev[idxPrev].SetSimilarElement(_infoTable, pageNext, idxNext); // Add next element to index return new XPathNodeRef(pageNext, idxNext); } /// <summary> /// Helper method that constructs a new Namespace XPathNode. /// </summary> private int NewNamespaceNode(out XPathNode[] page, string prefix, string namespaceUri, XPathNode[] pageElem, int idxElem) { XPathNode[] pageNode; int idxNode, lineNumOffset, linePosOffset; XPathNodeInfoAtom info; Debug.Assert(pageElem == null || pageElem[idxElem].NodeType == XPathNodeType.Element); // Allocate a page slot for the new XPathNode _nmspPageFact.AllocateSlot(out pageNode, out idxNode); // Compute node's line number information ComputeLineInfo(false, out lineNumOffset, out linePosOffset); // Obtain a XPathNodeInfoAtom object for this node info = _infoTable.Create(prefix, string.Empty, string.Empty, string.Empty, pageElem, pageNode, null, _doc, _lineNumBase, _linePosBase); // Initialize the new node pageNode[idxNode].Create(info, XPathNodeType.Namespace, idxElem); pageNode[idxNode].SetValue(namespaceUri); pageNode[idxNode].SetLineInfoOffsets(lineNumOffset, linePosOffset); page = pageNode; return idxNode; } /// <summary> /// Helper method that constructs a new XPathNode. /// </summary> private int NewNode(out XPathNode[] page, XPathNodeType xptyp, string localName, string namespaceUri, string prefix, string baseUri) { XPathNode[] pageNode; int idxNode, lineNumOffset, linePosOffset; XPathNodeInfoAtom info; Debug.Assert(xptyp != XPathNodeType.Namespace); // Allocate a page slot for the new XPathNode _nodePageFact.AllocateSlot(out pageNode, out idxNode); // Compute node's line number information ComputeLineInfo(XPathNavigator.IsText(xptyp), out lineNumOffset, out linePosOffset); // Obtain a XPathNodeInfoAtom object for this node info = _infoTable.Create(localName, namespaceUri, prefix, baseUri, _pageParent, pageNode, pageNode, _doc, _lineNumBase, _linePosBase); // Initialize the new node pageNode[idxNode].Create(info, xptyp, _idxParent); pageNode[idxNode].SetLineInfoOffsets(lineNumOffset, linePosOffset); page = pageNode; return idxNode; } /// <summary> /// Compute current node's line number information. /// </summary> private void ComputeLineInfo(bool isTextNode, out int lineNumOffset, out int linePosOffset) { int lineNum, linePos; if (_lineInfo == null) { lineNumOffset = 0; linePosOffset = 0; return; } // Get line number info from TextBlockBuilder if current node is a text node if (isTextNode) { lineNum = _textBldr.LineNumber; linePos = _textBldr.LinePosition; } else { Debug.Assert(_lineInfo.HasLineInfo(), "HasLineInfo should have been checked before this."); lineNum = _lineInfo.LineNumber; linePos = _lineInfo.LinePosition; } lineNumOffset = lineNum - _lineNumBase; if (lineNumOffset < 0 || lineNumOffset > XPathNode.MaxLineNumberOffset) { _lineNumBase = lineNum; lineNumOffset = 0; } linePosOffset = linePos - _linePosBase; if (linePosOffset < 0 || linePosOffset > XPathNode.MaxLinePositionOffset) { _linePosBase = linePos; linePosOffset = 0; } } /// <summary> /// Add a sibling node. If no previous sibling exists, add the node as the first child of the parent. /// If no parent exists, make this node the root of the document. /// </summary> private void AddSibling(XPathNodeType xptyp, string localName, string namespaceUri, string prefix, string baseUri) { XPathNode[] pageNew; int idxNew; Debug.Assert(xptyp != XPathNodeType.Root && xptyp != XPathNodeType.Namespace); if (_textBldr.HasText) CachedTextNode(); idxNew = NewNode(out pageNew, xptyp, localName, namespaceUri, prefix, baseUri); // this.idxParent is only 0 for the top-most node if (_idxParent != 0) { // Set properties on parent _pageParent[_idxParent].SetParentProperties(xptyp); if (_idxSibling == 0) { // This is the first child of the parent (so should be allocated immediately after parent) Debug.Assert(_idxParent + 1 == idxNew || idxNew == 1); } else { // There is already a previous sibling _pageSibling[_idxSibling].SetSibling(_infoTable, pageNew, idxNew); } } _pageSibling = pageNew; _idxSibling = idxNew; } /// <summary> /// Creates a text node from cached text parts. /// </summary> private void CachedTextNode() { TextBlockType textType; string text; Debug.Assert(_textBldr.HasText || (_idxSibling == 0 && _idxParent == 0), "Cannot create empty text node unless it's a top-level text node."); Debug.Assert(_idxSibling == 0 || !_pageSibling[_idxSibling].IsText, "Cannot create adjacent text nodes."); // Create a text node textType = _textBldr.TextType; text = _textBldr.ReadText(); AddSibling((XPathNodeType)textType, string.Empty, string.Empty, string.Empty, string.Empty); _pageSibling[_idxSibling].SetValue(text); } /// <summary> /// Allocates pages of nodes for the XPathDocumentBuilder. The initial pages and arrays are /// fairly small. As each page fills, a new page that is twice as big is allocated. /// The max size of a page is 65536 nodes, since XPathNode indexes are 16-bits. /// </summary> private struct NodePageFactory { private XPathNode[] _page; private XPathNodePageInfo _pageInfo; private int _pageSize; /// <summary> /// Allocates and returns the initial node page. /// </summary> public void Init(int initialPageSize) { // 0th slot: Index 0 is reserved to mean "null node". Only use 0th slot to store PageInfo. _pageSize = initialPageSize; _page = new XPathNode[_pageSize]; _pageInfo = new XPathNodePageInfo(null, 1); _page[0].Create(_pageInfo); } /// <summary> /// Return the page on which the next node will be allocated. /// </summary> public XPathNode[] NextNodePage { get { return _page; } } /// <summary> /// Return the page index that the next node will be given. /// </summary> public int NextNodeIndex { get { return _pageInfo.NodeCount; } } /// <summary> /// Allocate the next slot in the current node page. Return a reference to the page and the index /// of the allocated slot. /// </summary> public void AllocateSlot(out XPathNode[] page, out int idx) { page = _page; idx = _pageInfo.NodeCount; // Allocate new page if necessary if (++_pageInfo.NodeCount >= _page.Length) { if (_pageSize < (1 << 16)) { // New page shouldn't contain more slots than 16 bits can address _pageSize *= 2; } _page = new XPathNode[_pageSize]; _pageInfo.NextPage = _page; _pageInfo = new XPathNodePageInfo(page, _pageInfo.PageNumber + 1); _page[0].Create(_pageInfo); } } } /// <summary> /// This class concatenates adjacent text blocks and tracks TextBlockType and line number information. /// </summary> private struct TextBlockBuilder { private IXmlLineInfo _lineInfo; private TextBlockType _textType; private string _text; private int _lineNum, _linePos; /// <summary> /// Constructor. /// </summary> public void Initialize(IXmlLineInfo lineInfo) { _lineInfo = lineInfo; _textType = TextBlockType.None; } /// <summary> /// Return the type of the cached text block. /// </summary> public TextBlockType TextType { get { return _textType; } } /// <summary> /// Returns true if text has been cached. /// </summary> public bool HasText { get { return _textType != TextBlockType.None; } } /// <summary> /// Returns the line number of the last text block to be cached. /// </summary> public int LineNumber { get { return _lineNum; } } /// <summary> /// Returns the line position of the last text block to be cached. /// </summary> public int LinePosition { get { return _linePos; } } /// <summary> /// Append a text block with the specified type. /// </summary> public void WriteTextBlock(string text, TextBlockType textType) { Debug.Assert((int)XPathNodeType.Text < (int)XPathNodeType.SignificantWhitespace); Debug.Assert((int)XPathNodeType.SignificantWhitespace < (int)XPathNodeType.Whitespace); if (text.Length != 0) { if (_textType == TextBlockType.None) { _text = text; _textType = textType; if (_lineInfo != null) { _lineNum = _lineInfo.LineNumber; _linePos = _lineInfo.LinePosition; } } else { _text = string.Concat(_text, text); // Determine whether text is Text, Whitespace, or SignificantWhitespace if ((int)textType < (int)_textType) _textType = textType; } } } /// <summary> /// Read all cached text, or string.Empty if no text has been cached, and clear the text block type. /// </summary> public string ReadText() { if (_textType == TextBlockType.None) return string.Empty; _textType = TextBlockType.None; return _text; } } } }
// 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 Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security.Authentication.ExtendedProtection; namespace System.Net.Security { // // Used when working with SSPI APIs, like SafeSspiAuthDataHandle(). Holds the pointer to the auth data blob. // #if DEBUG internal sealed class SafeSspiAuthDataHandle : DebugSafeHandle { #else internal sealed class SafeSspiAuthDataHandle : SafeHandleZeroOrMinusOneIsInvalid { #endif public SafeSspiAuthDataHandle() : base(true) { } protected override bool ReleaseHandle() { return Interop.SspiCli.SspiFreeAuthIdentity(handle) == Interop.SecurityStatus.OK; } } // // A set of Safe Handles that depend on native FreeContextBuffer finalizer. // #if DEBUG internal abstract class SafeFreeContextBuffer : DebugSafeHandle { #else internal abstract class SafeFreeContextBuffer : SafeHandleZeroOrMinusOneIsInvalid { #endif protected SafeFreeContextBuffer() : base(true) { } // This must be ONLY called from this file. internal void Set(IntPtr value) { this.handle = value; } internal static int EnumeratePackages(out int pkgnum, out SafeFreeContextBuffer pkgArray) { int res = -1; SafeFreeContextBuffer_SECURITY pkgArray_SECURITY = null; res = Interop.SspiCli.EnumerateSecurityPackagesW(out pkgnum, out pkgArray_SECURITY); pkgArray = pkgArray_SECURITY; if (res != 0 && pkgArray != null) { pkgArray.SetHandleAsInvalid(); } return res; } internal static SafeFreeContextBuffer CreateEmptyHandle() { return new SafeFreeContextBuffer_SECURITY(); } // // After PInvoke call the method will fix the refHandle.handle with the returned value. // The caller is responsible for creating a correct SafeHandle template or null can be passed if no handle is returned. // // This method switches between three non-interruptible helper methods. (This method can't be both non-interruptible and // reference imports from all three DLLs - doing so would cause all three DLLs to try to be bound to.) // public unsafe static int QueryContextAttributes(SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute contextAttribute, byte* buffer, SafeHandle refHandle) { return QueryContextAttributes_SECURITY(phContext, contextAttribute, buffer, refHandle); } private unsafe static int QueryContextAttributes_SECURITY( SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute contextAttribute, byte* buffer, SafeHandle refHandle) { int status = (int)Interop.SecurityStatus.InvalidHandle; try { bool ignore = false; phContext.DangerousAddRef(ref ignore); status = Interop.SspiCli.QueryContextAttributesW(ref phContext._handle, contextAttribute, buffer); } finally { phContext.DangerousRelease(); } if (status == 0 && refHandle != null) { if (refHandle is SafeFreeContextBuffer) { ((SafeFreeContextBuffer)refHandle).Set(*(IntPtr*)buffer); } else { ((SafeFreeCertContext)refHandle).Set(*(IntPtr*)buffer); } } if (status != 0 && refHandle != null) { refHandle.SetHandleAsInvalid(); } return status; } public static int SetContextAttributes( SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute contextAttribute, byte[] buffer) { return SetContextAttributes_SECURITY(phContext, contextAttribute, buffer); } private static int SetContextAttributes_SECURITY( SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute contextAttribute, byte[] buffer) { try { bool ignore = false; phContext.DangerousAddRef(ref ignore); return Interop.SspiCli.SetContextAttributesW(ref phContext._handle, contextAttribute, buffer, buffer.Length); } finally { phContext.DangerousRelease(); } } } internal sealed class SafeFreeContextBuffer_SECURITY : SafeFreeContextBuffer { internal SafeFreeContextBuffer_SECURITY() : base() { } protected override bool ReleaseHandle() { return Interop.SspiCli.FreeContextBuffer(handle) == 0; } } // // Implementation of handles required CertFreeCertificateContext // #if DEBUG internal sealed class SafeFreeCertContext : DebugSafeHandle { #else internal sealed class SafeFreeCertContext : SafeHandleZeroOrMinusOneIsInvalid { #endif internal SafeFreeCertContext() : base(true) { } // This must be ONLY called from this file. internal void Set(IntPtr value) { this.handle = value; } private const uint CRYPT_ACQUIRE_SILENT_FLAG = 0x00000040; protected override bool ReleaseHandle() { Interop.Crypt32.CertFreeCertificateContext(handle); return true; } } // // Implementation of handles dependable on FreeCredentialsHandle // #if DEBUG internal abstract class SafeFreeCredentials : DebugSafeHandle { #else internal abstract class SafeFreeCredentials : SafeHandle { #endif internal Interop.SspiCli.SSPIHandle _handle; //should be always used as by ref in PInvokes parameters protected SafeFreeCredentials() : base(IntPtr.Zero, true) { _handle = new Interop.SspiCli.SSPIHandle(); } #if TRACE_VERBOSE public override string ToString() { return "0x" + _handle.ToString(); } #endif public override bool IsInvalid { get { return IsClosed || _handle.IsZero; } } #if DEBUG public new IntPtr DangerousGetHandle() { Debug.Fail("This method should never be called for this type"); throw NotImplemented.ByDesign; } #endif public unsafe static int AcquireCredentialsHandle( string package, Interop.SspiCli.CredentialUse intent, ref Interop.SspiCli.AuthIdentity authdata, out SafeFreeCredentials outCredential) { if (GlobalLog.IsEnabled) { GlobalLog.Print("SafeFreeCredentials::AcquireCredentialsHandle#1(" + package + ", " + intent + ", " + authdata + ")"); } int errorCode = -1; long timeStamp; outCredential = new SafeFreeCredential_SECURITY(); errorCode = Interop.SspiCli.AcquireCredentialsHandleW( null, package, (int)intent, null, ref authdata, null, null, ref outCredential._handle, out timeStamp); #if TRACE_VERBOSE if (GlobalLog.IsEnabled) { GlobalLog.Print("Unmanaged::AcquireCredentialsHandle() returns 0x" + String.Format("{0:x}", errorCode) + ", handle = " + outCredential.ToString()); } #endif if (errorCode != 0) { outCredential.SetHandleAsInvalid(); } return errorCode; } public unsafe static int AcquireDefaultCredential( string package, Interop.SspiCli.CredentialUse intent, out SafeFreeCredentials outCredential) { if (GlobalLog.IsEnabled) { GlobalLog.Print("SafeFreeCredentials::AcquireDefaultCredential(" + package + ", " + intent + ")"); } int errorCode = -1; long timeStamp; outCredential = new SafeFreeCredential_SECURITY(); errorCode = Interop.SspiCli.AcquireCredentialsHandleW( null, package, (int)intent, null, IntPtr.Zero, null, null, ref outCredential._handle, out timeStamp); #if TRACE_VERBOSE if (GlobalLog.IsEnabled) { GlobalLog.Print("Unmanaged::AcquireCredentialsHandle() returns 0x" + errorCode.ToString("x") + ", handle = " + outCredential.ToString()); } #endif if (errorCode != 0) { outCredential.SetHandleAsInvalid(); } return errorCode; } public unsafe static int AcquireCredentialsHandle( string package, Interop.SspiCli.CredentialUse intent, ref SafeSspiAuthDataHandle authdata, out SafeFreeCredentials outCredential) { int errorCode = -1; long timeStamp; outCredential = new SafeFreeCredential_SECURITY(); errorCode = Interop.SspiCli.AcquireCredentialsHandleW( null, package, (int)intent, null, authdata, null, null, ref outCredential._handle, out timeStamp); if (errorCode != 0) { outCredential.SetHandleAsInvalid(); } return errorCode; } public unsafe static int AcquireCredentialsHandle( string package, Interop.SspiCli.CredentialUse intent, ref Interop.SspiCli.SecureCredential authdata, out SafeFreeCredentials outCredential) { if (GlobalLog.IsEnabled) { GlobalLog.Print("SafeFreeCredentials::AcquireCredentialsHandle#2(" + package + ", " + intent + ", " + authdata + ")"); } int errorCode = -1; long timeStamp; // If there is a certificate, wrap it into an array. // Not threadsafe. IntPtr copiedPtr = authdata.certContextArray; try { IntPtr certArrayPtr = new IntPtr(&copiedPtr); if (copiedPtr != IntPtr.Zero) { authdata.certContextArray = certArrayPtr; } outCredential = new SafeFreeCredential_SECURITY(); errorCode = Interop.SspiCli.AcquireCredentialsHandleW( null, package, (int)intent, null, ref authdata, null, null, ref outCredential._handle, out timeStamp); } finally { authdata.certContextArray = copiedPtr; } #if TRACE_VERBOSE if (GlobalLog.IsEnabled) { GlobalLog.Print("Unmanaged::AcquireCredentialsHandle() returns 0x" + errorCode.ToString("x") + ", handle = " + outCredential.ToString()); } #endif if (errorCode != 0) { outCredential.SetHandleAsInvalid(); } return errorCode; } } // // This is a class holding a Credential handle reference, used for static handles cache // #if DEBUG internal sealed class SafeCredentialReference : DebugCriticalHandleMinusOneIsInvalid { #else internal sealed class SafeCredentialReference : CriticalHandleMinusOneIsInvalid { #endif // // Static cache will return the target handle if found the reference in the table. // internal SafeFreeCredentials Target; internal static SafeCredentialReference CreateReference(SafeFreeCredentials target) { SafeCredentialReference result = new SafeCredentialReference(target); if (result.IsInvalid) { return null; } return result; } private SafeCredentialReference(SafeFreeCredentials target) : base() { // Bumps up the refcount on Target to signify that target handle is statically cached so // its dispose should be postponed bool ignore = false; target.DangerousAddRef(ref ignore); Target = target; SetHandle(new IntPtr(0)); // make this handle valid } protected override bool ReleaseHandle() { SafeFreeCredentials target = Target; if (target != null) { target.DangerousRelease(); } Target = null; return true; } } internal sealed class SafeFreeCredential_SECURITY : SafeFreeCredentials { public SafeFreeCredential_SECURITY() : base() { } protected override bool ReleaseHandle() { return Interop.SspiCli.FreeCredentialsHandle(ref _handle) == 0; } } // // Implementation of handles that are dependent on DeleteSecurityContext // #if DEBUG internal abstract class SafeDeleteContext : DebugSafeHandle { #else internal abstract class SafeDeleteContext : SafeHandle { #endif private const string dummyStr = " "; private static readonly byte[] s_dummyBytes = new byte[] { 0 }; // // ATN: _handle is internal since it is used on PInvokes by other wrapper methods. // However all such wrappers MUST manually and reliably adjust refCounter of SafeDeleteContext handle. // internal Interop.SspiCli.SSPIHandle _handle; protected SafeFreeCredentials _EffectiveCredential; protected SafeDeleteContext() : base(IntPtr.Zero, true) { _handle = new Interop.SspiCli.SSPIHandle(); } public override bool IsInvalid { get { return IsClosed || _handle.IsZero; } } public override string ToString() { return _handle.ToString(); } #if DEBUG //This method should never be called for this type public new IntPtr DangerousGetHandle() { throw new InvalidOperationException(); } #endif //------------------------------------------------------------------- internal unsafe static int InitializeSecurityContext( ref SafeFreeCredentials inCredentials, ref SafeDeleteContext refContext, string targetName, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, SecurityBuffer inSecBuffer, SecurityBuffer[] inSecBuffers, SecurityBuffer outSecBuffer, ref Interop.SspiCli.ContextFlags outFlags) { #if TRACE_VERBOSE if (GlobalLog.IsEnabled) { GlobalLog.Enter("SafeDeleteContext::InitializeSecurityContext"); GlobalLog.Print(" credential = " + inCredentials.ToString()); GlobalLog.Print(" refContext = " + LoggingHash.ObjectToString(refContext)); GlobalLog.Print(" targetName = " + targetName); GlobalLog.Print(" inFlags = " + inFlags); GlobalLog.Print(" reservedI = 0x0"); GlobalLog.Print(" endianness = " + endianness); if (inSecBuffers == null) { GlobalLog.Print(" inSecBuffers = (null)"); } else { GlobalLog.Print(" inSecBuffers[] = length:" + inSecBuffers.Length); } } #endif if (outSecBuffer == null) { if (GlobalLog.IsEnabled) { GlobalLog.Assert("SafeDeleteContext::InitializeSecurityContext()|outSecBuffer != null"); } Debug.Fail("SafeDeleteContext::InitializeSecurityContext()|outSecBuffer != null"); } if (inSecBuffer != null && inSecBuffers != null) { if (GlobalLog.IsEnabled) { GlobalLog.Assert("SafeDeleteContext::InitializeSecurityContext()|inSecBuffer == null || inSecBuffers == null"); } Debug.Fail("SafeDeleteContext::InitializeSecurityContext()|inSecBuffer == null || inSecBuffers == null"); } if (inCredentials == null) { throw new ArgumentNullException(nameof(inCredentials)); } Interop.SspiCli.SecurityBufferDescriptor inSecurityBufferDescriptor = null; if (inSecBuffer != null) { inSecurityBufferDescriptor = new Interop.SspiCli.SecurityBufferDescriptor(1); } else if (inSecBuffers != null) { inSecurityBufferDescriptor = new Interop.SspiCli.SecurityBufferDescriptor(inSecBuffers.Length); } Interop.SspiCli.SecurityBufferDescriptor outSecurityBufferDescriptor = new Interop.SspiCli.SecurityBufferDescriptor(1); // Actually, this is returned in outFlags. bool isSspiAllocated = (inFlags & Interop.SspiCli.ContextFlags.AllocateMemory) != 0 ? true : false; int errorCode = -1; Interop.SspiCli.SSPIHandle contextHandle = new Interop.SspiCli.SSPIHandle(); if (refContext != null) { contextHandle = refContext._handle; } // These are pinned user byte arrays passed along with SecurityBuffers. GCHandle[] pinnedInBytes = null; GCHandle pinnedOutBytes = new GCHandle(); // Optional output buffer that may need to be freed. SafeFreeContextBuffer outFreeContextBuffer = null; try { pinnedOutBytes = GCHandle.Alloc(outSecBuffer.token, GCHandleType.Pinned); Interop.SspiCli.SecurityBufferStruct[] inUnmanagedBuffer = new Interop.SspiCli.SecurityBufferStruct[inSecurityBufferDescriptor == null ? 1 : inSecurityBufferDescriptor.Count]; fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer) { if (inSecurityBufferDescriptor != null) { // Fix Descriptor pointer that points to unmanaged SecurityBuffers. inSecurityBufferDescriptor.UnmanagedPointer = inUnmanagedBufferPtr; pinnedInBytes = new GCHandle[inSecurityBufferDescriptor.Count]; SecurityBuffer securityBuffer; for (int index = 0; index < inSecurityBufferDescriptor.Count; ++index) { securityBuffer = inSecBuffer != null ? inSecBuffer : inSecBuffers[index]; if (securityBuffer != null) { // Copy the SecurityBuffer content into unmanaged place holder. inUnmanagedBuffer[index].count = securityBuffer.size; inUnmanagedBuffer[index].type = securityBuffer.type; // Use the unmanaged token if it's not null; otherwise use the managed buffer. if (securityBuffer.unmanagedToken != null) { inUnmanagedBuffer[index].token = securityBuffer.unmanagedToken.DangerousGetHandle(); } else if (securityBuffer.token == null || securityBuffer.token.Length == 0) { inUnmanagedBuffer[index].token = IntPtr.Zero; } else { pinnedInBytes[index] = GCHandle.Alloc(securityBuffer.token, GCHandleType.Pinned); inUnmanagedBuffer[index].token = Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset); } #if TRACE_VERBOSE if (GlobalLog.IsEnabled) { GlobalLog.Print("SecBuffer: cbBuffer:" + securityBuffer.size + " BufferType:" + securityBuffer.type); } #endif } } } Interop.SspiCli.SecurityBufferStruct[] outUnmanagedBuffer = new Interop.SspiCli.SecurityBufferStruct[1]; fixed (void* outUnmanagedBufferPtr = outUnmanagedBuffer) { // Fix Descriptor pointer that points to unmanaged SecurityBuffers. outSecurityBufferDescriptor.UnmanagedPointer = outUnmanagedBufferPtr; outUnmanagedBuffer[0].count = outSecBuffer.size; outUnmanagedBuffer[0].type = outSecBuffer.type; if (outSecBuffer.token == null || outSecBuffer.token.Length == 0) { outUnmanagedBuffer[0].token = IntPtr.Zero; } else { outUnmanagedBuffer[0].token = Marshal.UnsafeAddrOfPinnedArrayElement(outSecBuffer.token, outSecBuffer.offset); } if (isSspiAllocated) { outFreeContextBuffer = SafeFreeContextBuffer.CreateEmptyHandle(); } if (refContext == null || refContext.IsInvalid) { refContext = new SafeDeleteContext_SECURITY(); } if (targetName == null || targetName.Length == 0) { targetName = dummyStr; } fixed (char* namePtr = targetName) { errorCode = MustRunInitializeSecurityContext_SECURITY( ref inCredentials, contextHandle.IsZero ? null : &contextHandle, (byte*)(((object)targetName == (object)dummyStr) ? null : namePtr), inFlags, endianness, inSecurityBufferDescriptor, refContext, outSecurityBufferDescriptor, ref outFlags, outFreeContextBuffer); } if (GlobalLog.IsEnabled) { GlobalLog.Print("SafeDeleteContext:InitializeSecurityContext Marshalling OUT buffer"); } // Get unmanaged buffer with index 0 as the only one passed into PInvoke. outSecBuffer.size = outUnmanagedBuffer[0].count; outSecBuffer.type = outUnmanagedBuffer[0].type; if (outSecBuffer.size > 0) { outSecBuffer.token = new byte[outSecBuffer.size]; Marshal.Copy(outUnmanagedBuffer[0].token, outSecBuffer.token, 0, outSecBuffer.size); } else { outSecBuffer.token = null; } } } } finally { if (pinnedInBytes != null) { for (int index = 0; index < pinnedInBytes.Length; index++) { if (pinnedInBytes[index].IsAllocated) { pinnedInBytes[index].Free(); } } } if (pinnedOutBytes.IsAllocated) { pinnedOutBytes.Free(); } if (outFreeContextBuffer != null) { outFreeContextBuffer.Dispose(); } } if (GlobalLog.IsEnabled) { GlobalLog.Leave("SafeDeleteContext::InitializeSecurityContext() unmanaged InitializeSecurityContext()", "errorCode:0x" + errorCode.ToString("x8") + " refContext:" + LoggingHash.ObjectToString(refContext)); } return errorCode; } // // After PInvoke call the method will fix the handleTemplate.handle with the returned value. // The caller is responsible for creating a correct SafeFreeContextBuffer_XXX flavor or null can be passed if no handle is returned. // private static unsafe int MustRunInitializeSecurityContext_SECURITY( ref SafeFreeCredentials inCredentials, void* inContextPtr, byte* targetName, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, Interop.SspiCli.SecurityBufferDescriptor inputBuffer, SafeDeleteContext outContext, Interop.SspiCli.SecurityBufferDescriptor outputBuffer, ref Interop.SspiCli.ContextFlags attributes, SafeFreeContextBuffer handleTemplate) { int errorCode = (int)Interop.SecurityStatus.InvalidHandle; try { bool ignore = false; inCredentials.DangerousAddRef(ref ignore); outContext.DangerousAddRef(ref ignore); Interop.SspiCli.SSPIHandle credentialHandle = inCredentials._handle; long timeStamp; errorCode = Interop.SspiCli.InitializeSecurityContextW( ref credentialHandle, inContextPtr, targetName, inFlags, 0, endianness, inputBuffer, 0, ref outContext._handle, outputBuffer, ref attributes, out timeStamp); } finally { // // When a credential handle is first associated with the context we keep credential // ref count bumped up to ensure ordered finalization. // If the credential handle has been changed we de-ref the old one and associate the // context with the new cred handle but only if the call was successful. if (outContext._EffectiveCredential != inCredentials && (errorCode & 0x80000000) == 0) { // Disassociate the previous credential handle if (outContext._EffectiveCredential != null) { outContext._EffectiveCredential.DangerousRelease(); } outContext._EffectiveCredential = inCredentials; } else { inCredentials.DangerousRelease(); } outContext.DangerousRelease(); } // The idea is that SSPI has allocated a block and filled up outUnmanagedBuffer+8 slot with the pointer. if (handleTemplate != null) { //ATTN: on 64 BIT that is still +8 cause of 2* c++ unsigned long == 8 bytes handleTemplate.Set(((Interop.SspiCli.SecurityBufferStruct*)outputBuffer.UnmanagedPointer)->token); if (handleTemplate.IsInvalid) { handleTemplate.SetHandleAsInvalid(); } } if (inContextPtr == null && (errorCode & 0x80000000) != 0) { // an error on the first call, need to set the out handle to invalid value outContext._handle.SetToInvalid(); } return errorCode; } //------------------------------------------------------------------- internal unsafe static int AcceptSecurityContext( ref SafeFreeCredentials inCredentials, ref SafeDeleteContext refContext, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, SecurityBuffer inSecBuffer, SecurityBuffer[] inSecBuffers, SecurityBuffer outSecBuffer, ref Interop.SspiCli.ContextFlags outFlags) { #if TRACE_VERBOSE if (GlobalLog.IsEnabled) { GlobalLog.Enter("SafeDeleteContext::AcceptSecurityContex"); GlobalLog.Print(" credential = " + inCredentials.ToString()); GlobalLog.Print(" refContext = " + LoggingHash.ObjectToString(refContext)); GlobalLog.Print(" inFlags = " + inFlags); if (inSecBuffers == null) { GlobalLog.Print(" inSecBuffers = (null)"); } else { GlobalLog.Print(" inSecBuffers[] = length:" + inSecBuffers.Length); } } #endif if (outSecBuffer == null) { if (GlobalLog.IsEnabled) { GlobalLog.Assert("SafeDeleteContext::AcceptSecurityContext()|outSecBuffer != null"); } Debug.Fail("SafeDeleteContext::AcceptSecurityContext()|outSecBuffer != null"); } if (inSecBuffer != null && inSecBuffers != null) { if (GlobalLog.IsEnabled) { GlobalLog.Assert("SafeDeleteContext::AcceptSecurityContext()|inSecBuffer == null || inSecBuffers == null"); } Debug.Fail("SafeDeleteContext::AcceptSecurityContext()|outSecBuffer != null"); } if (inCredentials == null) { throw new ArgumentNullException(nameof(inCredentials)); } Interop.SspiCli.SecurityBufferDescriptor inSecurityBufferDescriptor = null; if (inSecBuffer != null) { inSecurityBufferDescriptor = new Interop.SspiCli.SecurityBufferDescriptor(1); } else if (inSecBuffers != null) { inSecurityBufferDescriptor = new Interop.SspiCli.SecurityBufferDescriptor(inSecBuffers.Length); } Interop.SspiCli.SecurityBufferDescriptor outSecurityBufferDescriptor = new Interop.SspiCli.SecurityBufferDescriptor(1); // Actually, this is returned in outFlags. bool isSspiAllocated = (inFlags & Interop.SspiCli.ContextFlags.AllocateMemory) != 0 ? true : false; int errorCode = -1; Interop.SspiCli.SSPIHandle contextHandle = new Interop.SspiCli.SSPIHandle(); if (refContext != null) { contextHandle = refContext._handle; } // These are pinned user byte arrays passed along with SecurityBuffers. GCHandle[] pinnedInBytes = null; GCHandle pinnedOutBytes = new GCHandle(); // Optional output buffer that may need to be freed. SafeFreeContextBuffer outFreeContextBuffer = null; try { pinnedOutBytes = GCHandle.Alloc(outSecBuffer.token, GCHandleType.Pinned); var inUnmanagedBuffer = new Interop.SspiCli.SecurityBufferStruct[inSecurityBufferDescriptor == null ? 1 : inSecurityBufferDescriptor.Count]; fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer) { if (inSecurityBufferDescriptor != null) { // Fix Descriptor pointer that points to unmanaged SecurityBuffers. inSecurityBufferDescriptor.UnmanagedPointer = inUnmanagedBufferPtr; pinnedInBytes = new GCHandle[inSecurityBufferDescriptor.Count]; SecurityBuffer securityBuffer; for (int index = 0; index < inSecurityBufferDescriptor.Count; ++index) { securityBuffer = inSecBuffer != null ? inSecBuffer : inSecBuffers[index]; if (securityBuffer != null) { // Copy the SecurityBuffer content into unmanaged place holder. inUnmanagedBuffer[index].count = securityBuffer.size; inUnmanagedBuffer[index].type = securityBuffer.type; // Use the unmanaged token if it's not null; otherwise use the managed buffer. if (securityBuffer.unmanagedToken != null) { inUnmanagedBuffer[index].token = securityBuffer.unmanagedToken.DangerousGetHandle(); } else if (securityBuffer.token == null || securityBuffer.token.Length == 0) { inUnmanagedBuffer[index].token = IntPtr.Zero; } else { pinnedInBytes[index] = GCHandle.Alloc(securityBuffer.token, GCHandleType.Pinned); inUnmanagedBuffer[index].token = Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset); } #if TRACE_VERBOSE if (GlobalLog.IsEnabled) { GlobalLog.Print("SecBuffer: cbBuffer:" + securityBuffer.size + " BufferType:" + securityBuffer.type); } #endif } } } var outUnmanagedBuffer = new Interop.SspiCli.SecurityBufferStruct[1]; fixed (void* outUnmanagedBufferPtr = outUnmanagedBuffer) { // Fix Descriptor pointer that points to unmanaged SecurityBuffers. outSecurityBufferDescriptor.UnmanagedPointer = outUnmanagedBufferPtr; // Copy the SecurityBuffer content into unmanaged place holder. outUnmanagedBuffer[0].count = outSecBuffer.size; outUnmanagedBuffer[0].type = outSecBuffer.type; if (outSecBuffer.token == null || outSecBuffer.token.Length == 0) { outUnmanagedBuffer[0].token = IntPtr.Zero; } else { outUnmanagedBuffer[0].token = Marshal.UnsafeAddrOfPinnedArrayElement(outSecBuffer.token, outSecBuffer.offset); } if (isSspiAllocated) { outFreeContextBuffer = SafeFreeContextBuffer.CreateEmptyHandle(); } if (refContext == null || refContext.IsInvalid) { refContext = new SafeDeleteContext_SECURITY(); } errorCode = MustRunAcceptSecurityContext_SECURITY( ref inCredentials, contextHandle.IsZero ? null : &contextHandle, inSecurityBufferDescriptor, inFlags, endianness, refContext, outSecurityBufferDescriptor, ref outFlags, outFreeContextBuffer); if (GlobalLog.IsEnabled) { GlobalLog.Print("SafeDeleteContext:AcceptSecurityContext Marshalling OUT buffer"); } // Get unmanaged buffer with index 0 as the only one passed into PInvoke. outSecBuffer.size = outUnmanagedBuffer[0].count; outSecBuffer.type = outUnmanagedBuffer[0].type; if (outSecBuffer.size > 0) { outSecBuffer.token = new byte[outSecBuffer.size]; Marshal.Copy(outUnmanagedBuffer[0].token, outSecBuffer.token, 0, outSecBuffer.size); } else { outSecBuffer.token = null; } } } } finally { if (pinnedInBytes != null) { for (int index = 0; index < pinnedInBytes.Length; index++) { if (pinnedInBytes[index].IsAllocated) { pinnedInBytes[index].Free(); } } } if (pinnedOutBytes.IsAllocated) { pinnedOutBytes.Free(); } if (outFreeContextBuffer != null) { outFreeContextBuffer.Dispose(); } } if (GlobalLog.IsEnabled) { GlobalLog.Leave("SafeDeleteContext::AcceptSecurityContex() unmanaged AcceptSecurityContex()", "errorCode:0x" + errorCode.ToString("x8") + " refContext:" + LoggingHash.ObjectToString(refContext)); } return errorCode; } // // After PInvoke call the method will fix the handleTemplate.handle with the returned value. // The caller is responsible for creating a correct SafeFreeContextBuffer_XXX flavor or null can be passed if no handle is returned. // private static unsafe int MustRunAcceptSecurityContext_SECURITY( ref SafeFreeCredentials inCredentials, void* inContextPtr, Interop.SspiCli.SecurityBufferDescriptor inputBuffer, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, SafeDeleteContext outContext, Interop.SspiCli.SecurityBufferDescriptor outputBuffer, ref Interop.SspiCli.ContextFlags outFlags, SafeFreeContextBuffer handleTemplate) { int errorCode = (int)Interop.SecurityStatus.InvalidHandle; // Run the body of this method as a non-interruptible block. try { bool ignore = false; inCredentials.DangerousAddRef(ref ignore); outContext.DangerousAddRef(ref ignore); Interop.SspiCli.SSPIHandle credentialHandle = inCredentials._handle; long timeStamp; errorCode = Interop.SspiCli.AcceptSecurityContext( ref credentialHandle, inContextPtr, inputBuffer, inFlags, endianness, ref outContext._handle, outputBuffer, ref outFlags, out timeStamp); } finally { // // When a credential handle is first associated with the context we keep credential // ref count bumped up to ensure ordered finalization. // If the credential handle has been changed we de-ref the old one and associate the // context with the new cred handle but only if the call was successful. if (outContext._EffectiveCredential != inCredentials && (errorCode & 0x80000000) == 0) { // Disassociate the previous credential handle. if (outContext._EffectiveCredential != null) { outContext._EffectiveCredential.DangerousRelease(); } outContext._EffectiveCredential = inCredentials; } else { inCredentials.DangerousRelease(); } outContext.DangerousRelease(); } // The idea is that SSPI has allocated a block and filled up outUnmanagedBuffer+8 slot with the pointer. if (handleTemplate != null) { //ATTN: on 64 BIT that is still +8 cause of 2* c++ unsigned long == 8 bytes. handleTemplate.Set(((Interop.SspiCli.SecurityBufferStruct*)outputBuffer.UnmanagedPointer)->token); if (handleTemplate.IsInvalid) { handleTemplate.SetHandleAsInvalid(); } } if (inContextPtr == null && (errorCode & 0x80000000) != 0) { // An error on the first call, need to set the out handle to invalid value. outContext._handle.SetToInvalid(); } return errorCode; } internal unsafe static int CompleteAuthToken( ref SafeDeleteContext refContext, SecurityBuffer[] inSecBuffers) { if (GlobalLog.IsEnabled) { GlobalLog.Enter("SafeDeleteContext::CompleteAuthToken"); GlobalLog.Print(" refContext = " + LoggingHash.ObjectToString(refContext)); #if TRACE_VERBOSE GlobalLog.Print(" inSecBuffers[] = length:" + inSecBuffers.Length); #endif } if (inSecBuffers == null) { if (GlobalLog.IsEnabled) { GlobalLog.Assert("SafeDeleteContext::CompleteAuthToken()|inSecBuffers == null"); } Debug.Fail("SafeDeleteContext::CompleteAuthToken()|inSecBuffers == null"); } var inSecurityBufferDescriptor = new Interop.SspiCli.SecurityBufferDescriptor(inSecBuffers.Length); int errorCode = (int)Interop.SecurityStatus.InvalidHandle; // These are pinned user byte arrays passed along with SecurityBuffers. GCHandle[] pinnedInBytes = null; var inUnmanagedBuffer = new Interop.SspiCli.SecurityBufferStruct[inSecurityBufferDescriptor.Count]; fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer) { // Fix Descriptor pointer that points to unmanaged SecurityBuffers. inSecurityBufferDescriptor.UnmanagedPointer = inUnmanagedBufferPtr; pinnedInBytes = new GCHandle[inSecurityBufferDescriptor.Count]; SecurityBuffer securityBuffer; for (int index = 0; index < inSecurityBufferDescriptor.Count; ++index) { securityBuffer = inSecBuffers[index]; if (securityBuffer != null) { inUnmanagedBuffer[index].count = securityBuffer.size; inUnmanagedBuffer[index].type = securityBuffer.type; // Use the unmanaged token if it's not null; otherwise use the managed buffer. if (securityBuffer.unmanagedToken != null) { inUnmanagedBuffer[index].token = securityBuffer.unmanagedToken.DangerousGetHandle(); } else if (securityBuffer.token == null || securityBuffer.token.Length == 0) { inUnmanagedBuffer[index].token = IntPtr.Zero; } else { pinnedInBytes[index] = GCHandle.Alloc(securityBuffer.token, GCHandleType.Pinned); inUnmanagedBuffer[index].token = Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset); } #if TRACE_VERBOSE if (GlobalLog.IsEnabled) { GlobalLog.Print("SecBuffer: cbBuffer:" + securityBuffer.size + " BufferType:" + securityBuffer.type); } #endif } } Interop.SspiCli.SSPIHandle contextHandle = new Interop.SspiCli.SSPIHandle(); if (refContext != null) { contextHandle = refContext._handle; } try { if (refContext == null || refContext.IsInvalid) { refContext = new SafeDeleteContext_SECURITY(); } try { bool ignore = false; refContext.DangerousAddRef(ref ignore); errorCode = Interop.SspiCli.CompleteAuthToken(contextHandle.IsZero ? null : &contextHandle, inSecurityBufferDescriptor); } finally { refContext.DangerousRelease(); } } finally { if (pinnedInBytes != null) { for (int index = 0; index < pinnedInBytes.Length; index++) { if (pinnedInBytes[index].IsAllocated) { pinnedInBytes[index].Free(); } } } } } if (GlobalLog.IsEnabled) { GlobalLog.Leave("SafeDeleteContext::CompleteAuthToken() unmanaged CompleteAuthToken()", "errorCode:0x" + errorCode.ToString("x8") + " refContext:" + LoggingHash.ObjectToString(refContext)); } return errorCode; } } internal sealed class SafeDeleteContext_SECURITY : SafeDeleteContext { internal SafeDeleteContext_SECURITY() : base() { } protected override bool ReleaseHandle() { if (this._EffectiveCredential != null) { this._EffectiveCredential.DangerousRelease(); } return Interop.SspiCli.DeleteSecurityContext(ref _handle) == 0; } } // Based on SafeFreeContextBuffer. internal abstract class SafeFreeContextBufferChannelBinding : ChannelBinding { private int _size; public override int Size { get { return _size; } } public override bool IsInvalid { get { return handle == new IntPtr(0) || handle == new IntPtr(-1); } } internal unsafe void Set(IntPtr value) { this.handle = value; } internal static SafeFreeContextBufferChannelBinding CreateEmptyHandle() { return new SafeFreeContextBufferChannelBinding_SECURITY(); } public unsafe static int QueryContextChannelBinding(SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute contextAttribute, Bindings* buffer, SafeFreeContextBufferChannelBinding refHandle) { return QueryContextChannelBinding_SECURITY(phContext, contextAttribute, buffer, refHandle); } private unsafe static int QueryContextChannelBinding_SECURITY(SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute contextAttribute, Bindings* buffer, SafeFreeContextBufferChannelBinding refHandle) { int status = (int)Interop.SecurityStatus.InvalidHandle; // SCHANNEL only supports SECPKG_ATTR_ENDPOINT_BINDINGS and SECPKG_ATTR_UNIQUE_BINDINGS which // map to our enum ChannelBindingKind.Endpoint and ChannelBindingKind.Unique. if (contextAttribute != Interop.SspiCli.ContextAttribute.EndpointBindings && contextAttribute != Interop.SspiCli.ContextAttribute.UniqueBindings) { return status; } try { bool ignore = false; phContext.DangerousAddRef(ref ignore); status = Interop.SspiCli.QueryContextAttributesW(ref phContext._handle, contextAttribute, buffer); } finally { phContext.DangerousRelease(); } if (status == 0 && refHandle != null) { refHandle.Set((*buffer).pBindings); refHandle._size = (*buffer).BindingsLength; } if (status != 0 && refHandle != null) { refHandle.SetHandleAsInvalid(); } return status; } } internal sealed class SafeFreeContextBufferChannelBinding_SECURITY : SafeFreeContextBufferChannelBinding { protected override bool ReleaseHandle() { return Interop.SspiCli.FreeContextBuffer(handle) == 0; } } }
//////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2009, Daniel Kollmann // 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 Daniel Kollmann 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. //////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Text; using Brainiac.Design.Properties; namespace Brainiac.Design.Nodes { public partial class Node { /// <summary> /// This class holds all connectors registered on a node. There may only be one ConnectedChildren class per node. /// </summary> public class ConnectedChildren : System.Collections.IEnumerable { /// <summary> /// Holds if the list of children needs to be rebuilt from the connectors. /// </summary> protected bool _requiresRebuild= true; /// <summary> /// The registered connecors. /// </summary> protected List<Connector> _connectors= new List<Connector>(); protected Connector _defaultConnector= null; /// <summary> /// The default connector which is the first one registered. /// </summary> public Connector DefaultConnector { get { return _defaultConnector; } } protected Node _owner; /// <summary> /// The node this class belongs to. /// </summary> public Node Owner { get { return _owner; } } protected List<Node> _children= new List<Node>(); /// <summary> /// A list of all children connected via connectors. /// </summary> public IList<Node> Children { get { RebuildChildList(); return _children.AsReadOnly(); } } /// <summary> /// All connectors registered on the ndoe. /// </summary> public IList<Connector> Connectors { get { return _connectors.AsReadOnly(); } } /// <summary> /// Creates a new instance to store all available connectors on an node. /// </summary> /// <param name="owner">The node this instance belongs to.</param> public ConnectedChildren(Node owner) { _owner= owner; } /// <summary> /// Rebuilds the list of all children connected via connectors. /// </summary> protected void RebuildChildList() { if(_requiresRebuild) { _requiresRebuild= false; // clear the list _children.Clear(); // for every connector foreach(Connector connector in _connectors) { // add its children for(int i= 0; i <connector.ChildCount; ++i) { Node child= connector.GetChild(i); if(child !=null) _children.Add(child); } } } } /// <summary> /// Registeres a connector. /// </summary> /// <param name="connector">The connector which will be registered.</param> public void RegisterConnector(Connector connector) { // check if this connector has already been registered. The identifier must be unique on the node. foreach(Connector conn in _connectors) { if(conn.Identifier ==connector.Identifier) throw new Exception(Resources.ExceptionDuplicatedConnectorIdentifier); } // store the first connector as the default one if(_defaultConnector ==null) _defaultConnector= connector; // add the connector and queue and update of the child list _connectors.Add(connector); _requiresRebuild= true; // add the visual subitems for the connector for(int i= 0; i <connector.MinCount; ++i) _owner.AddSubItem( new SubItemConnector(connector, null, i) ); } /// <summary> /// Queues a rebuild of the list of children. /// </summary> public void RequiresRebuild() { _requiresRebuild= true; } /// <summary> /// Gets a connector by one of its children. /// </summary> /// <param name="child">The child whose connector we are looking for.</param> /// <returns>Returns null if no connector could be found.</returns> public Connector GetConnector(Node child) { foreach(Connector connector in _connectors) { for(int i= 0; i <connector.ChildCount; ++i) { if(connector.GetChild(i) ==child) return connector; } } return null; } /// <summary> /// Gets a connector by its identifier. /// </summary> /// <param name="identifier">The identifier we are looking for.</param> /// <returns>Returns null if no connector with this identifier exists.</returns> public Connector GetConnector(string identifier) { foreach(Connector connector in _connectors) { if(connector.Identifier ==identifier) return connector; } return null; } /// <summary> /// Checks if a connector is regsitered. Mainly for debug purposes. /// </summary> /// <param name="conn">The connector we want to check.</param> /// <returns>Returns true if the connector is registered.</returns> public bool HasConnector(Connector conn) { return _connectors.Contains(conn); } /// <summary> /// The number of children connected. /// </summary> public int ChildCount { get { RebuildChildList(); return _children.Count; } } public System.Collections.IEnumerator GetEnumerator() { RebuildChildList(); return _children.GetEnumerator(); } /// <summary> /// Checks if a node can be adopted by this one. /// </summary> /// <param name="child">The node we want to adopt.</param> /// <returns>Returns true if this node can adopt the given child.</returns> public bool CanAdoptNode(Node child) { Connector connector= GetConnector(child.ParentConnector.Identifier); if(connector ==null) connector= _defaultConnector; return connector !=null && connector.AcceptsChildren(1); } /// <summary> /// Clears all children from all connectors. /// </summary> public void ClearChildren() { foreach(Connector conn in _connectors) conn.ClearChildren(); } /// <summary> /// Exchanges any registered connector with the given one. This is used internally for subreferenced behaviours. /// </summary> /// <param name="connector">The connector which will replace all the others.</param> public void SetConnector(Connector connector) { _connectors.Clear(); _connectors.Add(connector); _defaultConnector= connector; _requiresRebuild= true; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics; using Validation; namespace System.Collections.Immutable { /// <summary> /// A thin wrapper around the Keys or Values enumerators so they look like a collection. /// </summary> /// <typeparam name="TKey">The type of key in the dictionary.</typeparam> /// <typeparam name="TValue">The type of value in the dictionary.</typeparam> /// <typeparam name="T">Either TKey or TValue.</typeparam> internal abstract class KeysOrValuesCollectionAccessor<TKey, TValue, T> : ICollection<T>, ICollection { /// <summary> /// The underlying wrapped dictionary. /// </summary> private readonly IImmutableDictionary<TKey, TValue> dictionary; /// <summary> /// The key or value enumerable that this instance wraps. /// </summary> private readonly IEnumerable<T> keysOrValues; /// <summary> /// Initializes a new instance of the <see cref="KeysOrValuesCollectionAccessor{TKey, TValue, T}"/> class. /// </summary> /// <param name="dictionary">The dictionary to base on.</param> /// <param name="keysOrValues">The keys or values enumeration to wrap as a collection.</param> protected KeysOrValuesCollectionAccessor(IImmutableDictionary<TKey, TValue> dictionary, IEnumerable<T> keysOrValues) { Requires.NotNull(dictionary, "dictionary"); Requires.NotNull(keysOrValues, "keysOrValues"); this.dictionary = dictionary; this.keysOrValues = keysOrValues; } /// <summary> /// See <see cref="ICollection&lt;T&gt;"/> /// </summary> public bool IsReadOnly { get { return true; } } /// <summary> /// See <see cref="ICollection&lt;T&gt;"/> /// </summary> /// <returns>The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</returns> public int Count { get { return this.dictionary.Count; } } /// <summary> /// Gets the wrapped dictionary. /// </summary> protected IImmutableDictionary<TKey, TValue> Dictionary { get { return this.dictionary; } } /// <summary> /// See <see cref="ICollection&lt;T&gt;"/> /// </summary> public void Add(T item) { throw new NotSupportedException(); } /// <summary> /// See <see cref="ICollection&lt;T&gt;"/> /// </summary> public void Clear() { throw new NotSupportedException(); } /// <summary> /// See <see cref="ICollection&lt;T&gt;"/> /// </summary> public abstract bool Contains(T item); /// <summary> /// See <see cref="ICollection&lt;T&gt;"/> /// </summary> public void CopyTo(T[] array, int arrayIndex) { Requires.NotNull(array, "array"); Requires.Range(arrayIndex >= 0, "arrayIndex"); Requires.Range(array.Length >= arrayIndex + this.Count, "arrayIndex"); foreach (T item in this) { array[arrayIndex++] = item; } } /// <summary> /// See <see cref="ICollection&lt;T&gt;"/> /// </summary> public bool Remove(T item) { throw new NotSupportedException(); } /// <summary> /// See <see cref="IEnumerable&lt;T&gt;"/> /// </summary> public IEnumerator<T> GetEnumerator() { return this.keysOrValues.GetEnumerator(); } /// <summary> /// See <see cref="System.Collections.IEnumerable"/> /// </summary> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } /// <summary> /// Copies the elements of the <see cref="T:System.Collections.ICollection" /> to an <see cref="T:System.Array" />, starting at a particular <see cref="T:System.Array" /> index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array" /> that is the destination of the elements copied from <see cref="T:System.Collections.ICollection" />. The <see cref="T:System.Array" /> must have zero-based indexing.</param> /// <param name="arrayIndex">The zero-based index in <paramref name="array" /> at which copying begins.</param> void ICollection.CopyTo(Array array, int arrayIndex) { Requires.NotNull(array, "array"); Requires.Range(arrayIndex >= 0, "arrayIndex"); Requires.Range(array.Length >= arrayIndex + this.Count, "arrayIndex"); if (this.Count == 0) { return; } int[] indices = new int[1]; // SetValue takes a params array; lifting out the implicit allocation from the loop foreach (T item in this) { indices[0] = arrayIndex++; array.SetValue(item, indices); } } /// <summary> /// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection" /> is synchronized (thread safe). /// </summary> /// <returns>true if access to the <see cref="T:System.Collections.ICollection" /> is synchronized (thread safe); otherwise, false.</returns> [DebuggerBrowsable(DebuggerBrowsableState.Never)] bool ICollection.IsSynchronized { get { return true; } } /// <summary> /// Gets an object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection" />. /// </summary> /// <returns>An object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection" />.</returns> [DebuggerBrowsable(DebuggerBrowsableState.Never)] object ICollection.SyncRoot { get { return this; } } } /// <summary> /// A lightweight collection view over and IEnumerable of keys. /// </summary> internal class KeysCollectionAccessor<TKey, TValue> : KeysOrValuesCollectionAccessor<TKey, TValue, TKey> { /// <summary> /// Initializes a new instance of the <see cref="KeysCollectionAccessor{TKey, TValue}"/> class. /// </summary> internal KeysCollectionAccessor(IImmutableDictionary<TKey, TValue> dictionary) : base(dictionary, dictionary.Keys) { } /// <summary> /// See <see cref="ICollection&lt;T&gt;"/> /// </summary> public override bool Contains(TKey item) { return this.Dictionary.ContainsKey(item); } } /// <summary> /// A lightweight collection view over and IEnumerable of values. /// </summary> internal class ValuesCollectionAccessor<TKey, TValue> : KeysOrValuesCollectionAccessor<TKey, TValue, TValue> { /// <summary> /// Initializes a new instance of the <see cref="ValuesCollectionAccessor{TKey, TValue}"/> class. /// </summary> internal ValuesCollectionAccessor(IImmutableDictionary<TKey, TValue> dictionary) : base(dictionary, dictionary.Values) { } /// <summary> /// See <see cref="ICollection&lt;T&gt;"/> /// </summary> public override bool Contains(TValue item) { var sortedDictionary = this.Dictionary as ImmutableSortedDictionary<TKey, TValue>; if (sortedDictionary != null) { return sortedDictionary.ContainsValue(item); } var dictionary = this.Dictionary as IImmutableDictionaryInternal<TKey, TValue>; if (dictionary != null) { return dictionary.ContainsValue(item); } throw new NotSupportedException(); } } }
// 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.Runtime.InteropServices; using System.Threading; using System.Xml.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Venus; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.TextManager.Interop; using MSXML; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets { internal abstract class AbstractSnippetExpansionClient : ForegroundThreadAffinitizedObject, IVsExpansionClient { protected readonly IVsEditorAdaptersFactoryService EditorAdaptersFactoryService; protected readonly Guid LanguageServiceGuid; protected readonly ITextView TextView; protected readonly ITextBuffer SubjectBuffer; protected bool indentCaretOnCommit; protected int indentDepth; protected bool earlyEndExpansionHappened; internal IVsExpansionSession ExpansionSession; public AbstractSnippetExpansionClient(Guid languageServiceGuid, ITextView textView, ITextBuffer subjectBuffer, IVsEditorAdaptersFactoryService editorAdaptersFactoryService) { this.LanguageServiceGuid = languageServiceGuid; this.TextView = textView; this.SubjectBuffer = subjectBuffer; this.EditorAdaptersFactoryService = editorAdaptersFactoryService; } public abstract int GetExpansionFunction(IXMLDOMNode xmlFunctionNode, string bstrFieldName, out IVsExpansionFunction pFunc); protected abstract ITrackingSpan InsertEmptyCommentAndGetEndPositionTrackingSpan(); internal abstract Document AddImports(Document document, XElement snippetNode, bool placeSystemNamespaceFirst, CancellationToken cancellationToken); public int FormatSpan(IVsTextLines pBuffer, VsTextSpan[] tsInSurfaceBuffer) { // Formatting a snippet isn't cancellable. var cancellationToken = CancellationToken.None; // At this point, the $selection$ token has been replaced with the selected text and // declarations have been replaced with their default text. We need to format the // inserted snippet text while carefully handling $end$ position (where the caret goes // after Return is pressed). The IVsExpansionSession keeps a tracking point for this // position but we do the tracking ourselves to properly deal with virtual space. To // ensure the end location is correct, we take three extra steps: // 1. Insert an empty comment ("/**/" or "'") at the current $end$ position (prior // to formatting), and keep a tracking span for the comment. // 2. After formatting the new snippet text, find and delete the empty multiline // comment (via the tracking span) and notify the IVsExpansionSession of the new // $end$ location. If the line then contains only whitespace (due to the formatter // putting the empty comment on its own line), then delete the white space and // remember the indentation depth for that line. // 3. When the snippet is finally completed (via Return), and PositionCaretForEditing() // is called, check to see if the end location was on a line containing only white // space in the previous step. If so, and if that line is still empty, then position // the caret in virtual space. // This technique ensures that a snippet like "if($condition$) { $end$ }" will end up // as: // if ($condition$) // { // $end$ // } SnapshotSpan snippetSpan; if (!TryGetSubjectBufferSpan(tsInSurfaceBuffer[0], out snippetSpan)) { return VSConstants.S_OK; } // Insert empty comment and track end position var snippetTrackingSpan = snippetSpan.CreateTrackingSpan(SpanTrackingMode.EdgeInclusive); var fullSnippetSpan = new VsTextSpan[1]; ExpansionSession.GetSnippetSpan(fullSnippetSpan); var isFullSnippetFormat = fullSnippetSpan[0].iStartLine == tsInSurfaceBuffer[0].iStartLine && fullSnippetSpan[0].iStartIndex == tsInSurfaceBuffer[0].iStartIndex && fullSnippetSpan[0].iEndLine == tsInSurfaceBuffer[0].iEndLine && fullSnippetSpan[0].iEndIndex == tsInSurfaceBuffer[0].iEndIndex; var endPositionTrackingSpan = isFullSnippetFormat ? InsertEmptyCommentAndGetEndPositionTrackingSpan() : null; var formattingSpan = CommonFormattingHelpers.GetFormattingSpan(SubjectBuffer.CurrentSnapshot, snippetTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot)); SubjectBuffer.CurrentSnapshot.FormatAndApplyToBuffer(formattingSpan, CancellationToken.None); if (isFullSnippetFormat) { CleanUpEndLocation(endPositionTrackingSpan); // Unfortunately, this is the only place we can safely add references and imports // specified in the snippet xml. In OnBeforeInsertion we have no guarantee that the // snippet xml will be available, and changing the buffer during OnAfterInsertion can // cause the underlying tracking spans to get out of sync. AddReferencesAndImports(ExpansionSession, cancellationToken); SetNewEndPosition(endPositionTrackingSpan); } return VSConstants.S_OK; } private void SetNewEndPosition(ITrackingSpan endTrackingSpan) { if (SetEndPositionIfNoneSpecified(ExpansionSession)) { return; } if (endTrackingSpan != null) { SnapshotSpan endSpanInSurfaceBuffer; if (!TryGetSpanOnHigherBuffer( endTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot), TextView.TextBuffer, out endSpanInSurfaceBuffer)) { return; } int endLine, endColumn; TextView.TextSnapshot.GetLineAndColumn(endSpanInSurfaceBuffer.Start.Position, out endLine, out endColumn); ExpansionSession.SetEndSpan(new VsTextSpan { iStartLine = endLine, iStartIndex = endColumn, iEndLine = endLine, iEndIndex = endColumn }); } } private void CleanUpEndLocation(ITrackingSpan endTrackingSpan) { if (endTrackingSpan != null) { // Find the empty comment and remove it... var endSnapshotSpan = endTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot); SubjectBuffer.Delete(endSnapshotSpan.Span); // Remove the whitespace before the comment if necessary. If whitespace is removed, // then remember the indentation depth so we can appropriately position the caret // in virtual space when the session is ended. var line = SubjectBuffer.CurrentSnapshot.GetLineFromPosition(endSnapshotSpan.Start.Position); var lineText = line.GetText(); if (lineText.Trim() == string.Empty) { indentCaretOnCommit = true; var document = this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null) { var optionService = document.Project.Solution.Workspace.Services.GetService<IOptionService>(); var tabSize = optionService.GetOption(FormattingOptions.TabSize, document.Project.Language); indentDepth = lineText.GetColumnFromLineOffset(lineText.Length, tabSize); } else { // If we don't have a document, then just guess the typical default TabSize value. indentDepth = lineText.GetColumnFromLineOffset(lineText.Length, tabSize: 4); } SubjectBuffer.Delete(new Span(line.Start.Position, line.Length)); endSnapshotSpan = SubjectBuffer.CurrentSnapshot.GetSpan(new Span(line.Start.Position, 0)); } } } /// <summary> /// If there was no $end$ token, place it at the end of the snippet code. Otherwise, it /// defaults to the beginning of the snippet code. /// </summary> private static bool SetEndPositionIfNoneSpecified(IVsExpansionSession pSession) { XElement snippetNode; if (!TryGetSnippetNode(pSession, out snippetNode)) { return false; } var ns = snippetNode.Name.NamespaceName; var codeNode = snippetNode.Element(XName.Get("Code", ns)); if (codeNode == null) { return false; } var delimiterAttribute = codeNode.Attribute("Delimiter"); var delimiter = delimiterAttribute != null ? delimiterAttribute.Value : "$"; if (codeNode.Value.IndexOf(string.Format("{0}end{0}", delimiter), StringComparison.OrdinalIgnoreCase) != -1) { return false; } var snippetSpan = new VsTextSpan[1]; if (pSession.GetSnippetSpan(snippetSpan) != VSConstants.S_OK) { return false; } var newEndSpan = new VsTextSpan { iStartLine = snippetSpan[0].iEndLine, iStartIndex = snippetSpan[0].iEndIndex, iEndLine = snippetSpan[0].iEndLine, iEndIndex = snippetSpan[0].iEndIndex }; pSession.SetEndSpan(newEndSpan); return true; } protected static bool TryGetSnippetNode(IVsExpansionSession pSession, out XElement snippetNode) { IXMLDOMNode xmlNode = null; snippetNode = null; try { // Cast to our own version of IVsExpansionSession so that we can get pNode as an // IntPtr instead of a via a RCW. This allows us to guarantee that it pNode is // released before leaving this method. Otherwise, a second invocation of the same // snippet may cause an AccessViolationException. var session = (IVsExpansionSessionInternal)pSession; IntPtr pNode; if (session.GetSnippetNode(null, out pNode) != VSConstants.S_OK) { return false; } xmlNode = (IXMLDOMNode)Marshal.GetUniqueObjectForIUnknown(pNode); snippetNode = XElement.Parse(xmlNode.xml); return true; } finally { if (xmlNode != null && Marshal.IsComObject(xmlNode)) { Marshal.ReleaseComObject(xmlNode); } } } public int PositionCaretForEditing(IVsTextLines pBuffer, [ComAliasName("Microsoft.VisualStudio.TextManager.Interop.TextSpan")]VsTextSpan[] ts) { // If the formatted location of the $end$ position (the inserted comment) was on an // empty line and indented, then we have already removed the white space on that line // and the navigation location will be at column 0 on a blank line. We must now // position the caret in virtual space. int lineLength; pBuffer.GetLengthOfLine(ts[0].iStartLine, out lineLength); string endLineText; pBuffer.GetLineText(ts[0].iStartLine, 0, ts[0].iStartLine, lineLength, out endLineText); int endLinePosition; pBuffer.GetPositionOfLine(ts[0].iStartLine, out endLinePosition); PositionCaretForEditingInternal(endLineText, endLinePosition); return VSConstants.S_OK; } /// <summary> /// Internal for testing purposes. All real caret positioning logic takes place here. <see cref="PositionCaretForEditing"/> /// only extracts the <paramref name="endLineText"/> and <paramref name="endLinePosition"/> from the provided <see cref="IVsTextLines"/>. /// Tests can call this method directly to avoid producing an IVsTextLines. /// </summary> /// <param name="endLineText"></param> /// <param name="endLinePosition"></param> internal void PositionCaretForEditingInternal(string endLineText, int endLinePosition) { if (indentCaretOnCommit && endLineText == string.Empty) { TextView.TryMoveCaretToAndEnsureVisible(new VirtualSnapshotPoint(TextView.TextSnapshot.GetPoint(endLinePosition), indentDepth)); } } public virtual bool TryHandleTab() { if (ExpansionSession != null) { var tabbedInsideSnippetField = VSConstants.S_OK == ExpansionSession.GoToNextExpansionField(0); if (!tabbedInsideSnippetField) { ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1); ExpansionSession = null; } return tabbedInsideSnippetField; } return false; } public virtual bool TryHandleBackTab() { if (ExpansionSession != null) { var tabbedInsideSnippetField = VSConstants.S_OK == ExpansionSession.GoToPreviousExpansionField(); if (!tabbedInsideSnippetField) { ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1); ExpansionSession = null; } return tabbedInsideSnippetField; } return false; } public virtual bool TryHandleEscape() { if (ExpansionSession != null) { ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1); ExpansionSession = null; return true; } return false; } public virtual bool TryHandleReturn() { // TODO(davip): Only move the caret if the enter was hit within the editable spans if (ExpansionSession != null) { ExpansionSession.EndCurrentExpansion(fLeaveCaret: 0); ExpansionSession = null; return true; } return false; } public virtual bool TryInsertExpansion(int startPositionInSubjectBuffer, int endPositionInSubjectBuffer) { int startLine = 0; int startIndex = 0; int endLine = 0; int endIndex = 0; // The expansion itself needs to be created in the data buffer, so map everything up var startPointInSubjectBuffer = SubjectBuffer.CurrentSnapshot.GetPoint(startPositionInSubjectBuffer); var endPointInSubjectBuffer = SubjectBuffer.CurrentSnapshot.GetPoint(endPositionInSubjectBuffer); SnapshotSpan dataBufferSpan; if (!TryGetSpanOnHigherBuffer( SubjectBuffer.CurrentSnapshot.GetSpan(startPositionInSubjectBuffer, endPositionInSubjectBuffer - startPositionInSubjectBuffer), TextView.TextViewModel.DataBuffer, out dataBufferSpan)) { return false; } var buffer = EditorAdaptersFactoryService.GetBufferAdapter(TextView.TextViewModel.DataBuffer); var expansion = buffer as IVsExpansion; if (buffer == null || expansion == null) { return false; } buffer.GetLineIndexOfPosition(dataBufferSpan.Start.Position, out startLine, out startIndex); buffer.GetLineIndexOfPosition(dataBufferSpan.End.Position, out endLine, out endIndex); var textSpan = new VsTextSpan { iStartLine = startLine, iStartIndex = startIndex, iEndLine = endLine, iEndIndex = endIndex }; return expansion.InsertExpansion(textSpan, textSpan, this, LanguageServiceGuid, out ExpansionSession) == VSConstants.S_OK; } public int EndExpansion() { if (ExpansionSession == null) { earlyEndExpansionHappened = true; } ExpansionSession = null; indentCaretOnCommit = false; return VSConstants.S_OK; } public int IsValidKind(IVsTextLines pBuffer, VsTextSpan[] ts, string bstrKind, out int pfIsValidKind) { pfIsValidKind = 1; return VSConstants.S_OK; } public int IsValidType(IVsTextLines pBuffer, VsTextSpan[] ts, string[] rgTypes, int iCountTypes, out int pfIsValidType) { pfIsValidType = 1; return VSConstants.S_OK; } public int OnAfterInsertion(IVsExpansionSession pSession) { Logger.Log(FunctionId.Snippet_OnAfterInsertion); return VSConstants.S_OK; } public int OnBeforeInsertion(IVsExpansionSession pSession) { Logger.Log(FunctionId.Snippet_OnBeforeInsertion); this.ExpansionSession = pSession; return VSConstants.S_OK; } public int OnItemChosen(string pszTitle, string pszPath) { var hr = VSConstants.S_OK; try { VsTextSpan textSpan; GetCaretPositionInSurfaceBuffer(out textSpan.iStartLine, out textSpan.iStartIndex); textSpan.iEndLine = textSpan.iStartLine; textSpan.iEndIndex = textSpan.iStartIndex; IVsExpansion expansion = EditorAdaptersFactoryService.GetBufferAdapter(TextView.TextViewModel.DataBuffer) as IVsExpansion; earlyEndExpansionHappened = false; hr = expansion.InsertNamedExpansion(pszTitle, pszPath, textSpan, this, LanguageServiceGuid, fShowDisambiguationUI: 0, pSession: out ExpansionSession); if (earlyEndExpansionHappened) { // EndExpansion was called before InsertNamedExpansion returned, so set // expansionSession to null to indicate that there is no active expansion // session. This can occur when the snippet inserted doesn't have any expansion // fields. ExpansionSession = null; earlyEndExpansionHappened = false; } } catch (COMException ex) { hr = ex.ErrorCode; } return hr; } private void GetCaretPositionInSurfaceBuffer(out int caretLine, out int caretColumn) { var vsTextView = EditorAdaptersFactoryService.GetViewAdapter(TextView); vsTextView.GetCaretPos(out caretLine, out caretColumn); IVsTextLines textLines; vsTextView.GetBuffer(out textLines); // Handle virtual space (e.g, see Dev10 778675) int lineLength; textLines.GetLengthOfLine(caretLine, out lineLength); if (caretColumn > lineLength) { caretColumn = lineLength; } } private void AddReferencesAndImports(IVsExpansionSession pSession, CancellationToken cancellationToken) { XElement snippetNode; if (!TryGetSnippetNode(pSession, out snippetNode)) { return; } var documentWithImports = this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (documentWithImports == null) { return; } var optionService = documentWithImports.Project.Solution.Workspace.Services.GetService<IOptionService>(); var placeSystemNamespaceFirst = optionService.GetOption(OrganizerOptions.PlaceSystemNamespaceFirst, documentWithImports.Project.Language); documentWithImports = AddImports(documentWithImports, snippetNode, placeSystemNamespaceFirst, cancellationToken); AddReferences(documentWithImports.Project, snippetNode); } private void AddReferences(Project originalProject, XElement snippetNode) { var referencesNode = snippetNode.Element(XName.Get("References", snippetNode.Name.NamespaceName)); if (referencesNode == null) { return; } var existingReferenceNames = originalProject.MetadataReferences.Select(r => Path.GetFileNameWithoutExtension(r.Display)); var workspace = originalProject.Solution.Workspace; var projectId = originalProject.Id; var assemblyXmlName = XName.Get("Assembly", snippetNode.Name.NamespaceName); var failedReferenceAdditions = new List<string>(); var visualStudioWorkspace = workspace as VisualStudioWorkspaceImpl; foreach (var reference in referencesNode.Elements(XName.Get("Reference", snippetNode.Name.NamespaceName))) { // Note: URL references are not supported var assemblyElement = reference.Element(assemblyXmlName); var assemblyName = assemblyElement != null ? assemblyElement.Value.Trim() : null; if (string.IsNullOrEmpty(assemblyName)) { continue; } if (visualStudioWorkspace == null || !visualStudioWorkspace.TryAddReferenceToProject(projectId, assemblyName)) { failedReferenceAdditions.Add(assemblyName); } } if (failedReferenceAdditions.Any()) { var notificationService = workspace.Services.GetService<INotificationService>(); notificationService.SendNotification( string.Join(Environment.NewLine, failedReferenceAdditions), string.Format(ServicesVSResources.ReferencesNotFound, Environment.NewLine), NotificationSeverity.Warning); } } protected static bool TryAddImportsToContainedDocument(Document document, IEnumerable<string> memberImportsNamespaces) { var vsWorkspace = document.Project.Solution.Workspace as VisualStudioWorkspaceImpl; if (vsWorkspace == null) { return false; } var containedDocument = vsWorkspace.GetHostDocument(document.Id) as ContainedDocument; if (containedDocument == null) { return false; } var containedLanguageHost = containedDocument.ContainedLanguage.ContainedLanguageHost as IVsContainedLanguageHostInternal; if (containedLanguageHost != null) { foreach (var importClause in memberImportsNamespaces) { if (containedLanguageHost.InsertImportsDirective(importClause) != VSConstants.S_OK) { return false; } } } return true; } protected static bool TryGetSnippetFunctionInfo(IXMLDOMNode xmlFunctionNode, out string snippetFunctionName, out string param) { if (xmlFunctionNode.text.IndexOf('(') == -1 || xmlFunctionNode.text.IndexOf(')') == -1 || xmlFunctionNode.text.IndexOf(')') < xmlFunctionNode.text.IndexOf('(')) { snippetFunctionName = null; param = null; return false; } snippetFunctionName = xmlFunctionNode.text.Substring(0, xmlFunctionNode.text.IndexOf('(')); var paramStart = xmlFunctionNode.text.IndexOf('(') + 1; var paramLength = xmlFunctionNode.text.LastIndexOf(')') - xmlFunctionNode.text.IndexOf('(') - 1; param = xmlFunctionNode.text.Substring(paramStart, paramLength); return true; } internal bool TryGetSubjectBufferSpan(VsTextSpan surfaceBufferTextSpan, out SnapshotSpan subjectBufferSpan) { var snapshotSpan = TextView.TextSnapshot.GetSpan(surfaceBufferTextSpan); var subjectBufferSpanCollection = TextView.BufferGraph.MapDownToBuffer(snapshotSpan, SpanTrackingMode.EdgeExclusive, SubjectBuffer); // Bail if a snippet span does not map down to exactly one subject buffer span. if (subjectBufferSpanCollection.Count == 1) { subjectBufferSpan = subjectBufferSpanCollection.Single(); return true; } subjectBufferSpan = default(SnapshotSpan); return false; } internal bool TryGetSpanOnHigherBuffer(SnapshotSpan snapshotSpan, ITextBuffer targetBuffer, out SnapshotSpan span) { var spanCollection = TextView.BufferGraph.MapUpToBuffer(snapshotSpan, SpanTrackingMode.EdgeExclusive, targetBuffer); // Bail if a snippet span does not map up to exactly one span. if (spanCollection.Count == 1) { span = spanCollection.Single(); return true; } span = default(SnapshotSpan); return false; } } }
using YAF.Lucene.Net.Diagnostics; namespace YAF.Lucene.Net.Codecs.Lucene41 { /* * 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 IOUtils = YAF.Lucene.Net.Util.IOUtils; using SegmentReadState = YAF.Lucene.Net.Index.SegmentReadState; using SegmentWriteState = YAF.Lucene.Net.Index.SegmentWriteState; /// <summary> /// Lucene 4.1 postings format, which encodes postings in packed integer blocks /// for fast decode. /// /// <para><b>NOTE</b>: this format is still experimental and /// subject to change without backwards compatibility. /// /// <para> /// Basic idea: /// <list type="bullet"> /// <item><description> /// <b>Packed Blocks and VInt Blocks</b>: /// <para>In packed blocks, integers are encoded with the same bit width packed format (<see cref="Util.Packed.PackedInt32s"/>): /// the block size (i.e. number of integers inside block) is fixed (currently 128). Additionally blocks /// that are all the same value are encoded in an optimized way.</para> /// <para>In VInt blocks, integers are encoded as VInt (<see cref="Store.DataOutput.WriteVInt32(int)"/>): /// the block size is variable.</para> /// </description></item> /// /// <item><description> /// <b>Block structure</b>: /// <para>When the postings are long enough, Lucene41PostingsFormat will try to encode most integer data /// as a packed block.</para> /// <para>Take a term with 259 documents as an example, the first 256 document ids are encoded as two packed /// blocks, while the remaining 3 are encoded as one VInt block. </para> /// <para>Different kinds of data are always encoded separately into different packed blocks, but may /// possibly be interleaved into the same VInt block. </para> /// <para>This strategy is applied to pairs: /// &lt;document number, frequency&gt;, /// &lt;position, payload length&gt;, /// &lt;position, offset start, offset length&gt;, and /// &lt;position, payload length, offsetstart, offset length&gt;.</para> /// </description></item> /// /// <item><description> /// <b>Skipdata settings</b>: /// <para>The structure of skip table is quite similar to previous version of Lucene. Skip interval is the /// same as block size, and each skip entry points to the beginning of each block. However, for /// the first block, skip data is omitted.</para> /// </description></item> /// /// <item><description> /// <b>Positions, Payloads, and Offsets</b>: /// <para>A position is an integer indicating where the term occurs within one document. /// A payload is a blob of metadata associated with current position. /// An offset is a pair of integers indicating the tokenized start/end offsets for given term /// in current position: it is essentially a specialized payload. </para> /// <para>When payloads and offsets are not omitted, numPositions==numPayloads==numOffsets (assuming a /// null payload contributes one count). As mentioned in block structure, it is possible to encode /// these three either combined or separately.</para> /// <para>In all cases, payloads and offsets are stored together. When encoded as a packed block, /// position data is separated out as .pos, while payloads and offsets are encoded in .pay (payload /// metadata will also be stored directly in .pay). When encoded as VInt blocks, all these three are /// stored interleaved into the .pos (so is payload metadata).</para> /// <para>With this strategy, the majority of payload and offset data will be outside .pos file. /// So for queries that require only position data, running on a full index with payloads and offsets, /// this reduces disk pre-fetches.</para> /// </description></item> /// </list> /// </para> /// /// <para> /// Files and detailed format: /// <list type="bullet"> /// <item><description><c>.tim</c>: <a href="#Termdictionary">Term Dictionary</a></description></item> /// <item><description><c>.tip</c>: <a href="#Termindex">Term Index</a></description></item> /// <item><description><c>.doc</c>: <a href="#Frequencies">Frequencies and Skip Data</a></description></item> /// <item><description><c>.pos</c>: <a href="#Positions">Positions</a></description></item> /// <item><description><c>.pay</c>: <a href="#Payloads">Payloads and Offsets</a></description></item> /// </list> /// </para> /// /// <a name="Termdictionary" id="Termdictionary"></a> /// <dl> /// <dd> /// <b>Term Dictionary</b> /// /// <para>The .tim file contains the list of terms in each /// field along with per-term statistics (such as docfreq) /// and pointers to the frequencies, positions, payload and /// skip data in the .doc, .pos, and .pay files. /// See <see cref="BlockTreeTermsWriter"/> for more details on the format. /// </para> /// /// <para>NOTE: The term dictionary can plug into different postings implementations: /// the postings writer/reader are actually responsible for encoding /// and decoding the PostingsHeader and TermMetadata sections described here:</para> /// /// <list type="bullet"> /// <item><description>PostingsHeader --&gt; Header, PackedBlockSize</description></item> /// <item><description>TermMetadata --&gt; (DocFPDelta|SingletonDocID), PosFPDelta?, PosVIntBlockFPDelta?, PayFPDelta?, /// SkipFPDelta?</description></item> /// <item><description>Header, --&gt; CodecHeader (<see cref="CodecUtil.WriteHeader(Store.DataOutput, string, int)"/>) </description></item> /// <item><description>PackedBlockSize, SingletonDocID --&gt; VInt (<see cref="Store.DataOutput.WriteVInt32(int)"/>) </description></item> /// <item><description>DocFPDelta, PosFPDelta, PayFPDelta, PosVIntBlockFPDelta, SkipFPDelta --&gt; VLong (<see cref="Store.DataOutput.WriteVInt64(long)"/>) </description></item> /// <item><description>Footer --&gt; CodecFooter (<see cref="CodecUtil.WriteFooter(Store.IndexOutput)"/>) </description></item> /// </list> /// <para>Notes:</para> /// <list type="bullet"> /// <item><description>Header is a CodecHeader (<see cref="CodecUtil.WriteHeader(Store.DataOutput, string, int)"/>) storing the version information /// for the postings.</description></item> /// <item><description>PackedBlockSize is the fixed block size for packed blocks. In packed block, bit width is /// determined by the largest integer. Smaller block size result in smaller variance among width /// of integers hence smaller indexes. Larger block size result in more efficient bulk i/o hence /// better acceleration. This value should always be a multiple of 64, currently fixed as 128 as /// a tradeoff. It is also the skip interval used to accelerate <see cref="Search.DocIdSetIterator.Advance(int)"/>.</description></item> /// <item><description>DocFPDelta determines the position of this term's TermFreqs within the .doc file. /// In particular, it is the difference of file offset between this term's /// data and previous term's data (or zero, for the first term in the block).On disk it is /// stored as the difference from previous value in sequence. </description></item> /// <item><description>PosFPDelta determines the position of this term's TermPositions within the .pos file. /// While PayFPDelta determines the position of this term's &lt;TermPayloads, TermOffsets?&gt; within /// the .pay file. Similar to DocFPDelta, it is the difference between two file positions (or /// neglected, for fields that omit payloads and offsets).</description></item> /// <item><description>PosVIntBlockFPDelta determines the position of this term's last TermPosition in last pos packed /// block within the .pos file. It is synonym for PayVIntBlockFPDelta or OffsetVIntBlockFPDelta. /// This is actually used to indicate whether it is necessary to load following /// payloads and offsets from .pos instead of .pay. Every time a new block of positions are to be /// loaded, the PostingsReader will use this value to check whether current block is packed format /// or VInt. When packed format, payloads and offsets are fetched from .pay, otherwise from .pos. /// (this value is neglected when total number of positions i.e. totalTermFreq is less or equal /// to PackedBlockSize).</description></item> /// <item><description>SkipFPDelta determines the position of this term's SkipData within the .doc /// file. In particular, it is the length of the TermFreq data. /// SkipDelta is only stored if DocFreq is not smaller than SkipMinimum /// (i.e. 128 in Lucene41PostingsFormat).</description></item> /// <item><description>SingletonDocID is an optimization when a term only appears in one document. In this case, instead /// of writing a file pointer to the .doc file (DocFPDelta), and then a VIntBlock at that location, the /// single document ID is written to the term dictionary.</description></item> /// </list> /// </dd> /// </dl> /// /// <a name="Termindex" id="Termindex"></a> /// <dl> /// <dd> /// <b>Term Index</b> /// <para>The .tip file contains an index into the term dictionary, so that it can be /// accessed randomly. See <see cref="BlockTreeTermsWriter"/> for more details on the format.</para> /// </dd> /// </dl> /// /// /// <a name="Frequencies" id="Frequencies"></a> /// <dl> /// <dd> /// <b>Frequencies and Skip Data</b> /// /// <para>The .doc file contains the lists of documents which contain each term, along /// with the frequency of the term in that document (except when frequencies are /// omitted: <see cref="Index.IndexOptions.DOCS_ONLY"/>). It also saves skip data to the beginning of /// each packed or VInt block, when the length of document list is larger than packed block size.</para> /// /// <list type="bullet"> /// <item><description>docFile(.doc) --&gt; Header, &lt;TermFreqs, SkipData?&gt;<sup>TermCount</sup>, Footer</description></item> /// <item><description>Header --&gt; CodecHeader (<see cref="CodecUtil.WriteHeader(Store.DataOutput, string, int)"/>)</description></item> /// <item><description>TermFreqs --&gt; &lt;PackedBlock&gt; <sup>PackedDocBlockNum</sup>, /// VIntBlock? </description></item> /// <item><description>PackedBlock --&gt; PackedDocDeltaBlock, PackedFreqBlock?</description></item> /// <item><description>VIntBlock --&gt; &lt;DocDelta[, Freq?]&gt;<sup>DocFreq-PackedBlockSize*PackedDocBlockNum</sup></description></item> /// <item><description>SkipData --&gt; &lt;&lt;SkipLevelLength, SkipLevel&gt; /// <sup>NumSkipLevels-1</sup>, SkipLevel&gt;, SkipDatum?</description></item> /// <item><description>SkipLevel --&gt; &lt;SkipDatum&gt; <sup>TrimmedDocFreq/(PackedBlockSize^(Level + 1))</sup></description></item> /// <item><description>SkipDatum --&gt; DocSkip, DocFPSkip, &lt;PosFPSkip, PosBlockOffset, PayLength?, /// PayFPSkip?&gt;?, SkipChildLevelPointer?</description></item> /// <item><description>PackedDocDeltaBlock, PackedFreqBlock --&gt; PackedInts (<see cref="Util.Packed.PackedInt32s"/>) </description></item> /// <item><description>DocDelta, Freq, DocSkip, DocFPSkip, PosFPSkip, PosBlockOffset, PayByteUpto, PayFPSkip /// --&gt; /// VInt (<see cref="Store.DataOutput.WriteVInt32(int)"/>) </description></item> /// <item><description>SkipChildLevelPointer --&gt; VLong (<see cref="Store.DataOutput.WriteVInt64(long)"/>) </description></item> /// <item><description>Footer --&gt; CodecFooter (<see cref="CodecUtil.WriteFooter(Store.IndexOutput)"/>) </description></item> /// </list> /// <para>Notes:</para> /// <list type="bullet"> /// <item><description>PackedDocDeltaBlock is theoretically generated from two steps: /// <list type="number"> /// <item><description>Calculate the difference between each document number and previous one, /// and get a d-gaps list (for the first document, use absolute value); </description></item> /// <item><description>For those d-gaps from first one to PackedDocBlockNum*PackedBlockSize<sup>th</sup>, /// separately encode as packed blocks.</description></item> /// </list> /// If frequencies are not omitted, PackedFreqBlock will be generated without d-gap step. /// </description></item> /// <item><description>VIntBlock stores remaining d-gaps (along with frequencies when possible) with a format /// that encodes DocDelta and Freq: /// <para>DocDelta: if frequencies are indexed, this determines both the document /// number and the frequency. In particular, DocDelta/2 is the difference between /// this document number and the previous document number (or zero when this is the /// first document in a TermFreqs). When DocDelta is odd, the frequency is one. /// When DocDelta is even, the frequency is read as another VInt. If frequencies /// are omitted, DocDelta contains the gap (not multiplied by 2) between document /// numbers and no frequency information is stored.</para> /// <para>For example, the TermFreqs for a term which occurs once in document seven /// and three times in document eleven, with frequencies indexed, would be the /// following sequence of VInts:</para> /// <para>15, 8, 3</para> /// <para>If frequencies were omitted (<see cref="Index.IndexOptions.DOCS_ONLY"/>) it would be this /// sequence of VInts instead:</para> /// <para>7,4</para> /// </description></item> /// <item><description>PackedDocBlockNum is the number of packed blocks for current term's docids or frequencies. /// In particular, PackedDocBlockNum = floor(DocFreq/PackedBlockSize) </description></item> /// <item><description>TrimmedDocFreq = DocFreq % PackedBlockSize == 0 ? DocFreq - 1 : DocFreq. /// We use this trick since the definition of skip entry is a little different from base interface. /// In <see cref="MultiLevelSkipListWriter"/>, skip data is assumed to be saved for /// skipInterval<sup>th</sup>, 2*skipInterval<sup>th</sup> ... posting in the list. However, /// in Lucene41PostingsFormat, the skip data is saved for skipInterval+1<sup>th</sup>, /// 2*skipInterval+1<sup>th</sup> ... posting (skipInterval==PackedBlockSize in this case). /// When DocFreq is multiple of PackedBlockSize, MultiLevelSkipListWriter will expect one /// more skip data than Lucene41SkipWriter. </description></item> /// <item><description>SkipDatum is the metadata of one skip entry. /// For the first block (no matter packed or VInt), it is omitted.</description></item> /// <item><description>DocSkip records the document number of every PackedBlockSize<sup>th</sup> document number in /// the postings (i.e. last document number in each packed block). On disk it is stored as the /// difference from previous value in the sequence. </description></item> /// <item><description>DocFPSkip records the file offsets of each block (excluding )posting at /// PackedBlockSize+1<sup>th</sup>, 2*PackedBlockSize+1<sup>th</sup> ... , in DocFile. /// The file offsets are relative to the start of current term's TermFreqs. /// On disk it is also stored as the difference from previous SkipDatum in the sequence.</description></item> /// <item><description>Since positions and payloads are also block encoded, the skip should skip to related block first, /// then fetch the values according to in-block offset. PosFPSkip and PayFPSkip record the file /// offsets of related block in .pos and .pay, respectively. While PosBlockOffset indicates /// which value to fetch inside the related block (PayBlockOffset is unnecessary since it is always /// equal to PosBlockOffset). Same as DocFPSkip, the file offsets are relative to the start of /// current term's TermFreqs, and stored as a difference sequence.</description></item> /// <item><description>PayByteUpto indicates the start offset of the current payload. It is equivalent to /// the sum of the payload lengths in the current block up to PosBlockOffset</description></item> /// </list> /// </dd> /// </dl> /// /// <a name="Positions" id="Positions"></a> /// <dl> /// <dd> /// <b>Positions</b> /// <para>The .pos file contains the lists of positions that each term occurs at within documents. It also /// sometimes stores part of payloads and offsets for speedup.</para> /// <list type="bullet"> /// <item><description>PosFile(.pos) --&gt; Header, &lt;TermPositions&gt; <sup>TermCount</sup>, Footer</description></item> /// <item><description>Header --&gt; CodecHeader (<see cref="CodecUtil.WriteHeader(Store.DataOutput, string, int)"/>) </description></item> /// <item><description>TermPositions --&gt; &lt;PackedPosDeltaBlock&gt; <sup>PackedPosBlockNum</sup>, /// VIntBlock? </description></item> /// <item><description>VIntBlock --&gt; &lt;PositionDelta[, PayloadLength?], PayloadData?, /// OffsetDelta?, OffsetLength?&gt;<sup>PosVIntCount</sup></description></item> /// <item><description>PackedPosDeltaBlock --&gt; PackedInts (<see cref="Util.Packed.PackedInt32s"/>)</description></item> /// <item><description>PositionDelta, OffsetDelta, OffsetLength --&gt; /// VInt (<see cref="Store.DataOutput.WriteVInt32(int)"/>) </description></item> /// <item><description>PayloadData --&gt; byte (<see cref="Store.DataOutput.WriteByte(byte)"/>)<sup>PayLength</sup></description></item> /// <item><description>Footer --&gt; CodecFooter (<see cref="CodecUtil.WriteFooter(Store.IndexOutput)"/>) </description></item> /// </list> /// <para>Notes:</para> /// <list type="bullet"> /// <item><description>TermPositions are order by term (terms are implicit, from the term dictionary), and position /// values for each term document pair are incremental, and ordered by document number.</description></item> /// <item><description>PackedPosBlockNum is the number of packed blocks for current term's positions, payloads or offsets. /// In particular, PackedPosBlockNum = floor(totalTermFreq/PackedBlockSize) </description></item> /// <item><description>PosVIntCount is the number of positions encoded as VInt format. In particular, /// PosVIntCount = totalTermFreq - PackedPosBlockNum*PackedBlockSize</description></item> /// <item><description>The procedure how PackedPosDeltaBlock is generated is the same as PackedDocDeltaBlock /// in chapter <a href="#Frequencies">Frequencies and Skip Data</a>.</description></item> /// <item><description>PositionDelta is, if payloads are disabled for the term's field, the /// difference between the position of the current occurrence in the document and /// the previous occurrence (or zero, if this is the first occurrence in this /// document). If payloads are enabled for the term's field, then PositionDelta/2 /// is the difference between the current and the previous position. If payloads /// are enabled and PositionDelta is odd, then PayloadLength is stored, indicating /// the length of the payload at the current term position.</description></item> /// <item><description>For example, the TermPositions for a term which occurs as the fourth term in /// one document, and as the fifth and ninth term in a subsequent document, would /// be the following sequence of VInts (payloads disabled): /// <para>4, 5, 4</para></description></item> /// <item><description>PayloadData is metadata associated with the current term position. If /// PayloadLength is stored at the current position, then it indicates the length /// of this payload. If PayloadLength is not stored, then this payload has the same /// length as the payload at the previous position.</description></item> /// <item><description>OffsetDelta/2 is the difference between this position's startOffset from the /// previous occurrence (or zero, if this is the first occurrence in this document). /// If OffsetDelta is odd, then the length (endOffset-startOffset) differs from the /// previous occurrence and an OffsetLength follows. Offset data is only written for /// <see cref="Index.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS"/>.</description></item> /// </list> /// </dd> /// </dl> /// /// <a name="Payloads" id="Payloads"></a> /// <dl> /// <dd> /// <b>Payloads and Offsets</b> /// <para>The .pay file will store payloads and offsets associated with certain term-document positions. /// Some payloads and offsets will be separated out into .pos file, for performance reasons.</para> /// <list type="bullet"> /// <item><description>PayFile(.pay): --&gt; Header, &lt;TermPayloads, TermOffsets?&gt; <sup>TermCount</sup>, Footer</description></item> /// <item><description>Header --&gt; CodecHeader (<see cref="CodecUtil.WriteHeader(Store.DataOutput, string, int)"/>) </description></item> /// <item><description>TermPayloads --&gt; &lt;PackedPayLengthBlock, SumPayLength, PayData&gt; <sup>PackedPayBlockNum</sup></description></item> /// <item><description>TermOffsets --&gt; &lt;PackedOffsetStartDeltaBlock, PackedOffsetLengthBlock&gt; <sup>PackedPayBlockNum</sup></description></item> /// <item><description>PackedPayLengthBlock, PackedOffsetStartDeltaBlock, PackedOffsetLengthBlock --&gt; PackedInts (<see cref="Util.Packed.PackedInt32s"/>) </description></item> /// <item><description>SumPayLength --&gt; VInt (<see cref="Store.DataOutput.WriteVInt32(int)"/>) </description></item> /// <item><description>PayData --&gt; byte (<see cref="Store.DataOutput.WriteByte(byte)"/>) <sup>SumPayLength</sup></description></item> /// <item><description>Footer --&gt; CodecFooter (<see cref="CodecUtil.WriteFooter(Store.IndexOutput)"/>) </description></item> /// </list> /// <para>Notes:</para> /// <list type="bullet"> /// <item><description>The order of TermPayloads/TermOffsets will be the same as TermPositions, note that part of /// payload/offsets are stored in .pos.</description></item> /// <item><description>The procedure how PackedPayLengthBlock and PackedOffsetLengthBlock are generated is the /// same as PackedFreqBlock in chapter <a href="#Frequencies">Frequencies and Skip Data</a>. /// While PackedStartDeltaBlock follows a same procedure as PackedDocDeltaBlock.</description></item> /// <item><description>PackedPayBlockNum is always equal to PackedPosBlockNum, for the same term. It is also synonym /// for PackedOffsetBlockNum.</description></item> /// <item><description>SumPayLength is the total length of payloads written within one block, should be the sum /// of PayLengths in one packed block.</description></item> /// <item><description>PayLength in PackedPayLengthBlock is the length of each payload associated with the current /// position.</description></item> /// </list> /// </dd> /// </dl> /// </para> /// /// @lucene.experimental /// </summary> [PostingsFormatName("Lucene41")] // LUCENENET specific - using PostingsFormatName attribute to ensure the default name passed from subclasses is the same as this class name public sealed class Lucene41PostingsFormat : PostingsFormat { /// <summary> /// Filename extension for document number, frequencies, and skip data. /// See chapter: <a href="#Frequencies">Frequencies and Skip Data</a> /// </summary> public const string DOC_EXTENSION = "doc"; /// <summary> /// Filename extension for positions. /// See chapter: <a href="#Positions">Positions</a> /// </summary> public const string POS_EXTENSION = "pos"; /// <summary> /// Filename extension for payloads and offsets. /// See chapter: <a href="#Payloads">Payloads and Offsets</a> /// </summary> public const string PAY_EXTENSION = "pay"; private readonly int minTermBlockSize; private readonly int maxTermBlockSize; /// <summary> /// Fixed packed block size, number of integers encoded in /// a single packed block. /// </summary> // NOTE: must be multiple of 64 because of PackedInts long-aligned encoding/decoding public static int BLOCK_SIZE = 128; /// <summary> /// Creates <see cref="Lucene41PostingsFormat"/> with default /// settings. /// </summary> public Lucene41PostingsFormat() : this(BlockTreeTermsWriter.DEFAULT_MIN_BLOCK_SIZE, BlockTreeTermsWriter.DEFAULT_MAX_BLOCK_SIZE) { } /// <summary> /// Creates <see cref="Lucene41PostingsFormat"/> with custom /// values for <paramref name="minTermBlockSize"/> and /// <paramref name="maxTermBlockSize"/> passed to block terms dictionary. </summary> /// <seealso cref="BlockTreeTermsWriter.BlockTreeTermsWriter(SegmentWriteState,PostingsWriterBase,int,int)"/> public Lucene41PostingsFormat(int minTermBlockSize, int maxTermBlockSize) : base() { this.minTermBlockSize = minTermBlockSize; if (Debugging.AssertsEnabled) Debugging.Assert(minTermBlockSize > 1); this.maxTermBlockSize = maxTermBlockSize; if (Debugging.AssertsEnabled) Debugging.Assert(minTermBlockSize <= maxTermBlockSize); } public override string ToString() { return Name + "(blocksize=" + BLOCK_SIZE + ")"; } public override FieldsConsumer FieldsConsumer(SegmentWriteState state) { PostingsWriterBase postingsWriter = new Lucene41PostingsWriter(state); bool success = false; try { FieldsConsumer ret = new BlockTreeTermsWriter(state, postingsWriter, minTermBlockSize, maxTermBlockSize); success = true; return ret; } finally { if (!success) { IOUtils.DisposeWhileHandlingException(postingsWriter); } } } public override FieldsProducer FieldsProducer(SegmentReadState state) { PostingsReaderBase postingsReader = new Lucene41PostingsReader(state.Directory, state.FieldInfos, state.SegmentInfo, state.Context, state.SegmentSuffix); bool success = false; try { FieldsProducer ret = new BlockTreeTermsReader(state.Directory, state.FieldInfos, state.SegmentInfo, postingsReader, state.Context, state.SegmentSuffix, state.TermsIndexDivisor); success = true; return ret; } finally { if (!success) { IOUtils.DisposeWhileHandlingException(postingsReader); } } } } }
#region license // Copyright 2004-2011 Castle Project - http://www.castleproject.org/ // // 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. #endregion namespace Castle.Transactions.IO.Tests { using System; using System.IO; using System.Linq; using System.Text; using Castle.IO.Extensions; using NUnit.Framework; using SharpTestsEx; public class File_Specs : TxFTestFixtureBase { private string _TfPath; [SetUp] public void TFSetup() { var dllPath = Environment.CurrentDirectory; _TfPath = dllPath.CombineAssert("File_Specs"); } [TearDown] public void TFTearDown() { if (_TfPath != null) Directory.Delete(_TfPath, true); } [Test] public void Smoke() { } [Test] public void WriteAllText() { var filepath = _TfPath.Combine("write-text.txt"); using (ITransaction tx = new FileTransaction("Commit TX")) { var fa = (IFileAdapter) tx; fa.WriteAllText(filepath, "Transacted file."); tx.Complete(); Assert.That(tx.State == TransactionState.CommittedOrCompleted); } File.Exists(filepath).Should("exist after the transaction") .Be.True(); File.ReadAllLines(filepath) .First().Should() .Be.EqualTo("Transacted file."); } [Test] public void Move_ToDirectory() { var folder = _TfPath.CombineAssert("source_folder"); var toFolder = _TfPath.CombineAssert("target_folder"); const string fileName = "Move_ToDirectory.txt"; var file = folder.Combine(fileName); Directory.Exists(toFolder).Should().Be.False(); (File.Exists(file)).Should().Be.False(); File.WriteAllText(file, "this string is the contents of the file"); using (ITransaction t = new FileTransaction("moving file")) { File.Exists(toFolder.Combine("file")) .Should("not exist before move") .Be.False(); // moving file to folder ((IFileAdapter) t) .Move(file, toFolder); File.Exists(file) .Should("call through tx and be deleted") .Be.False(); File.Exists(toFolder.Combine("file")) .Should("call through tx and visible in its new location") .Be.True(); t.Complete(); } File.Exists(toFolder.Combine("file")) .Should( "be visible to the outside now and since we tried to move it to " + " an existing folder, it should put itself in that folder with its current name.") .Be.True(); } [Test] public void Move_ToDirectory_PlusFileName() { // given var folder = _TfPath.CombineAssert("source_folder"); var toFolder = _TfPath.CombineAssert("target_folder"); const string fileName = "Move_ToDirectory_PlusFileName.txt"; var file = folder.Combine(fileName); File.Exists(file) .Should() .Be.False(); File.WriteAllText(file, "testing move"); // when using (ITransaction t = new FileTransaction()) { File.Exists(toFolder.Combine(fileName)) .Should("not exist before move") .Be.False(); // method under test: ((IFileAdapter) t).Move(file, toFolder.Combine(fileName)); File.Exists(file) .Should("call through tx and be deleted") .Be.False(); t.Complete(); } // then File.Exists(toFolder.Combine(fileName)) .Should("call through tx and visible in its new location") .Be.True(); File.ReadAllText(toFolder.Combine(fileName)) .Should("have same contents") .Be("testing move"); } [Test] public void Write_And_ReplaceContents() { var filePath = _TfPath.Combine("Write_And_ReplaceContents.txt"); // simply write something to to file. using (var wr = File.CreateText(filePath)) wr.WriteLine("Hello"); using (ITransaction tx = new FileTransaction()) { using (var fs = ((IFileAdapter) tx).Create(filePath)) { var str = new UTF8Encoding().GetBytes("Goodbye"); fs.Write(str, 0, str.Length); fs.Flush(); } tx.Complete(); } File.ReadAllLines(filePath) .First().Should() .Be.EqualTo("Goodbye"); } [Test] public void CreateFileTransactionally_ThenRollback() { var filePath = _TfPath.Combine("transacted-file"); // simply write something to to file. using (var wr = File.CreateText(filePath)) wr.WriteLine("CreateFileTransactionally_ThenRollback"); using (ITransaction tx = new FileTransaction("rollback tx")) { var fa = (IFileAdapter) tx; using (var fs = fa.Open(filePath, FileMode.Truncate)) { var str = new UTF8Encoding().GetBytes("Goodbye"); fs.Write(str, 0, str.Length); fs.Flush(); } tx.Rollback(); } File.ReadAllLines(filePath) .First().Should().Be.EqualTo("CreateFileTransactionally_ThenRollback"); } } }
// 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.Linq; using System.Threading.Tasks; using Xunit; namespace System.Diagnostics.Tests { public class ProcessWaitingTests : ProcessTestBase { [Fact] public void MultipleProcesses_StartAllKillAllWaitAll() { const int Iters = 10; Process[] processes = Enumerable.Range(0, Iters).Select(_ => CreateProcessLong()).ToArray(); foreach (Process p in processes) p.Start(); foreach (Process p in processes) p.Kill(); foreach (Process p in processes) Assert.True(p.WaitForExit(WaitInMS)); } [Fact] public void MultipleProcesses_SerialStartKillWait() { const int Iters = 10; for (int i = 0; i < Iters; i++) { Process p = CreateProcessLong(); p.Start(); p.Kill(); p.WaitForExit(WaitInMS); } } [Fact] public void MultipleProcesses_ParallelStartKillWait() { const int Tasks = 4, ItersPerTask = 10; Action work = () => { for (int i = 0; i < ItersPerTask; i++) { Process p = CreateProcessLong(); p.Start(); p.Kill(); p.WaitForExit(WaitInMS); } }; Task.WaitAll(Enumerable.Range(0, Tasks).Select(_ => Task.Run(work)).ToArray()); } [Theory] [InlineData(0)] // poll [InlineData(10)] // real timeout public void CurrentProcess_WaitNeverCompletes(int milliseconds) { Assert.False(Process.GetCurrentProcess().WaitForExit(milliseconds)); } [Fact] public void SingleProcess_TryWaitMultipleTimesBeforeCompleting() { Process p = CreateProcessLong(); p.Start(); // Verify we can try to wait for the process to exit multiple times Assert.False(p.WaitForExit(0)); Assert.False(p.WaitForExit(0)); // Then wait until it exits and concurrently kill it. // There's a race condition here, in that we really want to test // killing it while we're waiting, but we could end up killing it // before hand, in which case we're simply not testing exactly // what we wanted to test, but everything should still work. Task.Delay(10).ContinueWith(_ => p.Kill()); Assert.True(p.WaitForExit(WaitInMS)); Assert.True(p.WaitForExit(0)); } [Theory] [InlineData(false)] [InlineData(true)] public async Task SingleProcess_WaitAfterExited(bool addHandlerBeforeStart) { Process p = CreateProcessLong(); p.EnableRaisingEvents = true; var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); if (addHandlerBeforeStart) { p.Exited += delegate { tcs.SetResult(true); }; } p.Start(); if (!addHandlerBeforeStart) { p.Exited += delegate { tcs.SetResult(true); }; } p.Kill(); Assert.True(await tcs.Task); Assert.True(p.WaitForExit(0)); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(127)] public async Task SingleProcess_EnableRaisingEvents_CorrectExitCode(int exitCode) { using (Process p = CreateProcessPortable(RemotelyInvokable.ExitWithCode, exitCode.ToString())) { var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); p.EnableRaisingEvents = true; p.Exited += delegate { tcs.SetResult(true); }; p.Start(); Assert.True(await tcs.Task); Assert.Equal(exitCode, p.ExitCode); } } [Fact] public void SingleProcess_CopiesShareExitInformation() { Process p = CreateProcessLong(); p.Start(); Process[] copies = Enumerable.Range(0, 3).Select(_ => Process.GetProcessById(p.Id)).ToArray(); Assert.False(p.WaitForExit(0)); p.Kill(); Assert.True(p.WaitForExit(WaitInMS)); foreach (Process copy in copies) { Assert.True(copy.WaitForExit(0)); } } [Fact] [ActiveIssue("https://github.com/dotnet/corefx/issues/22269", TargetFrameworkMonikers.UapNotUapAot)] public void WaitForPeerProcess() { Process child1 = CreateProcessLong(); child1.Start(); Process child2 = CreateProcess(peerId => { Process peer = Process.GetProcessById(int.Parse(peerId)); Console.WriteLine("Signal"); Assert.True(peer.WaitForExit(WaitInMS)); return SuccessExitCode; }, child1.Id.ToString()); child2.StartInfo.RedirectStandardOutput = true; child2.Start(); char[] output = new char[6]; child2.StandardOutput.Read(output, 0, output.Length); Assert.Equal("Signal", new string(output)); // wait for the signal before killing the peer child1.Kill(); Assert.True(child1.WaitForExit(WaitInMS)); Assert.True(child2.WaitForExit(WaitInMS)); Assert.Equal(SuccessExitCode, child2.ExitCode); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "Not applicable on uap - RemoteInvoke does not give back process handle")] [ActiveIssue(15844, TestPlatforms.AnyUnix)] public void WaitChain() { Process root = CreateProcess(() => { Process child1 = CreateProcess(() => { Process child2 = CreateProcess(() => { Process child3 = CreateProcess(() => SuccessExitCode); child3.Start(); Assert.True(child3.WaitForExit(WaitInMS)); return child3.ExitCode; }); child2.Start(); Assert.True(child2.WaitForExit(WaitInMS)); return child2.ExitCode; }); child1.Start(); Assert.True(child1.WaitForExit(WaitInMS)); return child1.ExitCode; }); root.Start(); Assert.True(root.WaitForExit(WaitInMS)); Assert.Equal(SuccessExitCode, root.ExitCode); } [Fact] public void WaitForSelfTerminatingChild() { Process child = CreateProcessPortable(RemotelyInvokable.SelfTerminate); child.Start(); Assert.True(child.WaitForExit(WaitInMS)); Assert.NotEqual(SuccessExitCode, child.ExitCode); } [Fact] public void WaitForInputIdle_NotDirected_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.WaitForInputIdle()); } [Fact] public void WaitForExit_NotDirected_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.WaitForExit()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using IoC; namespace NodeService { public class CompendiumTransclusionRelationship : IRelationship { private List<IDescriptor> _descriptors; private INode _toNode; private INode _fromNode; private INode _mapNode; private INode _transclusionNode; private List<string> _notes; private List<string> _attachments; public CompendiumTransclusionRelationship() { _descriptors = new List<IDescriptor>(); _notes = new List<string>(); _attachments = new List<string>(); RelationshipType = IoCContainer.GetInjectionInstance().GetInstance<CompendiumNodeRelationshipBaseType>(); } public CompendiumTransclusionRelationship(IRelationship relationship, CompendiumViewRelationship viewRelationship, INode toNode, INode fromNode, INode transclusionNode, INode mapNode) : this() { _toNode = toNode; IDescriptor toDescriptor = new CompendiumRelationshipDescriptor(toNode, this, IoCContainer.GetInjectionInstance().GetInstance<CompendiumToDescriptor>()); _descriptors.Add(toDescriptor); _toNode.AddDescriptor(toDescriptor); _fromNode = fromNode; IDescriptor fromDescriptor = new CompendiumRelationshipDescriptor(fromNode, this, IoCContainer.GetInjectionInstance().GetInstance<CompendiumFromDescriptor>()); _descriptors.Add(fromDescriptor); _fromNode.AddDescriptor(fromDescriptor); _transclusionNode = transclusionNode; IDescriptor transclusionNodeDescriptor = new CompendiumRelationshipDescriptor(transclusionNode, this, IoCContainer.GetInjectionInstance().GetInstance<CompendiumTransclusionNodeDescriptor>()); _descriptors.Add(transclusionNodeDescriptor); _transclusionNode.AddDescriptor(transclusionNodeDescriptor); _mapNode = mapNode; IDescriptor mapDescriptor = new CompendiumRelationshipDescriptor(mapNode, this, IoCContainer.GetInjectionInstance().GetInstance<CompendiumTransclusionMapDescriptor>()); _descriptors.Add(mapDescriptor); _mapNode.AddDescriptor(mapDescriptor); this.Id = relationship.Id; this.Created = relationship.Created; this.CreatedBy = relationship.CreatedBy; this.LastModified = relationship.LastModified; this.Name = relationship.Name; this.XPosition = viewRelationship.XPosition; this.YPosition = viewRelationship.YPosition; } public INode ToNode { get { return _toNode; } } public INode FromNode { get { return _fromNode; } } public INode MapNode { get { return _mapNode; } } public int XPosition { get; set; } public int YPosition { get; set; } #region IRelationship public string[] Notes { get { return _notes.ToArray(); } set { _notes.Clear(); _notes.AddRange(value); } } public string[] Attachments { get { return _attachments.ToArray(); } set { _attachments.Clear(); _attachments.AddRange(value); } } public IDescriptor[] Descriptors { get { return _descriptors.ToArray(); } set { _descriptors.Clear(); _descriptors.AddRange(value); } } public IRelationshipType RelationshipType { get; set; } public void AddNote(string note) { _notes.Add(note); } public void AddAttachment(string attachment) { _attachments.Add(attachment); } public void AddDescriptor(IDescriptor descriptor) { _descriptors.Add(descriptor); } public void RemoveNote(string note) { _notes.Remove(note); } public void RemoveAttachment(string attachment) { _attachments.Remove(attachment); } public void RemoveDescriptor(IDescriptor descriptor) { _descriptors.Remove(descriptor); } public string Id { get; set; } public string Name { get; set; } public string CreatedBy { get; set; } public string LastModifiedBy { get; set; } public DateTime Created { get; set; } public DateTime LastModified { get; set; } public bool Equals(IStorageElement secondElement) { return (Id == secondElement.Id); } #endregion } }
/* * 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 System.Collections.Generic; using System.Threading; namespace Apache.Geode.Client.UnitTests { using NUnit.Framework; using Apache.Geode.DUnitFramework; using Apache.Geode.Client.Tests; using Apache.Geode.Client; public class MyCqListener2<TKey, TResult> : ICqListener<TKey, TResult> { private int m_create = 0; private int m_update = 0; private int m_id = 0; public MyCqListener2(int id) { this.m_id = id; } public int Creates { get { return m_create; } } public int Updates { get { return m_update; } } #region ICqListener Members void ICqListener<TKey, TResult>.Close() { Util.Log("CqListener closed with ID = " + m_id); } void ICqListener<TKey, TResult>.OnError(CqEvent<TKey, TResult> ev) { Util.Log("CqListener OnError called "); } void ICqListener<TKey, TResult>.OnEvent(CqEvent<TKey, TResult> ev) { Util.Log("CqListener OnEvent ops = " + ev.getBaseOperation()); if (ev.getBaseOperation() == CqOperationType.OP_TYPE_CREATE) m_create++; else if (ev.getBaseOperation() == CqOperationType.OP_TYPE_UPDATE) m_update++; } #endregion } [TestFixture] [Category("group4")] [Category("unicast_only")] [Category("generics")] public class ThinClientSecurityAuthzTestsMU : ThinClientSecurityAuthzTestBase { #region Private members IRegion<object, object> region; IRegion<object, object> region1; private UnitProcess m_client1; private UnitProcess m_client2; private UnitProcess m_client3; private TallyListener<object, object> m_listener; private TallyWriter<object, object> m_writer; private string/*<object>*/ keys = "Key"; private string value = "Value"; #endregion protected override ClientBase[] GetClients() { m_client1 = new UnitProcess(); m_client2 = new UnitProcess(); m_client3 = new UnitProcess(); return new ClientBase[] { m_client1, m_client2, m_client3 }; } public void CreateRegion(string locators, bool caching, bool listener, bool writer) { Util.Log(" in CreateRegion " + listener + " : " + writer); if (listener) { m_listener = new TallyListener<object, object>(); } else { m_listener = null; } IRegion<object, object> region = null; region = CacheHelper.CreateTCRegion_Pool<object, object>(RegionName, true, caching, m_listener, locators, "__TESTPOOL1_", true); if (writer) { m_writer = new TallyWriter<object, object>(); } else { m_writer = null; } Util.Log("region created "); AttributesMutator<object, object> at = region.AttributesMutator; at.SetCacheWriter(m_writer); } public void DoPut() { region = CacheHelper.GetRegion<object, object>(RegionName); region[keys.ToString()] = value; } public void CheckAssert() { Assert.AreEqual(true, m_writer.IsWriterInvoked, "Writer Should be invoked"); Assert.AreEqual(false, m_listener.IsListenerInvoked, "Listener Should not be invoked"); Assert.IsFalse(region.ContainsKey(keys.ToString()), "Key should have been found in the region"); } public void DoLocalPut() { region1 = CacheHelper.GetRegion<object, object>(RegionName); region1.GetLocalView()[m_keys[2]] = m_vals[2]; //this check is no loger valid as ContainsKey goes on server //Assert.IsTrue(region1.ContainsKey(m_keys[2]), "Key should have been found in the region"); Assert.AreEqual(true, m_writer.IsWriterInvoked, "Writer Should be invoked"); Assert.AreEqual(true, m_listener.IsListenerInvoked, "Listener Should be invoked"); //try Update try { Util.Log("Trying UpdateEntry"); m_listener.ResetListenerInvokation(); UpdateEntry(RegionName, m_keys[2], m_nvals[2], false); Assert.Fail("Should have got NotAuthorizedException during updateEntry"); } catch (NotAuthorizedException) { Util.Log("NotAuthorizedException Caught"); Util.Log("Success"); } catch (Exception other) { Util.Log("Stack trace: {0} ", other.StackTrace); Util.Log("Got exception : {0}", other.Message); } Assert.AreEqual(true, m_writer.IsWriterInvoked, "Writer should be invoked"); Assert.AreEqual(false, m_listener.IsListenerInvoked, "Listener should not be invoked"); //Assert.IsTrue(region1.ContainsKey(m_keys[2]), "Key should have been found in the region"); VerifyEntry(RegionName, m_keys[2], m_vals[2]); m_writer.SetWriterFailed(); //test CacheWriter try { Util.Log("Testing CacheWriterException"); UpdateEntry(RegionName, m_keys[2], m_nvals[2], false); Assert.Fail("Should have got NotAuthorizedException during updateEntry"); } catch (CacheWriterException) { Util.Log("CacheWriterException Caught"); Util.Log("Success"); } } [TestFixtureTearDown] public override void EndTests() { CacheHelper.StopJavaServers(); base.EndTests(); } [TearDown] public override void EndTest() { try { if (m_clients != null) { foreach (ClientBase client in m_clients) { client.Call(CacheHelper.Close); } } CacheHelper.Close(); CacheHelper.ClearEndpoints(); } finally { CacheHelper.StopJavaServers(); } base.EndTest(); } protected const string RegionName_CQ = "Portfolios"; static QueryService<object, object> gQueryService = null; static string [] QueryStrings = { "select * from /Portfolios p where p.ID < 1", "select * from /Portfolios p where p.ID < 2", "select * from /Portfolios p where p.ID = 2", "select * from /Portfolios p where p.ID >= 3",//this should pass "select * from /Portfolios p where p.ID = 4",//this should pass "select * from /Portfolios p where p.ID = 5", "select * from /Portfolios p where p.ID = 6", "select * from /Portfolios p where p.ID = 7" }; public void registerCQ(Properties<string, string> credentials, bool durableCQ) { Util.Log("registerCQ"); try { Serializable.RegisterTypeGeneric(Portfolio.CreateDeserializable); Serializable.RegisterTypeGeneric(Position.CreateDeserializable); Util.Log("registerCQ portfolio registered"); } catch (IllegalStateException) { Util.Log("registerCQ portfolio NOT registered"); // ignore since we run multiple iterations for pool and non pool configs } // VJR: TODO fix cache.GetQueryService to also be generic gQueryService = CacheHelper.getMultiuserCache(credentials).GetQueryService<object, object>(); for (int i = 0; i < QueryStrings.Length; i++) { CqAttributesFactory<object, object> cqAttrFact = new CqAttributesFactory<object, object>(); cqAttrFact.AddCqListener(new MyCqListener2<object, object>(i)); CqQuery<object, object> cq = gQueryService.NewCq("cq_" + i, QueryStrings[i], cqAttrFact.Create(), durableCQ); cq.Execute(); } Util.Log("registerCQ Done."); } public void doCQPut(Properties<string, string> credentials) { Util.Log("doCQPut"); try { Serializable.RegisterTypeGeneric(Portfolio.CreateDeserializable); Serializable.RegisterTypeGeneric(Position.CreateDeserializable); Util.Log("doCQPut portfolio registered"); } catch (IllegalStateException) { Util.Log("doCQPut portfolio NOT registered"); // ignore since we run multiple iterations for pool and non pool configs } //IRegion<object, object> region = CacheHelper.GetVerifyRegion(RegionName_CQ, credentials); IRegionService userRegionService = CacheHelper.getMultiuserCache(credentials); IRegion<object, object>[] regions = userRegionService.RootRegions<object, object>(); IRegion<object, object> region = null; Console.Out.WriteLine("Number of regions " + regions.Length); for (int i = 0; i < regions.Length; i++) { if (regions[i].Name.Equals(RegionName_CQ)) { region = regions[i]; break; } } for (int i = 0; i < QueryStrings.Length; i++) { string key = "port1-" + i; Portfolio p = new Portfolio(i); region[key] = p; } IRegionService rgServ = region.RegionService; Cache cache = rgServ as Cache; Assert.IsNull(cache); Thread.Sleep(20000); Util.Log("doCQPut Done."); } public void verifyCQEvents(bool whetherResult, CqOperationType opType ) { Util.Log("verifyCQEvents " + gQueryService); Assert.IsNotNull(gQueryService); CqQuery<object, object> cq = gQueryService.GetCq("cq_" + 3); ICqListener<object, object>[] cqL = cq.GetCqAttributes().getCqListeners(); MyCqListener2<object, object> mcqL = (MyCqListener2<object, object>)cqL[0]; Util.Log("got result for cq listener3 " + cq.Name + " : " + mcqL.Creates); if (opType == CqOperationType.OP_TYPE_CREATE) { if (whetherResult) Assert.AreEqual(1, mcqL.Creates, "CQ listener 3 should get one create event "); else Assert.AreEqual(0, mcqL.Creates, "CQ listener 3 should not get any create event "); } else if (opType == CqOperationType.OP_TYPE_UPDATE) { if (whetherResult) Assert.AreEqual(1, mcqL.Updates, "CQ listener 3 should get one update event "); else Assert.AreEqual(0, mcqL.Updates, "CQ listener 3 should not get any update event "); } cq = gQueryService.GetCq("cq_" + 4); cqL = cq.GetCqAttributes().getCqListeners(); mcqL = (MyCqListener2<object, object>)cqL[0]; Util.Log("got result for cq listener4 " + cq.Name + " : " + mcqL.Creates); if (opType == CqOperationType.OP_TYPE_CREATE) { if (whetherResult) Assert.AreEqual(1, mcqL.Creates, "CQ listener 4 should get one create event "); else Assert.AreEqual(0, mcqL.Creates, "CQ listener 4 should not get any create event "); } else if (opType == CqOperationType.OP_TYPE_UPDATE) { if (whetherResult) Assert.AreEqual(1, mcqL.Updates, "CQ listener 4 should get one update event "); else Assert.AreEqual(0, mcqL.Updates, "CQ listener 4 should not get any update event "); } cq = gQueryService.GetCq("cq_" + 0); cqL = cq.GetCqAttributes().getCqListeners(); mcqL = (MyCqListener2<object, object>)cqL[0]; Util.Log("got result for cq listener0 " + cq.Name + " : " + mcqL.Creates); Assert.AreEqual(0, mcqL.Creates, "CQ listener 0 should get one create event "); // CacheHelper.getMultiuserCache(null).Close(); gQueryService = null; } void runCQTest() { CacheHelper.SetupJavaServers(true, "remotequeryN.xml"); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator started"); DummyAuthorization3 da = new DummyAuthorization3(); string authenticator = da.Authenticator; string authInit = da.AuthInit; string accessorPP = da.AuthenticatorPP; Util.Log("testAllowPutsGets: Using authinit: " + authInit); Util.Log("testAllowPutsGets: Using authenticator: " + authenticator); Util.Log("testAllowPutsGets: Using accessorPP: " + accessorPP); // Start servers with all required properties string serverArgs = SecurityTestUtil.GetServerArgs(authenticator, null, accessorPP, null, null); // Start the two servers. CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1, serverArgs); Util.Log("Cacheserver 1 started."); CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1, serverArgs); Util.Log("Cacheserver 2 started."); // Start client1 with valid CREATE credentials, this index will be used to authorzie the user Properties<string, string> createCredentials = da.GetValidCredentials(4); Util.Log("runCQTest: "); m_client1.Call(SecurityTestUtil.CreateClientMU2, RegionName_CQ, CacheHelper.Locators, authInit, (Properties<string, string>)null, true, true); m_client2.Call(SecurityTestUtil.CreateClientMU, RegionName_CQ, CacheHelper.Locators, authInit, (Properties<string, string>)null, true); // Perform some put operations from client1 m_client1.Call(registerCQ, createCredentials, false); // Verify that the gets succeed m_client2.Call(doCQPut, createCredentials); m_client1.Call(verifyCQEvents, true, CqOperationType.OP_TYPE_CREATE); m_client1.Call(CloseUserCache, false); m_client1.Call(Close); m_client2.Call(Close); CacheHelper.StopJavaServer(1); // CacheHelper.StopJavaServer(2); CacheHelper.StopJavaLocator(1); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } public void CloseUserCache(bool keepAlive) { Util.Log("CloseUserCache keepAlive: " + keepAlive); CacheHelper.CloseUserCache(keepAlive); } private static string DurableClientId1 = "DurableClientId1"; //private static string DurableClientId2 = "DurableClientId2"; void runDurableCQTest(bool logicalCacheClose, bool durableCQ, bool whetherResult) { CacheHelper.SetupJavaServers(true, "remotequeryN.xml"); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator started"); DummyAuthorization3 da = new DummyAuthorization3(); string authenticator = da.Authenticator; string authInit = da.AuthInit; string accessorPP = da.AuthenticatorPP; Util.Log("testAllowPutsGets: Using authinit: " + authInit); Util.Log("testAllowPutsGets: Using authenticator: " + authenticator); Util.Log("testAllowPutsGets: Using accessorPP: " + accessorPP); // Start servers with all required properties string serverArgs = SecurityTestUtil.GetServerArgs(authenticator, null, accessorPP, null, null); // Start the two servers. CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1, serverArgs); Util.Log("Cacheserver 1 started."); CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1, serverArgs); Util.Log("Cacheserver 2 started."); // Start client1 with valid CREATE credentials, this index will be used to authorzie the user Properties<string, string> createCredentials = da.GetValidCredentials(4); Util.Log("runCQTest: "); /* regionName, string endpoints, string locators, authInit, Properties credentials, bool pool, bool locator, bool isMultiuser, bool notificationEnabled, string durableClientId) */ m_client1.Call(SecurityTestUtil.CreateMUDurableClient, RegionName_CQ, CacheHelper.Locators, authInit, DurableClientId1, true, true ); m_client2.Call(SecurityTestUtil.CreateClientMU, RegionName_CQ, CacheHelper.Locators, authInit, (Properties<string, string>)null, true); m_client1.Call(ReadyForEvents2); // Perform some put operations from client1 m_client1.Call(registerCQ, createCredentials, durableCQ); Properties<string, string> createCredentials2 = da.GetValidCredentials(3); // Verify that the gets succeed m_client2.Call(doCQPut, createCredentials2); //close cache client-1 m_client1.Call(verifyCQEvents, true, CqOperationType.OP_TYPE_CREATE); Thread.Sleep(10000); Util.Log("Before calling CloseUserCache: " + logicalCacheClose); if (logicalCacheClose) m_client1.Call(CloseUserCache, logicalCacheClose); m_client1.Call(CloseKeepAlive); //put again from other client m_client2.Call(doCQPut, createCredentials2); //client-1 will up again m_client1.Call(SecurityTestUtil.CreateMUDurableClient, RegionName_CQ, CacheHelper.Locators, authInit, DurableClientId1, true, true); // Perform some put operations from client1 m_client1.Call(registerCQ, createCredentials, durableCQ); m_client1.Call(ReadyForEvents2); Thread.Sleep(20000); m_client1.Call(verifyCQEvents, whetherResult, CqOperationType.OP_TYPE_UPDATE); m_client1.Call(Close); m_client2.Call(Close); CacheHelper.StopJavaServer(1); // CacheHelper.StopJavaServer(2); CacheHelper.StopJavaLocator(1); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } void runAllowPutsGets() { CacheHelper.SetupJavaServers(true, CacheXml1, CacheXml2); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator started"); foreach (AuthzCredentialGenerator authzGen in GetAllGeneratorCombos(true)) { CredentialGenerator cGen = authzGen.GetCredentialGenerator(); Properties<string, string> extraAuthProps = cGen.SystemProperties; Properties<string, string> javaProps = cGen.JavaProperties; Properties<string, string> extraAuthzProps = authzGen.SystemProperties; string authenticator = cGen.Authenticator; string authInit = cGen.AuthInit; string accessor = authzGen.AccessControl; Util.Log("testAllowPutsGets: Using authinit: " + authInit); Util.Log("testAllowPutsGets: Using authenticator: " + authenticator); Util.Log("testAllowPutsGets: Using accessor: " + accessor); // Start servers with all required properties string serverArgs = SecurityTestUtil.GetServerArgs(authenticator, accessor, null, SecurityTestUtil.ConcatProperties(extraAuthProps, extraAuthzProps), javaProps); // Start the two servers. CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1, serverArgs); Util.Log("Cacheserver 1 started."); CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1, serverArgs); Util.Log("Cacheserver 2 started."); // Start client1 with valid CREATE credentials Properties<string, string> createCredentials = authzGen.GetAllowedCredentials( new OperationCode[] { OperationCode.Put }, new string[] { RegionName }, 1); javaProps = cGen.JavaProperties; Util.Log("AllowPutsGets: For first client PUT credentials: " + createCredentials); m_client1.Call(SecurityTestUtil.CreateClientMU, RegionName, CacheHelper.Locators, authInit, (Properties<string, string>)null, true); // Start client2 with valid GET credentials Properties<string, string> getCredentials = authzGen.GetAllowedCredentials( new OperationCode[] { OperationCode.Get }, new string[] { RegionName }, 2); javaProps = cGen.JavaProperties; Util.Log("AllowPutsGets: For second client GET credentials: " + getCredentials); m_client2.Call(SecurityTestUtil.CreateClientMU, RegionName, CacheHelper.Locators, authInit, (Properties<string, string>)null, true); // Perform some put operations from client1 m_client1.Call(DoPutsMU, 10 , createCredentials, true); // Verify that the gets succeed m_client2.Call(DoGetsMU, 10, getCredentials, true); m_client1.Call(DoPutsTx, 10, true, ExpectedResult.Success, getCredentials, true); m_client2.Call(DoGets, 10, true, ExpectedResult.Success, getCredentials, true); m_client1.Call(Close); m_client2.Call(Close); CacheHelper.StopJavaServer(1); CacheHelper.StopJavaServer(2); } CacheHelper.StopJavaLocator(1); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } void runDisallowPutsGets() { CacheHelper.SetupJavaServers(true, CacheXml1, CacheXml2); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator started"); foreach (AuthzCredentialGenerator authzGen in GetAllGeneratorCombos(true)) { CredentialGenerator cGen = authzGen.GetCredentialGenerator(); Properties<string, string> extraAuthProps = cGen.SystemProperties; Properties<string, string> javaProps = cGen.JavaProperties; Properties<string, string> extraAuthzProps = authzGen.SystemProperties; string authenticator = cGen.Authenticator; string authInit = cGen.AuthInit; string accessor = authzGen.AccessControl; Util.Log("DisallowPutsGets: Using authinit: " + authInit); Util.Log("DisallowPutsGets: Using authenticator: " + authenticator); Util.Log("DisallowPutsGets: Using accessor: " + accessor); // Check that we indeed can obtain valid credentials not allowed to do // gets Properties<string, string> createCredentials = authzGen.GetAllowedCredentials( new OperationCode[] { OperationCode.Put }, new string[] { RegionName }, 1); Properties<string, string> createJavaProps = cGen.JavaProperties; Properties<string, string> getCredentials = authzGen.GetDisallowedCredentials( new OperationCode[] { OperationCode.Get }, new string[] { RegionName }, 2); Properties<string, string> getJavaProps = cGen.JavaProperties; if (getCredentials == null || getCredentials.Size == 0) { Util.Log("DisallowPutsGets: Unable to obtain valid credentials " + "with no GET permission; skipping this combination."); continue; } // Start servers with all required properties string serverArgs = SecurityTestUtil.GetServerArgs(authenticator, accessor, null, SecurityTestUtil.ConcatProperties(extraAuthProps, extraAuthzProps), javaProps); // Start the two servers. CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1, serverArgs); Util.Log("Cacheserver 1 started."); CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1, serverArgs); Util.Log("Cacheserver 2 started."); // Start client1 with valid CREATE credentials createCredentials = authzGen.GetAllowedCredentials( new OperationCode[] { OperationCode.Put }, new string[] { RegionName }, 1); javaProps = cGen.JavaProperties; Util.Log("DisallowPutsGets: For first client PUT credentials: " + createCredentials); m_client1.Call(SecurityTestUtil.CreateClientMU, RegionName, CacheHelper.Locators, authInit, (Properties<string, string>)null, true); // Start client2 with invalid GET credentials getCredentials = authzGen.GetDisallowedCredentials( new OperationCode[] { OperationCode.Get }, new string[] { RegionName }, 2); javaProps = cGen.JavaProperties; Util.Log("DisallowPutsGets: For second client invalid GET " + "credentials: " + getCredentials); m_client2.Call(SecurityTestUtil.CreateClientMU, RegionName, CacheHelper.Locators, authInit, (Properties<string, string>)null, true); // Perform some put operations from client1 m_client1.Call(DoPutsMU, 10, createCredentials, true); // Verify that the gets throw exception m_client2.Call(DoGetsMU, 10, getCredentials, true, ExpectedResult.NotAuthorizedException); // Try to connect client2 with reader credentials getCredentials = authzGen.GetAllowedCredentials( new OperationCode[] { OperationCode.Get }, new string[] { RegionName }, 5); javaProps = cGen.JavaProperties; Util.Log("DisallowPutsGets: For second client valid GET " + "credentials: " + getCredentials); m_client2.Call(SecurityTestUtil.CreateClientMU, RegionName, CacheHelper.Locators, authInit, (Properties<string, string>)null, true); // Verify that the gets succeed m_client2.Call(DoGetsMU, 10, getCredentials, true); // Verify that the puts throw exception m_client2.Call(DoPutsMU, 10, getCredentials, true, ExpectedResult.NotAuthorizedException); m_client1.Call(Close); m_client2.Call(Close); CacheHelper.StopJavaServer(1); CacheHelper.StopJavaServer(2); } CacheHelper.StopJavaLocator(1); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } void runInvalidAccessor() { CacheHelper.SetupJavaServers(true, CacheXml1, CacheXml2); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator started"); foreach (AuthzCredentialGenerator authzGen in GetAllGeneratorCombos(true)) { CredentialGenerator cGen = authzGen.GetCredentialGenerator(); Util.Log("NIl:792:Current credential is = {0}", cGen); //if (cGen.GetClassCode() == CredentialGenerator.ClassCode.LDAP) // continue; Properties<string, string> extraAuthProps = cGen.SystemProperties; Properties<string, string> javaProps = cGen.JavaProperties; Properties<string, string> extraAuthzProps = authzGen.SystemProperties; string authenticator = cGen.Authenticator; string authInit = cGen.AuthInit; string accessor = authzGen.AccessControl; Util.Log("InvalidAccessor: Using authinit: " + authInit); Util.Log("InvalidAccessor: Using authenticator: " + authenticator); // Start server1 with invalid accessor string serverArgs = SecurityTestUtil.GetServerArgs(authenticator, "com.gemstone.none", null, SecurityTestUtil.ConcatProperties(extraAuthProps, extraAuthzProps), javaProps); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1, serverArgs); Util.Log("Cacheserver 1 started."); // Client creation should throw exceptions Properties<string, string> createCredentials = authzGen.GetAllowedCredentials( new OperationCode[] { OperationCode.Put }, new string[] { RegionName }, 3); javaProps = cGen.JavaProperties; Util.Log("InvalidAccessor: For first client PUT credentials: " + createCredentials); m_client1.Call(SecurityTestUtil.CreateClientMU, RegionName, CacheHelper.Locators, authInit, (Properties<string, string>)null, true); // Now perform some put operations from client1 m_client1.Call(DoPutsMU, 10, createCredentials, true, ExpectedResult.OtherException); Properties<string, string> getCredentials = authzGen.GetAllowedCredentials( new OperationCode[] { OperationCode.Get }, new string[] { RegionName }, 7); javaProps = cGen.JavaProperties; Util.Log("InvalidAccessor: For second client GET credentials: " + getCredentials); m_client2.Call(SecurityTestUtil.CreateClientMU, RegionName, CacheHelper.Locators, authInit, (Properties<string, string>)null, true); // Now perform some put operations from client1 m_client2.Call(DoGetsMU, 10, getCredentials, true, ExpectedResult.OtherException); // Now start server2 that has valid accessor Util.Log("InvalidAccessor: Using accessor: " + accessor); serverArgs = SecurityTestUtil.GetServerArgs(authenticator, accessor, null, SecurityTestUtil.ConcatProperties(extraAuthProps, extraAuthzProps), javaProps); CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1, serverArgs); Util.Log("Cacheserver 2 started."); CacheHelper.StopJavaServer(1); // Client creation should be successful now m_client1.Call(SecurityTestUtil.CreateClientMU, RegionName, CacheHelper.Locators, authInit, (Properties<string, string>)null, true); m_client2.Call(SecurityTestUtil.CreateClientMU, RegionName, CacheHelper.Locators, authInit, (Properties<string, string>)null, true); // Now perform some put operations from client1 m_client1.Call(DoPutsMU, 10, createCredentials, true); // Verify that the gets succeed m_client2.Call(DoGetsMU, 10, getCredentials, true); m_client1.Call(Close); m_client2.Call(Close); CacheHelper.StopJavaServer(2); } CacheHelper.StopJavaLocator(1); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } void runAllOpsWithFailover() { OperationWithAction[] allOps = { // Test CREATE and verify with a GET new OperationWithAction(OperationCode.Put, 3, OpFlags.CheckNotAuthz, 4), new OperationWithAction(OperationCode.Put), new OperationWithAction(OperationCode.Get, 3, OpFlags.CheckNoKey | OpFlags.CheckNotAuthz, 4), new OperationWithAction(OperationCode.Get, 2, OpFlags.CheckNoKey, 4), // OPBLOCK_END indicates end of an operation block; the above block of // three operations will be first executed on server1 and then on // server2 after failover OperationWithAction.OpBlockEnd, // Test GetServerKeys (KEY_SET) operation. new OperationWithAction(OperationCode.GetServerKeys), new OperationWithAction(OperationCode.GetServerKeys, 3, OpFlags.CheckNotAuthz, 4), OperationWithAction.OpBlockEnd, // Test UPDATE and verify with a GET new OperationWithAction(OperationCode.Put, 3, OpFlags.UseNewVal | OpFlags.CheckNotAuthz, 4), new OperationWithAction(OperationCode.Put, 1, OpFlags.UseNewVal, 4), new OperationWithAction(OperationCode.Get, 2, OpFlags.UseOldConn | OpFlags.UseNewVal, 4), OperationWithAction.OpBlockEnd, // Test DESTROY and verify with a GET and that key should not exist new OperationWithAction(OperationCode.Destroy, 3, OpFlags.UseNewVal | OpFlags.CheckNotAuthz, 4), new OperationWithAction(OperationCode.Destroy), new OperationWithAction(OperationCode.Get, 2, OpFlags.UseOldConn | OpFlags.CheckFail, 4), // Repopulate the region new OperationWithAction(OperationCode.Put, 1, OpFlags.UseNewVal, 4), OperationWithAction.OpBlockEnd, // Check QUERY new OperationWithAction(OperationCode.Put), new OperationWithAction(OperationCode.Query, 3, OpFlags.CheckNotAuthz, 4), new OperationWithAction(OperationCode.Query), OperationWithAction.OpBlockEnd, // UPDATE and test with GET new OperationWithAction(OperationCode.Put), new OperationWithAction(OperationCode.Get, 2, OpFlags.UseOldConn | OpFlags.LocalOp, 4), // UPDATE and test with GET for no updates new OperationWithAction(OperationCode.Put, 1, OpFlags.UseOldConn | OpFlags.UseNewVal, 4), new OperationWithAction(OperationCode.Get, 2, OpFlags.UseOldConn | OpFlags.LocalOp, 4), OperationWithAction.OpBlockEnd, /// PutAll, GetAll, ExecuteCQ and ExecuteFunction ops new OperationWithAction(OperationCode.PutAll), // NOTE: GetAll depends on previous PutAll so it should happen right after. new OperationWithAction(OperationCode.GetAll), new OperationWithAction(OperationCode.RemoveAll), //new OperationWithAction(OperationCode.ExecuteCQ), new OperationWithAction(OperationCode.ExecuteFunction), OperationWithAction.OpBlockEnd, // UPDATE and test with GET new OperationWithAction(OperationCode.Put, 2), new OperationWithAction(OperationCode.Get, 1, OpFlags.UseOldConn | OpFlags.LocalOp, 4), // UPDATE and test with GET for no updates new OperationWithAction(OperationCode.Put, 2, OpFlags.UseOldConn | OpFlags.UseNewVal, 4), new OperationWithAction(OperationCode.Get, 1, OpFlags.UseOldConn | OpFlags.LocalOp, 4), OperationWithAction.OpBlockEnd, // UPDATE and test with GET new OperationWithAction(OperationCode.Put), new OperationWithAction(OperationCode.Get, 2, OpFlags.UseOldConn | OpFlags.LocalOp, 4), // UPDATE and test with GET for no updates new OperationWithAction(OperationCode.Put, 1, OpFlags.UseOldConn | OpFlags.UseNewVal, 4), new OperationWithAction(OperationCode.Get, 2, OpFlags.UseOldConn | OpFlags.LocalOp, 4), OperationWithAction.OpBlockEnd, // Do REGION_DESTROY of the sub-region and check with GET new OperationWithAction(OperationCode.Put, 1, OpFlags.UseSubRegion, 8), new OperationWithAction(OperationCode.RegionDestroy, 3, OpFlags.UseSubRegion | OpFlags.CheckNotAuthz, 1), new OperationWithAction(OperationCode.RegionDestroy, 1, OpFlags.UseSubRegion, 1), new OperationWithAction(OperationCode.Get, 2, OpFlags.UseSubRegion | OpFlags.CheckNoKey | OpFlags.CheckException, 8), // Do REGION_DESTROY of the region and check with GET new OperationWithAction(OperationCode.RegionDestroy, 3, OpFlags.CheckNotAuthz, 1), new OperationWithAction(OperationCode.RegionDestroy, 1, OpFlags.None, 1), new OperationWithAction(OperationCode.Get, 2, OpFlags.UseOldConn | OpFlags.CheckNoKey | OpFlags.CheckException, 8), // Skip failover for region destroy since it shall fail // without restarting the server OperationWithAction.OpBlockNoFailover }; RunOpsWithFailover(allOps, "AllOpsWithFailover", true); } void runThinClientWriterExceptionTest() { CacheHelper.SetupJavaServers(true, CacheXml1); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator started"); foreach (AuthzCredentialGenerator authzGen in GetAllGeneratorCombos(true)) { for (int i = 1; i <= 2; ++i) { CredentialGenerator cGen = authzGen.GetCredentialGenerator(); //TODO: its not working for multiuser mode.. need to fix later if (cGen.GetClassCode() == CredentialGenerator.ClassCode.PKCS) continue; Properties<string, string> extraAuthProps = cGen.SystemProperties; Properties<string, string> javaProps = cGen.JavaProperties; Properties<string, string> extraAuthzProps = authzGen.SystemProperties; string authenticator = cGen.Authenticator; string authInit = cGen.AuthInit; string accessor = authzGen.AccessControl; Util.Log("ThinClientWriterException: Using authinit: " + authInit); Util.Log("ThinClientWriterException: Using authenticator: " + authenticator); Util.Log("ThinClientWriterException: Using accessor: " + accessor); // Start servers with all required properties string serverArgs = SecurityTestUtil.GetServerArgs(authenticator, accessor, null, SecurityTestUtil.ConcatProperties(extraAuthProps, extraAuthzProps), javaProps); // Start the server. CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1, serverArgs); Util.Log("Cacheserver 1 started."); // Start client1 with valid CREATE credentials Properties<string, string> createCredentials = authzGen.GetDisallowedCredentials( new OperationCode[] { OperationCode.Put }, new string[] { RegionName }, 1); javaProps = cGen.JavaProperties; Util.Log("DisallowPuts: For first client PUT credentials: " + createCredentials); m_client1.Call(SecurityTestUtil.CreateClientR0, RegionName, CacheHelper.Locators, authInit, createCredentials); Util.Log("Creating region in client1 , no-ack, no-cache, with listener and writer"); m_client1.Call(CreateRegion, CacheHelper.Locators, true, true, true); m_client1.Call(RegisterAllKeys, new string[] { RegionName }); try { Util.Log("Trying put Operation"); m_client1.Call(DoPut); Util.Log(" Put Operation Successful"); Assert.Fail("Should have got NotAuthorizedException during put"); } catch (NotAuthorizedException) { Util.Log("NotAuthorizedException Caught"); Util.Log("Success"); } catch (Exception other) { Util.Log("Stack trace: {0} ", other.StackTrace); Util.Log("Got exception : {0}", other.Message); } m_client1.Call(CheckAssert); // Do LocalPut m_client1.Call(DoLocalPut); m_client1.Call(Close); CacheHelper.StopJavaServer(1); } } CacheHelper.StopJavaLocator(1); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } #region Tests [Test] public void TestCQ() { runCQTest(); } [Test] public void TestDurableCQ() { //for all run real cache will be true //logical cache true/false and durable cq true/false combination.... //result..whether events should be there or not runDurableCQTest(false, true, true);//no usercache close as it will close user's durable cq runDurableCQTest(true, false, false); runDurableCQTest(false, true, true); runDurableCQTest(false, false, false); } [Test] public void AllowPutsGets() { runAllowPutsGets(); } [Test] public void DisallowPutsGets() { runDisallowPutsGets(); } [Test] public void AllOpsWithFailover() { runAllOpsWithFailover(); } [Test] public void ThinClientWriterExceptionTest() { runThinClientWriterExceptionTest(); } #endregion } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // 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 Microsoft.Azure.Commands.Common.Authentication.Models; using Microsoft.Azure.Commands.Sql.Database.Model; using Microsoft.Azure.Commands.Sql.Database.Services; using Microsoft.Azure.Commands.Sql.FailoverGroup.Model; using Microsoft.Azure.Commands.Sql.Server.Adapter; using Microsoft.Azure.Commands.Sql.Services; using Microsoft.Azure.Management.Sql.LegacySdk.Models; using System.Collections.Generic; using System.Linq; namespace Microsoft.Azure.Commands.Sql.FailoverGroup.Services { /// <summary> /// Adapter for FailoverGroup operations /// </summary> public class AzureSqlFailoverGroupAdapter { /// <summary> /// Gets or sets the AzureEndpointsCommunicator which has all the needed management clients /// </summary> private AzureSqlFailoverGroupCommunicator Communicator { get; set; } /// <summary> /// Gets or sets the Azure profile /// </summary> public AzureContext Context { get; set; } /// <summary> /// Gets or sets the Azure Subscription /// </summary> private AzureSubscription _subscription { get; set; } /// <summary> /// Constructs a database adapter /// </summary> /// <param name="profile">The current azure profile</param> /// <param name="subscription">The current azure subscription</param> public AzureSqlFailoverGroupAdapter(AzureContext context) { _subscription = context.Subscription; Context = context; Communicator = new AzureSqlFailoverGroupCommunicator(Context); } /// <summary> /// Gets an Azure Sql Database FailoverGroup by name. /// </summary> /// <param name="resourceGroupName">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="failoverGroupName">The name of the Azure Sql Database FailoverGroup</param> /// <returns>The Azure Sql Database FailoverGroup object</returns> internal AzureSqlFailoverGroupModel GetFailoverGroup(string resourceGroupName, string serverName, string failoverGroupName) { var resp = Communicator.Get(resourceGroupName, serverName, failoverGroupName, Util.GenerateTracingId()); return CreateFailoverGroupModelFromResponse(resp); } /// <summary> /// Gets a list of Azure Sql Databases FailoverGroup. /// </summary> /// <param name="resourceGroupName">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <returns>A list of database objects</returns> internal ICollection<AzureSqlFailoverGroupModel> ListFailoverGroups(string resourceGroupName, string serverName) { var resp = Communicator.List(resourceGroupName, serverName, Util.GenerateTracingId()); return resp.Select((db) => { return CreateFailoverGroupModelFromResponse(db); }).ToList(); } /// <summary> /// Creates or updates an Azure Sql Database FailoverGroup. /// </summary> /// <param name="resourceGroup">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="model">The input parameters for the create/update operation</param> /// <returns>The upserted Azure Sql Database FailoverGroup</returns> internal AzureSqlFailoverGroupModel UpsertFailoverGroup(AzureSqlFailoverGroupModel model) { List < FailoverGroupPartnerServer > partnerServers = new List<FailoverGroupPartnerServer>(); FailoverGroupPartnerServer partnerServer = new FailoverGroupPartnerServer(); partnerServer.Id = string.Format( AzureSqlFailoverGroupModel.PartnerServerIdTemplate, _subscription.Id.ToString(), model.PartnerResourceGroupName, model.PartnerServerName); partnerServers.Add(partnerServer); ReadOnlyEndpoint readOnlyEndpoint = new ReadOnlyEndpoint(); readOnlyEndpoint.FailoverPolicy = model.ReadOnlyFailoverPolicy; ReadWriteEndpoint readWriteEndpoint = new ReadWriteEndpoint(); readWriteEndpoint.FailoverPolicy = model.ReadWriteFailoverPolicy; if (model.FailoverWithDataLossGracePeriodHours.HasValue) { readWriteEndpoint.FailoverWithDataLossGracePeriodMinutes = checked(model.FailoverWithDataLossGracePeriodHours * 60); } var resp = Communicator.CreateOrUpdate(model.ResourceGroupName, model.ServerName, model.FailoverGroupName, Util.GenerateTracingId(), new FailoverGroupCreateOrUpdateParameters() { Location = model.Location, Properties = new FailoverGroupCreateOrUpdateProperties() { PartnerServers = partnerServers, ReadOnlyEndpoint = readOnlyEndpoint, ReadWriteEndpoint = readWriteEndpoint, } }); return CreateFailoverGroupModelFromResponse(resp); } /// <summary> /// Patch updates an Azure Sql Database FailoverGroup. /// </summary> /// <param name="resourceGroup">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="model">The input parameters for the create/update operation</param> /// <returns>The upserted Azure Sql Database FailoverGroup</returns> internal AzureSqlFailoverGroupModel PatchUpdateFailoverGroup(AzureSqlFailoverGroupModel model) { ReadOnlyEndpoint readOnlyEndpoint = new ReadOnlyEndpoint(); readOnlyEndpoint.FailoverPolicy = model.ReadOnlyFailoverPolicy; ReadWriteEndpoint readWriteEndpoint = new ReadWriteEndpoint(); readWriteEndpoint.FailoverPolicy = model.ReadWriteFailoverPolicy; if (model.FailoverWithDataLossGracePeriodHours.HasValue) { readWriteEndpoint.FailoverWithDataLossGracePeriodMinutes = checked(model.FailoverWithDataLossGracePeriodHours * 60); } var resp = Communicator.PatchUpdate(model.ResourceGroupName, model.ServerName, model.FailoverGroupName, Util.GenerateTracingId(), new FailoverGroupPatchUpdateParameters() { Location = model.Location, Properties = new FailoverGroupPatchUpdateProperties() { ReadOnlyEndpoint = readOnlyEndpoint, ReadWriteEndpoint = readWriteEndpoint, } }); return CreateFailoverGroupModelFromResponse(resp); } /// <summary> /// Deletes a failvoer group /// </summary> /// <param name="resourceGroupName">The resource group the server is in</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="failvoerGroupName">The name of the Azure SQL Database Failover Group to delete</param> public void RemoveFailoverGroup(string resourceGroupName, string serverName, string failoverGroupName) { Communicator.Remove(resourceGroupName, serverName, failoverGroupName, Util.GenerateTracingId()); } /// <summary> /// Gets a list of Azure Sql Databases in a secondary server. /// </summary> /// <param name="resourceGroupName">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <returns>A list of database objects</returns> internal ICollection<AzureSqlDatabaseModel> ListDatabasesOnServer(string resourceGroupName, string serverName) { var resp = Communicator.ListDatabasesOnServer(resourceGroupName, serverName,Util.GenerateTracingId()); return resp.Select((db) => { return AzureSqlDatabaseAdapter.CreateDatabaseModelFromResponse(resourceGroupName, serverName, db); }).ToList(); } /// <summary> /// Patch updates an Azure Sql Database FailoverGroup. /// </summary> /// <param name="resourceGroup">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="model">The input parameters for the create/update operation</param> /// <returns>The updated Azure Sql Database FailoverGroup</returns> internal AzureSqlFailoverGroupModel AddOrRemoveDatabaseToFailoverGroup(string resourceGroupName, string serverName, string failoverGroupName, AzureSqlFailoverGroupModel model) { var resp = Communicator.PatchUpdate(resourceGroupName, serverName, failoverGroupName, Util.GenerateTracingId(), new FailoverGroupPatchUpdateParameters() { Location = model.Location, Properties = new FailoverGroupPatchUpdateProperties() { Databases = model.Databases, } }); return CreateFailoverGroupModelFromResponse(resp); } /// <summary> /// Finds and removes the Secondary Link by the secondary resource group and Azure SQL Server /// </summary> /// <param name="resourceGroupName">The name of the Resource Group containing the primary database</param> /// <param name="serverName">The name of the Azure SQL Server containing the primary database</param> /// <param name="databaseName">The name of primary database</param> /// <param name="partnerResourceGroupName">The name of the Resource Group containing the secondary database</param> /// <param name="partnerServerName">The name of the Azure SQL Server containing the secondary database</param> /// <param name="allowDataLoss">Whether the failover operation will allow data loss</param> /// <returns>The Azure SQL Database ReplicationLink object</returns> internal AzureSqlFailoverGroupModel Failover(string resourceGroupName, string serverName, string failoverGroupName, bool allowDataLoss) { if (!allowDataLoss) { Communicator.Failover(resourceGroupName, serverName, failoverGroupName, Util.GenerateTracingId()); } else { Communicator.ForceFailoverAllowDataLoss(resourceGroupName, serverName, failoverGroupName, Util.GenerateTracingId()); } return null; } /// <summary> /// Gets the Location of the server. /// </summary> /// <param name="resourceGroupName">The resource group the server is in</param> /// <param name="serverName">The name of the server</param> /// <returns></returns> public string GetServerLocation(string resourceGroupName, string serverName) { AzureSqlServerAdapter serverAdapter = new AzureSqlServerAdapter(Context); var server = serverAdapter.GetServer(resourceGroupName, serverName); return server.Location; } /// <summary> /// Converts the response from the service to a powershell database object /// </summary> /// <param name="resourceGroupName">The resource group the server is in</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="pool">The service response</param> /// <returns>The converted model</returns> private AzureSqlFailoverGroupModel CreateFailoverGroupModelFromResponse(Management.Sql.LegacySdk.Models.FailoverGroup failoverGroup) { AzureSqlFailoverGroupModel model = new AzureSqlFailoverGroupModel(); model.FailoverGroupName = failoverGroup.Name; model.Databases = failoverGroup.Properties.Databases; model.ReadOnlyFailoverPolicy = failoverGroup.Properties.ReadOnlyEndpoint.FailoverPolicy; model.ReadWriteFailoverPolicy = failoverGroup.Properties.ReadWriteEndpoint.FailoverPolicy; model.ReplicationRole = failoverGroup.Properties.ReplicationRole; model.ReplicationState = failoverGroup.Properties.ReplicationState; model.PartnerServers = failoverGroup.Properties.PartnerServers; model.FailoverWithDataLossGracePeriodHours = failoverGroup.Properties.ReadWriteEndpoint.FailoverWithDataLossGracePeriodMinutes == null ? null : failoverGroup.Properties.ReadWriteEndpoint.FailoverWithDataLossGracePeriodMinutes / 60; model.Id = failoverGroup.Id; model.Location = failoverGroup.Location; model.DatabaseNames = failoverGroup.Properties.Databases .Select(dbId => GetUriSegment(dbId, 10)) .ToList(); model.ResourceGroupName = GetUriSegment(failoverGroup.Id, 4); model.ServerName = GetUriSegment(failoverGroup.Id, 8); FailoverGroupPartnerServer partnerServer = failoverGroup.Properties.PartnerServers.FirstOrDefault(); if (partnerServer != null) { model.PartnerResourceGroupName = GetUriSegment(partnerServer.Id, 4); model.PartnerServerName = GetUriSegment(partnerServer.Id, 8); model.PartnerLocation = partnerServer.Location; } return model; } private string GetUriSegment(string uri, int segmentNum) { if (uri != null) { var segments = uri.Split('/'); if (segments.Length > segmentNum) { return segments[segmentNum]; } } return null; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.Memory; using Orleans; using Orleans.Configuration; using Orleans.Runtime; using Orleans.TestingHost; using TestExtensions; using TestVersionGrainInterfaces; using TestVersionGrains; using Xunit; namespace Tester.HeterogeneousSilosTests.UpgradeTests { public abstract class UpgradeTestsBase : IDisposable, IAsyncLifetime { private static readonly TimeSpan RefreshInterval = TimeSpan.FromMilliseconds(200); private TimeSpan waitDelay; protected IClusterClient Client => this.cluster.Client; protected IManagementGrain ManagementGrain => this.cluster.Client.GetGrain<IManagementGrain>(0); #if DEBUG private const string BuildConfiguration = "Debug"; #else private const string BuildConfiguration = "Release"; #endif private const string CommonParentDirectory = "test"; private const string BinDirectory = "bin"; private const string VersionsProjectDirectory = "Grains"; private const string GrainsV1ProjectName = "TestVersionGrains"; private const string GrainsV2ProjectName = "TestVersionGrains2"; private const string VersionTestBinaryName = "TestVersionGrains.exe"; private readonly FileInfo assemblyGrainsV1; private readonly FileInfo assemblyGrainsV2; private readonly List<SiloHandle> deployedSilos = new List<SiloHandle>(); private int siloIdx = 0; private TestClusterBuilder builder; private TestCluster cluster; protected abstract Type VersionSelectorStrategy { get; } protected abstract Type CompatibilityStrategy { get; } protected virtual short SiloCount => 2; protected UpgradeTestsBase() { var testDirectory = new DirectoryInfo(GetType().Assembly.Location); while (String.Compare(testDirectory.Name, CommonParentDirectory, StringComparison.OrdinalIgnoreCase) != 0 || testDirectory.Parent == null) { testDirectory = testDirectory.Parent; } if (testDirectory.Parent == null) { throw new InvalidOperationException($"Cannot locate 'test' directory starting from '{GetType().Assembly.Location}'"); } assemblyGrainsV1 = GetVersionTestDirectory(testDirectory, GrainsV1ProjectName); assemblyGrainsV2 = GetVersionTestDirectory(testDirectory, GrainsV2ProjectName); } private FileInfo GetVersionTestDirectory(DirectoryInfo testDirectory, string directoryName) { var projectDirectory = Path.Combine(testDirectory.FullName, VersionsProjectDirectory, directoryName, BinDirectory); var directories = Directory.GetDirectories(projectDirectory, BuildConfiguration, SearchOption.AllDirectories); if (directories.Length != 1) { throw new InvalidOperationException($"Number of directories found for pattern: '{BuildConfiguration}' under {testDirectory.FullName}: {directories.Length}"); } var directory = directories[0]; var files = Directory.GetFiles(directory, VersionTestBinaryName, SearchOption.AllDirectories) .Where(f => !f.Contains(Path.DirectorySeparatorChar + "ref" + Path.DirectorySeparatorChar)) .Where(f => f.Contains("publish")) #if NET5_0_OR_GREATER .Where(f => f.Contains("net5")) #else .Where(f => f.Contains("netcoreapp")) #endif .ToArray(); if (files.Length != 1) { throw new InvalidOperationException($"Found {files.Length} files found for pattern: '{VersionTestBinaryName}' under {directory}: {string.Join(", ", files)}"); } return new FileInfo(files[0]); } protected async Task Step1_StartV1Silo_Step2_StartV2Silo_Step3_StopV2Silo(int step2Version) { const int numberOfGrains = 100; await StartSiloV1(); // Only V1 exist for now for (var i = 0; i < numberOfGrains; i++) { var grain = Client.GetGrain<IVersionUpgradeTestGrain>(i); Assert.Equal(1, await grain.GetVersion()); } // Start a new silo with V2 var siloV2 = await StartSiloV2(); for (var i = 0; i < numberOfGrains; i++) { var grain = Client.GetGrain<IVersionUpgradeTestGrain>(i); Assert.Equal(1, await grain.GetVersion()); } for (var i = numberOfGrains; i < numberOfGrains * 2; i++) { var grain = Client.GetGrain<IVersionUpgradeTestGrain>(i); Assert.Equal(step2Version, await grain.GetVersion()); } // Stop the V2 silo await StopSilo(siloV2); // Now all activation should be V1 for (var i = 0; i < numberOfGrains * 3; i++) { var grain = Client.GetGrain<IVersionUpgradeTestGrain>(i); Assert.Equal(1, await grain.GetVersion()); } } protected async Task ProxyCallNoPendingRequest(int expectedVersion) { await StartSiloV1(); // Only V1 exist for now var grain0 = Client.GetGrain<IVersionUpgradeTestGrain>(0); Assert.Equal(1, await grain0.GetVersion()); await StartSiloV2(); // New activation should be V2 var grain1 = Client.GetGrain<IVersionUpgradeTestGrain>(1); Assert.Equal(2, await grain1.GetVersion()); Assert.Equal(1, await grain0.GetVersion()); Assert.Equal(expectedVersion, await grain1.ProxyGetVersion(grain0)); Assert.Equal(expectedVersion, await grain0.GetVersion()); } protected async Task ProxyCallWithPendingRequest(int expectedVersion) { await StartSiloV1(); // Only V1 exist for now var grain0 = Client.GetGrain<IVersionUpgradeTestGrain>(0); Assert.Equal(1, await grain0.GetVersion()); // Start a new silo with V2 await StartSiloV2(); // New activation should be V2 var grain1 = Client.GetGrain<IVersionUpgradeTestGrain>(1); Assert.Equal(2, await grain1.GetVersion()); var waitingTask = grain0.LongRunningTask(TimeSpan.FromSeconds(5)); var callBeforeUpgrade = grain0.GetVersion(); await Task.Delay(100); // Make sure requests are not sent out of order var callProvokingUpgrade = grain1.ProxyGetVersion(grain0); await waitingTask; Assert.Equal(1, await callBeforeUpgrade); Assert.Equal(expectedVersion, await callProvokingUpgrade); } protected async Task<SiloHandle> StartSiloV1() { var handle = await StartSilo(assemblyGrainsV1); await Task.Delay(waitDelay); return handle; } protected async Task<SiloHandle> StartSiloV2() { var handle = await StartSilo(assemblyGrainsV2); await Task.Delay(waitDelay); return handle; } private async Task<SiloHandle> StartSilo(FileInfo grainAssembly) { SiloHandle silo; if (this.siloIdx == 0) { // Setup configuration this.builder = new TestClusterBuilder(1); builder.CreateSiloAsync = StandaloneSiloHandle.Create; TestDefaultConfiguration.ConfigureTestCluster(this.builder); builder.AddSiloBuilderConfigurator<VersionGrainsSiloBuilderConfigurator>(); builder.AddClientBuilderConfigurator<VersionGrainsClientConfigurator>(); builder.Properties[nameof(SiloCount)] = this.SiloCount.ToString(); builder.Properties[nameof(RefreshInterval)] = RefreshInterval.ToString(); builder.Properties[nameof(VersionSelectorStrategy)] = this.VersionSelectorStrategy.Name; builder.Properties[nameof(CompatibilityStrategy)] = this.CompatibilityStrategy.Name; builder.Properties["GrainAssembly"] = grainAssembly.FullName; builder.Properties[StandaloneSiloHandle.ExecutablePathConfigKey] = grainAssembly.FullName; waitDelay = TestCluster.GetLivenessStabilizationTime(new ClusterMembershipOptions(), didKill: false); this.cluster = builder.Build(); await this.cluster.DeployAsync(); silo = this.cluster.Primary; } else { var configBuilder = new ConfigurationBuilder(); foreach (var source in cluster.ConfigurationSources) configBuilder.Add(source); var testClusterOptions = new TestClusterOptions(); configBuilder.Build().Bind(testClusterOptions); // Override the root directory. var sources = new IConfigurationSource[] { new MemoryConfigurationSource { InitialData = new Dictionary<string, string> { [StandaloneSiloHandle.ExecutablePathConfigKey] = grainAssembly.FullName } } }; silo = await TestCluster.StartSiloAsync(cluster, siloIdx, testClusterOptions, sources); } this.deployedSilos.Add(silo); this.siloIdx++; return silo; } protected async Task StopSilo(SiloHandle handle) { await handle?.StopSiloAsync(true); this.deployedSilos.Remove(handle); await Task.Delay(waitDelay); } public void Dispose() { try { if (deployedSilos.Count == 0) return; var primarySilo = this.deployedSilos[0]; foreach (var silo in this.deployedSilos.Skip(1)) { silo.Dispose(); } primarySilo.Dispose(); } finally { this.cluster?.Dispose(); } } public Task InitializeAsync() { return Task.CompletedTask; } public async Task DisposeAsync() { if (deployedSilos.Count == 0) return; var primarySilo = this.deployedSilos[0]; foreach (var silo in this.deployedSilos.Skip(1)) { await silo.DisposeAsync(); } await primarySilo.DisposeAsync(); if (Client is { }) { await cluster.StopClusterClientAsync(); } } public class VersionGrainsClientConfigurator : IClientBuilderConfigurator { public void Configure(IConfiguration configuration, IClientBuilder clientBuilder) { clientBuilder.Configure<GatewayOptions>(options => options.PreferedGatewayIndex = 0); } } } }
// 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.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; using Test.Utilities; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.CodeQuality.Analyzers.QualityGuidelines.SealMethodsThatSatisfyPrivateInterfacesAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.CodeQuality.Analyzers.QualityGuidelines.SealMethodsThatSatisfyPrivateInterfacesAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; namespace Microsoft.CodeQuality.Analyzers.QualityGuidelines.UnitTests { public class SealMethodsThatSatisfyPrivateInterfacesTests { [Fact] public async Task TestCSharp_ClassesThatCannotBeSubClassedOutsideThisAssembly_HasNoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" internal interface IFace { void M(); } // Declaring type only accessible to this assembly internal class C : IFace { public virtual void M() { } } // Declaring type can only be instantiated in this assembly public class D : IFace { internal D() { } public virtual void M() { } } "); } [Fact] public async Task TestCSharp_VirtualImplicit_HasDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" internal interface IFace { void M(); } public class C : IFace { public virtual void M() { } } ", GetCSharpResultAt(9, 25)); } [Fact] public async Task TestCSharp_AbstractImplicit_HasDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" internal interface IFace { void M(); } public abstract class C : IFace { public abstract void M(); } ", GetCSharpResultAt(9, 26)); } [Fact] public async Task TestCSharp_Explicit_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" internal interface IFace { void M(); } public class C : IFace { void IFace.M() { } } "); } [Fact] public async Task TestCSharp_NoInterface_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" public class C { public void M() { } } "); } [Fact] public async Task TestCSharp_StructImplicit_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" internal interface IFace { void M(); } public class C : IFace { public void M() { } } "); } [Fact] public async Task TestCSharp_PublicInterface_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" public interface IFace { void M(); } public class C : IFace { public void M() { } } "); } [Fact] public async Task TestCSharp_OverriddenFromBase_HasDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" internal interface IFace { void M(); } public abstract class B { public abstract void M(); } public class C : B, IFace { public override void M() { } } ", GetCSharpResultAt(14, 26)); } [Fact] public async Task TestCSharp_OverriddenFromBaseButMethodIsSealed_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" internal interface IFace { void M(); } public abstract class B { public abstract void M(); } public class C : B, IFace { public sealed override void M() { } } "); } [Fact] public async Task TestCSharp_OverriddenFromBaseButClassIsSealed_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" internal interface IFace { void M(); } public abstract class B { public abstract void M(); } public sealed class C : B, IFace { public override void M() { } } "); } [Fact] public async Task TestCSharp_ImplicitlyImplementedFromBaseMember_HasDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" internal interface IFace { void M(); } public class B { public virtual void M() { } } public class C : B, IFace { } ", GetCSharpResultAt(14, 14)); } [Fact] public async Task TestCSharp_ImplicitlyImplementedFromBaseMember_Public_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" public interface IFace { void M(); } public class B { public virtual void M() { } } class C : B, IFace { } "); } [Fact] public async Task TestVB_Overridable_HasDiagnostic() { await VerifyVB.VerifyAnalyzerAsync(@" Friend Interface IFace Sub M() End Interface Public Class C Implements IFace Public Overridable Sub M() Implements IFace.M End Sub End Class ", GetBasicResultAt(9, 28)); } [Fact] public async Task TestVB_MustOverride_HasDiagnostic() { await VerifyVB.VerifyAnalyzerAsync(@" Friend Interface IFace Sub M() End Interface Public MustInherit Class C Implements IFace Public MustOverride Sub M() Implements IFace.M End Class ", GetBasicResultAt(9, 29)); } [Fact] public async Task TestVB_OverridenFromBase_HasDiagnostic() { await VerifyVB.VerifyAnalyzerAsync(@" Friend Interface IFace Sub M() End Interface Public MustInherit Class B Public MustOverride Sub M() End Class Public Class C Inherits B Implements IFace Public Overrides Sub M() Implements IFace.M End Sub End Class ", GetBasicResultAt(14, 26)); } [Fact] public async Task TestVB_OverridenFromBaseButNotOverridable_NoDiagnostic() { await VerifyVB.VerifyAnalyzerAsync(@" Friend Interface IFace Sub M() End Interface Public MustInherit Class B Public MustOverride Sub M() End Class Public Class C Inherits B Implements IFace Public NotOverridable Overrides Sub M() Implements IFace.M End Sub End Class "); } [Fact] public async Task TestVB_NotExplicit_NoDiagnostic() { await VerifyVB.VerifyAnalyzerAsync(@" Friend Interface IFace Sub M() End Interface Public MustInherit Class C Implements IFace Public MustOverride Sub M() Public Sub IFace_M() Implements IFace.M End Sub End Class "); } [Fact] public async Task TestVB_PrivateMethod_NoDiagnostic() { await VerifyVB.VerifyAnalyzerAsync(@" Friend Interface IFace Sub M() End Interface Public Class C Implements IFace Private Sub M() Implements IFace.M End Sub End Class "); } [Fact] public async Task TestVB_PublicMethod_NoDiagnostic() { await VerifyVB.VerifyAnalyzerAsync(@" Friend Interface IFace Sub M() End Interface Public Class C Implements IFace Public Sub M() Implements IFace.M End Sub End Class "); } [Fact] public async Task TestVB_FriendMethod_NoDiagnostic() { await VerifyVB.VerifyAnalyzerAsync(@" Friend Interface IFace Sub M() End Interface Public Class C Implements IFace Friend Sub M() Implements IFace.M End Sub End Class "); } [Fact] public async Task TestVB_PublicInterface_NoDiagnostic() { await VerifyVB.VerifyAnalyzerAsync(@" Public Interface IFace Sub M() End Interface Public Class C Implements IFace Public Overridable Sub M() Implements IFace.M End Sub End Class "); } [Fact, WorkItem(4406, "https://github.com/dotnet/roslyn-analyzers/issues/4406")] public async Task CA2119_ExtendedInterface() { await VerifyCS.VerifyAnalyzerAsync(@" namespace FxCopRule { internal interface IInternal1 { void Method(); } internal interface IInternal2 : IInternal1 { } public abstract class ImplementationBase : IInternal2 { public abstract void [|Method|](); } }"); await VerifyVB.VerifyAnalyzerAsync(@" Namespace FxCopRule Friend Interface IInternal1 Sub Method() End Interface Friend Interface IInternal2 Inherits IInternal1 End Interface Public MustInherit Class ImplementationBase Implements IInternal2 Public MustOverride Sub [|Method|]() Implements IInternal1.Method End Class End Namespace"); } // TODO: // sealed overrides - no diagnostic [Fact, WorkItem(4566, "https://github.com/dotnet/roslyn-analyzers/issues/4566")] public async Task CA2119_BaseClassInterface_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" namespace NS { internal interface IInternal { void Method1(); } public class C : IInternal { public virtual void [|Method1|]() { } } public class InheritFromC : C { } }"); await VerifyVB.VerifyAnalyzerAsync(@" Namespace NS Friend Interface IInternal Sub Method1() End Interface Public Class C Implements IInternal Public Overridable Sub [|Method1|]() Implements IInternal.Method1 End Sub End Class Public Class InheritFromC Inherits C End Class End Namespace"); } private static DiagnosticResult GetCSharpResultAt(int line, int column) #pragma warning disable RS0030 // Do not used banned APIs => VerifyCS.Diagnostic() .WithLocation(line, column); #pragma warning restore RS0030 // Do not used banned APIs private static DiagnosticResult GetBasicResultAt(int line, int column) #pragma warning disable RS0030 // Do not used banned APIs => VerifyVB.Diagnostic() .WithLocation(line, column); #pragma warning restore RS0030 // Do not used banned APIs } }
// ---------------------------------------------------------------------------- // FunctorTestFixture.cs // // Contains the definition of the FunctorTestFixture class. // Copyright 2009 Steve Guidi. // // File created: 3/23/2009 08:44:38 // ---------------------------------------------------------------------------- using System; using System.IO; using System.Linq; using System.Reflection; using Jolt.Functional; using NUnit.Framework; using Rhino.Mocks; namespace Jolt.Test.Functional { [TestFixture] public sealed class FunctorTestFixture { #region public methods -------------------------------------------------------------------- /// <summary> /// Verifies the behavior of the ToAction() method, for functions /// that have zero arguments. /// </summary> [Test] public void ToAction_NoArgs() { Func<int> function = MockRepository.GenerateMock<Func<int>>(); function.Expect(f => f()).Return(0); Action action = Functor.ToAction(function); action(); function.VerifyAllExpectations(); } /// <summary> /// Verifies the behavior of the ToAction() method, for functions /// that have one argument. /// </summary> [Test] public void ToAction_OneArg() { Func<string, int> function = MockRepository.GenerateMock<Func<string, int>>(); string functionArg = "first-arg"; function.Expect(f => f(functionArg)).Return(0); Action<string> action = Functor.ToAction(function); action(functionArg); function.VerifyAllExpectations(); } /// <summary> /// Verifies the behavior of the ToAction() method, for functions /// that have two arguments. /// </summary> [Test] public void ToAction_TwoArgs() { Func<string, Stream, int> function = MockRepository.GenerateMock<Func<string, Stream, int>>(); string functionArg = "first-arg"; function.Expect(f => f(functionArg, Stream.Null)).Return(0); Action<string, Stream> action = Functor.ToAction(function); action(functionArg, Stream.Null); function.VerifyAllExpectations(); } /// <summary> /// Verifies the behavior of the ToAction() method, for functions /// that have three arguments. /// </summary> [Test] public void ToAction_ThreeArgs() { Func<string, Stream, TextReader, int> function = MockRepository.GenerateMock<Func<string, Stream, TextReader, int>>(); string functionArg_1 = "first-arg"; StreamReader functionArg_3 = new StreamReader(Stream.Null); function.Expect(f => f(functionArg_1, Stream.Null, functionArg_3)).Return(0); Action<string, Stream, TextReader> action = Functor.ToAction(function); action(functionArg_1, Stream.Null, functionArg_3); function.VerifyAllExpectations(); } /// <summary> /// Verifies the behavior of the ToAction() method, for functions /// that have four arguments. /// </summary> [Test] public void ToAction_FourArgs() { Func<string, Stream, TextReader, DayOfWeek, int> function = MockRepository.GenerateMock<Func<string, Stream, TextReader, DayOfWeek, int>>(); string functionArg_1 = "first-arg"; StreamReader functionArg_3 = new StreamReader(Stream.Null); DayOfWeek functionArg_4 = DayOfWeek.Friday; function.Expect(f => f(functionArg_1, Stream.Null, functionArg_3, functionArg_4)).Return(0); Action<string, Stream, TextReader, DayOfWeek> action = Functor.ToAction(function); action(functionArg_1, Stream.Null, functionArg_3, functionArg_4); function.VerifyAllExpectations(); } /// <summary> /// Verifies the behavior of the ToAction() method, accepting /// an EventHandler for adapting. /// </summary> [Test] public void ToAction_EventHandler() { EventHandler<EventArgs> eventHandler = MockRepository.GenerateStub<EventHandler<EventArgs>>(); Action<object, EventArgs> action = Functor.ToAction(eventHandler); Assert.That(action.Method, Is.SameAs(eventHandler.Method)); Assert.That(action.Target, Is.SameAs(eventHandler.Target)); eventHandler.VerifyAllExpectations(); } /// <summary> /// Verifies the behavior of the ToEventHandler() method. /// </summary> [Test] public void ToEventHandler() { Action<object, EventArgs> action = MockRepository.GenerateStub<Action<object, EventArgs>>(); EventHandler<EventArgs> eventHandler = Functor.ToEventHandler(action); Assert.That(eventHandler.Method, Is.SameAs(action.Method)); Assert.That(eventHandler.Target, Is.SameAs(action.Target)); action.VerifyAllExpectations(); } /// <summary> /// Verifies the behavior of the ToPredicate() method. /// </summary> [Test] public void ToPredicate() { Func<int, bool> functionPredicate = MockRepository.GenerateStub<Func<int, bool>>(); Predicate<int> predicate = Functor.ToPredicate(functionPredicate); Assert.That(predicate.Method, Is.SameAs(functionPredicate.Method)); Assert.That(predicate.Target, Is.SameAs(functionPredicate.Target)); } /// <summary> /// Verifies the behavior of the ToPredicateFunc() method. /// </summary> [Test] public void ToPredicateFunc() { Predicate<int> predicate = MockRepository.GenerateStub<Predicate<int>>(); Func<int, bool> functionPredicate = Functor.ToPredicateFunc(predicate); Assert.That(functionPredicate.Method, Is.SameAs(predicate.Method)); Assert.That(functionPredicate.Target, Is.SameAs(predicate.Target)); } /// <summary> /// Verifies the behavior of the Idempotency() method, for functions /// that have zero arguments. /// </summary> [Test] public void Idempotency_NoArgs() { string constant = "constant-value"; Func<string> function = Functor.Idempotency(constant); Assert.That(function.Target, Is.Not.Null); for (int i = 0; i < 200; ++i) { Assert.That(function(), Is.SameAs(constant)); } } /// <summary> /// Verifies the behavior of the Idempotency() method, for functions /// that have one argument. /// </summary> [Test] public void Idempotency_OneArg() { string constant = "constant-value"; Func<int, string> function = Functor.Idempotency<int, string>(constant); Assert.That(function.Target, Is.Not.Null); for (int i = 0; i < 20; ++i) { Assert.That(function(i), Is.SameAs(constant)); } } /// <summary> /// Verifies the behavior of the Idempotency() method, for functions /// that have two arguments. /// </summary> [Test] public void Idempotency_TwoArgs() { string constant = "constant-value"; Func<int, double, string> function = Functor.Idempotency<int, double, string>(constant); Assert.That(function.Target, Is.Not.Null); for (int i = 0; i < 200; ++i) { Assert.That(function(i, 2.5 * i), Is.SameAs(constant)); } } /// <summary> /// Verifies the behavior of the Idempotency() method, for functions /// that have three arguments. /// </summary> [Test] public void Idempotency_ThreeArgs() { string constant = "constant-value"; Func<int, double, DateTime, string> function = Functor.Idempotency<int, double, DateTime, string>(constant); Assert.That(function.Target, Is.Not.Null); for (int i = 0; i < 200; ++i) { Assert.That(function(i, 2.5 * i, DateTime.Now), Is.SameAs(constant)); } } /// <summary> /// Verifies the behavior of the Idempotency() method, for functions /// that have four arguments. /// </summary> [Test] public void Idempotency_FourArgs() { string constant = "constant-value"; Func<int, double, DateTime, char, string> function = Functor.Idempotency<int, double, DateTime, char, string>(constant); Assert.That(function.Target, Is.Not.Null); for (int i = 0; i < 200; ++i) { Assert.That(function(i, 2.5 * i, DateTime.Now, System.Convert.ToChar(i)), Is.SameAs(constant)); } } /// <summary> /// Verifies the behavior of the NoOperation() method, for functions /// that have zero arguments. /// </summary> [Test] public void NoOperation_NoArgs() { Action no_op = Functor.NoOperation(); Assert.That(no_op.Target, Is.Null); Assert.That(no_op.Method, Is.SameAs(GetNoOpMethod())); } /// <summary> /// Verifies the behavior of the NoOperation() method, for functions /// that have one argument. /// </summary> [Test] public void NoOperation_OneArg() { Action<int> no_op = Functor.NoOperation<int>(); Assert.That(no_op.Target, Is.Null); Assert.That(no_op.Method, Is.SameAs(GetNoOpMethod(typeof(int)))); } /// <summary> /// Verifies the behavior of the NoOperation() method, for functions /// that have two arguments. /// </summary> [Test] public void NoOperation_TwoArgs() { Action<int, char> no_op = Functor.NoOperation<int, char>(); Assert.That(no_op.Target, Is.Null); Assert.That(no_op.Method, Is.SameAs(GetNoOpMethod(typeof(int), typeof(char)))); } /// <summary> /// Verifies the behavior of the NoOperation() method, for functions /// that have three arguments. /// </summary> [Test] public void NoOperation_ThreeArgs() { Action<int, char, string> no_op = Functor.NoOperation<int, char, string>(); Assert.That(no_op.Target, Is.Null); Assert.That(no_op.Method, Is.SameAs(GetNoOpMethod(typeof(int), typeof(char), typeof(string)))); } /// <summary> /// Verifies the behavior of the NoOperation() method, for functions /// that have four arguments. /// </summary> [Test] public void NoOperation_FourArgs() { Action<int, char, string, byte> no_op = Functor.NoOperation<int, char, string, byte>(); Assert.That(no_op.Target, Is.Null); Assert.That(no_op.Method, Is.SameAs(GetNoOpMethod(typeof(int), typeof(char), typeof(string), typeof(byte)))); } /// <summary> /// Verifies the behavior of the Identity() method. /// </summary> [Test] public void Identity() { Func<string, string> identity = Functor.Identity<string>(); Assert.That(identity.Target, Is.Null); for (int i = 0; i < 200; ++i) { string functionArg = new String('z', i); Assert.That(identity(functionArg), Is.SameAs(functionArg)); } } /// <summary> /// Verifies the behavior of the TrueForAll() method. /// </summary> [Test] public void TrueForAll() { Func<int, bool> predicate = Functor.TrueForAll<int>(); Assert.That(predicate.Target, Is.Null); for (int i = 0; i < 200; ++i) { Assert.That(predicate(i)); } } /// <summary> /// Verifies the behavior of the FalseForAll() method. /// </summary> [Test] public void FalseForAll() { Func<int, bool> predicate = Functor.FalseForAll<int>(); Assert.That(predicate.Target, Is.Null); for (int i = 0; i < 200; ++i) { Assert.That(!predicate(i)); } } #endregion #region private methods ------------------------------------------------------------------- /// <summary> /// Gets the compiler-generated no-op method, constructed with the given /// generic method parameters. /// </summary> /// /// <param name="genericMethodArgs"> /// The generic method parameters used to construct the resulting method. /// </param> private static MethodInfo GetNoOpMethod(params Type[] genericMethodArgs) { MethodInfo noOpMethod = typeof(Functor).GetMethods(BindingFlags.NonPublic | BindingFlags.Static).Single( method => method.Name.StartsWith("<NoOperation>") && method.GetGenericArguments().Length == genericMethodArgs.Length); return !noOpMethod.IsGenericMethod ? noOpMethod : noOpMethod.MakeGenericMethod(genericMethodArgs); } #endregion } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; namespace _4PosBackOffice.NET { [Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] partial class frmCompanyEmails { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmCompanyEmails() : base() { Load += frmCompanyEmails_Load; FormClosed += frmCompanyEmails_FormClosed; KeyPress += frmCompanyEmails_KeyPress; //This call is required by the Windows Form Designer. InitializeComponent(); } //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool Disposing) { if (Disposing) { if ((components != null)) { components.Dispose(); } } base.Dispose(Disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; public System.Windows.Forms.ToolTip ToolTip1; public System.Windows.Forms.TextBox _txtFields_7; public System.Windows.Forms.TextBox _txtFields_6; public System.Windows.Forms.TextBox _txtFields_5; public System.Windows.Forms.TextBox _txtFields_4; private System.Windows.Forms.Button withEventsField_cmdClose; public System.Windows.Forms.Button cmdClose { get { return withEventsField_cmdClose; } set { if (withEventsField_cmdClose != null) { withEventsField_cmdClose.Click -= cmdClose_Click; } withEventsField_cmdClose = value; if (withEventsField_cmdClose != null) { withEventsField_cmdClose.Click += cmdClose_Click; } } } private System.Windows.Forms.Button withEventsField_cmdCancel; public System.Windows.Forms.Button cmdCancel { get { return withEventsField_cmdCancel; } set { if (withEventsField_cmdCancel != null) { withEventsField_cmdCancel.Click -= cmdCancel_Click; } withEventsField_cmdCancel = value; if (withEventsField_cmdCancel != null) { withEventsField_cmdCancel.Click += cmdCancel_Click; } } } public System.Windows.Forms.Panel picButtons; public System.Windows.Forms.TextBox _txtFields_3; public System.Windows.Forms.TextBox _txtFields_2; public System.Windows.Forms.TextBox _txtFields_1; public System.Windows.Forms.TextBox _txtFields_0; public System.Windows.Forms.Label Label10; public System.Windows.Forms.Label Label9; public Microsoft.VisualBasic.PowerPacks.RectangleShape Shape1; public System.Windows.Forms.Label Label8; public System.Windows.Forms.Label Label7; public System.Windows.Forms.Label Label5; public System.Windows.Forms.Label Label4; public System.Windows.Forms.Label Label3; public System.Windows.Forms.Label Label2; public System.Windows.Forms.Label Label1; public Microsoft.VisualBasic.PowerPacks.RectangleShape Shape2; public System.Windows.Forms.Label Label6; //Public WithEvents txtFields As Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray public Microsoft.VisualBasic.PowerPacks.ShapeContainer ShapeContainer1; //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(this.components); this.ShapeContainer1 = new Microsoft.VisualBasic.PowerPacks.ShapeContainer(); this.Shape1 = new Microsoft.VisualBasic.PowerPacks.RectangleShape(); this.Shape2 = new Microsoft.VisualBasic.PowerPacks.RectangleShape(); this._txtFields_7 = new System.Windows.Forms.TextBox(); this._txtFields_6 = new System.Windows.Forms.TextBox(); this._txtFields_5 = new System.Windows.Forms.TextBox(); this._txtFields_4 = new System.Windows.Forms.TextBox(); this.picButtons = new System.Windows.Forms.Panel(); this.cmdClose = new System.Windows.Forms.Button(); this.cmdCancel = new System.Windows.Forms.Button(); this._txtFields_3 = new System.Windows.Forms.TextBox(); this._txtFields_2 = new System.Windows.Forms.TextBox(); this._txtFields_1 = new System.Windows.Forms.TextBox(); this._txtFields_0 = new System.Windows.Forms.TextBox(); this.Label10 = new System.Windows.Forms.Label(); this.Label9 = new System.Windows.Forms.Label(); this.Label8 = new System.Windows.Forms.Label(); this.Label7 = new System.Windows.Forms.Label(); this.Label5 = new System.Windows.Forms.Label(); this.Label4 = new System.Windows.Forms.Label(); this.Label3 = new System.Windows.Forms.Label(); this.Label2 = new System.Windows.Forms.Label(); this.Label1 = new System.Windows.Forms.Label(); this.Label6 = new System.Windows.Forms.Label(); this.picButtons.SuspendLayout(); this.SuspendLayout(); // //ShapeContainer1 // this.ShapeContainer1.Location = new System.Drawing.Point(0, 0); this.ShapeContainer1.Margin = new System.Windows.Forms.Padding(0); this.ShapeContainer1.Name = "ShapeContainer1"; this.ShapeContainer1.Shapes.AddRange(new Microsoft.VisualBasic.PowerPacks.Shape[] { this.Shape1, this.Shape2 }); this.ShapeContainer1.Size = new System.Drawing.Size(298, 282); this.ShapeContainer1.TabIndex = 21; this.ShapeContainer1.TabStop = false; // //Shape1 // this.Shape1.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255))); this.Shape1.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque; this.Shape1.BorderColor = System.Drawing.SystemColors.WindowText; this.Shape1.FillColor = System.Drawing.Color.Black; this.Shape1.Location = new System.Drawing.Point(6, 236); this.Shape1.Name = "Shape1"; this.Shape1.Size = new System.Drawing.Size(287, 31); // //Shape2 // this.Shape2.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255))); this.Shape2.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque; this.Shape2.BorderColor = System.Drawing.SystemColors.WindowText; this.Shape2.FillColor = System.Drawing.Color.Black; this.Shape2.Location = new System.Drawing.Point(6, 52); this.Shape2.Name = "Shape2"; this.Shape2.Size = new System.Drawing.Size(287, 165); // //_txtFields_7 // this._txtFields_7.AcceptsReturn = true; this._txtFields_7.BackColor = System.Drawing.SystemColors.Window; this._txtFields_7.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFields_7.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFields_7.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFields_7.Location = new System.Drawing.Point(228, 240); this._txtFields_7.MaxLength = 0; this._txtFields_7.Name = "_txtFields_7"; this._txtFields_7.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFields_7.Size = new System.Drawing.Size(59, 20); this._txtFields_7.TabIndex = 19; this._txtFields_7.Text = "0"; this._txtFields_7.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //_txtFields_6 // this._txtFields_6.AcceptsReturn = true; this._txtFields_6.BackColor = System.Drawing.SystemColors.Window; this._txtFields_6.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFields_6.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFields_6.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFields_6.Location = new System.Drawing.Point(76, 192); this._txtFields_6.MaxLength = 0; this._txtFields_6.Name = "_txtFields_6"; this._txtFields_6.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFields_6.Size = new System.Drawing.Size(214, 20); this._txtFields_6.TabIndex = 16; // //_txtFields_5 // this._txtFields_5.AcceptsReturn = true; this._txtFields_5.BackColor = System.Drawing.SystemColors.Window; this._txtFields_5.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFields_5.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFields_5.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFields_5.Location = new System.Drawing.Point(76, 170); this._txtFields_5.MaxLength = 0; this._txtFields_5.Name = "_txtFields_5"; this._txtFields_5.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFields_5.Size = new System.Drawing.Size(214, 20); this._txtFields_5.TabIndex = 14; // //_txtFields_4 // this._txtFields_4.AcceptsReturn = true; this._txtFields_4.BackColor = System.Drawing.SystemColors.Window; this._txtFields_4.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFields_4.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFields_4.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFields_4.Location = new System.Drawing.Point(76, 148); this._txtFields_4.MaxLength = 0; this._txtFields_4.Name = "_txtFields_4"; this._txtFields_4.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFields_4.Size = new System.Drawing.Size(214, 20); this._txtFields_4.TabIndex = 12; // //picButtons // this.picButtons.BackColor = System.Drawing.Color.Blue; this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.picButtons.Controls.Add(this.cmdClose); this.picButtons.Controls.Add(this.cmdCancel); this.picButtons.Cursor = System.Windows.Forms.Cursors.Default; this.picButtons.Dock = System.Windows.Forms.DockStyle.Top; this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText; this.picButtons.Location = new System.Drawing.Point(0, 0); this.picButtons.Name = "picButtons"; this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No; this.picButtons.Size = new System.Drawing.Size(298, 33); this.picButtons.TabIndex = 9; // //cmdClose // this.cmdClose.BackColor = System.Drawing.SystemColors.Control; this.cmdClose.Cursor = System.Windows.Forms.Cursors.Default; this.cmdClose.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdClose.Location = new System.Drawing.Point(216, 2); this.cmdClose.Name = "cmdClose"; this.cmdClose.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdClose.Size = new System.Drawing.Size(73, 23); this.cmdClose.TabIndex = 11; this.cmdClose.TabStop = false; this.cmdClose.Text = "E&xit"; this.cmdClose.UseVisualStyleBackColor = false; // //cmdCancel // this.cmdCancel.BackColor = System.Drawing.SystemColors.Control; this.cmdCancel.Cursor = System.Windows.Forms.Cursors.Default; this.cmdCancel.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdCancel.Location = new System.Drawing.Point(4, 2); this.cmdCancel.Name = "cmdCancel"; this.cmdCancel.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdCancel.Size = new System.Drawing.Size(73, 23); this.cmdCancel.TabIndex = 10; this.cmdCancel.TabStop = false; this.cmdCancel.Text = "&Undo"; this.cmdCancel.UseVisualStyleBackColor = false; // //_txtFields_3 // this._txtFields_3.AcceptsReturn = true; this._txtFields_3.BackColor = System.Drawing.SystemColors.Window; this._txtFields_3.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFields_3.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFields_3.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFields_3.Location = new System.Drawing.Point(76, 126); this._txtFields_3.MaxLength = 0; this._txtFields_3.Name = "_txtFields_3"; this._txtFields_3.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFields_3.Size = new System.Drawing.Size(214, 20); this._txtFields_3.TabIndex = 4; // //_txtFields_2 // this._txtFields_2.AcceptsReturn = true; this._txtFields_2.BackColor = System.Drawing.SystemColors.Window; this._txtFields_2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFields_2.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFields_2.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFields_2.Location = new System.Drawing.Point(76, 104); this._txtFields_2.MaxLength = 0; this._txtFields_2.Name = "_txtFields_2"; this._txtFields_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFields_2.Size = new System.Drawing.Size(214, 20); this._txtFields_2.TabIndex = 3; // //_txtFields_1 // this._txtFields_1.AcceptsReturn = true; this._txtFields_1.BackColor = System.Drawing.SystemColors.Window; this._txtFields_1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFields_1.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFields_1.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFields_1.Location = new System.Drawing.Point(76, 82); this._txtFields_1.MaxLength = 0; this._txtFields_1.Name = "_txtFields_1"; this._txtFields_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFields_1.Size = new System.Drawing.Size(214, 20); this._txtFields_1.TabIndex = 2; // //_txtFields_0 // this._txtFields_0.AcceptsReturn = true; this._txtFields_0.BackColor = System.Drawing.SystemColors.Window; this._txtFields_0.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFields_0.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFields_0.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFields_0.Location = new System.Drawing.Point(76, 60); this._txtFields_0.MaxLength = 0; this._txtFields_0.Name = "_txtFields_0"; this._txtFields_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFields_0.Size = new System.Drawing.Size(214, 20); this._txtFields_0.TabIndex = 1; // //Label10 // this.Label10.AutoSize = true; this.Label10.BackColor = System.Drawing.Color.Transparent; this.Label10.Cursor = System.Windows.Forms.Cursors.Default; this.Label10.ForeColor = System.Drawing.SystemColors.ControlText; this.Label10.Location = new System.Drawing.Point(138, 242); this.Label10.Name = "Label10"; this.Label10.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label10.Size = new System.Drawing.Size(94, 13); this.Label10.TabIndex = 20; this.Label10.Text = "Company Number:"; this.Label10.TextAlign = System.Drawing.ContentAlignment.TopRight; // //Label9 // this.Label9.BackColor = System.Drawing.Color.Transparent; this.Label9.Cursor = System.Windows.Forms.Cursors.Default; this.Label9.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.Label9.ForeColor = System.Drawing.SystemColors.ControlText; this.Label9.Location = new System.Drawing.Point(10, 220); this.Label9.Name = "Label9"; this.Label9.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label9.Size = new System.Drawing.Size(121, 15); this.Label9.TabIndex = 18; this.Label9.Text = "2. Company Number"; // //Label8 // this.Label8.BackColor = System.Drawing.Color.Transparent; this.Label8.Cursor = System.Windows.Forms.Cursors.Default; this.Label8.ForeColor = System.Drawing.SystemColors.ControlText; this.Label8.Location = new System.Drawing.Point(10, 194); this.Label8.Name = "Label8"; this.Label8.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label8.Size = new System.Drawing.Size(63, 17); this.Label8.TabIndex = 17; this.Label8.Text = "Email No 7:"; this.Label8.TextAlign = System.Drawing.ContentAlignment.TopRight; // //Label7 // this.Label7.BackColor = System.Drawing.Color.Transparent; this.Label7.Cursor = System.Windows.Forms.Cursors.Default; this.Label7.ForeColor = System.Drawing.SystemColors.ControlText; this.Label7.Location = new System.Drawing.Point(10, 172); this.Label7.Name = "Label7"; this.Label7.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label7.Size = new System.Drawing.Size(63, 17); this.Label7.TabIndex = 15; this.Label7.Text = "Email No 6:"; this.Label7.TextAlign = System.Drawing.ContentAlignment.TopRight; // //Label5 // this.Label5.BackColor = System.Drawing.Color.Transparent; this.Label5.Cursor = System.Windows.Forms.Cursors.Default; this.Label5.ForeColor = System.Drawing.SystemColors.ControlText; this.Label5.Location = new System.Drawing.Point(10, 150); this.Label5.Name = "Label5"; this.Label5.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label5.Size = new System.Drawing.Size(63, 17); this.Label5.TabIndex = 13; this.Label5.Text = "Email No 5:"; this.Label5.TextAlign = System.Drawing.ContentAlignment.TopRight; // //Label4 // this.Label4.BackColor = System.Drawing.Color.Transparent; this.Label4.Cursor = System.Windows.Forms.Cursors.Default; this.Label4.ForeColor = System.Drawing.SystemColors.ControlText; this.Label4.Location = new System.Drawing.Point(10, 130); this.Label4.Name = "Label4"; this.Label4.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label4.Size = new System.Drawing.Size(63, 17); this.Label4.TabIndex = 8; this.Label4.Text = "Email No 4:"; this.Label4.TextAlign = System.Drawing.ContentAlignment.TopRight; // //Label3 // this.Label3.BackColor = System.Drawing.Color.Transparent; this.Label3.Cursor = System.Windows.Forms.Cursors.Default; this.Label3.ForeColor = System.Drawing.SystemColors.ControlText; this.Label3.Location = new System.Drawing.Point(10, 108); this.Label3.Name = "Label3"; this.Label3.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label3.Size = new System.Drawing.Size(63, 17); this.Label3.TabIndex = 7; this.Label3.Text = "Email No 3:"; this.Label3.TextAlign = System.Drawing.ContentAlignment.TopRight; // //Label2 // this.Label2.AutoSize = true; this.Label2.BackColor = System.Drawing.Color.Transparent; this.Label2.Cursor = System.Windows.Forms.Cursors.Default; this.Label2.ForeColor = System.Drawing.SystemColors.ControlText; this.Label2.Location = new System.Drawing.Point(19, 84); this.Label2.Name = "Label2"; this.Label2.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label2.Size = new System.Drawing.Size(61, 13); this.Label2.TabIndex = 6; this.Label2.Text = "Email No 2:"; this.Label2.TextAlign = System.Drawing.ContentAlignment.TopRight; // //Label1 // this.Label1.AutoSize = true; this.Label1.BackColor = System.Drawing.Color.Transparent; this.Label1.Cursor = System.Windows.Forms.Cursors.Default; this.Label1.ForeColor = System.Drawing.SystemColors.ControlText; this.Label1.Location = new System.Drawing.Point(19, 64); this.Label1.Name = "Label1"; this.Label1.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label1.Size = new System.Drawing.Size(61, 13); this.Label1.TabIndex = 5; this.Label1.Text = "Email No 1:"; this.Label1.TextAlign = System.Drawing.ContentAlignment.TopRight; // //Label6 // this.Label6.BackColor = System.Drawing.Color.Transparent; this.Label6.Cursor = System.Windows.Forms.Cursors.Default; this.Label6.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.Label6.ForeColor = System.Drawing.SystemColors.ControlText; this.Label6.Location = new System.Drawing.Point(8, 36); this.Label6.Name = "Label6"; this.Label6.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label6.Size = new System.Drawing.Size(161, 15); this.Label6.TabIndex = 0; this.Label6.Text = "1. Email For Remote Office"; // //frmCompanyEmails // this.AutoScaleDimensions = new System.Drawing.SizeF(6f, 13f); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.Control; this.ClientSize = new System.Drawing.Size(298, 282); this.ControlBox = false; this.Controls.Add(this._txtFields_7); this.Controls.Add(this._txtFields_6); this.Controls.Add(this._txtFields_5); this.Controls.Add(this._txtFields_4); this.Controls.Add(this.picButtons); this.Controls.Add(this._txtFields_3); this.Controls.Add(this._txtFields_2); this.Controls.Add(this._txtFields_1); this.Controls.Add(this._txtFields_0); this.Controls.Add(this.Label10); this.Controls.Add(this.Label9); this.Controls.Add(this.Label8); this.Controls.Add(this.Label7); this.Controls.Add(this.Label5); this.Controls.Add(this.Label4); this.Controls.Add(this.Label3); this.Controls.Add(this.Label2); this.Controls.Add(this.Label1); this.Controls.Add(this.Label6); this.Controls.Add(this.ShapeContainer1); this.Cursor = System.Windows.Forms.Cursors.Default; this.KeyPreview = true; this.Location = new System.Drawing.Point(4, 23); this.Name = "frmCompanyEmails"; this.RightToLeft = System.Windows.Forms.RightToLeft.No; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Edit Store Emails"; this.picButtons.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #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; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Xml; using System.Reflection; using System.Reflection.Emit; using System.IO; using System.Security; using System.Diagnostics; #if !NET_NATIVE namespace System.Runtime.Serialization { internal class CodeGenerator { private static MethodInfo s_getTypeFromHandle; private static MethodInfo GetTypeFromHandle { get { if (s_getTypeFromHandle == null) { s_getTypeFromHandle = typeof(Type).GetMethod("GetTypeFromHandle"); Debug.Assert(s_getTypeFromHandle != null); } return s_getTypeFromHandle; } } private static MethodInfo s_objectEquals; private static MethodInfo ObjectEquals { get { if (s_objectEquals == null) { s_objectEquals = Globals.TypeOfObject.GetMethod("Equals", BindingFlags.Public | BindingFlags.Static); Debug.Assert(s_objectEquals != null); } return s_objectEquals; } } private static MethodInfo s_arraySetValue; private static MethodInfo ArraySetValue { get { if (s_arraySetValue == null) { s_arraySetValue = typeof(Array).GetMethod("SetValue", new Type[] { typeof(object), typeof(int) }); Debug.Assert(s_arraySetValue != null); } return s_arraySetValue; } } #if !NET_NATIVE private static MethodInfo s_objectToString; private static MethodInfo ObjectToString { get { if (s_objectToString == null) { s_objectToString = typeof(object).GetMethod("ToString", Array.Empty<Type>()); Debug.Assert(s_objectToString != null); } return s_objectToString; } } private static MethodInfo s_stringFormat; private static MethodInfo StringFormat { get { if (s_stringFormat == null) { s_stringFormat = typeof(string).GetMethod("Format", new Type[] { typeof(string), typeof(object[]) }); Debug.Assert(s_stringFormat != null); } return s_stringFormat; } } #endif private Type _delegateType; #if USE_REFEMIT AssemblyBuilder assemblyBuilder; ModuleBuilder moduleBuilder; TypeBuilder typeBuilder; static int typeCounter; MethodBuilder methodBuilder; #else private static Module s_serializationModule; private static Module SerializationModule { get { if (s_serializationModule == null) { s_serializationModule = typeof(CodeGenerator).Module; // could to be replaced by different dll that has SkipVerification set to false } return s_serializationModule; } } private DynamicMethod _dynamicMethod; #endif private ILGenerator _ilGen; private List<ArgBuilder> _argList; private Stack<object> _blockStack; private Label _methodEndLabel; private Dictionary<LocalBuilder, string> _localNames = new Dictionary<LocalBuilder, string>(); private enum CodeGenTrace { None, Save, Tron }; private CodeGenTrace _codeGenTrace; #if !NET_NATIVE private LocalBuilder _stringFormatArray; #endif internal CodeGenerator() { //Defaulting to None as thats the default value in WCF _codeGenTrace = CodeGenTrace.None; } #if !USE_REFEMIT internal void BeginMethod(DynamicMethod dynamicMethod, Type delegateType, string methodName, Type[] argTypes, bool allowPrivateMemberAccess) { _dynamicMethod = dynamicMethod; _ilGen = _dynamicMethod.GetILGenerator(); _delegateType = delegateType; InitILGeneration(methodName, argTypes); } #endif internal void BeginMethod(string methodName, Type delegateType, bool allowPrivateMemberAccess) { MethodInfo signature = delegateType.GetMethod("Invoke"); ParameterInfo[] parameters = signature.GetParameters(); Type[] paramTypes = new Type[parameters.Length]; for (int i = 0; i < parameters.Length; i++) paramTypes[i] = parameters[i].ParameterType; BeginMethod(signature.ReturnType, methodName, paramTypes, allowPrivateMemberAccess); _delegateType = delegateType; } private void BeginMethod(Type returnType, string methodName, Type[] argTypes, bool allowPrivateMemberAccess) { #if USE_REFEMIT string typeName = "Type" + (typeCounter++); InitAssemblyBuilder(typeName + "." + methodName); this.typeBuilder = moduleBuilder.DefineType(typeName, TypeAttributes.Public); this.methodBuilder = typeBuilder.DefineMethod(methodName, MethodAttributes.Public|MethodAttributes.Static, returnType, argTypes); this.ilGen = this.methodBuilder.GetILGenerator(); #else _dynamicMethod = new DynamicMethod(methodName, returnType, argTypes, SerializationModule, allowPrivateMemberAccess); _ilGen = _dynamicMethod.GetILGenerator(); #endif InitILGeneration(methodName, argTypes); } private void InitILGeneration(string methodName, Type[] argTypes) { _methodEndLabel = _ilGen.DefineLabel(); _blockStack = new Stack<object>(); _argList = new List<ArgBuilder>(); for (int i = 0; i < argTypes.Length; i++) _argList.Add(new ArgBuilder(i, argTypes[i])); if (_codeGenTrace != CodeGenTrace.None) EmitSourceLabel("Begin method " + methodName + " {"); } internal Delegate EndMethod() { MarkLabel(_methodEndLabel); if (_codeGenTrace != CodeGenTrace.None) EmitSourceLabel("} End method"); Ret(); Delegate retVal = null; #if USE_REFEMIT Type type = typeBuilder.CreateType(); MethodInfo method = type.GetMethod(methodBuilder.Name); retVal = Delegate.CreateDelegate(delegateType, method); methodBuilder = null; #else retVal = _dynamicMethod.CreateDelegate(_delegateType); _dynamicMethod = null; #endif _delegateType = null; _ilGen = null; _blockStack = null; _argList = null; return retVal; } internal MethodInfo CurrentMethod { get { #if USE_REFEMIT return methodBuilder; #else return _dynamicMethod; #endif } } internal ArgBuilder GetArg(int index) { return (ArgBuilder)_argList[index]; } internal Type GetVariableType(object var) { if (var is ArgBuilder) return ((ArgBuilder)var).ArgType; else if (var is LocalBuilder) return ((LocalBuilder)var).LocalType; else return var.GetType(); } internal LocalBuilder DeclareLocal(Type type, string name, object initialValue) { LocalBuilder local = DeclareLocal(type, name); Load(initialValue); Store(local); return local; } internal LocalBuilder DeclareLocal(Type type, string name) { return DeclareLocal(type, name, false); } internal LocalBuilder DeclareLocal(Type type, string name, bool isPinned) { LocalBuilder local = _ilGen.DeclareLocal(type, isPinned); if (_codeGenTrace != CodeGenTrace.None) { _localNames[local] = name; EmitSourceComment("Declare local '" + name + "' of type " + type); } return local; } internal void Set(LocalBuilder local, object value) { Load(value); Store(local); } internal object For(LocalBuilder local, object start, object end) { ForState forState = new ForState(local, DefineLabel(), DefineLabel(), end); if (forState.Index != null) { Load(start); Stloc(forState.Index); Br(forState.TestLabel); } MarkLabel(forState.BeginLabel); _blockStack.Push(forState); return forState; } internal void EndFor() { object stackTop = _blockStack.Pop(); ForState forState = stackTop as ForState; if (forState == null) ThrowMismatchException(stackTop); if (forState.Index != null) { Ldloc(forState.Index); Ldc(1); Add(); Stloc(forState.Index); MarkLabel(forState.TestLabel); Ldloc(forState.Index); Load(forState.End); if (GetVariableType(forState.End).IsArray) Ldlen(); Blt(forState.BeginLabel); } else Br(forState.BeginLabel); if (forState.RequiresEndLabel) MarkLabel(forState.EndLabel); } internal void Break(object forState) { InternalBreakFor(forState, OpCodes.Br); } internal void IfFalseBreak(object forState) { InternalBreakFor(forState, OpCodes.Brfalse); } internal void InternalBreakFor(object userForState, OpCode branchInstruction) { foreach (object block in _blockStack) { ForState forState = block as ForState; if (forState != null && (object)forState == userForState) { if (!forState.RequiresEndLabel) { forState.EndLabel = DefineLabel(); forState.RequiresEndLabel = true; } if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction(branchInstruction + " " + forState.EndLabel.GetHashCode()); _ilGen.Emit(branchInstruction, forState.EndLabel); break; } } } internal void ForEach(LocalBuilder local, Type elementType, Type enumeratorType, LocalBuilder enumerator, MethodInfo getCurrentMethod) { ForState forState = new ForState(local, DefineLabel(), DefineLabel(), enumerator); Br(forState.TestLabel); MarkLabel(forState.BeginLabel); Call(enumerator, getCurrentMethod); ConvertValue(elementType, GetVariableType(local)); Stloc(local); _blockStack.Push(forState); } internal void EndForEach(MethodInfo moveNextMethod) { object stackTop = _blockStack.Pop(); ForState forState = stackTop as ForState; if (forState == null) ThrowMismatchException(stackTop); MarkLabel(forState.TestLabel); object enumerator = forState.End; Call(enumerator, moveNextMethod); Brtrue(forState.BeginLabel); if (forState.RequiresEndLabel) MarkLabel(forState.EndLabel); } internal void IfNotDefaultValue(object value) { Type type = GetVariableType(value); TypeCode typeCode = type.GetTypeCode(); if ((typeCode == TypeCode.Object && type.IsValueType) || typeCode == TypeCode.DateTime || typeCode == TypeCode.Decimal) { LoadDefaultValue(type); ConvertValue(type, Globals.TypeOfObject); Load(value); ConvertValue(type, Globals.TypeOfObject); Call(ObjectEquals); IfNot(); } else { LoadDefaultValue(type); Load(value); If(Cmp.NotEqualTo); } } internal void If() { InternalIf(false); } internal void IfNot() { InternalIf(true); } private OpCode GetBranchCode(Cmp cmp) { switch (cmp) { case Cmp.LessThan: return OpCodes.Bge; case Cmp.EqualTo: return OpCodes.Bne_Un; case Cmp.LessThanOrEqualTo: return OpCodes.Bgt; case Cmp.GreaterThan: return OpCodes.Ble; case Cmp.NotEqualTo: return OpCodes.Beq; default: DiagnosticUtility.DebugAssert(cmp == Cmp.GreaterThanOrEqualTo, "Unexpected cmp"); return OpCodes.Blt; } } internal void If(Cmp cmpOp) { IfState ifState = new IfState(); ifState.EndIf = DefineLabel(); ifState.ElseBegin = DefineLabel(); _ilGen.Emit(GetBranchCode(cmpOp), ifState.ElseBegin); _blockStack.Push(ifState); } internal void If(object value1, Cmp cmpOp, object value2) { Load(value1); Load(value2); If(cmpOp); } internal void Else() { IfState ifState = PopIfState(); Br(ifState.EndIf); MarkLabel(ifState.ElseBegin); ifState.ElseBegin = ifState.EndIf; _blockStack.Push(ifState); } internal void ElseIf(object value1, Cmp cmpOp, object value2) { IfState ifState = (IfState)_blockStack.Pop(); Br(ifState.EndIf); MarkLabel(ifState.ElseBegin); Load(value1); Load(value2); ifState.ElseBegin = DefineLabel(); _ilGen.Emit(GetBranchCode(cmpOp), ifState.ElseBegin); _blockStack.Push(ifState); } internal void EndIf() { IfState ifState = PopIfState(); if (!ifState.ElseBegin.Equals(ifState.EndIf)) MarkLabel(ifState.ElseBegin); MarkLabel(ifState.EndIf); } internal void VerifyParameterCount(MethodInfo methodInfo, int expectedCount) { if (methodInfo.GetParameters().Length != expectedCount) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ParameterCountMismatch, methodInfo.Name, methodInfo.GetParameters().Length, expectedCount))); } internal void Call(object thisObj, MethodInfo methodInfo) { VerifyParameterCount(methodInfo, 0); LoadThis(thisObj, methodInfo); Call(methodInfo); } internal void Call(object thisObj, MethodInfo methodInfo, object param1) { VerifyParameterCount(methodInfo, 1); LoadThis(thisObj, methodInfo); LoadParam(param1, 1, methodInfo); Call(methodInfo); } internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2) { VerifyParameterCount(methodInfo, 2); LoadThis(thisObj, methodInfo); LoadParam(param1, 1, methodInfo); LoadParam(param2, 2, methodInfo); Call(methodInfo); } internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2, object param3) { VerifyParameterCount(methodInfo, 3); LoadThis(thisObj, methodInfo); LoadParam(param1, 1, methodInfo); LoadParam(param2, 2, methodInfo); LoadParam(param3, 3, methodInfo); Call(methodInfo); } internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2, object param3, object param4) { VerifyParameterCount(methodInfo, 4); LoadThis(thisObj, methodInfo); LoadParam(param1, 1, methodInfo); LoadParam(param2, 2, methodInfo); LoadParam(param3, 3, methodInfo); LoadParam(param4, 4, methodInfo); Call(methodInfo); } internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2, object param3, object param4, object param5) { VerifyParameterCount(methodInfo, 5); LoadThis(thisObj, methodInfo); LoadParam(param1, 1, methodInfo); LoadParam(param2, 2, methodInfo); LoadParam(param3, 3, methodInfo); LoadParam(param4, 4, methodInfo); LoadParam(param5, 5, methodInfo); Call(methodInfo); } internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2, object param3, object param4, object param5, object param6) { VerifyParameterCount(methodInfo, 6); LoadThis(thisObj, methodInfo); LoadParam(param1, 1, methodInfo); LoadParam(param2, 2, methodInfo); LoadParam(param3, 3, methodInfo); LoadParam(param4, 4, methodInfo); LoadParam(param5, 5, methodInfo); LoadParam(param6, 6, methodInfo); Call(methodInfo); } internal void Call(MethodInfo methodInfo) { if (methodInfo.IsVirtual && !methodInfo.DeclaringType.IsValueType) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Callvirt " + methodInfo.ToString() + " on type " + methodInfo.DeclaringType.ToString()); _ilGen.Emit(OpCodes.Callvirt, methodInfo); } else if (methodInfo.IsStatic) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Static Call " + methodInfo.ToString() + " on type " + methodInfo.DeclaringType.ToString()); _ilGen.Emit(OpCodes.Call, methodInfo); } else { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Call " + methodInfo.ToString() + " on type " + methodInfo.DeclaringType.ToString()); _ilGen.Emit(OpCodes.Call, methodInfo); } } internal void Call(ConstructorInfo ctor) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Call " + ctor.ToString() + " on type " + ctor.DeclaringType.ToString()); _ilGen.Emit(OpCodes.Call, ctor); } internal void New(ConstructorInfo constructorInfo) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Newobj " + constructorInfo.ToString() + " on type " + constructorInfo.DeclaringType.ToString()); _ilGen.Emit(OpCodes.Newobj, constructorInfo); } internal void InitObj(Type valueType) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Initobj " + valueType); _ilGen.Emit(OpCodes.Initobj, valueType); } internal void NewArray(Type elementType, object len) { Load(len); if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Newarr " + elementType); _ilGen.Emit(OpCodes.Newarr, elementType); } internal void LoadArrayElement(object obj, object arrayIndex) { Type objType = GetVariableType(obj).GetElementType(); Load(obj); Load(arrayIndex); if (IsStruct(objType)) { Ldelema(objType); Ldobj(objType); } else Ldelem(objType); } internal void StoreArrayElement(object obj, object arrayIndex, object value) { Type arrayType = GetVariableType(obj); if (arrayType == Globals.TypeOfArray) { Call(obj, ArraySetValue, value, arrayIndex); } else { Type objType = arrayType.GetElementType(); Load(obj); Load(arrayIndex); if (IsStruct(objType)) Ldelema(objType); Load(value); ConvertValue(GetVariableType(value), objType); if (IsStruct(objType)) Stobj(objType); else Stelem(objType); } } private static bool IsStruct(Type objType) { return objType.IsValueType && !objType.IsPrimitive; } internal Type LoadMember(MemberInfo memberInfo) { Type memberType = null; if (memberInfo is FieldInfo) { FieldInfo fieldInfo = (FieldInfo)memberInfo; memberType = fieldInfo.FieldType; if (fieldInfo.IsStatic) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldsfld " + fieldInfo + " on type " + fieldInfo.DeclaringType); _ilGen.Emit(OpCodes.Ldsfld, fieldInfo); } else { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldfld " + fieldInfo + " on type " + fieldInfo.DeclaringType); _ilGen.Emit(OpCodes.Ldfld, fieldInfo); } } else if (memberInfo is PropertyInfo) { PropertyInfo property = memberInfo as PropertyInfo; memberType = property.PropertyType; if (property != null) { MethodInfo getMethod = property.GetMethod; if (getMethod == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.NoGetMethodForProperty, property.DeclaringType, property))); Call(getMethod); } } else if (memberInfo is MethodInfo) { MethodInfo method = (MethodInfo)memberInfo; memberType = method.ReturnType; Call(method); } else throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.CannotLoadMemberType, "Unknown", memberInfo.DeclaringType, memberInfo.Name))); EmitStackTop(memberType); return memberType; } internal void StoreMember(MemberInfo memberInfo) { if (memberInfo is FieldInfo) { FieldInfo fieldInfo = (FieldInfo)memberInfo; if (fieldInfo.IsStatic) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Stsfld " + fieldInfo + " on type " + fieldInfo.DeclaringType); _ilGen.Emit(OpCodes.Stsfld, fieldInfo); } else { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Stfld " + fieldInfo + " on type " + fieldInfo.DeclaringType); _ilGen.Emit(OpCodes.Stfld, fieldInfo); } } else if (memberInfo is PropertyInfo) { PropertyInfo property = memberInfo as PropertyInfo; if (property != null) { MethodInfo setMethod = property.SetMethod; if (setMethod == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.NoSetMethodForProperty, property.DeclaringType, property))); Call(setMethod); } } else if (memberInfo is MethodInfo) Call((MethodInfo)memberInfo); else throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.CannotLoadMemberType, "Unknown"))); } internal void LoadDefaultValue(Type type) { if (type.IsValueType) { switch (type.GetTypeCode()) { case TypeCode.Boolean: Ldc(false); break; case TypeCode.Char: case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: Ldc(0); break; case TypeCode.Int64: case TypeCode.UInt64: Ldc(0L); break; case TypeCode.Single: Ldc(0.0F); break; case TypeCode.Double: Ldc(0.0); break; case TypeCode.Decimal: case TypeCode.DateTime: default: LocalBuilder zero = DeclareLocal(type, "zero"); LoadAddress(zero); InitObj(type); Load(zero); break; } } else Load(null); } internal void Load(object obj) { if (obj == null) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldnull"); _ilGen.Emit(OpCodes.Ldnull); } else if (obj is ArgBuilder) Ldarg((ArgBuilder)obj); else if (obj is LocalBuilder) Ldloc((LocalBuilder)obj); else Ldc(obj); } internal void Store(object var) { if (var is ArgBuilder) Starg((ArgBuilder)var); else if (var is LocalBuilder) Stloc((LocalBuilder)var); else { DiagnosticUtility.DebugAssert("Data can only be stored into ArgBuilder or LocalBuilder."); throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.CanOnlyStoreIntoArgOrLocGot0, DataContract.GetClrTypeFullName(var.GetType())))); } } internal void Dec(object var) { Load(var); Load(1); Subtract(); Store(var); } internal void LoadAddress(object obj) { if (obj is ArgBuilder) LdargAddress((ArgBuilder)obj); else if (obj is LocalBuilder) LdlocAddress((LocalBuilder)obj); else Load(obj); } internal void ConvertAddress(Type source, Type target) { InternalConvert(source, target, true); } internal void ConvertValue(Type source, Type target) { InternalConvert(source, target, false); } internal void Castclass(Type target) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Castclass " + target); _ilGen.Emit(OpCodes.Castclass, target); } internal void Box(Type type) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Box " + type); _ilGen.Emit(OpCodes.Box, type); } internal void Unbox(Type type) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Unbox " + type); _ilGen.Emit(OpCodes.Unbox, type); } private OpCode GetLdindOpCode(TypeCode typeCode) { switch (typeCode) { case TypeCode.Boolean: return OpCodes.Ldind_I1; // TypeCode.Boolean: case TypeCode.Char: return OpCodes.Ldind_I2; // TypeCode.Char: case TypeCode.SByte: return OpCodes.Ldind_I1; // TypeCode.SByte: case TypeCode.Byte: return OpCodes.Ldind_U1; // TypeCode.Byte: case TypeCode.Int16: return OpCodes.Ldind_I2; // TypeCode.Int16: case TypeCode.UInt16: return OpCodes.Ldind_U2; // TypeCode.UInt16: case TypeCode.Int32: return OpCodes.Ldind_I4; // TypeCode.Int32: case TypeCode.UInt32: return OpCodes.Ldind_U4; // TypeCode.UInt32: case TypeCode.Int64: return OpCodes.Ldind_I8; // TypeCode.Int64: case TypeCode.UInt64: return OpCodes.Ldind_I8; // TypeCode.UInt64: case TypeCode.Single: return OpCodes.Ldind_R4; // TypeCode.Single: case TypeCode.Double: return OpCodes.Ldind_R8; // TypeCode.Double: case TypeCode.String: return OpCodes.Ldind_Ref; // TypeCode.String: default: return OpCodes.Nop; } } internal void Ldobj(Type type) { OpCode opCode = GetLdindOpCode(type.GetTypeCode()); if (!opCode.Equals(OpCodes.Nop)) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction(opCode.ToString()); _ilGen.Emit(opCode); } else { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldobj " + type); _ilGen.Emit(OpCodes.Ldobj, type); } } internal void Stobj(Type type) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Stobj " + type); _ilGen.Emit(OpCodes.Stobj, type); } internal void Ceq() { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ceq"); _ilGen.Emit(OpCodes.Ceq); } internal void Throw() { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Throw"); _ilGen.Emit(OpCodes.Throw); } internal void Ldtoken(Type t) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldtoken " + t); _ilGen.Emit(OpCodes.Ldtoken, t); } internal void Ldc(object o) { Type valueType = o.GetType(); if (o is Type) { Ldtoken((Type)o); Call(GetTypeFromHandle); } else if (valueType.IsEnum) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceComment("Ldc " + o.GetType() + "." + o); Ldc(Convert.ChangeType(o, Enum.GetUnderlyingType(valueType), null)); } else { switch (valueType.GetTypeCode()) { case TypeCode.Boolean: Ldc((bool)o); break; case TypeCode.Char: DiagnosticUtility.DebugAssert("Char is not a valid schema primitive and should be treated as int in DataContract"); throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.CharIsInvalidPrimitive))); case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: Ldc(Convert.ToInt32(o, CultureInfo.InvariantCulture)); break; case TypeCode.Int32: Ldc((int)o); break; case TypeCode.UInt32: Ldc((int)(uint)o); break; case TypeCode.UInt64: Ldc((long)(ulong)o); break; case TypeCode.Int64: Ldc((long)o); break; case TypeCode.Single: Ldc((float)o); break; case TypeCode.Double: Ldc((double)o); break; case TypeCode.String: Ldstr((string)o); break; case TypeCode.Object: case TypeCode.Decimal: case TypeCode.DateTime: case TypeCode.Empty: default: throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.UnknownConstantType, DataContract.GetClrTypeFullName(valueType)))); } } } internal void Ldc(bool boolVar) { if (boolVar) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldc.i4 1"); _ilGen.Emit(OpCodes.Ldc_I4_1); } else { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldc.i4 0"); _ilGen.Emit(OpCodes.Ldc_I4_0); } } internal void Ldc(int intVar) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldc.i4 " + intVar); switch (intVar) { case -1: _ilGen.Emit(OpCodes.Ldc_I4_M1); break; case 0: _ilGen.Emit(OpCodes.Ldc_I4_0); break; case 1: _ilGen.Emit(OpCodes.Ldc_I4_1); break; case 2: _ilGen.Emit(OpCodes.Ldc_I4_2); break; case 3: _ilGen.Emit(OpCodes.Ldc_I4_3); break; case 4: _ilGen.Emit(OpCodes.Ldc_I4_4); break; case 5: _ilGen.Emit(OpCodes.Ldc_I4_5); break; case 6: _ilGen.Emit(OpCodes.Ldc_I4_6); break; case 7: _ilGen.Emit(OpCodes.Ldc_I4_7); break; case 8: _ilGen.Emit(OpCodes.Ldc_I4_8); break; default: _ilGen.Emit(OpCodes.Ldc_I4, intVar); break; } } internal void Ldc(long l) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldc.i8 " + l); _ilGen.Emit(OpCodes.Ldc_I8, l); } internal void Ldc(float f) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldc.r4 " + f); _ilGen.Emit(OpCodes.Ldc_R4, f); } internal void Ldc(double d) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldc.r8 " + d); _ilGen.Emit(OpCodes.Ldc_R8, d); } internal void Ldstr(string strVar) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldstr " + strVar); _ilGen.Emit(OpCodes.Ldstr, strVar); } internal void LdlocAddress(LocalBuilder localBuilder) { if (localBuilder.LocalType.IsValueType) Ldloca(localBuilder); else Ldloc(localBuilder); } internal void Ldloc(LocalBuilder localBuilder) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldloc " + _localNames[localBuilder]); _ilGen.Emit(OpCodes.Ldloc, localBuilder); EmitStackTop(localBuilder.LocalType); } internal void Stloc(LocalBuilder local) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Stloc " + _localNames[local]); EmitStackTop(local.LocalType); _ilGen.Emit(OpCodes.Stloc, local); } internal void Ldloca(LocalBuilder localBuilder) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldloca " + _localNames[localBuilder]); _ilGen.Emit(OpCodes.Ldloca, localBuilder); EmitStackTop(localBuilder.LocalType); } internal void LdargAddress(ArgBuilder argBuilder) { if (argBuilder.ArgType.IsValueType) Ldarga(argBuilder); else Ldarg(argBuilder); } internal void Ldarg(ArgBuilder arg) { Ldarg(arg.Index); } internal void Starg(ArgBuilder arg) { Starg(arg.Index); } internal void Ldarg(int slot) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldarg " + slot); switch (slot) { case 0: _ilGen.Emit(OpCodes.Ldarg_0); break; case 1: _ilGen.Emit(OpCodes.Ldarg_1); break; case 2: _ilGen.Emit(OpCodes.Ldarg_2); break; case 3: _ilGen.Emit(OpCodes.Ldarg_3); break; default: if (slot <= 255) _ilGen.Emit(OpCodes.Ldarg_S, slot); else _ilGen.Emit(OpCodes.Ldarg, slot); break; } } internal void Starg(int slot) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Starg " + slot); if (slot <= 255) _ilGen.Emit(OpCodes.Starg_S, slot); else _ilGen.Emit(OpCodes.Starg, slot); } internal void Ldarga(ArgBuilder argBuilder) { Ldarga(argBuilder.Index); } internal void Ldarga(int slot) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldarga " + slot); if (slot <= 255) _ilGen.Emit(OpCodes.Ldarga_S, slot); else _ilGen.Emit(OpCodes.Ldarga, slot); } internal void Ldlen() { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ldlen"); _ilGen.Emit(OpCodes.Ldlen); if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Conv.i4"); _ilGen.Emit(OpCodes.Conv_I4); } private OpCode GetLdelemOpCode(TypeCode typeCode) { switch (typeCode) { case TypeCode.Object: return OpCodes.Ldelem_Ref;// TypeCode.Object: case TypeCode.Boolean: return OpCodes.Ldelem_I1;// TypeCode.Boolean: case TypeCode.Char: return OpCodes.Ldelem_I2;// TypeCode.Char: case TypeCode.SByte: return OpCodes.Ldelem_I1;// TypeCode.SByte: case TypeCode.Byte: return OpCodes.Ldelem_U1;// TypeCode.Byte: case TypeCode.Int16: return OpCodes.Ldelem_I2;// TypeCode.Int16: case TypeCode.UInt16: return OpCodes.Ldelem_U2;// TypeCode.UInt16: case TypeCode.Int32: return OpCodes.Ldelem_I4;// TypeCode.Int32: case TypeCode.UInt32: return OpCodes.Ldelem_U4;// TypeCode.UInt32: case TypeCode.Int64: return OpCodes.Ldelem_I8;// TypeCode.Int64: case TypeCode.UInt64: return OpCodes.Ldelem_I8;// TypeCode.UInt64: case TypeCode.Single: return OpCodes.Ldelem_R4;// TypeCode.Single: case TypeCode.Double: return OpCodes.Ldelem_R8;// TypeCode.Double: case TypeCode.String: return OpCodes.Ldelem_Ref;// TypeCode.String: default: return OpCodes.Nop; } } internal void Ldelem(Type arrayElementType) { if (arrayElementType.IsEnum) { Ldelem(Enum.GetUnderlyingType(arrayElementType)); } else { OpCode opCode = GetLdelemOpCode(arrayElementType.GetTypeCode()); if (opCode.Equals(OpCodes.Nop)) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ArrayTypeIsNotSupported, DataContract.GetClrTypeFullName(arrayElementType)))); if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction(opCode.ToString()); _ilGen.Emit(opCode); EmitStackTop(arrayElementType); } } internal void Ldelema(Type arrayElementType) { OpCode opCode = OpCodes.Ldelema; if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction(opCode.ToString()); _ilGen.Emit(opCode, arrayElementType); EmitStackTop(arrayElementType); } private OpCode GetStelemOpCode(TypeCode typeCode) { switch (typeCode) { case TypeCode.Object: return OpCodes.Stelem_Ref;// TypeCode.Object: case TypeCode.Boolean: return OpCodes.Stelem_I1;// TypeCode.Boolean: case TypeCode.Char: return OpCodes.Stelem_I2;// TypeCode.Char: case TypeCode.SByte: return OpCodes.Stelem_I1;// TypeCode.SByte: case TypeCode.Byte: return OpCodes.Stelem_I1;// TypeCode.Byte: case TypeCode.Int16: return OpCodes.Stelem_I2;// TypeCode.Int16: case TypeCode.UInt16: return OpCodes.Stelem_I2;// TypeCode.UInt16: case TypeCode.Int32: return OpCodes.Stelem_I4;// TypeCode.Int32: case TypeCode.UInt32: return OpCodes.Stelem_I4;// TypeCode.UInt32: case TypeCode.Int64: return OpCodes.Stelem_I8;// TypeCode.Int64: case TypeCode.UInt64: return OpCodes.Stelem_I8;// TypeCode.UInt64: case TypeCode.Single: return OpCodes.Stelem_R4;// TypeCode.Single: case TypeCode.Double: return OpCodes.Stelem_R8;// TypeCode.Double: case TypeCode.String: return OpCodes.Stelem_Ref;// TypeCode.String: default: return OpCodes.Nop; } } internal void Stelem(Type arrayElementType) { if (arrayElementType.IsEnum) Stelem(Enum.GetUnderlyingType(arrayElementType)); else { OpCode opCode = GetStelemOpCode(arrayElementType.GetTypeCode()); if (opCode.Equals(OpCodes.Nop)) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ArrayTypeIsNotSupported, DataContract.GetClrTypeFullName(arrayElementType)))); if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction(opCode.ToString()); EmitStackTop(arrayElementType); _ilGen.Emit(opCode); } } internal Label DefineLabel() { return _ilGen.DefineLabel(); } internal void MarkLabel(Label label) { _ilGen.MarkLabel(label); if (_codeGenTrace != CodeGenTrace.None) EmitSourceLabel(label.GetHashCode() + ":"); } internal void Add() { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Add"); _ilGen.Emit(OpCodes.Add); } internal void Subtract() { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Sub"); _ilGen.Emit(OpCodes.Sub); } internal void And() { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("And"); _ilGen.Emit(OpCodes.And); } internal void Or() { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Or"); _ilGen.Emit(OpCodes.Or); } internal void Not() { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Not"); _ilGen.Emit(OpCodes.Not); } internal void Ret() { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Ret"); _ilGen.Emit(OpCodes.Ret); } internal void Br(Label label) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Br " + label.GetHashCode()); _ilGen.Emit(OpCodes.Br, label); } internal void Blt(Label label) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Blt " + label.GetHashCode()); _ilGen.Emit(OpCodes.Blt, label); } internal void Brfalse(Label label) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Brfalse " + label.GetHashCode()); _ilGen.Emit(OpCodes.Brfalse, label); } internal void Brtrue(Label label) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Brtrue " + label.GetHashCode()); _ilGen.Emit(OpCodes.Brtrue, label); } internal void Pop() { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Pop"); _ilGen.Emit(OpCodes.Pop); } internal void Dup() { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Dup"); _ilGen.Emit(OpCodes.Dup); } private void LoadThis(object thisObj, MethodInfo methodInfo) { if (thisObj != null && !methodInfo.IsStatic) { LoadAddress(thisObj); ConvertAddress(GetVariableType(thisObj), methodInfo.DeclaringType); } } private void LoadParam(object arg, int oneBasedArgIndex, MethodBase methodInfo) { Load(arg); if (arg != null) ConvertValue(GetVariableType(arg), methodInfo.GetParameters()[oneBasedArgIndex - 1].ParameterType); } private void InternalIf(bool negate) { IfState ifState = new IfState(); ifState.EndIf = DefineLabel(); ifState.ElseBegin = DefineLabel(); if (negate) Brtrue(ifState.ElseBegin); else Brfalse(ifState.ElseBegin); _blockStack.Push(ifState); } private OpCode GetConvOpCode(TypeCode typeCode) { switch (typeCode) { case TypeCode.Boolean: return OpCodes.Conv_I1;// TypeCode.Boolean: case TypeCode.Char: return OpCodes.Conv_I2;// TypeCode.Char: case TypeCode.SByte: return OpCodes.Conv_I1;// TypeCode.SByte: case TypeCode.Byte: return OpCodes.Conv_U1;// TypeCode.Byte: case TypeCode.Int16: return OpCodes.Conv_I2;// TypeCode.Int16: case TypeCode.UInt16: return OpCodes.Conv_U2;// TypeCode.UInt16: case TypeCode.Int32: return OpCodes.Conv_I4;// TypeCode.Int32: case TypeCode.UInt32: return OpCodes.Conv_U4;// TypeCode.UInt32: case TypeCode.Int64: return OpCodes.Conv_I8;// TypeCode.Int64: case TypeCode.UInt64: return OpCodes.Conv_I8;// TypeCode.UInt64: case TypeCode.Single: return OpCodes.Conv_R4;// TypeCode.Single: case TypeCode.Double: return OpCodes.Conv_R8;// TypeCode.Double: default: return OpCodes.Nop; } } private void InternalConvert(Type source, Type target, bool isAddress) { if (target == source) return; if (target.IsValueType) { if (source.IsValueType) { OpCode opCode = GetConvOpCode(target.GetTypeCode()); if (opCode.Equals(OpCodes.Nop)) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.NoConversionPossibleTo, DataContract.GetClrTypeFullName(target)))); else { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction(opCode.ToString()); _ilGen.Emit(opCode); } } else if (source.IsAssignableFrom(target)) { Unbox(target); if (!isAddress) Ldobj(target); } else throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IsNotAssignableFrom, DataContract.GetClrTypeFullName(target), DataContract.GetClrTypeFullName(source)))); } else if (target.IsAssignableFrom(source)) { if (source.IsValueType) { if (isAddress) Ldobj(source); Box(source); } } else if (source.IsAssignableFrom(target)) { Castclass(target); } else if (target.IsInterface || source.IsInterface) { Castclass(target); } else throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IsNotAssignableFrom, DataContract.GetClrTypeFullName(target), DataContract.GetClrTypeFullName(source)))); } private IfState PopIfState() { object stackTop = _blockStack.Pop(); IfState ifState = stackTop as IfState; if (ifState == null) ThrowMismatchException(stackTop); return ifState; } #if USE_REFEMIT void InitAssemblyBuilder(string methodName) { AssemblyName name = new AssemblyName(); name.Name = "Microsoft.GeneratedCode."+methodName; //Add SecurityCritical and SecurityTreatAsSafe attributes to the generated method assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run); moduleBuilder = assemblyBuilder.DefineDynamicModule(name.Name + ".dll", false); } #endif private void ThrowMismatchException(object expected) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ExpectingEnd, expected.ToString()))); } [Conditional("NOT_SILVERLIGHT")] internal void EmitSourceInstruction(string line) { } [Conditional("NOT_SILVERLIGHT")] internal void EmitSourceLabel(string line) { } [Conditional("NOT_SILVERLIGHT")] internal void EmitSourceComment(string comment) { } internal void EmitStackTop(Type stackTopType) { if (_codeGenTrace != CodeGenTrace.Tron) return; } internal Label[] Switch(int labelCount) { SwitchState switchState = new SwitchState(DefineLabel(), DefineLabel()); Label[] caseLabels = new Label[labelCount]; for (int i = 0; i < caseLabels.Length; i++) caseLabels[i] = DefineLabel(); _ilGen.Emit(OpCodes.Switch, caseLabels); Br(switchState.DefaultLabel); _blockStack.Push(switchState); return caseLabels; } internal void Case(Label caseLabel1, string caseLabelName) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("case " + caseLabelName + "{"); MarkLabel(caseLabel1); } internal void EndCase() { object stackTop = _blockStack.Peek(); SwitchState switchState = stackTop as SwitchState; if (switchState == null) ThrowMismatchException(stackTop); Br(switchState.EndOfSwitchLabel); if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("} //end case "); } internal void EndSwitch() { object stackTop = _blockStack.Pop(); SwitchState switchState = stackTop as SwitchState; if (switchState == null) ThrowMismatchException(stackTop); if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("} //end switch"); if (!switchState.DefaultDefined) MarkLabel(switchState.DefaultLabel); MarkLabel(switchState.EndOfSwitchLabel); } private static MethodInfo s_stringLength = typeof(string).GetProperty("Length").GetMethod; internal void ElseIfIsEmptyString(LocalBuilder strLocal) { IfState ifState = (IfState)_blockStack.Pop(); Br(ifState.EndIf); MarkLabel(ifState.ElseBegin); Load(strLocal); Call(s_stringLength); Load(0); ifState.ElseBegin = DefineLabel(); _ilGen.Emit(GetBranchCode(Cmp.EqualTo), ifState.ElseBegin); _blockStack.Push(ifState); } internal void IfNotIsEmptyString(LocalBuilder strLocal) { Load(strLocal); Call(s_stringLength); Load(0); If(Cmp.NotEqualTo); } #if !NET_NATIVE internal void BeginWhileCondition() { Label startWhile = DefineLabel(); MarkLabel(startWhile); _blockStack.Push(startWhile); } internal void BeginWhileBody(Cmp cmpOp) { Label startWhile = (Label)_blockStack.Pop(); If(cmpOp); _blockStack.Push(startWhile); } internal void EndWhile() { Label startWhile = (Label)_blockStack.Pop(); Br(startWhile); EndIf(); } internal void CallStringFormat(string msg, params object[] values) { NewArray(typeof(object), values.Length); if (_stringFormatArray == null) _stringFormatArray = DeclareLocal(typeof(object[]), "stringFormatArray"); Stloc(_stringFormatArray); for (int i = 0; i < values.Length; i++) StoreArrayElement(_stringFormatArray, i, values[i]); Load(msg); Load(_stringFormatArray); Call(StringFormat); } internal void ToString(Type type) { if (type != Globals.TypeOfString) { if (type.IsValueType) { Box(type); } Call(ObjectToString); } } #endif } internal class ArgBuilder { internal int Index; internal Type ArgType; internal ArgBuilder(int index, Type argType) { this.Index = index; this.ArgType = argType; } } internal class ForState { private LocalBuilder _indexVar; private Label _beginLabel; private Label _testLabel; private Label _endLabel; private bool _requiresEndLabel; private object _end; internal ForState(LocalBuilder indexVar, Label beginLabel, Label testLabel, object end) { _indexVar = indexVar; _beginLabel = beginLabel; _testLabel = testLabel; _end = end; } internal LocalBuilder Index { get { return _indexVar; } } internal Label BeginLabel { get { return _beginLabel; } } internal Label TestLabel { get { return _testLabel; } } internal Label EndLabel { get { return _endLabel; } set { _endLabel = value; } } internal bool RequiresEndLabel { get { return _requiresEndLabel; } set { _requiresEndLabel = value; } } internal object End { get { return _end; } } } internal enum Cmp { LessThan, EqualTo, LessThanOrEqualTo, GreaterThan, NotEqualTo, GreaterThanOrEqualTo } internal class IfState { private Label _elseBegin; private Label _endIf; internal Label EndIf { get { return _endIf; } set { _endIf = value; } } internal Label ElseBegin { get { return _elseBegin; } set { _elseBegin = value; } } } internal class SwitchState { private Label _defaultLabel; private Label _endOfSwitchLabel; private bool _defaultDefined; internal SwitchState(Label defaultLabel, Label endOfSwitchLabel) { _defaultLabel = defaultLabel; _endOfSwitchLabel = endOfSwitchLabel; _defaultDefined = false; } internal Label DefaultLabel { get { return _defaultLabel; } } internal Label EndOfSwitchLabel { get { return _endOfSwitchLabel; } } internal bool DefaultDefined { get { return _defaultDefined; } set { _defaultDefined = value; } } } } #endif
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using Google.GData.Client; using Google.GData.Extensions; using Google.GData.Calendar; namespace SampleApp { /// <summary> /// Summary description for Calendar. /// </summary> public class Calendar : System.Windows.Forms.Form { private System.Windows.Forms.TextBox CalendarURI; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox UserName; private System.Windows.Forms.TextBox Password; private System.Windows.Forms.Button Go; private System.Windows.Forms.MonthCalendar calendarControl; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; private System.Windows.Forms.ListView DayEvents; private System.Windows.Forms.ColumnHeader columnHeader1; private System.Windows.Forms.ColumnHeader columnHeader2; private System.Windows.Forms.ColumnHeader columnHeader3; private System.Windows.Forms.ColumnHeader columnHeader4; private ArrayList entryList; public Calendar() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // this.entryList = new ArrayList(); } /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.Run(new Calendar()); } /// <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 Windows Form 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.calendarControl = new System.Windows.Forms.MonthCalendar(); this.CalendarURI = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.UserName = new System.Windows.Forms.TextBox(); this.Password = new System.Windows.Forms.TextBox(); this.Go = new System.Windows.Forms.Button(); this.DayEvents = new System.Windows.Forms.ListView(); this.columnHeader1 = new System.Windows.Forms.ColumnHeader(); this.columnHeader2 = new System.Windows.Forms.ColumnHeader(); this.columnHeader3 = new System.Windows.Forms.ColumnHeader(); this.columnHeader4 = new System.Windows.Forms.ColumnHeader(); this.SuspendLayout(); // // calendarControl // this.calendarControl.Location = new System.Drawing.Point(0, 8); this.calendarControl.Name = "calendarControl"; this.calendarControl.ShowTodayCircle = false; this.calendarControl.TabIndex = 0; this.calendarControl.DateSelected += new System.Windows.Forms.DateRangeEventHandler(this.calendarControl_DateSelected); // // CalendarURI // this.CalendarURI.Location = new System.Drawing.Point(280, 32); this.CalendarURI.Name = "CalendarURI"; this.CalendarURI.Size = new System.Drawing.Size(296, 20); this.CalendarURI.TabIndex = 1; this.CalendarURI.Text = "https://www.google.com/calendar/feeds/default/private/full"; // // label1 // this.label1.Location = new System.Drawing.Point(200, 32); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(64, 16); this.label1.TabIndex = 2; this.label1.Text = "URL:"; // // label2 // this.label2.Location = new System.Drawing.Point(200, 68); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(64, 24); this.label2.TabIndex = 3; this.label2.Text = "User:"; // // label3 // this.label3.Location = new System.Drawing.Point(200, 112); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(64, 16); this.label3.TabIndex = 4; this.label3.Text = "Password"; // // UserName // this.UserName.Location = new System.Drawing.Point(280, 68); this.UserName.Name = "UserName"; this.UserName.Size = new System.Drawing.Size(296, 20); this.UserName.TabIndex = 5; this.UserName.Text = "sample@gmail.com"; // // Password // this.Password.Location = new System.Drawing.Point(280, 104); this.Password.Name = "Password"; this.Password.PasswordChar = '*'; this.Password.Size = new System.Drawing.Size(296, 20); this.Password.TabIndex = 6; this.Password.Text = ""; // // Go // this.Go.FlatStyle = System.Windows.Forms.FlatStyle.Popup; this.Go.Location = new System.Drawing.Point(480, 208); this.Go.Name = "Go"; this.Go.Size = new System.Drawing.Size(96, 24); this.Go.TabIndex = 7; this.Go.Text = "&Go"; this.Go.Click += new System.EventHandler(this.Go_Click); // // DayEvents // this.DayEvents.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeader1, this.columnHeader2, this.columnHeader3, this.columnHeader4}); this.DayEvents.FullRowSelect = true; this.DayEvents.GridLines = true; this.DayEvents.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable; this.DayEvents.LabelWrap = false; this.DayEvents.Location = new System.Drawing.Point(8, 184); this.DayEvents.Name = "DayEvents"; this.DayEvents.Size = new System.Drawing.Size(424, 88); this.DayEvents.TabIndex = 8; this.DayEvents.View = System.Windows.Forms.View.Details; // // columnHeader1 // this.columnHeader1.Text = "Event"; this.columnHeader1.Width = 200; // // columnHeader2 // this.columnHeader2.Text = "Author"; this.columnHeader2.Width = 100; // // columnHeader3 // this.columnHeader3.Text = "Start"; // // columnHeader4 // this.columnHeader4.Text = "End"; // // Calendar // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(592, 278); this.Controls.Add(this.DayEvents); this.Controls.Add(this.Go); this.Controls.Add(this.Password); this.Controls.Add(this.UserName); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.CalendarURI); this.Controls.Add(this.calendarControl); this.Cursor = System.Windows.Forms.Cursors.Arrow; this.Name = "Calendar"; this.Text = "Google Calendar Demo Application"; this.ResumeLayout(false); } #endregion private void textBox1_TextChanged(object sender, System.EventArgs e) { } private void Go_Click(object sender, System.EventArgs e) { RefreshFeed(); } private void RefreshFeed() { string calendarURI = this.CalendarURI.Text; string userName = this.UserName.Text; string passWord = this.Password.Text; this.entryList = new ArrayList(50); ArrayList dates = new ArrayList(50); EventQuery query = new EventQuery(); CalendarService service = new CalendarService("CalendarSampleApp"); if (userName != null && userName.Length > 0) { service.setUserCredentials(userName, passWord); } // only get event's for today - 1 month until today + 1 year query.Uri = new Uri(calendarURI); query.StartTime = DateTime.Now.AddDays(-28); query.EndTime = DateTime.Now.AddMonths(6); EventFeed calFeed = service.Query(query) as EventFeed; // now populate the calendar while (calFeed != null && calFeed.Entries.Count > 0) { // look for the one with dinner time... foreach (EventEntry entry in calFeed.Entries) { this.entryList.Add(entry); if (entry.Times.Count > 0) { foreach (When w in entry.Times) { dates.Add(w.StartTime); } } } // just query the same query again. if (calFeed.NextChunk != null) { query.Uri = new Uri(calFeed.NextChunk); calFeed = service.Query(query) as EventFeed; } else calFeed = null; } DateTime[] aDates = new DateTime[dates.Count]; int i =0; foreach (DateTime d in dates) { aDates[i++] = d; } this.calendarControl.BoldedDates = aDates; } private void calendarControl_DateSelected(object sender, System.Windows.Forms.DateRangeEventArgs e) { this.DayEvents.Items.Clear(); ArrayList results = new ArrayList(5); foreach (EventEntry entry in this.entryList) { // let's find the entries for that date if (entry.Times.Count > 0) { foreach (When w in entry.Times) { if (e.Start.Date == w.StartTime.Date || e.Start.Date == w.EndTime.Date) { results.Add(entry); break; } } } } foreach (EventEntry entry in results) { ListViewItem item = new ListViewItem(entry.Title.Text); item.SubItems.Add(entry.Authors[0].Name); if (entry.Times.Count > 0) { item.SubItems.Add(entry.Times[0].StartTime.TimeOfDay.ToString()); item.SubItems.Add(entry.Times[0].EndTime.TimeOfDay.ToString()); } this.DayEvents.Items.Add(item); } } } }
using System; using System.Threading; using System.Runtime.InteropServices; using System.Runtime.Remoting; using System.Runtime.Remoting.Messaging; using System.Runtime.Remoting.Proxies; class MyProxy : RealProxy { readonly MarshalByRefObject target; public MyProxy (MarshalByRefObject target) : base (target.GetType()) { this.target = target; } public override IMessage Invoke (IMessage request) { IMethodCallMessage call = (IMethodCallMessage)request; Console.WriteLine ("Invoke " + call.MethodName); Console.Write ("ARGS("); for (int i = 0; i < call.ArgCount; i++) { if (i != 0) Console.Write (", "); Console.Write (call.GetArgName (i) + " " + call.GetArg (i)); } Console.WriteLine (")"); Console.Write ("INARGS("); for (int i = 0; i < call.InArgCount; i++) { if (i != 0) Console.Write (", "); Console.Write (call.GetInArgName (i) + " " + call.GetInArg (i)); } Console.WriteLine (")"); IMethodReturnMessage res = RemotingServices.ExecuteMessage (target, call); Console.Write ("RESARGS("); for (int i = 0; i < res.ArgCount; i++) { if (i != 0) Console.Write (", "); Console.Write (res.GetArgName (i) + " " + res.GetArg (i)); } Console.WriteLine (")"); Console.Write ("RESOUTARGS("); for (int i = 0; i < res.OutArgCount; i++) { if (i != 0) Console.Write (", "); Console.Write (res.GetOutArgName (i) + " " + res.GetOutArg (i)); } Console.WriteLine (")"); return res; } } public class EmptyProxy : RealProxy { public EmptyProxy ( Type type ) : base( type ) { } public override IMessage Invoke( IMessage msg ) { IMethodCallMessage call = (IMethodCallMessage)msg; return new ReturnMessage( null, null, 0, null, call ); } } public struct MyStruct { public int a; public int b; public int c; } interface R2 { } class R1 : MarshalByRefObject, R2 { public int test_field = 5; public object null_test_field; public virtual MyStruct Add (int a, out int c, int b) { Console.WriteLine ("ADD"); c = a + b; MyStruct res = new MyStruct (); res.a = a; res.b = b; res.c = c; return res; } public long nonvirtual_Add (int a, int b) { Console.WriteLine ("nonvirtual_Add " + a + " + " + b); return a + b; } } class R3 : MarshalByRefObject { public object anObject; } class Test { delegate MyStruct RemoteDelegate1 (int a, out int c, int b); delegate long RemoteDelegate2 (int a, int b); static long test_call (R1 o) { return o.nonvirtual_Add (2, 3); } static int Main () { R1 myobj = new R1 (); int res = 0; long lres; MyProxy real_proxy = new MyProxy (myobj); R1 o = (R1)real_proxy.GetTransparentProxy (); if (RemotingServices.IsTransparentProxy (null)) return 1; if (!RemotingServices.IsTransparentProxy (o)) return 2; Console.WriteLine ("XXXXXXXXXXXX: " + RemotingServices.GetRealProxy (o)); if (o.GetType () != myobj.GetType ()) return 3; MyStruct myres = o.Add (2, out res, 3); Console.WriteLine ("Result: " + myres.a + " " + myres.b + " " + myres.c + " " + res); if (myres.a != 2) return 4; if (myres.b != 3) return 5; if (myres.c != 5) return 6; if (res != 5) return 7; R1 o2 = new R1 (); lres = test_call (o2); lres = test_call (o); Console.WriteLine ("Result: " + lres); if (lres != 5) return 8; lres = test_call (o); o.test_field = 2; Console.WriteLine ("test_field: " + o.test_field); if (o.test_field != 2) return 9; RemoteDelegate1 d1 = new RemoteDelegate1 (o.Add); MyStruct myres2 = d1 (2, out res, 3); Console.WriteLine ("Result: " + myres2.a + " " + myres2.b + " " + myres2.c + " " + res); if (myres2.a != 2) return 10; if (myres2.b != 3) return 11; if (myres2.c != 5) return 12; if (res != 5) return 13; RemoteDelegate2 d2 = new RemoteDelegate2 (o.nonvirtual_Add); d2 (6, 7); if (!(real_proxy.GetTransparentProxy () is R2)) return 14; /* Test what happens if the proxy doesn't return the required information */ EmptyProxy handler = new EmptyProxy ( typeof (R3) ); R3 o3 = (R3)handler.GetTransparentProxy(); if (o3.anObject != null) return 15; if (o.null_test_field != null) return 16; return 0; } }
// 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.Globalization; using Xunit; public static class DoubleTests { [Fact] public static void TestCtor() { Double i = new Double(); Assert.True(i == 0); i = 41; Assert.True(i == 41); i = (Double)41.3; Assert.True(i == (Double)41.3); } [Fact] public static void TestMaxValue() { Double max = Double.MaxValue; Assert.True(max == (Double)1.7976931348623157E+308); } [Fact] public static void TestMinValue() { Double min = Double.MinValue; Assert.True(min == ((Double)(-1.7976931348623157E+308))); } [Fact] public static void TestEpsilon() { // Double Double.Epsilon Assert.Equal<Double>((Double)4.9406564584124654E-324, Double.Epsilon); } [Fact] public static void TestIsInfinity() { // Boolean Double.IsInfinity(Double) Assert.True(Double.IsInfinity(Double.NegativeInfinity)); Assert.True(Double.IsInfinity(Double.PositiveInfinity)); } [Fact] public static void TestNaN() { // Double Double.NaN Assert.Equal<Double>((Double)0.0 / (Double)0.0, Double.NaN); } [Fact] public static void TestIsNaN() { // Boolean Double.IsNaN(Double) Assert.True(Double.IsNaN(Double.NaN)); } [Fact] public static void TestNegativeInfinity() { // Double Double.NegativeInfinity Assert.Equal<Double>((Double)(-1.0) / (Double)0.0, Double.NegativeInfinity); } [Fact] public static void TestIsNegativeInfinity() { // Boolean Double.IsNegativeInfinity(Double) Assert.True(Double.IsNegativeInfinity(Double.NegativeInfinity)); } [Fact] public static void TestPositiveInfinity() { // Double Double.PositiveInfinity Assert.Equal<Double>((Double)1.0 / (Double)0.0, Double.PositiveInfinity); } [Fact] public static void TestIsPositiveInfinity() { // Boolean Double.IsPositiveInfinity(Double) Assert.True(Double.IsPositiveInfinity(Double.PositiveInfinity)); } [Fact] public static void TestCompareToObject() { Double i = 234; IComparable comparable = i; Assert.Equal(1, comparable.CompareTo(null)); Assert.Equal(0, comparable.CompareTo((Double)234)); Assert.True(comparable.CompareTo(Double.MinValue) > 0); Assert.True(comparable.CompareTo((Double)0) > 0); Assert.True(comparable.CompareTo((Double)(-123)) > 0); Assert.True(comparable.CompareTo((Double)123) > 0); Assert.True(comparable.CompareTo((Double)456) < 0); Assert.True(comparable.CompareTo(Double.MaxValue) < 0); Assert.Throws<ArgumentException>(() => comparable.CompareTo("a")); } [Fact] public static void TestCompareTo() { Double i = 234; Assert.Equal(0, i.CompareTo((Double)234)); Assert.True(i.CompareTo(Double.MinValue) > 0); Assert.True(i.CompareTo((Double)0) > 0); Assert.True(i.CompareTo((Double)(-123)) > 0); Assert.True(i.CompareTo((Double)123) > 0); Assert.True(i.CompareTo((Double)456) < 0); Assert.True(i.CompareTo(Double.MaxValue) < 0); Assert.True(Double.NaN.CompareTo(Double.NaN) == 0); Assert.True(Double.NaN.CompareTo(0) < 0); Assert.True(i.CompareTo(Double.NaN) > 0); } [Fact] public static void TestEqualsObject() { Double i = 789; object obj1 = (Double)789; Assert.True(i.Equals(obj1)); object obj2 = (Double)(-789); Assert.True(!i.Equals(obj2)); object obj3 = (Double)0; Assert.True(!i.Equals(obj3)); } [Fact] public static void TestEquals() { Double i = -911; Assert.True(i.Equals((Double)(-911))); Assert.True(!i.Equals((Double)911)); Assert.True(!i.Equals((Double)0)); Assert.True(Double.NaN.Equals(Double.NaN)); } [Fact] public static void TestGetHashCode() { Double i1 = 123; Double i2 = 654; Assert.NotEqual(0, i1.GetHashCode()); Assert.NotEqual(i1.GetHashCode(), i2.GetHashCode()); } [Fact] public static void TestToString() { Double i1 = 6310; Assert.Equal("6310", i1.ToString()); Double i2 = -8249; Assert.Equal("-8249", i2.ToString()); } [Fact] public static void TestToStringFormatProvider() { var numberFormat = new System.Globalization.NumberFormatInfo(); Double i1 = 6310; Assert.Equal("6310", i1.ToString(numberFormat)); Double i2 = -8249; Assert.Equal("-8249", i2.ToString(numberFormat)); Double i3 = -2468; // Changing the negative pattern doesn't do anything without also passing in a format string numberFormat.NumberNegativePattern = 0; Assert.Equal("-2468", i3.ToString(numberFormat)); Assert.Equal("NaN", Double.NaN.ToString(NumberFormatInfo.InvariantInfo)); Assert.Equal("Infinity", Double.PositiveInfinity.ToString(NumberFormatInfo.InvariantInfo)); Assert.Equal("-Infinity", Double.NegativeInfinity.ToString(NumberFormatInfo.InvariantInfo)); } [Fact] public static void TestToStringFormat() { Double i1 = 6310; Assert.Equal("6310", i1.ToString("G")); Double i2 = -8249; Assert.Equal("-8249", i2.ToString("g")); Double i3 = -2468; Assert.Equal(string.Format("{0:N}", -2468.00), i3.ToString("N")); } [Fact] public static void TestToStringFormatFormatProvider() { var numberFormat = new System.Globalization.NumberFormatInfo(); Double i1 = 6310; Assert.Equal("6310", i1.ToString("G", numberFormat)); Double i2 = -8249; Assert.Equal("-8249", i2.ToString("g", numberFormat)); numberFormat.NegativeSign = "xx"; // setting it to trash to make sure it doesn't show up numberFormat.NumberGroupSeparator = "*"; numberFormat.NumberNegativePattern = 0; Double i3 = -2468; Assert.Equal("(2*468.00)", i3.ToString("N", numberFormat)); } [Fact] public static void TestParse() { Assert.Equal(123, Double.Parse("123")); Assert.Equal(-123, Double.Parse("-123")); //TODO: Negative tests once we get better exceptions } [Fact] public static void TestParseNumberStyle() { Assert.Equal<Double>((Double)123.1, Double.Parse(string.Format("{0}", 123.1), NumberStyles.AllowDecimalPoint)); Assert.Equal(1000, Double.Parse(string.Format("{0}", 1000), NumberStyles.AllowThousands)); //TODO: Negative tests once we get better exceptions } [Fact] public static void TestParseFormatProvider() { var nfi = new NumberFormatInfo(); Assert.Equal(123, Double.Parse("123", nfi)); Assert.Equal(-123, Double.Parse("-123", nfi)); //TODO: Negative tests once we get better exceptions } [Fact] public static void TestParseNumberStyleFormatProvider() { var nfi = new NumberFormatInfo(); nfi.NumberDecimalSeparator = "."; Assert.Equal<Double>((Double)123.123, Double.Parse("123.123", NumberStyles.Float, nfi)); nfi.CurrencySymbol = "$"; nfi.CurrencyGroupSeparator = ","; Assert.Equal(1000, Double.Parse("$1,000", NumberStyles.Currency, nfi)); //TODO: Negative tests once we get better exception support } [Fact] public static void TestTryParse() { // Defaults AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowDecimalPoint | AllowExponent | AllowThousands Double i; Assert.True(Double.TryParse("123", out i)); // Simple Assert.Equal(123, i); Assert.True(Double.TryParse("-385", out i)); // LeadingSign Assert.Equal(-385, i); Assert.True(Double.TryParse(" 678 ", out i)); // Leading/Trailing whitespace Assert.Equal(678, i); Assert.True(Double.TryParse((678.90).ToString("F2"), out i)); // Decimal Assert.Equal((Double)678.90, i); Assert.True(Double.TryParse("1E23", out i)); // Exponent Assert.Equal((Double)1E23, i); Assert.True(Double.TryParse((1000).ToString("N0"), out i)); // Thousands Assert.Equal(1000, i); var nfi = new NumberFormatInfo() { CurrencyGroupSeparator = "" }; Assert.False(Double.TryParse((1000).ToString("C0", nfi), out i)); // Currency Assert.False(Double.TryParse("abc", out i)); // Hex digits Assert.False(Double.TryParse("(135)", out i)); // Parentheses } [Fact] public static void TestTryParseNumberStyleFormatProvider() { Double i; var nfi = new NumberFormatInfo(); nfi.NumberDecimalSeparator = "."; Assert.True(Double.TryParse("123.123", NumberStyles.Any, nfi, out i)); // Simple positive Assert.Equal((Double)123.123, i); Assert.True(Double.TryParse("123", NumberStyles.Float, nfi, out i)); // Simple Hex Assert.Equal(123, i); nfi.CurrencySymbol = "$"; nfi.CurrencyGroupSeparator = ","; Assert.True(Double.TryParse("$1,000", NumberStyles.Currency, nfi, out i)); // Currency/Thousands postive Assert.Equal(1000, i); Assert.False(Double.TryParse("abc", NumberStyles.None, nfi, out i)); // Hex Number negative Assert.False(Double.TryParse("678.90", NumberStyles.Integer, nfi, out i)); // Decimal Assert.False(Double.TryParse(" 678 ", NumberStyles.None, nfi, out i)); // Trailing/Leading whitespace negative Assert.True(Double.TryParse("(135)", NumberStyles.AllowParentheses, nfi, out i)); // Parenthese postive Assert.Equal(-135, i); Assert.True(Double.TryParse("Infinity", NumberStyles.Any, NumberFormatInfo.InvariantInfo, out i)); Assert.True(Double.IsPositiveInfinity(i)); Assert.True(Double.TryParse("-Infinity", NumberStyles.Any, NumberFormatInfo.InvariantInfo, out i)); Assert.True(Double.IsNegativeInfinity(i)); Assert.True(Double.TryParse("NaN", NumberStyles.Any, NumberFormatInfo.InvariantInfo, out i)); Assert.True(Double.IsNaN(i)); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using SIL.Code; using SIL.Extensions; using SIL.Linq; using SIL.Text; namespace SIL.Windows.Forms.ImageToolbox.ImageGallery { /// <summary> /// A set of images on disk that have an index file with key words in one or more languages. /// For example, "Art of Reading" is one of these collections. /// See https://github.com/sillsdev/image-collection-starter and https://github.com/sillsdev/ArtOfReading /// </summary> public class ImageCollection { public readonly string FolderPath; public IEnumerable<string> IndexLanguages => _imageIndexReader.LanguageIds; public bool Enabled = true; public string Key => FolderPath; internal const string kStandardImageFolderName = "images"; private Dictionary<string, List<string>> _indexOfWordsToRelativePath; private Dictionary<string, string> _indexOfRelativeFilePathToKeywordsCsv; private static readonly object _padlock = new object(); private ImageIndexReader _imageIndexReader; private Func<IEnumerable<string>, IEnumerable<string>> _fixPaths = p => p; // identity function, by default public ImageCollection(string path) { Require.That(Directory.Exists(path), "path must be a directory and must exist"); FolderPath = path; LoadLanguageChoices(); } /// <summary> /// Some sort of name for the collection /// </summary> public string Name => Path.GetFileName(FolderPath); /// <summary> /// Figure out in what languages we have keywords /// </summary> protected void LoadLanguageChoices() { var pathToIndexFile = FindIndexFileInFolder(FolderPath); _imageIndexReader = ImageIndexReader.FromFile(pathToIndexFile); } /// <summary> /// Note: you can call this more than once, in order to change the search language id /// </summary> public virtual void LoadIndex(string searchLanguageId) { if (_imageIndexReader == null) { LoadLanguageChoices(); } _indexOfWordsToRelativePath = new Dictionary<string, List<string>>(); _indexOfRelativeFilePathToKeywordsCsv = new Dictionary<string, string>(); var indexPath = FindIndexFileInFolder(FolderPath); using (var f = File.OpenText(indexPath)) { //skip header line, which was already read to make the index layout above f.ReadLine(); while (!f.EndOfStream) { var line = f.ReadLine(); var fields = line.Split(new char[] { '\t' }); var relativePath = _imageIndexReader.GetImageRelativePath(fields); var csvOfKeywords = _imageIndexReader.GetCSVOfKeywordsOrEmpty(searchLanguageId, fields); if (String.IsNullOrWhiteSpace(csvOfKeywords)) continue; lock(_padlock) { try { _indexOfRelativeFilePathToKeywordsCsv.Add(relativePath, csvOfKeywords.Replace(",", ", ")); } catch (System.ArgumentException) { if(_indexOfRelativeFilePathToKeywordsCsv.ContainsKey(relativePath)) throw new ApplicationException( $"{indexPath} has more than one row describing a file name '{relativePath}'. This is not allowed. You can use 'conditional formatting' with the condition 'duplicate' in a spreadsheet program to find duplicates."); else throw; } } var keys = csvOfKeywords.SplitTrimmed(','); foreach (var key in keys) { lock (_padlock) _indexOfWordsToRelativePath.GetOrCreate(key.ToLowerInvariant()).Add(relativePath); } } } } /// <summary> /// Get images that exactly match one or more search terms. /// </summary> public IEnumerable<string> GetMatchingImages(string searchTermsCsv) { searchTermsCsv = ImageCollectionManager.GetCleanedUpSearchString(searchTermsCsv); return GetMatchingImages(searchTermsCsv.SplitTrimmed(' ')); } /// <summary> /// Get images that exactly match one or more search terms. /// </summary> public IEnumerable<string> GetMatchingImages(IEnumerable<string> searchTerms) { var fullPathsToImages = new List<string>(); foreach (var term in searchTerms) { //try for exact matches lock (_padlock) { List<string> imagesForThisSearchTerm; if (_indexOfWordsToRelativePath.TryGetValue(term.ToLowerInvariant(), out imagesForThisSearchTerm)) { fullPathsToImages.AddRange(imagesForThisSearchTerm.Select(GetFullPath)); } } } var results = new List<string>(); fullPathsToImages.Distinct().ForEach(p => results.Add(p)); return _fixPaths(results); } /// <summary> /// Get images that are within one "edit" of matching an image in the collection /// </summary> public IEnumerable<string> GetApproximateMatchingImages(IEnumerable<string> searchTerms) { var fullPathsToImages = new List<string>(); foreach (var term in searchTerms) { lock (_padlock) { const int kMaxEditDistance = 1; var itemFormExtractor = new ApproximateMatcher.GetStringDelegate<KeyValuePair<string, List<string>>>(pair => pair.Key); var matches = ApproximateMatcher.FindClosestForms<KeyValuePair<string, List<string>>>(_indexOfWordsToRelativePath, itemFormExtractor, term.ToLowerInvariant(), ApproximateMatcherOptions.None, kMaxEditDistance); if (matches != null && matches.Count > 0) { foreach (var keyValuePair in matches) { fullPathsToImages.AddRange(keyValuePair.Value.Select(GetFullPath)); } } } } var results = new List<string>(); fullPathsToImages.Distinct().ForEach(p => results.Add(p)); return _fixPaths(results); } public string GetFullPath(string partialPath) { return Path.Combine(this.FolderPath, ImageCollection.kStandardImageFolderName, partialPath); } /* public string StripNonMatchingKeywords(string stringWhichMayContainKeywords) { string result = string.Empty; stringWhichMayContainKeywords = GetCleanedUpSearchString(stringWhichMayContainKeywords); var words = stringWhichMayContainKeywords.SplitTrimmed(' '); foreach (var key in words) { lock (_padlock) { if (_indexOfWordsToRelativePath.ContainsKey(key)) result += " " + key; } } return result.Trim(); } */ /* oddly, we have various methods around for captions, but non were wired up. * at the moment, I can't think of why you'd want captions... but not exactly ready * to delete all this in case it later occurs to me.... public string GetCaption(string path) { try { var partialPath = "";//TODO path.Replace(DefaultAorRootImagePath, ""); partialPath = partialPath.Replace(Path.DirectorySeparatorChar, ':'); partialPath = partialPath.Trim(new char[] { ':' }); lock (_padlock) return _indexOfRelativeFilePathToKeywordsCsv[partialPath]; } catch (Exception) { return "error"; } }*/ private string FindIndexFileInFolder(string folderPath) { // original English and Indonesian version of the index ArtOfReadingIndexV3_en.txt var p = Path.Combine(folderPath, "ArtOfReadingIndexV3_en.txt"); if (File.Exists(p)) { _fixPaths = FixOldArtOfReadingPaths; return p; } // Art Of Reading 3.1 and 3.2 p = Path.Combine(folderPath, "ArtOfReadingMultilingualIndex.txt"); if (File.Exists(p)) { _fixPaths = FixOldArtOfReadingPaths; return p; } // Art of Reading 3.3+ and any new collections p = Path.Combine(folderPath, "index.txt"); if (File.Exists(p)) { return p; } return string.Empty; // could not find an index } private static IEnumerable<string> FixOldArtOfReadingPaths(IEnumerable<string> paths) { foreach (var path in paths) { var p = path; if (!Path.HasExtension(path)) { p += ".png"; } var f = Path.GetFileName(p); if (!f.ToLowerInvariant().StartsWith("aor_")) { p = Path.Combine(Path.GetDirectoryName(p), "AOR_" + f); } yield return p; } } } }
using System; using System.Runtime.InteropServices; using WinBioNET.Enums; namespace WinBioNET { //[SuppressUnmanagedCodeSecurity] public class WinBio { protected const string LibName = "winbio.dll"; [DllImport(LibName, EntryPoint = "WinBioOpenSession")] private extern static WinBioErrorCode OpenSession( WinBioBiometricType factor, WinBioPoolType poolType, WinBioSessionFlag flags, int[] unitArray, int unitCount, IntPtr databaseId, out WinBioSessionHandle sessionHandle); [DllImport(LibName, EntryPoint = "WinBioOpenSession")] private extern static WinBioErrorCode OpenSession( WinBioBiometricType factor, WinBioPoolType poolType, WinBioSessionFlag flags, int[] unitArray, int unitCount, [MarshalAs(UnmanagedType.LPStruct)] Guid databaseId, out WinBioSessionHandle sessionHandle); private static WinBioSessionHandle OpenSession(WinBioBiometricType factor, WinBioPoolType poolType, WinBioSessionFlag flags, int[] unitArray, IntPtr databaseId) { WinBioSessionHandle sessionHandle; var code = OpenSession(factor, poolType, flags, unitArray, unitArray == null ? 0 : unitArray.Length, databaseId, out sessionHandle); WinBioException.ThrowOnError(code, "WinBioOpenSession failed"); return sessionHandle; } public static WinBioSessionHandle OpenSession(WinBioBiometricType factor, WinBioPoolType poolType, WinBioSessionFlag flags, int[] unitArray, Guid databaseId) { WinBioSessionHandle sessionHandle; var code = OpenSession(factor, poolType, flags, unitArray, unitArray.Length, databaseId, out sessionHandle); WinBioException.ThrowOnError(code, "WinBioOpenSession failed"); return sessionHandle; } public static WinBioSessionHandle OpenSession(WinBioBiometricType factor, WinBioPoolType poolType, WinBioSessionFlag flags, int[] unitArray, WinBioDatabaseId databaseId) { return OpenSession(factor, poolType, flags, unitArray, (IntPtr)databaseId); } public static WinBioSessionHandle OpenSession(WinBioBiometricType factor) { return OpenSession(factor, WinBioPoolType.System, WinBioSessionFlag.Default, null, WinBioDatabaseId.Default); } [DllImport(LibName, EntryPoint = "WinBioCloseSession")] private extern static WinBioErrorCode WinBioCloseSession(WinBioSessionHandle sessionHandle); public static void CloseSession(WinBioSessionHandle sessionHandle) { if (!sessionHandle.IsValid) return; var code = WinBioCloseSession(sessionHandle); WinBioException.ThrowOnError(code, "WinBioOpenSession failed"); sessionHandle.Invalidate(); } [DllImport(LibName, EntryPoint = "WinBioCancel")] private extern static WinBioErrorCode WinBioCancel(WinBioSessionHandle sessionHandle); public static void Cancel(WinBioSessionHandle sessionHandle) { var code = WinBioCancel(sessionHandle); WinBioException.ThrowOnError(code, "WinBioCancel failed"); } [DllImport(LibName, EntryPoint = "WinBioEnumDatabases")] private extern static WinBioErrorCode EnumDatabases(WinBioBiometricType factor, out IntPtr storageSchemaArray, out int storageCount); public static WinBioStorageSchema[] EnumDatabases(WinBioBiometricType factor) { IntPtr pointer; int count; var code = EnumDatabases(factor, out pointer, out count); WinBioException.ThrowOnError(code, "WinBioEnumDatabases failed"); return MarshalArray<WinBioStorageSchema>(pointer, count); } [DllImport(LibName, EntryPoint = "WinBioCaptureSample")] private extern static WinBioErrorCode CaptureSample( WinBioSessionHandle sessionHandle, WinBioBirPurpose purpose, WinBioBirDataFlags flags, out int unitId, out IntPtr sample, out int sampleSize, out WinBioRejectDetail rejectDetail); public static int CaptureSample( WinBioSessionHandle sessionHandle, WinBioBirPurpose purpose, WinBioBirDataFlags flags, out int sampleSize, out WinBioRejectDetail rejectDetail) { int unitId; IntPtr pointer; var code = CaptureSample(sessionHandle, purpose, flags, out unitId, out pointer, out sampleSize, out rejectDetail); WinBioException.ThrowOnError(code, "WinBioCaptureSample failed"); //TODO: parse WINBIO_BIR structure at pointer Free(pointer); return unitId; } [DllImport(LibName, EntryPoint = "WinBioLocateSensor")] private extern static WinBioErrorCode LocateSensor(WinBioSessionHandle sessionHandle, out int unitId); public static int LocateSensor(WinBioSessionHandle sessionHandle) { int unitId; var code = LocateSensor(sessionHandle, out unitId); WinBioException.ThrowOnError(code, "WinBioLocateSensor failed"); return unitId; } [DllImport(LibName, EntryPoint = "WinBioEnumBiometricUnits")] private extern static WinBioErrorCode EnumBiometricUnits(WinBioBiometricType factor, out IntPtr unitSchemaArray, out int unitCount); public static WinBioUnitSchema[] EnumBiometricUnits(WinBioBiometricType factor) { IntPtr pointer; int count; var code = EnumBiometricUnits(factor, out pointer, out count); WinBioException.ThrowOnError(code, "WinBioEnumBiometricUnits failed"); return MarshalArray<WinBioUnitSchema>(pointer, count); } [DllImport(LibName, EntryPoint = "WinBioIdentify")] private extern static WinBioErrorCode Identify( WinBioSessionHandle sessionHandle, out int unitId, IntPtr identity, out WinBioBiometricSubType subFactor, out WinBioRejectDetail rejectDetail); public static int Identify( WinBioSessionHandle sessionHandle, out WinBioIdentity identity, out WinBioBiometricSubType subFactor, out WinBioRejectDetail rejectDetail) { int unitId; var bytes = new byte[WinBioIdentity.Size]; var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned); try { var code = Identify(sessionHandle, out unitId, handle.AddrOfPinnedObject(), out subFactor, out rejectDetail); WinBioException.ThrowOnError(code, "WinBioIdentify failed"); } finally { handle.Free(); } identity = new WinBioIdentity(bytes); return unitId; } [DllImport(LibName, EntryPoint = "WinBioControlUnit")] public extern static WinBioErrorCode ControlUnit( WinBioSessionHandle sessionHandle, int unitId, WinBioComponentType componentType, uint controlCode, byte[] sendBuffer, int sendBufferSize, IntPtr receiveBuffer, int receiveBufferSize, ref int receiveDataSize, ref uint statusCode); [DllImport("Winbio.dll", EntryPoint = "WinBioUnlockUnit")] public extern static WinBioErrorCode UnlockUnit(WinBioSessionHandle SessionHandle, int UnitId); [DllImport("Winbio.dll", EntryPoint = "WinBioLockUnit")] public extern static WinBioErrorCode LockUnit(WinBioSessionHandle SessionHandle, int UnitId); [DllImport(LibName, EntryPoint = "WinBioEnumEnrollments")] private extern static WinBioErrorCode EnumEnrollments( WinBioSessionHandle sessionHandle, int unitId, IntPtr identity, out IntPtr subFactorArray, out int subFactorCount); public static WinBioBiometricSubType[] EnumEnrollments(WinBioSessionHandle sessionHandle, int unitId, WinBioIdentity identity) { var handle = GCHandle.Alloc(identity.GetBytes(), GCHandleType.Pinned); try { IntPtr subFactorArray; int subFactorCount; var code = EnumEnrollments(sessionHandle, unitId, handle.AddrOfPinnedObject(), out subFactorArray, out subFactorCount); WinBioException.ThrowOnError(code, "WinBioEnumEnrollments failed"); return MarshalArray<WinBioBiometricSubType>(subFactorArray, subFactorCount); } finally { handle.Free(); } } [DllImport(LibName, EntryPoint = "WinBioEnrollBegin")] private extern static WinBioErrorCode WinBioEnrollBegin(WinBioSessionHandle sessionHandle, WinBioBiometricSubType subType, int unitId); public static void EnrollBegin(WinBioSessionHandle sessionHandle, WinBioBiometricSubType subType, int unitId) { var code = WinBioEnrollBegin(sessionHandle, subType, unitId); WinBioException.ThrowOnError(code, "WinBioEnrollBegin failed"); } [DllImport(LibName, EntryPoint = "WinBioEnrollCapture")] public extern static WinBioErrorCode EnrollCapture(WinBioSessionHandle sessionHandle, out WinBioRejectDetail rejectDetail); [DllImport(LibName, EntryPoint = "WinBioEnrollCommit")] private extern static WinBioErrorCode EnrollCommit(WinBioSessionHandle sessionHandle, IntPtr identity, out bool isNewTemplate); public static bool EnrollCommit(WinBioSessionHandle sessionHandle, out WinBioIdentity identity) { bool isNewTemplate; var bytes = new byte[WinBioIdentity.Size]; var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned); try { var code = EnrollCommit(sessionHandle, handle.AddrOfPinnedObject(), out isNewTemplate); WinBioException.ThrowOnError(code, "WinBioEnrollCommit failed"); } finally { handle.Free(); } identity = new WinBioIdentity(bytes); return isNewTemplate; } [DllImport(LibName, EntryPoint = "WinBioEnrollDiscard")] private extern static WinBioErrorCode WinBioEnrollDiscard(WinBioSessionHandle sessionHandle); public static void EnrollDiscard(WinBioSessionHandle sessionHandle) { var code = WinBioEnrollDiscard(sessionHandle); WinBioException.ThrowOnError(code, "WinBioEnrollDiscard failed"); } [DllImport(LibName, EntryPoint = "WinBioVerify")] private static extern WinBioErrorCode Verify( WinBioSessionHandle sessionHandle, IntPtr identity, WinBioBiometricSubType subFactor, out int unitId, out bool match, out WinBioRejectDetail rejectDetail); public static bool Verify( WinBioSessionHandle sessionHandle, WinBioIdentity identity, WinBioBiometricSubType subFactor, out int unitId, out WinBioRejectDetail rejectDetail) { bool match; var handle = GCHandle.Alloc(identity.GetBytes(), GCHandleType.Pinned); try { var code = Verify(sessionHandle, handle.AddrOfPinnedObject(), subFactor, out unitId, out match, out rejectDetail); WinBioException.ThrowOnError(code, "WinBioVerify failed"); } finally { handle.Free(); } return match; } [DllImport(LibName, EntryPoint = "WinBioDeleteTemplate")] private static extern WinBioErrorCode DeleteTemplate( WinBioSessionHandle sessionHandle, int unitId, IntPtr identity, WinBioBiometricSubType subFactor); public static void DeleteTemplate( WinBioSessionHandle sessionHandle, int unitId, WinBioIdentity identity, WinBioBiometricSubType subFactor) { var handle = GCHandle.Alloc(identity.GetBytes(), GCHandleType.Pinned); try { var code = DeleteTemplate(sessionHandle, unitId, handle.AddrOfPinnedObject(), subFactor); WinBioException.ThrowOnError(code, "WinBioDeleteTemplate failed"); } finally { handle.Free(); } } [DllImport(LibName, EntryPoint = "WinBioEnumServiceProviders")] private static extern WinBioErrorCode EnumServiceProviders( WinBioBiometricType factor, out IntPtr bspSchemaArray, out int bspCount); public static WinBioBspSchema[] EnumServiceProviders(WinBioBiometricType factor) { IntPtr bspSchemaArray; int bspCount; var code = EnumServiceProviders(factor, out bspSchemaArray, out bspCount); WinBioException.ThrowOnError(code, "WinBioEnumServiceProviders failed"); return MarshalArray<WinBioBspSchema>(bspSchemaArray, bspCount); } [DllImport(LibName, EntryPoint = "WinBioGetLogonSetting")] private extern static WinBioErrorCode GetLogonSetting(out bool value, out WinBioSettingSourceType source); public static bool GetLogonSetting(out WinBioSettingSourceType source) { bool value; //BUG: does not seem to work var code = GetLogonSetting(out value, out source); //WinBioException.ThrowOnError(code, "WinBioGetLogonSetting failed"); return value; } [DllImport(LibName, EntryPoint = "WinBioGetEnabledSetting")] private extern static WinBioErrorCode GetEnabledSetting(out bool value, out WinBioSettingSourceType source); public static bool GetEnabledSetting(out WinBioSettingSourceType source) { bool value; //BUG: does not seem to work var code = GetEnabledSetting(out value, out source); //WinBioException.ThrowOnError(code, "WinBioGetEnabledSetting failed"); return value; } [DllImport(LibName, EntryPoint = "WinBioLogonIdentifiedUser")] public static extern WinBioErrorCode LogonIdentifiedUser(WinBioSessionHandle sessionHandle); [DllImport(LibName, EntryPoint = "WinBioAcquireFocus")] public static extern WinBioErrorCode AcquireFocus(WinBioSessionHandle sessionHandle); [DllImport(LibName, EntryPoint = "WinBioReleaseFocus")] public static extern WinBioErrorCode ReleaseFocus(WinBioSessionHandle sessionHandle); [DllImport(LibName, EntryPoint = "WinBioFree")] private extern static WinBioErrorCode Free(IntPtr address); /// <summary> /// Marshals an array of type T at the given address and frees the unmanaged memory afterwards. /// Supports primitive types, structures and enums. /// </summary> /// <typeparam name="T">Type of the array elements.</typeparam> /// <param name="pointer">Address of the array in unmanaged memory.</param> /// <param name="count">Number of elements in the array.</param> /// <returns>Managed array of the given type.</returns> private static T[] MarshalArray<T>(IntPtr pointer, int count) { if (pointer == IntPtr.Zero) return null; try { var offset = pointer; var data = new T[count]; var type = typeof (T); if (type.IsEnum) type = type.GetEnumUnderlyingType(); for (var i = 0; i < count; i++) { data[i] = (T) Marshal.PtrToStructure(offset, type); offset += Marshal.SizeOf(type); } return data; } finally { Free(pointer); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information using System; using System.Collections.Generic; using System.Linq; using Microsoft.Common.Core; using Microsoft.Common.Core.Services; using Microsoft.Languages.Editor.Document; using Microsoft.Languages.Editor.Text; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Projection; using Microsoft.VisualStudio.Utilities; namespace Microsoft.Languages.Editor.Projection { /// <summary> /// Manages the projection buffer for the primary language /// </summary> public sealed class ProjectionBufferManager : IProjectionBufferManager { private class ViewPosition { public int? CaretPosition; public double? ViewportTop; } private ViewPosition _savedViewPosition; public ProjectionBufferManager(ITextBuffer diskBuffer, IServiceContainer services, string topLevelContentTypeName, string secondaryContentTypeName) { DiskBuffer = diskBuffer; var projectionBufferFactoryService = services.GetService<IProjectionBufferFactoryService>(); var contentTypeRegistryService = services.GetService<IContentTypeRegistryService>(); var contentType = contentTypeRegistryService.GetContentType(topLevelContentTypeName); ViewBuffer = projectionBufferFactoryService.CreateProjectionBuffer(null, new List<object>(0), ProjectionBufferOptions.None, contentType); EditorBuffer.Create(ViewBuffer, services.GetService<ITextDocumentFactoryService>()); contentType = contentTypeRegistryService.GetContentType(secondaryContentTypeName); ContainedLanguageBuffer = projectionBufferFactoryService.CreateProjectionBuffer(null, new List<object>(0), ProjectionBufferOptions.WritableLiteralSpans, contentType); EditorBuffer.Create(ContainedLanguageBuffer, services.GetService<ITextDocumentFactoryService>()); DiskBuffer.AddService(this); ViewBuffer.AddService(this); } public static IProjectionBufferManager FromTextBuffer(ITextBuffer textBuffer) { var pbm = textBuffer.GetService<IProjectionBufferManager>(); if (pbm == null) { var pb = textBuffer as IProjectionBuffer; pbm = pb?.SourceBuffers?.Select(b => b.GetService<IProjectionBufferManager>())?.FirstOrDefault(b => b != null); } return pbm; } #region IProjectionBufferManager // Graph: // View Buffer [ContentType = RMD Projection] // | \ // | Secondary [ContentType = R] // | / // Disk Buffer [ContentType = RMD] public IProjectionBuffer ViewBuffer { get; } public IProjectionBuffer ContainedLanguageBuffer { get; } public ITextBuffer DiskBuffer { get; } public event EventHandler MappingsChanged; public void SetProjectionMappings(string secondaryContent, IReadOnlyList<ProjectionMapping> mappings) { // Changing projections can move caret to a visible area unexpectedly. // Save caret position so we can place it at the same location when // projections are re-established. SaveViewPosition(); var secondarySpans = CreateSecondarySpans(secondaryContent, mappings); if (IdenticalSpans(secondarySpans)) { return; } // While we are changing mappings map everything to the view mappings = mappings ?? new List<ProjectionMapping>(); MapEverythingToView(); // Now update language spans ContainedLanguageBuffer.ReplaceSpans(0, ContainedLanguageBuffer.CurrentSnapshot.SpanCount, secondarySpans, EditOptions.DefaultMinimalChange, this); if (secondarySpans.Count > 0) { // Update primary (view) buffer projected spans. View buffer spans are all tracking spans: // they either come from primary content or secondary content. Inert spans do not participate. var viewSpans = CreateViewSpans(mappings); if (viewSpans.Count > 0) { ViewBuffer.ReplaceSpans(0, ViewBuffer.CurrentSnapshot.SpanCount, viewSpans, EditOptions.DefaultMinimalChange, this); } } RestoreViewPosition(); MappingsChanged?.Invoke(this, EventArgs.Empty); } private void MapEverythingToView() { var diskSnap = DiskBuffer.CurrentSnapshot; var everything = new SnapshotSpan(diskSnap, 0, diskSnap.Length); var trackingSpan = diskSnap.CreateTrackingSpan(everything, SpanTrackingMode.EdgeInclusive); ViewBuffer.ReplaceSpans(0, ViewBuffer.CurrentSnapshot.SpanCount, new List<object>() { trackingSpan }, EditOptions.None, this); } public void Dispose() { DiskBuffer?.RemoveService(this); ViewBuffer?.RemoveService(this); } #endregion private List<object> CreateSecondarySpans(string secondaryText, IReadOnlyList<ProjectionMapping> mappings) { var spans = new List<object>(mappings.Count); var secondaryIndex = 0; Span span; for (var i = 0; i < mappings.Count; i++) { var mapping = mappings[i]; if (mapping.Length > 0) { span = Span.FromBounds(secondaryIndex, mapping.ProjectionRange.Start); if (!span.IsEmpty) { spans.Add(secondaryText.Substring(span.Start, span.Length)); // inert } span = new Span(mapping.SourceStart, mapping.Length); // Active span comes from the disk buffer spans.Add(new CustomTrackingSpan(DiskBuffer.CurrentSnapshot, span, PointTrackingMode.Positive, PointTrackingMode.Positive)); // active secondaryIndex = mapping.ProjectionRange.End; } } // Add the final inert text after the last span span = Span.FromBounds(secondaryIndex, secondaryText.Length); if (!span.IsEmpty) { spans.Add(secondaryText.Substring(span.Start, span.Length)); // inert } return spans; } private List<object> CreateViewSpans(IReadOnlyList<ProjectionMapping> mappings) { var spans = new List<object>(mappings.Count); var diskSnapshot = DiskBuffer.CurrentSnapshot; var primaryIndex = 0; Span span; for (var i = 0; i < mappings.Count; i++) { var mapping = mappings[i]; if (mapping.Length > 0) { span = Span.FromBounds(primaryIndex, mapping.SourceStart); spans.Add(new CustomTrackingSpan(diskSnapshot, span, i == 0 ? PointTrackingMode.Negative : PointTrackingMode.Positive, PointTrackingMode.Positive)); // Markdown primaryIndex = mapping.SourceRange.End; span = new Span(mapping.ProjectionStart, mapping.Length); spans.Add(new CustomTrackingSpan(ContainedLanguageBuffer.CurrentSnapshot, span, PointTrackingMode.Positive, PointTrackingMode.Positive)); // R } } // Add the final section after the last span span = Span.FromBounds(primaryIndex, diskSnapshot.Length); spans.Add(new CustomTrackingSpan(diskSnapshot, span, PointTrackingMode.Positive, PointTrackingMode.Positive)); // Markdown return spans; } private ITextCaret GetCaret() => DiskBuffer.GetFirstView()?.Caret; private int? GetCaretPosition() => GetCaret()?.Position.BufferPosition.Position; private void SaveViewPosition() { _savedViewPosition = new ViewPosition { CaretPosition = GetCaretPosition(), ViewportTop = DiskBuffer.GetFirstView()?.ViewportTop }; } private void RestoreViewPosition() { var textView = DiskBuffer.GetFirstView(); if(textView == null) { _savedViewPosition = null; return; } if (_savedViewPosition?.CaretPosition != null) { var caretPosition = GetCaretPosition(); if (caretPosition.HasValue && caretPosition.Value != _savedViewPosition.CaretPosition) { textView.Caret.MoveTo(new SnapshotPoint(textView.TextBuffer.CurrentSnapshot, _savedViewPosition.CaretPosition.Value)); } } if (_savedViewPosition?.ViewportTop != null) { textView.ViewScroller.ScrollViewportVerticallyByPixels(textView.ViewportTop - _savedViewPosition.ViewportTop.Value); } _savedViewPosition = null; } private bool IdenticalSpans(IReadOnlyList<object> newSpans) { var snapshot = ContainedLanguageBuffer.CurrentSnapshot; var currentSpans = snapshot.GetSourceSpans(); if (currentSpans.Count != newSpans.Count || currentSpans.Count == 0) { return false; } for (var i = 0; i < currentSpans.Count; i++) { var cs = currentSpans[i]; var currentText = cs.Snapshot.GetText(cs.Span); string newText; var ts = newSpans[i] as ITrackingSpan; if (ts != null) { var newSpan = ts.GetSpan(ts.TextBuffer.CurrentSnapshot); if (newSpan.Length != cs.Length || newSpan.Start.Position != cs.Start.Position) { return false; } newText = ts.TextBuffer.CurrentSnapshot.GetText(newSpan); } else { // New span is inert text newText = newSpans[i] as string; if(newText == null) { return false; } } if (!newText.EqualsOrdinal(currentText)) { return false; } } return true; } } }
/* * Copyright (c) 2006-2016, openmetaverse.co * 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. * - Neither the name of the openmetaverse.co 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. */ using System; using System.Runtime.InteropServices; namespace OpenMetaverse { /// <summary> /// An 8-bit color structure including an alpha channel /// </summary> [Serializable] [StructLayout(LayoutKind.Sequential)] public struct Color4 : IComparable<Color4>, IEquatable<Color4> { /// <summary>Red</summary> public float R; /// <summary>Green</summary> public float G; /// <summary>Blue</summary> public float B; /// <summary>Alpha</summary> public float A; #region Constructors /// <summary> /// /// </summary> /// <param name="r"></param> /// <param name="g"></param> /// <param name="b"></param> /// <param name="a"></param> public Color4(byte r, byte g, byte b, byte a) { const float quanta = 1.0f / 255.0f; R = (float)r * quanta; G = (float)g * quanta; B = (float)b * quanta; A = (float)a * quanta; } public Color4(float r, float g, float b, float a) { // Quick check to see if someone is doing something obviously wrong // like using float values from 0.0 - 255.0 if (r > 1f || g > 1f || b > 1f || a > 1f) throw new ArgumentException( String.Format("Attempting to initialize Color4 with out of range values <{0},{1},{2},{3}>", r, g, b, a)); // Valid range is from 0.0 to 1.0 R = Utils.Clamp(r, 0f, 1f); G = Utils.Clamp(g, 0f, 1f); B = Utils.Clamp(b, 0f, 1f); A = Utils.Clamp(a, 0f, 1f); } /// <summary> /// Builds a color from a byte array /// </summary> /// <param name="byteArray">Byte array containing a 16 byte color</param> /// <param name="pos">Beginning position in the byte array</param> /// <param name="inverted">True if the byte array stores inverted values, /// otherwise false. For example the color black (fully opaque) inverted /// would be 0xFF 0xFF 0xFF 0x00</param> public Color4(byte[] byteArray, int pos, bool inverted) { R = G = B = A = 0f; FromBytes(byteArray, pos, inverted); } /// <summary> /// Returns the raw bytes for this vector /// </summary> /// <param name="byteArray">Byte array containing a 16 byte color</param> /// <param name="pos">Beginning position in the byte array</param> /// <param name="inverted">True if the byte array stores inverted values, /// otherwise false. For example the color black (fully opaque) inverted /// would be 0xFF 0xFF 0xFF 0x00</param> /// <param name="alphaInverted">True if the alpha value is inverted in /// addition to whatever the inverted parameter is. Setting inverted true /// and alphaInverted true will flip the alpha value back to non-inverted, /// but keep the other color bytes inverted</param> /// <returns>A 16 byte array containing R, G, B, and A</returns> public Color4(byte[] byteArray, int pos, bool inverted, bool alphaInverted) { R = G = B = A = 0f; FromBytes(byteArray, pos, inverted, alphaInverted); } /// <summary> /// Copy constructor /// </summary> /// <param name="color">Color to copy</param> public Color4(Color4 color) { R = color.R; G = color.G; B = color.B; A = color.A; } #endregion Constructors #region Public Methods /// <summary> /// IComparable.CompareTo implementation /// </summary> /// <remarks>Sorting ends up like this: |--Grayscale--||--Color--|. /// Alpha is only used when the colors are otherwise equivalent</remarks> public int CompareTo(Color4 color) { float thisHue = GetHue(); float thatHue = color.GetHue(); if (thisHue < 0f && thatHue < 0f) { // Both monochromatic if (R == color.R) { // Monochromatic and equal, compare alpha return A.CompareTo(color.A); } else { // Compare lightness return R.CompareTo(R); } } else { if (thisHue == thatHue) { // RGB is equal, compare alpha return A.CompareTo(color.A); } else { // Compare hues return thisHue.CompareTo(thatHue); } } } public void FromBytes(byte[] byteArray, int pos, bool inverted) { const float quanta = 1.0f / 255.0f; if (inverted) { R = (float)(255 - byteArray[pos]) * quanta; G = (float)(255 - byteArray[pos + 1]) * quanta; B = (float)(255 - byteArray[pos + 2]) * quanta; A = (float)(255 - byteArray[pos + 3]) * quanta; } else { R = (float)byteArray[pos] * quanta; G = (float)byteArray[pos + 1] * quanta; B = (float)byteArray[pos + 2] * quanta; A = (float)byteArray[pos + 3] * quanta; } } /// <summary> /// Builds a color from a byte array /// </summary> /// <param name="byteArray">Byte array containing a 16 byte color</param> /// <param name="pos">Beginning position in the byte array</param> /// <param name="inverted">True if the byte array stores inverted values, /// otherwise false. For example the color black (fully opaque) inverted /// would be 0xFF 0xFF 0xFF 0x00</param> /// <param name="alphaInverted">True if the alpha value is inverted in /// addition to whatever the inverted parameter is. Setting inverted true /// and alphaInverted true will flip the alpha value back to non-inverted, /// but keep the other color bytes inverted</param> public void FromBytes(byte[] byteArray, int pos, bool inverted, bool alphaInverted) { FromBytes(byteArray, pos, inverted); if (alphaInverted) A = 1.0f - A; } public byte[] GetBytes() { return GetBytes(false); } public byte[] GetBytes(bool inverted) { byte[] byteArray = new byte[4]; ToBytes(byteArray, 0, inverted); return byteArray; } public byte[] GetFloatBytes() { byte[] bytes = new byte[16]; ToFloatBytes(bytes, 0); return bytes; } /// <summary> /// Writes the raw bytes for this color to a byte array /// </summary> /// <param name="dest">Destination byte array</param> /// <param name="pos">Position in the destination array to start /// writing. Must be at least 16 bytes before the end of the array</param> public void ToBytes(byte[] dest, int pos) { ToBytes(dest, pos, false); } /// <summary> /// Serializes this color into four bytes in a byte array /// </summary> /// <param name="dest">Destination byte array</param> /// <param name="pos">Position in the destination array to start /// writing. Must be at least 4 bytes before the end of the array</param> /// <param name="inverted">True to invert the output (1.0 becomes 0 /// instead of 255)</param> public void ToBytes(byte[] dest, int pos, bool inverted) { dest[pos + 0] = Utils.FloatToByte(R, 0f, 1f); dest[pos + 1] = Utils.FloatToByte(G, 0f, 1f); dest[pos + 2] = Utils.FloatToByte(B, 0f, 1f); dest[pos + 3] = Utils.FloatToByte(A, 0f, 1f); if (inverted) { dest[pos + 0] = (byte)(255 - dest[pos + 0]); dest[pos + 1] = (byte)(255 - dest[pos + 1]); dest[pos + 2] = (byte)(255 - dest[pos + 2]); dest[pos + 3] = (byte)(255 - dest[pos + 3]); } } /// <summary> /// Writes the raw bytes for this color to a byte array /// </summary> /// <param name="dest">Destination byte array</param> /// <param name="pos">Position in the destination array to start /// writing. Must be at least 16 bytes before the end of the array</param> public void ToFloatBytes(byte[] dest, int pos) { Buffer.BlockCopy(BitConverter.GetBytes(R), 0, dest, pos + 0, 4); Buffer.BlockCopy(BitConverter.GetBytes(G), 0, dest, pos + 4, 4); Buffer.BlockCopy(BitConverter.GetBytes(B), 0, dest, pos + 8, 4); Buffer.BlockCopy(BitConverter.GetBytes(A), 0, dest, pos + 12, 4); } public float GetHue() { const float HUE_MAX = 360f; float max = Math.Max(Math.Max(R, G), B); float min = Math.Min(Math.Min(R, B), B); if (max == min) { // Achromatic, hue is undefined return -1f; } else if (R == max) { float bDelta = (((max - B) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); float gDelta = (((max - G) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); return bDelta - gDelta; } else if (G == max) { float rDelta = (((max - R) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); float bDelta = (((max - B) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); return (HUE_MAX / 3f) + rDelta - bDelta; } else // B == max { float gDelta = (((max - G) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); float rDelta = (((max - R) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); return ((2f * HUE_MAX) / 3f) + gDelta - rDelta; } } /// <summary> /// Ensures that values are in range 0-1 /// </summary> public void ClampValues() { if (R < 0f) R = 0f; if (G < 0f) G = 0f; if (B < 0f) B = 0f; if (A < 0f) A = 0f; if (R > 1f) R = 1f; if (G > 1f) G = 1f; if (B > 1f) B = 1f; if (A > 1f) A = 1f; } #endregion Public Methods #region Static Methods /// <summary> /// Create an RGB color from a hue, saturation, value combination /// </summary> /// <param name="hue">Hue</param> /// <param name="saturation">Saturation</param> /// <param name="value">Value</param> /// <returns>An fully opaque RGB color (alpha is 1.0)</returns> public static Color4 FromHSV(double hue, double saturation, double value) { double r = 0d; double g = 0d; double b = 0d; if (saturation == 0d) { // If s is 0, all colors are the same. // This is some flavor of gray. r = value; g = value; b = value; } else { double p; double q; double t; double fractionalSector; int sectorNumber; double sectorPos; // The color wheel consists of 6 sectors. // Figure out which sector you//re in. sectorPos = hue / 60d; sectorNumber = (int)(Math.Floor(sectorPos)); // get the fractional part of the sector. // That is, how many degrees into the sector // are you? fractionalSector = sectorPos - sectorNumber; // Calculate values for the three axes // of the color. p = value * (1d - saturation); q = value * (1d - (saturation * fractionalSector)); t = value * (1d - (saturation * (1d - fractionalSector))); // Assign the fractional colors to r, g, and b // based on the sector the angle is in. switch (sectorNumber) { case 0: r = value; g = t; b = p; break; case 1: r = q; g = value; b = p; break; case 2: r = p; g = value; b = t; break; case 3: r = p; g = q; b = value; break; case 4: r = t; g = p; b = value; break; case 5: r = value; g = p; b = q; break; } } return new Color4((float)r, (float)g, (float)b, 1f); } /// <summary> /// Performs linear interpolation between two colors /// </summary> /// <param name="value1">Color to start at</param> /// <param name="value2">Color to end at</param> /// <param name="amount">Amount to interpolate</param> /// <returns>The interpolated color</returns> public static Color4 Lerp(Color4 value1, Color4 value2, float amount) { return new Color4( Utils.Lerp(value1.R, value2.R, amount), Utils.Lerp(value1.G, value2.G, amount), Utils.Lerp(value1.B, value2.B, amount), Utils.Lerp(value1.A, value2.A, amount)); } #endregion Static Methods #region Overrides public override string ToString() { return String.Format(Utils.EnUsCulture, "<{0}, {1}, {2}, {3}>", R, G, B, A); } public string ToRGBString() { return String.Format(Utils.EnUsCulture, "<{0}, {1}, {2}>", R, G, B); } public override bool Equals(object obj) { return (obj is Color4) ? this == (Color4)obj : false; } public bool Equals(Color4 other) { return this == other; } public override int GetHashCode() { return R.GetHashCode() ^ G.GetHashCode() ^ B.GetHashCode() ^ A.GetHashCode(); } #endregion Overrides #region Operators public static bool operator ==(Color4 lhs, Color4 rhs) { return (lhs.R == rhs.R) && (lhs.G == rhs.G) && (lhs.B == rhs.B) && (lhs.A == rhs.A); } public static bool operator !=(Color4 lhs, Color4 rhs) { return !(lhs == rhs); } public static Color4 operator +(Color4 lhs, Color4 rhs) { lhs.R += rhs.R; lhs.G += rhs.G; lhs.B += rhs.B; lhs.A += rhs.A; lhs.ClampValues(); return lhs; } public static Color4 operator -(Color4 lhs, Color4 rhs) { lhs.R -= rhs.R; lhs.G -= rhs.G; lhs.B -= rhs.B; lhs.A -= rhs.A; lhs.ClampValues(); return lhs; } public static Color4 operator *(Color4 lhs, Color4 rhs) { lhs.R *= rhs.R; lhs.G *= rhs.G; lhs.B *= rhs.B; lhs.A *= rhs.A; lhs.ClampValues(); return lhs; } #endregion Operators /// <summary>A Color4 with zero RGB values and fully opaque (alpha 1.0)</summary> public readonly static Color4 Black = new Color4(0f, 0f, 0f, 1f); /// <summary>A Color4 with full RGB values (1.0) and fully opaque (alpha 1.0)</summary> public readonly static Color4 White = new Color4(1f, 1f, 1f, 1f); } }
// 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.Diagnostics; using System.IO; using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; namespace System.Data.SqlClient.SNI { /// <summary> /// TCP connection handle /// </summary> internal class SNITCPHandle : SNIHandle { private readonly string _targetServer; private readonly object _callbackObject; private readonly Socket _socket; private NetworkStream _tcpStream; private readonly TaskScheduler _writeScheduler; private readonly TaskFactory _writeTaskFactory; private Stream _stream; private SslStream _sslStream; private SslOverTdsStream _sslOverTdsStream; private SNIAsyncCallback _receiveCallback; private SNIAsyncCallback _sendCallback; private bool _validateCert = true; private int _bufferSize = TdsEnums.DEFAULT_LOGIN_PACKET_SIZE; private uint _status = TdsEnums.SNI_UNINITIALIZED; private Guid _connectionId = Guid.NewGuid(); private const int MaxParallelIpAddresses = 64; /// <summary> /// Dispose object /// </summary> public override void Dispose() { lock (this) { if (_sslOverTdsStream != null) { _sslOverTdsStream.Dispose(); _sslOverTdsStream = null; } if (_sslStream != null) { _sslStream.Dispose(); _sslStream = null; } if (_tcpStream != null) { _tcpStream.Dispose(); _tcpStream = null; } //Release any references held by _stream. _stream = null; } } /// <summary> /// Connection ID /// </summary> public override Guid ConnectionId { get { return _connectionId; } } /// <summary> /// Connection status /// </summary> public override uint Status { get { return _status; } } /// <summary> /// Constructor /// </summary> /// <param name="serverName">Server name</param> /// <param name="port">TCP port number</param> /// <param name="timerExpire">Connection timer expiration</param> /// <param name="callbackObject">Callback object</param> public SNITCPHandle(string serverName, int port, long timerExpire, object callbackObject, bool parallel) { _writeScheduler = new ConcurrentExclusiveSchedulerPair().ExclusiveScheduler; _writeTaskFactory = new TaskFactory(_writeScheduler); _callbackObject = callbackObject; _targetServer = serverName; try { TimeSpan ts; // In case the Timeout is Infinite, we will receive the max value of Int64 as the tick count // The infinite Timeout is a function of ConnectionString Timeout=0 bool isInfiniteTimeOut = long.MaxValue == timerExpire; if (!isInfiniteTimeOut) { ts = DateTime.FromFileTime(timerExpire) - DateTime.Now; ts = ts.Ticks < 0 ? TimeSpan.FromTicks(0) : ts; } Task<Socket> connectTask; if (parallel) { Task<IPAddress[]> serverAddrTask = Dns.GetHostAddressesAsync(serverName); serverAddrTask.Wait(ts); IPAddress[] serverAddresses = serverAddrTask.Result; if (serverAddresses.Length > MaxParallelIpAddresses) { // Fail if above 64 to match legacy behavior ReportTcpSNIError(0, SNICommon.MultiSubnetFailoverWithMoreThan64IPs, string.Empty); return; } connectTask = ParallelConnectAsync(serverAddresses, port); } else { connectTask = ConnectAsync(serverName, port); } if (!(isInfiniteTimeOut ? connectTask.Wait(-1) : connectTask.Wait(ts))) { ReportTcpSNIError(0, SNICommon.ConnOpenFailedError, string.Empty); return; } _socket = connectTask.Result; if (_socket == null || !_socket.Connected) { if (_socket != null) { _socket.Dispose(); _socket = null; } ReportTcpSNIError(0, SNICommon.ConnOpenFailedError, string.Empty); return; } _socket.NoDelay = true; _tcpStream = new NetworkStream(_socket, true); _sslOverTdsStream = new SslOverTdsStream(_tcpStream); _sslStream = new SslStream(_sslOverTdsStream, true, new RemoteCertificateValidationCallback(ValidateServerCertificate), null); } catch (SocketException se) { ReportTcpSNIError(se); return; } catch (Exception e) { ReportTcpSNIError(e); return; } _stream = _tcpStream; _status = TdsEnums.SNI_SUCCESS; } private static async Task<Socket> ConnectAsync(string serverName, int port) { IPAddress[] addresses = await Dns.GetHostAddressesAsync(serverName).ConfigureAwait(false); IPAddress targetAddrV4 = Array.Find(addresses, addr => (addr.AddressFamily == AddressFamily.InterNetwork)); IPAddress targetAddrV6 = Array.Find(addresses, addr => (addr.AddressFamily == AddressFamily.InterNetworkV6)); if (targetAddrV4 != null && targetAddrV6 != null) { return await ParallelConnectAsync(new IPAddress[] { targetAddrV4, targetAddrV6 }, port).ConfigureAwait(false); } else { IPAddress targetAddr = (targetAddrV4 != null) ? targetAddrV4 : targetAddrV6; var socket = new Socket(targetAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp); try { await socket.ConnectAsync(targetAddr, port).ConfigureAwait(false); } catch { socket.Dispose(); throw; } return socket; } } private static Task<Socket> ParallelConnectAsync(IPAddress[] serverAddresses, int port) { if (serverAddresses == null) { throw new ArgumentNullException(nameof(serverAddresses)); } if (serverAddresses.Length == 0) { throw new ArgumentOutOfRangeException(nameof(serverAddresses)); } var sockets = new List<Socket>(serverAddresses.Length); var connectTasks = new List<Task>(serverAddresses.Length); var tcs = new TaskCompletionSource<Socket>(); var lastError = new StrongBox<Exception>(); var pendingCompleteCount = new StrongBox<int>(serverAddresses.Length); foreach (IPAddress address in serverAddresses) { var socket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp); sockets.Add(socket); // Start all connection tasks now, to prevent possible race conditions with // calling ConnectAsync on disposed sockets. try { connectTasks.Add(socket.ConnectAsync(address, port)); } catch (Exception e) { connectTasks.Add(Task.FromException(e)); } } for (int i = 0; i < sockets.Count; i++) { ParallelConnectHelper(sockets[i], connectTasks[i], tcs, pendingCompleteCount, lastError, sockets); } return tcs.Task; } private static async void ParallelConnectHelper( Socket socket, Task connectTask, TaskCompletionSource<Socket> tcs, StrongBox<int> pendingCompleteCount, StrongBox<Exception> lastError, List<Socket> sockets) { bool success = false; try { // Try to connect. If we're successful, store this task into the result task. await connectTask.ConfigureAwait(false); success = tcs.TrySetResult(socket); if (success) { // Whichever connection completes the return task is responsible for disposing // all of the sockets (except for whichever one is stored into the result task). // This ensures that only one thread will attempt to dispose of a socket. // This is also the closest thing we have to canceling connect attempts. foreach (Socket otherSocket in sockets) { if (otherSocket != socket) { otherSocket.Dispose(); } } } } catch (Exception e) { // Store an exception to be published if no connection succeeds Interlocked.Exchange(ref lastError.Value, e); } finally { // If we didn't successfully transition the result task to completed, // then someone else did and they would have cleaned up, so there's nothing // more to do. Otherwise, no one completed it yet or we failed; either way, // see if we're the last outstanding connection, and if we are, try to complete // the task, and if we're successful, it's our responsibility to dispose all of the sockets. if (!success && Interlocked.Decrement(ref pendingCompleteCount.Value) == 0) { if (lastError.Value != null) { tcs.TrySetException(lastError.Value); } else { tcs.TrySetCanceled(); } foreach (Socket s in sockets) { s.Dispose(); } } } } /// <summary> /// Enable SSL /// </summary> public override uint EnableSsl(uint options) { _validateCert = (options & TdsEnums.SNI_SSL_VALIDATE_CERTIFICATE) != 0; try { _sslStream.AuthenticateAsClientAsync(_targetServer).GetAwaiter().GetResult(); _sslOverTdsStream.FinishHandshake(); } catch (AuthenticationException aue) { return ReportTcpSNIError(aue); } catch (InvalidOperationException ioe) { return ReportTcpSNIError(ioe); } _stream = _sslStream; return TdsEnums.SNI_SUCCESS; } /// <summary> /// Disable SSL /// </summary> public override void DisableSsl() { _sslStream.Dispose(); _sslStream = null; _sslOverTdsStream.Dispose(); _sslOverTdsStream = null; _stream = _tcpStream; } /// <summary> /// Validate server certificate callback /// </summary> /// <param name="sender">Sender object</param> /// <param name="cert">X.509 certificate</param> /// <param name="chain">X.509 chain</param> /// <param name="policyErrors">Policy errors</param> /// <returns>True if certificate is valid</returns> private bool ValidateServerCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors policyErrors) { if (!_validateCert) { return true; } return SNICommon.ValidateSslServerCertificate(_targetServer, sender, cert, chain, policyErrors); } /// <summary> /// Set buffer size /// </summary> /// <param name="bufferSize">Buffer size</param> public override void SetBufferSize(int bufferSize) { _bufferSize = bufferSize; _socket.SendBufferSize = bufferSize; _socket.ReceiveBufferSize = bufferSize; } /// <summary> /// Send a packet synchronously /// </summary> /// <param name="packet">SNI packet</param> /// <returns>SNI error code</returns> public override uint Send(SNIPacket packet) { lock (this) { try { packet.WriteToStream(_stream); return TdsEnums.SNI_SUCCESS; } catch (ObjectDisposedException ode) { return ReportTcpSNIError(ode); } catch (SocketException se) { return ReportTcpSNIError(se); } catch (IOException ioe) { return ReportTcpSNIError(ioe); } } } /// <summary> /// Receive a packet synchronously /// </summary> /// <param name="packet">SNI packet</param> /// <param name="timeoutInMilliseconds">Timeout in Milliseconds</param> /// <returns>SNI error code</returns> public override uint Receive(out SNIPacket packet, int timeoutInMilliseconds) { lock (this) { packet = null; try { if (timeoutInMilliseconds > 0) { _socket.ReceiveTimeout = timeoutInMilliseconds; } else if (timeoutInMilliseconds == -1) { // SqlCient internally represents infinite timeout by -1, and for TcpClient this is translated to a timeout of 0 _socket.ReceiveTimeout = 0; } else { // otherwise it is timeout for 0 or less than -1 ReportTcpSNIError(0, SNICommon.ConnTimeoutError, string.Empty); return TdsEnums.SNI_WAIT_TIMEOUT; } packet = new SNIPacket(null); packet.Allocate(_bufferSize); packet.ReadFromStream(_stream); if (packet.Length == 0) { return ReportErrorAndReleasePacket(packet, 0, SNICommon.ConnTerminatedError, string.Empty); } return TdsEnums.SNI_SUCCESS; } catch (ObjectDisposedException ode) { return ReportErrorAndReleasePacket(packet, ode); } catch (SocketException se) { return ReportErrorAndReleasePacket(packet, se); } catch (IOException ioe) { uint errorCode = ReportErrorAndReleasePacket(packet, ioe); if (ioe.InnerException is SocketException && ((SocketException)(ioe.InnerException)).SocketErrorCode == SocketError.TimedOut) { errorCode = TdsEnums.SNI_WAIT_TIMEOUT; } return errorCode; } finally { _socket.ReceiveTimeout = 0; } } } /// <summary> /// Set async callbacks /// </summary> /// <param name="receiveCallback">Receive callback</param> /// <param name="sendCallback">Send callback</param> /// <summary> public override void SetAsyncCallbacks(SNIAsyncCallback receiveCallback, SNIAsyncCallback sendCallback) { _receiveCallback = receiveCallback; _sendCallback = sendCallback; } /// <summary> /// Send a packet asynchronously /// </summary> /// <param name="packet">SNI packet</param> /// <param name="callback">Completion callback</param> /// <returns>SNI error code</returns> public override uint SendAsync(SNIPacket packet, SNIAsyncCallback callback = null) { SNIPacket newPacket = packet; _writeTaskFactory.StartNew(() => { try { lock (this) { packet.WriteToStream(_stream); } } catch (Exception e) { SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.TCP_PROV, SNICommon.InternalExceptionError, e); if (callback != null) { callback(packet, TdsEnums.SNI_ERROR); } else { _sendCallback(packet, TdsEnums.SNI_ERROR); } return; } if (callback != null) { callback(packet, TdsEnums.SNI_SUCCESS); } else { _sendCallback(packet, TdsEnums.SNI_SUCCESS); } }); return TdsEnums.SNI_SUCCESS_IO_PENDING; } /// <summary> /// Receive a packet asynchronously /// </summary> /// <param name="packet">SNI packet</param> /// <returns>SNI error code</returns> public override uint ReceiveAsync(ref SNIPacket packet) { lock (this) { packet = new SNIPacket(null); packet.Allocate(_bufferSize); try { packet.ReadFromStreamAsync(_stream, _receiveCallback); return TdsEnums.SNI_SUCCESS_IO_PENDING; } catch (ObjectDisposedException ode) { return ReportErrorAndReleasePacket(packet, ode); } catch (SocketException se) { return ReportErrorAndReleasePacket(packet, se); } catch (IOException ioe) { return ReportErrorAndReleasePacket(packet, ioe); } } } /// <summary> /// Check SNI handle connection /// </summary> /// <param name="handle"></param> /// <returns>SNI error status</returns> public override uint CheckConnection() { try { if (!_socket.Connected || _socket.Poll(0, SelectMode.SelectError)) { return TdsEnums.SNI_ERROR; } } catch (SocketException se) { return ReportTcpSNIError(se); } catch (ObjectDisposedException ode) { return ReportTcpSNIError(ode); } return TdsEnums.SNI_SUCCESS; } private uint ReportTcpSNIError(Exception sniException) { _status = TdsEnums.SNI_ERROR; return SNICommon.ReportSNIError(SNIProviders.TCP_PROV, SNICommon.InternalExceptionError, sniException); } private uint ReportTcpSNIError(uint nativeError, uint sniError, string errorMessage) { _status = TdsEnums.SNI_ERROR; return SNICommon.ReportSNIError(SNIProviders.TCP_PROV, nativeError, sniError, errorMessage); } private uint ReportErrorAndReleasePacket(SNIPacket packet, Exception sniException) { if (packet != null) { packet.Release(); } return ReportTcpSNIError(sniException); } private uint ReportErrorAndReleasePacket(SNIPacket packet, uint nativeError, uint sniError, string errorMessage) { if (packet != null) { packet.Release(); } return ReportTcpSNIError(nativeError, sniError, errorMessage); } #if DEBUG /// <summary> /// Test handle for killing underlying connection /// </summary> public override void KillConnection() { _socket.Shutdown(SocketShutdown.Both); } #endif } }
// 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 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsHttp { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; public static partial class HttpClientFailureExtensions { /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Head400(this IHttpClientFailure operations) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Head400Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Head400Async( this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.Head400WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Get400(this IHttpClientFailure operations) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Get400Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Get400Async( this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.Get400WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Put400(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Put400Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Put400Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.Put400WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Patch400(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Patch400Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Patch400Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.Patch400WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Post400(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Post400Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Post400Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.Post400WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Delete400(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Delete400Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Delete400Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.Delete400WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Return 401 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Head401(this IHttpClientFailure operations) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Head401Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 401 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Head401Async( this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.Head401WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Return 402 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Get402(this IHttpClientFailure operations) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Get402Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 402 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Get402Async( this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.Get402WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Return 403 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Get403(this IHttpClientFailure operations) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Get403Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 403 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Get403Async( this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.Get403WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Return 404 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Put404(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Put404Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 404 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Put404Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.Put404WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Return 405 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Patch405(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Patch405Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 405 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Patch405Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.Patch405WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Return 406 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Post406(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Post406Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 406 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Post406Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.Post406WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Return 407 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Delete407(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Delete407Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 407 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Delete407Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.Delete407WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Return 409 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Put409(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Put409Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 409 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Put409Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.Put409WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Return 410 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Head410(this IHttpClientFailure operations) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Head410Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 410 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Head410Async( this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.Head410WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Return 411 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Get411(this IHttpClientFailure operations) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Get411Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 411 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Get411Async( this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.Get411WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Return 412 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Get412(this IHttpClientFailure operations) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Get412Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 412 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Get412Async( this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.Get412WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Return 413 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Put413(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Put413Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 413 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Put413Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.Put413WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Return 414 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Patch414(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Patch414Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 414 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Patch414Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.Patch414WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Return 415 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Post415(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Post415Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 415 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Post415Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.Post415WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Return 416 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Get416(this IHttpClientFailure operations) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Get416Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 416 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Get416Async( this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.Get416WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Return 417 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Delete417(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Delete417Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 417 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Delete417Async( this IHttpClientFailure operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.Delete417WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Return 429 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Head429(this IHttpClientFailure operations) { return Task.Factory.StartNew(s => ((IHttpClientFailure)s).Head429Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 429 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> Head429Async( this IHttpClientFailure operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.Head429WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } } }
/* * 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. */ namespace Apache.Ignite.Core.Impl.Compute { using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Impl.Cluster; using Apache.Ignite.Core.Impl.Compute.Closure; using Apache.Ignite.Core.Impl.Memory; using Apache.Ignite.Core.Impl.Portable; using Apache.Ignite.Core.Impl.Portable.IO; using Apache.Ignite.Core.Impl.Resource; using Apache.Ignite.Core.Portable; /// <summary> /// Holder for user-provided compute job. /// </summary> internal class ComputeJobHolder : IPortableWriteAware { /** Actual job. */ private readonly IComputeJob _job; /** Owning grid. */ private readonly Ignite _ignite; /** Result (set for local jobs only). */ private volatile ComputeJobResultImpl _jobRes; /// <summary> /// Default ctor for marshalling. /// </summary> /// <param name="reader"></param> public ComputeJobHolder(IPortableReader reader) { Debug.Assert(reader != null); var reader0 = (PortableReaderImpl) reader.RawReader(); _ignite = reader0.Marshaller.Ignite; _job = PortableUtils.ReadPortableOrSerializable<IComputeJob>(reader0); } /// <summary> /// Constructor. /// </summary> /// <param name="grid">Grid.</param> /// <param name="job">Job.</param> public ComputeJobHolder(Ignite grid, IComputeJob job) { Debug.Assert(grid != null); Debug.Assert(job != null); _ignite = grid; _job = job; } /// <summary> /// Executes local job. /// </summary> /// <param name="cancel">Cancel flag.</param> public void ExecuteLocal(bool cancel) { object res; bool success; Execute0(cancel, out res, out success); _jobRes = new ComputeJobResultImpl( success ? res : null, success ? null : res as Exception, _job, _ignite.LocalNode.Id, cancel ); } /// <summary> /// Execute job serializing result to the stream. /// </summary> /// <param name="cancel">Whether the job must be cancelled.</param> /// <param name="stream">Stream.</param> public void ExecuteRemote(PlatformMemoryStream stream, bool cancel) { // 1. Execute job. object res; bool success; Execute0(cancel, out res, out success); // 2. Try writing result to the stream. ClusterGroupImpl prj = _ignite.ClusterGroup; PortableWriterImpl writer = prj.Marshaller.StartMarshal(stream); try { // 3. Marshal results. PortableUtils.WriteWrappedInvocationResult(writer, success, res); } finally { // 4. Process metadata. prj.FinishMarshal(writer); } } /// <summary> /// Cancel the job. /// </summary> public void Cancel() { _job.Cancel(); } /// <summary> /// Serialize the job to the stream. /// </summary> /// <param name="stream">Stream.</param> /// <returns>True if successfull.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "User job can throw any exception")] internal bool Serialize(IPortableStream stream) { ClusterGroupImpl prj = _ignite.ClusterGroup; PortableWriterImpl writer = prj.Marshaller.StartMarshal(stream); try { writer.Write(this); return true; } catch (Exception e) { writer.WriteString("Failed to marshal job [job=" + _job + ", errType=" + e.GetType().Name + ", errMsg=" + e.Message + ']'); return false; } finally { // 4. Process metadata. prj.FinishMarshal(writer); } } /// <summary> /// Job. /// </summary> internal IComputeJob Job { get { return _job; } } /// <summary> /// Job result. /// </summary> internal ComputeJobResultImpl JobResult { get { return _jobRes; } } /// <summary> /// Internal job execution routine. /// </summary> /// <param name="cancel">Cancel flag.</param> /// <param name="res">Result.</param> /// <param name="success">Success flag.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "User job can throw any exception")] private void Execute0(bool cancel, out object res, out bool success) { // 1. Inject resources. IComputeResourceInjector injector = _job as IComputeResourceInjector; if (injector != null) injector.Inject(_ignite); else ResourceProcessor.Inject(_job, _ignite); // 2. Execute. try { if (cancel) _job.Cancel(); res = _job.Execute(); success = true; } catch (Exception e) { res = e; success = false; } } /** <inheritDoc /> */ public void WritePortable(IPortableWriter writer) { PortableWriterImpl writer0 = (PortableWriterImpl) writer.RawWriter(); writer0.DetachNext(); PortableUtils.WritePortableOrSerializable(writer0, _job); } /// <summary> /// Create job instance. /// </summary> /// <param name="grid">Grid.</param> /// <param name="stream">Stream.</param> /// <returns></returns> internal static ComputeJobHolder CreateJob(Ignite grid, IPortableStream stream) { try { return grid.Marshaller.StartUnmarshal(stream).ReadObject<ComputeJobHolder>(); } catch (Exception e) { throw new IgniteException("Failed to deserialize the job [errType=" + e.GetType().Name + ", errMsg=" + e.Message + ']'); } } } }
using System; using UnityEditor.UIElements; using UnityEngine; using UnityEngine.UIElements; using UnityEditor.Graphing.Util; using UnityEditor.ShaderGraph; using UnityEditor.ShaderGraph.Drawing; using UnityEditor.ShaderGraph.Drawing.Controls; using UnityEditor.Experimental.Rendering.HDPipeline; using UnityEngine.Experimental.Rendering.HDPipeline; namespace UnityEditor.Experimental.Rendering.HDPipeline.Drawing { class HDLitSettingsView : VisualElement { HDLitMasterNode m_Node; IntegerField m_SortPiorityField; Label CreateLabel(string text, int indentLevel) { string label = ""; for (var i = 0; i < indentLevel; i++) { label += " "; } return new Label(label + text); } public HDLitSettingsView(HDLitMasterNode node) { m_Node = node; PropertySheet ps = new PropertySheet(); int indentLevel = 0; ps.Add(new PropertyRow(CreateLabel("Surface Type", indentLevel)), (row) => { row.Add(new EnumField(SurfaceType.Opaque), (field) => { field.value = m_Node.surfaceType; field.RegisterValueChangedCallback(ChangeSurfaceType); }); }); ++indentLevel; switch (m_Node.surfaceType) { case SurfaceType.Opaque: ps.Add(new PropertyRow(CreateLabel("Rendering Pass", indentLevel)), (row) => { var valueList = HDSubShaderUtilities.GetRenderingPassList(true, false); row.Add(new PopupField<HDRenderQueue.RenderQueueType>(valueList, HDRenderQueue.RenderQueueType.Opaque, HDSubShaderUtilities.RenderQueueName, HDSubShaderUtilities.RenderQueueName), (field) => { field.value = HDRenderQueue.GetOpaqueEquivalent(m_Node.renderingPass); field.RegisterValueChangedCallback(ChangeRenderingPass); }); }); break; case SurfaceType.Transparent: ps.Add(new PropertyRow(CreateLabel("Rendering Pass", indentLevel)), (row) => { Enum defaultValue; switch (m_Node.renderingPass) // Migration { default: //when deserializing without issue, we still need to init the default to something even if not used. case HDRenderQueue.RenderQueueType.Transparent: defaultValue = HDRenderQueue.TransparentRenderQueue.Default; break; case HDRenderQueue.RenderQueueType.PreRefraction: defaultValue = HDRenderQueue.TransparentRenderQueue.BeforeRefraction; break; } var valueList = HDSubShaderUtilities.GetRenderingPassList(false, false); row.Add(new PopupField<HDRenderQueue.RenderQueueType>(valueList, HDRenderQueue.RenderQueueType.Transparent, HDSubShaderUtilities.RenderQueueName, HDSubShaderUtilities.RenderQueueName), (field) => { field.value = HDRenderQueue.GetTransparentEquivalent(m_Node.renderingPass); field.RegisterValueChangedCallback(ChangeRenderingPass); }); }); break; default: throw new ArgumentException("Unknown SurfaceType"); } --indentLevel; if (m_Node.surfaceType == SurfaceType.Transparent) { ++indentLevel; if (!m_Node.HasRefraction()) { ps.Add(new PropertyRow(CreateLabel("Blending Mode", indentLevel)), (row) => { row.Add(new EnumField(HDLitMasterNode.AlphaModeLit.Additive), (field) => { field.value = GetAlphaModeLit(m_Node.alphaMode); field.RegisterValueChangedCallback(ChangeBlendMode); }); }); ++indentLevel; ps.Add(new PropertyRow(CreateLabel("Preserve Specular Lighting", indentLevel)), (row) => { row.Add(new Toggle(), (toggle) => { toggle.value = m_Node.blendPreserveSpecular.isOn; toggle.OnToggleChanged(ChangeBlendPreserveSpecular); }); }); --indentLevel; } m_SortPiorityField = new IntegerField(); ps.Add(new PropertyRow(CreateLabel("Sorting Priority", indentLevel)), (row) => { row.Add(m_SortPiorityField, (field) => { field.value = m_Node.sortPriority; field.RegisterValueChangedCallback(ChangeSortPriority); }); }); ps.Add(new PropertyRow(CreateLabel("Receive Fog", indentLevel)), (row) => { row.Add(new Toggle(), (toggle) => { toggle.value = m_Node.transparencyFog.isOn; toggle.OnToggleChanged(ChangeTransparencyFog); }); }); ps.Add(new PropertyRow(CreateLabel("Back Then Front Rendering", indentLevel)), (row) => { row.Add(new Toggle(), (toggle) => { toggle.value = m_Node.backThenFrontRendering.isOn; toggle.OnToggleChanged(ChangeBackThenFrontRendering); }); }); ps.Add(new PropertyRow(CreateLabel("Transparent Depth Prepass", indentLevel)), (row) => { row.Add(new Toggle(), (toggle) => { toggle.value = m_Node.alphaTestDepthPrepass.isOn; toggle.OnToggleChanged(ChangeAlphaTestPrepass); }); }); ps.Add(new PropertyRow(CreateLabel("Transparent Depth Postpass", indentLevel)), (row) => { row.Add(new Toggle(), (toggle) => { toggle.value = m_Node.alphaTestDepthPostpass.isOn; toggle.OnToggleChanged(ChangeAlphaTestPostpass); }); }); ps.Add(new PropertyRow(CreateLabel("Transparent Writes Motion Vector", indentLevel)), (row) => { row.Add(new Toggle(), (toggle) => { toggle.value = m_Node.transparentWritesMotionVec.isOn; toggle.OnToggleChanged(ChangeTransparentWritesMotionVec); }); }); if (m_Node.renderingPass != HDRenderQueue.RenderQueueType.PreRefraction) { ps.Add(new PropertyRow(CreateLabel("Refraction Model", indentLevel)), (row) => { row.Add(new EnumField(ScreenSpaceRefraction.RefractionModel.None), (field) => { field.value = m_Node.refractionModel; field.RegisterValueChangedCallback(ChangeRefractionModel); }); }); } ps.Add(new PropertyRow(CreateLabel("Distortion", indentLevel)), (row) => { row.Add(new Toggle(), (toggle) => { toggle.value = m_Node.distortion.isOn; toggle.OnToggleChanged(ChangeDistortion); }); }); if (m_Node.distortion.isOn) { ++indentLevel; ps.Add(new PropertyRow(CreateLabel("Mode", indentLevel)), (row) => { row.Add(new EnumField(DistortionMode.Add), (field) => { field.value = m_Node.distortionMode; field.RegisterValueChangedCallback(ChangeDistortionMode); }); }); ps.Add(new PropertyRow(CreateLabel("Depth Test", indentLevel)), (row) => { row.Add(new Toggle(), (toggle) => { toggle.value = m_Node.distortionDepthTest.isOn; toggle.OnToggleChanged(ChangeDistortionDepthTest); }); }); --indentLevel; } --indentLevel; } ps.Add(new PropertyRow(CreateLabel("Double-Sided", indentLevel)), (row) => { row.Add(new EnumField(DoubleSidedMode.Disabled), (field) => { field.value = m_Node.doubleSidedMode; field.RegisterValueChangedCallback(ChangeDoubleSidedMode); }); }); ps.Add(new PropertyRow(CreateLabel("Alpha Clipping", indentLevel)), (row) => { row.Add(new Toggle(), (toggle) => { toggle.value = m_Node.alphaTest.isOn; toggle.OnToggleChanged(ChangeAlphaTest); }); }); if (m_Node.alphaTest.isOn) { ++indentLevel; ps.Add(new PropertyRow(CreateLabel("Use Shadow Threshold", indentLevel)), (row) => { row.Add(new Toggle(), (toggle) => { toggle.value = m_Node.alphaTestShadow.isOn; toggle.OnToggleChanged(ChangeAlphaTestShadow); }); }); --indentLevel; } ps.Add(new PropertyRow(CreateLabel("Material Type", indentLevel)), (row) => { row.Add(new EnumField(HDLitMasterNode.MaterialType.Standard), (field) => { field.value = m_Node.materialType; field.RegisterValueChangedCallback(ChangeMaterialType); }); }); ++indentLevel; if (m_Node.materialType == HDLitMasterNode.MaterialType.SubsurfaceScattering) { ps.Add(new PropertyRow(CreateLabel("Transmission", indentLevel)), (row) => { row.Add(new Toggle(), (toggle) => { toggle.value = m_Node.sssTransmission.isOn; toggle.OnToggleChanged(ChangeSSSTransmission); }); }); } if (m_Node.materialType == HDLitMasterNode.MaterialType.SpecularColor) { ps.Add(new PropertyRow(CreateLabel("Energy Conserving Specular", indentLevel)), (row) => { row.Add(new Toggle(), (toggle) => { toggle.value = m_Node.energyConservingSpecular.isOn; toggle.OnToggleChanged(ChangeEnergyConservingSpecular); }); }); } --indentLevel; ps.Add(new PropertyRow(CreateLabel("Receive Decals", indentLevel)), (row) => { row.Add(new Toggle(), (toggle) => { toggle.value = m_Node.receiveDecals.isOn; toggle.OnToggleChanged(ChangeDecal); }); }); ps.Add(new PropertyRow(CreateLabel("Receive SSR", indentLevel)), (row) => { row.Add(new Toggle(), (toggle) => { toggle.value = m_Node.receiveSSR.isOn; toggle.OnToggleChanged(ChangeSSR); }); }); ps.Add(new PropertyRow(CreateLabel("Geometric Specular AA", indentLevel)), (row) => { row.Add(new Toggle(), (toggle) => { toggle.value = m_Node.specularAA.isOn; toggle.OnToggleChanged(ChangeSpecularAA); }); }); ps.Add(new PropertyRow(CreateLabel("Specular Occlusion Mode", indentLevel)), (row) => { row.Add(new EnumField(SpecularOcclusionMode.Off), (field) => { field.value = m_Node.specularOcclusionMode; field.RegisterValueChangedCallback(ChangeSpecularOcclusionMode); }); }); ps.Add(new PropertyRow(CreateLabel("Override Baked GI", indentLevel)), (row) => { row.Add(new Toggle(), (toggle) => { toggle.value = m_Node.overrideBakedGI.isOn; toggle.OnToggleChanged(ChangeoverrideBakedGI); }); }); ps.Add(new PropertyRow(CreateLabel("Depth Offset", indentLevel)), (row) => { row.Add(new Toggle(), (toggle) => { toggle.value = m_Node.depthOffset.isOn; toggle.OnToggleChanged(ChangeDepthOffset); }); }); ps.Add(new PropertyRow(CreateLabel("DOTS instancing", indentLevel)), (row) => { row.Add(new Toggle(), (toggle) => { toggle.value = m_Node.dotsInstancing.isOn; toggle.OnToggleChanged(ChangeDotsInstancing); }); }); Add(ps); } void ChangeSurfaceType(ChangeEvent<Enum> evt) { if (Equals(m_Node.surfaceType, evt.newValue)) return; m_Node.owner.owner.RegisterCompleteObjectUndo("Surface Type Change"); m_Node.surfaceType = (SurfaceType)evt.newValue; UpdateRenderingPassValue(m_Node.renderingPass); } void ChangeDoubleSidedMode(ChangeEvent<Enum> evt) { if (Equals(m_Node.doubleSidedMode, evt.newValue)) return; m_Node.owner.owner.RegisterCompleteObjectUndo("Double-Sided Mode Change"); m_Node.doubleSidedMode = (DoubleSidedMode)evt.newValue; } void ChangeMaterialType(ChangeEvent<Enum> evt) { if (Equals(m_Node.materialType, evt.newValue)) return; m_Node.owner.owner.RegisterCompleteObjectUndo("Material Type Change"); m_Node.materialType = (HDLitMasterNode.MaterialType)evt.newValue; } void ChangeSSSTransmission(ChangeEvent<bool> evt) { m_Node.owner.owner.RegisterCompleteObjectUndo("SSS Transmission Change"); ToggleData td = m_Node.sssTransmission; td.isOn = evt.newValue; m_Node.sssTransmission = td; } void ChangeBlendMode(ChangeEvent<Enum> evt) { // Make sure the mapping is correct by handling each case. AlphaMode alphaMode = GetAlphaMode((HDLitMasterNode.AlphaModeLit)evt.newValue); if (Equals(m_Node.alphaMode, alphaMode)) return; m_Node.owner.owner.RegisterCompleteObjectUndo("Alpha Mode Change"); m_Node.alphaMode = alphaMode; } void ChangeRenderingPass(ChangeEvent<HDRenderQueue.RenderQueueType> evt) { switch (evt.newValue) { case HDRenderQueue.RenderQueueType.Overlay: case HDRenderQueue.RenderQueueType.Unknown: case HDRenderQueue.RenderQueueType.Background: throw new ArgumentException("Unexpected kind of RenderQueue, was " + evt.newValue); default: break; }; UpdateRenderingPassValue(evt.newValue); } void UpdateRenderingPassValue(HDRenderQueue.RenderQueueType newValue) { HDRenderQueue.RenderQueueType renderingPass; switch (m_Node.surfaceType) { case SurfaceType.Opaque: renderingPass = HDRenderQueue.GetOpaqueEquivalent(newValue); break; case SurfaceType.Transparent: renderingPass = HDRenderQueue.GetTransparentEquivalent(newValue); break; default: throw new ArgumentException("Unknown SurfaceType"); } if (Equals(m_Node.renderingPass, renderingPass)) return; m_Node.owner.owner.RegisterCompleteObjectUndo("Rendering Pass Change"); m_Node.renderingPass = renderingPass; } void ChangeBlendPreserveSpecular(ChangeEvent<bool> evt) { m_Node.owner.owner.RegisterCompleteObjectUndo("Blend Preserve Specular Change"); ToggleData td = m_Node.blendPreserveSpecular; td.isOn = evt.newValue; m_Node.blendPreserveSpecular = td; } void ChangeTransparencyFog(ChangeEvent<bool> evt) { m_Node.owner.owner.RegisterCompleteObjectUndo("Transparency Fog Change"); ToggleData td = m_Node.transparencyFog; td.isOn = evt.newValue; m_Node.transparencyFog = td; } void ChangeRefractionModel(ChangeEvent<Enum> evt) { if (Equals(m_Node.refractionModel, evt.newValue)) return; m_Node.owner.owner.RegisterCompleteObjectUndo("Refraction Model Change"); m_Node.refractionModel = (ScreenSpaceRefraction.RefractionModel)evt.newValue; } void ChangeDistortion(ChangeEvent<bool> evt) { m_Node.owner.owner.RegisterCompleteObjectUndo("Distortion Change"); ToggleData td = m_Node.distortion; td.isOn = evt.newValue; m_Node.distortion = td; } void ChangeDistortionMode(ChangeEvent<Enum> evt) { if (Equals(m_Node.distortionMode, evt.newValue)) return; m_Node.owner.owner.RegisterCompleteObjectUndo("Distortion Mode Change"); m_Node.distortionMode = (DistortionMode)evt.newValue; } void ChangeDistortionDepthTest(ChangeEvent<bool> evt) { m_Node.owner.owner.RegisterCompleteObjectUndo("Distortion Depth Test Change"); ToggleData td = m_Node.distortionDepthTest; td.isOn = evt.newValue; m_Node.distortionDepthTest = td; } void ChangeBackThenFrontRendering(ChangeEvent<bool> evt) { m_Node.owner.owner.RegisterCompleteObjectUndo("Back Then Front Rendering Change"); ToggleData td = m_Node.backThenFrontRendering; td.isOn = evt.newValue; m_Node.backThenFrontRendering = td; } void ChangeSortPriority(ChangeEvent<int> evt) { m_Node.sortPriority = HDRenderQueue.ClampsTransparentRangePriority(evt.newValue); // Force the text to match. m_SortPiorityField.value = m_Node.sortPriority; if (Equals(m_Node.sortPriority, evt.newValue)) return; m_Node.owner.owner.RegisterCompleteObjectUndo("Sort Priority Change"); } void ChangeAlphaTest(ChangeEvent<bool> evt) { m_Node.owner.owner.RegisterCompleteObjectUndo("Alpha Test Change"); ToggleData td = m_Node.alphaTest; td.isOn = evt.newValue; m_Node.alphaTest = td; } void ChangeAlphaTestPrepass(ChangeEvent<bool> evt) { m_Node.owner.owner.RegisterCompleteObjectUndo("Alpha Test Depth Prepass Change"); ToggleData td = m_Node.alphaTestDepthPrepass; td.isOn = evt.newValue; m_Node.alphaTestDepthPrepass = td; } void ChangeAlphaTestPostpass(ChangeEvent<bool> evt) { m_Node.owner.owner.RegisterCompleteObjectUndo("Alpha Test Depth Postpass Change"); ToggleData td = m_Node.alphaTestDepthPostpass; td.isOn = evt.newValue; m_Node.alphaTestDepthPostpass = td; } void ChangeTransparentWritesMotionVec(ChangeEvent<bool> evt) { m_Node.owner.owner.RegisterCompleteObjectUndo("Transparent Writes Motion Vector Change"); ToggleData td = m_Node.transparentWritesMotionVec; td.isOn = evt.newValue; m_Node.transparentWritesMotionVec = td; } void ChangeAlphaTestShadow(ChangeEvent<bool> evt) { m_Node.owner.owner.RegisterCompleteObjectUndo("Alpha Test Shadow Change"); ToggleData td = m_Node.alphaTestShadow; td.isOn = evt.newValue; m_Node.alphaTestShadow = td; } void ChangeDecal(ChangeEvent<bool> evt) { m_Node.owner.owner.RegisterCompleteObjectUndo("Decal Change"); ToggleData td = m_Node.receiveDecals; td.isOn = evt.newValue; m_Node.receiveDecals = td; } void ChangeSSR(ChangeEvent<bool> evt) { m_Node.owner.owner.RegisterCompleteObjectUndo("SSR Change"); ToggleData td = m_Node.receiveSSR; td.isOn = evt.newValue; m_Node.receiveSSR = td; } void ChangeSpecularAA(ChangeEvent<bool> evt) { m_Node.owner.owner.RegisterCompleteObjectUndo("Specular AA Change"); ToggleData td = m_Node.specularAA; td.isOn = evt.newValue; m_Node.specularAA = td; } void ChangeEnergyConservingSpecular(ChangeEvent<bool> evt) { m_Node.owner.owner.RegisterCompleteObjectUndo("Energy Conserving Specular Change"); ToggleData td = m_Node.energyConservingSpecular; td.isOn = evt.newValue; m_Node.energyConservingSpecular = td; } void ChangeSpecularOcclusionMode(ChangeEvent<Enum> evt) { if (Equals(m_Node.specularOcclusionMode, evt.newValue)) return; m_Node.owner.owner.RegisterCompleteObjectUndo("Specular Occlusion Mode Change"); m_Node.specularOcclusionMode = (SpecularOcclusionMode)evt.newValue; } void ChangeoverrideBakedGI(ChangeEvent<bool> evt) { m_Node.owner.owner.RegisterCompleteObjectUndo("overrideBakedGI Change"); ToggleData td = m_Node.overrideBakedGI; td.isOn = evt.newValue; m_Node.overrideBakedGI = td; } void ChangeDepthOffset(ChangeEvent<bool> evt) { m_Node.owner.owner.RegisterCompleteObjectUndo("DepthOffset Change"); ToggleData td = m_Node.depthOffset; td.isOn = evt.newValue; m_Node.depthOffset = td; } void ChangeDotsInstancing(ChangeEvent<bool> evt) { m_Node.owner.owner.RegisterCompleteObjectUndo("DotsInstancing Change"); ToggleData td = m_Node.dotsInstancing; td.isOn = evt.newValue; m_Node.dotsInstancing = td; } public AlphaMode GetAlphaMode(HDLitMasterNode.AlphaModeLit alphaModeLit) { switch (alphaModeLit) { case HDLitMasterNode.AlphaModeLit.Alpha: return AlphaMode.Alpha; case HDLitMasterNode.AlphaModeLit.Premultiply: return AlphaMode.Premultiply; case HDLitMasterNode.AlphaModeLit.Additive: return AlphaMode.Additive; default: { Debug.LogWarning("Not supported: " + alphaModeLit); return AlphaMode.Alpha; } } } public HDLitMasterNode.AlphaModeLit GetAlphaModeLit(AlphaMode alphaMode) { switch (alphaMode) { case AlphaMode.Alpha: return HDLitMasterNode.AlphaModeLit.Alpha; case AlphaMode.Premultiply: return HDLitMasterNode.AlphaModeLit.Premultiply; case AlphaMode.Additive: return HDLitMasterNode.AlphaModeLit.Additive; default: { Debug.LogWarning("Not supported: " + alphaMode); return HDLitMasterNode.AlphaModeLit.Alpha; } } } } }
// // Copyright (C) DataStax Inc. // // 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.Concurrent; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; using Cassandra.Connections; using Cassandra.Observers; using Cassandra.Requests; using Cassandra.Responses; using Cassandra.Serialization; using Moq; using NUnit.Framework; namespace Cassandra.Tests { [TestFixture] public class ConnectionTests { private static readonly IPEndPoint Address = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1000); private const int TestFrameLength = 12; private static Mock<Connection> GetConnectionMock(Configuration config = null, ISerializerManager serializer = null) { config = config ?? new Configuration(); return new Mock<Connection>( MockBehavior.Loose, serializer?.GetCurrentSerializer() ?? new SerializerManager(ProtocolVersion.MaxSupported).GetCurrentSerializer(), new ConnectionEndPoint(ConnectionTests.Address, config.ServerNameResolver, null), config, new StartupRequestFactory(config.StartupOptionsFactory), NullConnectionObserver.Instance); } [Test] public void ReadParse_Handles_Complete_Frames_In_Different_Buffers() { var connectionMock = GetConnectionMock(); var streamIds = new List<short>(); var responses = new ConcurrentBag<Response>(); connectionMock.Setup(c => c.RemoveFromPending(It.IsAny<short>())) .Callback<short>(id => streamIds.Add(id)) .Returns(() => OperationStateExtensions.CreateMock((ex, r) => responses.Add(r))); var connection = connectionMock.Object; var buffer = GetResultBuffer(127); connection.ReadParse(buffer, buffer.Length); CollectionAssert.AreEqual(new short[] { 127 }, streamIds); buffer = GetResultBuffer(126); connection.ReadParse(buffer, buffer.Length); CollectionAssert.AreEqual(new short[] { 127, 126 }, streamIds); buffer = GetResultBuffer(125); connection.ReadParse(buffer, buffer.Length); CollectionAssert.AreEqual(new short[] { 127, 126, 125 }, streamIds); TestHelper.WaitUntil(() => responses.Count == 3); Assert.AreEqual(3, responses.Count); CollectionAssert.AreEqual(Enumerable.Repeat(ResultResponse.ResultResponseKind.Void, 3), responses.Select(r => ((ResultResponse) r).Kind)); } [Test] public void ReadParse_Handles_Complete_Frames_In_A_Single_Frame() { var connectionMock = GetConnectionMock(); var streamIds = new List<short>(); var responses = new ConcurrentBag<Response>(); connectionMock.Setup(c => c.RemoveFromPending(It.IsAny<short>())) .Callback<short>(id => streamIds.Add(id)) .Returns(() => OperationStateExtensions.CreateMock((ex, r) => responses.Add(r))); var connection = connectionMock.Object; var buffer = GetResultBuffer(127).Concat(GetResultBuffer(126)).ToArray(); connection.ReadParse(buffer, buffer.Length); CollectionAssert.AreEqual(new short[] { 127, 126 }, streamIds); TestHelper.WaitUntil(() => responses.Count == 2); Assert.AreEqual(2, responses.Count); } [Test] public void ReadParse_Handles_UnComplete_Header() { var connectionMock = GetConnectionMock(); var streamIds = new List<short>(); var responses = new ConcurrentBag<Response>(); connectionMock.Setup(c => c.RemoveFromPending(It.IsAny<short>())) .Callback<short>(id => streamIds.Add(id)) .Returns(() => OperationStateExtensions.CreateMock((ex, r) => responses.Add(r))); var connection = connectionMock.Object; var buffer = GetResultBuffer(127).Concat(GetResultBuffer(126)).Concat(GetResultBuffer(100)).ToArray(); //first 2 messages and 2 bytes of the third message var firstSlice = buffer.Length - TestFrameLength + 2; connection.ReadParse(buffer, firstSlice); CollectionAssert.AreEqual(new short[] { 127, 126 }, streamIds); buffer = buffer.Skip(firstSlice).ToArray(); connection.ReadParse(buffer, buffer.Length); CollectionAssert.AreEqual(new short[] { 127, 126, 100 }, streamIds); TestHelper.WaitUntil(() => responses.Count == 3); CollectionAssert.AreEqual(Enumerable.Repeat(ResultResponse.ResultResponseKind.Void, 3), responses.Select(r => ((ResultResponse)r).Kind)); buffer = GetResultBuffer(99); connection.ReadParse(buffer, buffer.Length); CollectionAssert.AreEqual(new short[] { 127, 126, 100, 99 }, streamIds); } [Test] public void ReadParse_Handles_UnComplete_Header_In_Multiple_Messages() { var connectionMock = GetConnectionMock(); var streamIds = new List<short>(); var responses = new ConcurrentBag<Response>(); connectionMock.Setup(c => c.RemoveFromPending(It.IsAny<short>())) .Callback<short>(id => streamIds.Add(id)) .Returns(() => OperationStateExtensions.CreateMock((ex, r) => responses.Add(r))); var connection = connectionMock.Object; var buffer = GetResultBuffer(127).Concat(GetResultBuffer(126)).Concat(GetResultBuffer(100)).ToArray(); //first 2 messages and 2 bytes of the third message var length = buffer.Length - TestFrameLength + 2; connection.ReadParse(buffer, length); CollectionAssert.AreEqual(new short[] { 127, 126 }, streamIds); buffer = buffer.Skip(length).ToArray(); length = buffer.Length - 8; //header is still not completed connection.ReadParse(buffer, length); CollectionAssert.AreEqual(new short[] { 127, 126 }, streamIds); //header and body are completed buffer = buffer.Skip(length).ToArray(); length = buffer.Length; connection.ReadParse(buffer, length); CollectionAssert.AreEqual(new short[] { 127, 126, 100 }, streamIds); TestHelper.WaitUntil(() => responses.Count == 3); CollectionAssert.AreEqual(Enumerable.Repeat(ResultResponse.ResultResponseKind.Void, 3), responses.Select(r => ((ResultResponse)r).Kind)); buffer = GetResultBuffer(99); connection.ReadParse(buffer, buffer.Length); CollectionAssert.AreEqual(new short[] { 127, 126, 100, 99 }, streamIds); } [Test] public void ReadParse_Handles_UnComplete_Body() { var connectionMock = GetConnectionMock(); var streamIds = new List<short>(); var responses = new ConcurrentBag<Response>(); var exceptions = new ConcurrentBag<Exception>(); connectionMock.Setup(c => c.RemoveFromPending(It.IsAny<short>())) .Callback<short>(id => streamIds.Add(id)) .Returns(() => OperationStateExtensions.CreateMock((ex, r) => { if (ex != null) { exceptions.Add(ex); return; } responses.Add(r); })); var connection = connectionMock.Object; var buffer = GetResultBuffer(127).Concat(GetResultBuffer(126)).Concat(GetResultBuffer(100)).ToArray(); //almost 3 responses, just 1 byte of the body left var firstSlice = buffer.Length - 1; connection.ReadParse(buffer, firstSlice); CollectionAssert.AreEqual(new short[] { 127, 126 }, streamIds); buffer = buffer.Skip(firstSlice).ToArray(); connection.ReadParse(buffer, buffer.Length); CollectionAssert.AreEqual(new short[] { 127, 126, 100 }, streamIds); TestHelper.WaitUntil(() => responses.Count + exceptions.Count == 3, 500, 5); CollectionAssert.IsEmpty(exceptions); CollectionAssert.AreEqual(Enumerable.Repeat(ResultResponse.ResultResponseKind.Void, 3), responses.Select(r => ((ResultResponse)r).Kind)); buffer = GetResultBuffer(1); connection.ReadParse(buffer, buffer.Length); CollectionAssert.AreEqual(new short[] { 127, 126, 100, 1 }, streamIds); } [Test] public void ReadParse_Handles_UnComplete_Body_In_Multiple_Messages() { var connectionMock = GetConnectionMock(); var streamIds = new List<short>(); var responses = new ConcurrentBag<Response>(); connectionMock.Setup(c => c.RemoveFromPending(It.IsAny<short>())) .Callback<short>(id => streamIds.Add(id)) .Returns(() => OperationStateExtensions.CreateMock((ex, r) => responses.Add(r))); var connection = connectionMock.Object; var originalBuffer = GetResultBuffer(127).Concat(GetResultBuffer(126)).Concat(GetResultBuffer(100)).ToArray(); //almost 3 responses, 3 byte of the body left var firstSlice = originalBuffer.Length - 3; connection.ReadParse(originalBuffer, firstSlice); CollectionAssert.AreEqual(new short[] { 127, 126 }, streamIds); //2 more bytes, but not enough var buffer = originalBuffer.Skip(firstSlice).Take(2).ToArray(); connection.ReadParse(buffer, buffer.Length); CollectionAssert.AreEqual(new short[] { 127, 126}, streamIds); //the last byte buffer = originalBuffer.Skip(firstSlice + 2).ToArray(); connection.ReadParse(buffer, buffer.Length); CollectionAssert.AreEqual(new short[] { 127, 126, 100 }, streamIds); TestHelper.WaitUntil(() => responses.Count == 3); CollectionAssert.AreEqual(Enumerable.Repeat(ResultResponse.ResultResponseKind.Void, 3), responses.Select(r => ((ResultResponse)r).Kind)); buffer = GetResultBuffer(1); connection.ReadParse(buffer, buffer.Length); CollectionAssert.AreEqual(new short[] { 127, 126, 100, 1 }, streamIds); } [Test] public void ReadParse_Handles_UnComplete_Body_Multiple_Times() { var connectionMock = GetConnectionMock(); var streamIds = new List<short>(); var responses = new ConcurrentBag<Response>(); connectionMock.Setup(c => c.RemoveFromPending(It.IsAny<short>())) .Callback<short>(id => streamIds.Add(id)) .Returns(() => OperationStateExtensions.CreateMock((ex, r) => responses.Add(r))); var connection = connectionMock.Object; var buffer = GetResultBuffer(127) .Concat(GetResultBuffer(126)) .Concat(GetResultBuffer(100)) .ToArray(); //almost 3 responses, 3 byte of the body left var length = buffer.Length - 3; connection.ReadParse(buffer, length); CollectionAssert.AreEqual(new short[] { 127, 126 }, streamIds); //the rest of the last message plus a new message buffer = buffer.Skip(length).Concat(GetResultBuffer(99)).ToArray(); length = buffer.Length - 3; connection.ReadParse(buffer, length); CollectionAssert.AreEqual(new short[] { 127, 126, 100 }, streamIds); buffer = buffer.Skip(length).Concat(GetResultBuffer(98)).ToArray(); length = buffer.Length - 3; connection.ReadParse(buffer, length); CollectionAssert.AreEqual(new short[] { 127, 126, 100, 99 }, streamIds); buffer = buffer.Skip(length).Concat(GetResultBuffer(97)).ToArray(); length = buffer.Length; connection.ReadParse(buffer, length); CollectionAssert.AreEqual(new short[] { 127, 126, 100, 99, 98, 97 }, streamIds); TestHelper.WaitUntil(() => responses.Count == 6); CollectionAssert.AreEqual(Enumerable.Repeat(ResultResponse.ResultResponseKind.Void, 6), responses.Select(r => ((ResultResponse)r).Kind)); buffer = GetResultBuffer(1); connection.ReadParse(buffer, buffer.Length); CollectionAssert.AreEqual(new short[] { 127, 126, 100, 99, 98, 97, 1 }, streamIds); } [Test] public void ReadParse_Handles_UnComplete_Body_With_Following_Frames() { var connectionMock = GetConnectionMock(); var streamIds = new List<short>(); var responses = new ConcurrentBag<Response>(); connectionMock.Setup(c => c.RemoveFromPending(It.IsAny<short>())) .Callback<short>(id => streamIds.Add(id)) .Returns(() => OperationStateExtensions.CreateMock((ex, r) => responses.Add(r))); var connection = connectionMock.Object; var buffer = GetResultBuffer(127).Concat(GetResultBuffer(126)).Concat(GetResultBuffer(100)).ToArray(); //almost 3 responses, just 1 byte of the body left var firstSlice = buffer.Length - 1; connection.ReadParse(buffer, firstSlice); CollectionAssert.AreEqual(new short[] { 127, 126 }, streamIds); buffer = buffer.Skip(firstSlice).Concat(GetResultBuffer(99)).ToArray(); connection.ReadParse(buffer, buffer.Length); CollectionAssert.AreEqual(new short[] { 127, 126, 100, 99 }, streamIds); TestHelper.WaitUntil(() => responses.Count == 4); CollectionAssert.AreEqual(Enumerable.Repeat(ResultResponse.ResultResponseKind.Void, 4), responses.Select(r => ((ResultResponse)r).Kind)); buffer = GetResultBuffer(1); connection.ReadParse(buffer, buffer.Length); CollectionAssert.AreEqual(new short[] { 127, 126, 100, 99, 1 }, streamIds); } [Test] public async Task ReadParse_While_Disposing_Faults_Tasks_But_Never_Throws() { var connectionMock = GetConnectionMock(); var responses = new ConcurrentBag<object>(); connectionMock.Setup(c => c.RemoveFromPending(It.IsAny<short>())) .Returns(() => OperationStateExtensions.CreateMock((ex, r) => responses.Add((object) ex ?? r))); var connection = connectionMock.Object; var bufferBuilder = Enumerable.Empty<byte>(); const int totalFrames = 63; for (var i = 0; i < totalFrames; i++) { bufferBuilder = bufferBuilder.Concat(GetResultBuffer((byte)i)); } var buffer = bufferBuilder.ToArray(); var schedulerPair = new ConcurrentExclusiveSchedulerPair(); var tasks = new List<Task>(buffer.Length); for (var i = 0; i < buffer.Length; i++) { var index = i; tasks.Add( Task.Factory.StartNew(() => connection.ReadParse(buffer.Skip(index).ToArray(), 1), CancellationToken.None, TaskCreationOptions.None, schedulerPair.ExclusiveScheduler)); } var random = new Random(); // Lets wait for some of the read tasks to be completed await tasks[random.Next(20, 50)].ConfigureAwait(false); await Task.Run(() => connection.Dispose()).ConfigureAwait(false); await Task.WhenAll(tasks).ConfigureAwait(false); // We must await for a short while until operation states are callback (on the TaskScheduler) await TestHelper.WaitUntilAsync(() => totalFrames == responses.Count, 100, 30).ConfigureAwait(false); Assert.AreEqual(totalFrames, responses.Count); } [Test] public void Should_HandleDifferentProtocolVersionsInDifferentConnections_When_OneConnectionResponseVersionIsDifferentThanSerializer() { var serializer = new SerializerManager(ProtocolVersion.V4); var connectionMock = GetConnectionMock(null, serializer); var connectionMock2 = GetConnectionMock(null, serializer); var streamIds = new List<short>(); var responses = new ConcurrentBag<Response>(); connectionMock.Setup(c => c.RemoveFromPending(It.IsAny<short>())) .Callback<short>(id => streamIds.Add(id)) .Returns(() => OperationStateExtensions.CreateMock((ex, r) => responses.Add(r))); connectionMock2.Setup(c => c.RemoveFromPending(It.IsAny<short>())) .Callback<short>(id => streamIds.Add(id)) .Returns(() => OperationStateExtensions.CreateMock((ex, r) => responses.Add(r))); var connection = connectionMock.Object; var buffer = GetResultBuffer(128, ProtocolVersion.V4); connection.ReadParse(buffer, buffer.Length); buffer = ConnectionTests.GetResultBuffer(100, ProtocolVersion.V2); connectionMock2.Object.ReadParse(buffer, buffer.Length); buffer = GetResultBuffer(129, ProtocolVersion.V4); connection.ReadParse(buffer, buffer.Length); CollectionAssert.AreEqual(new short[] { 128, 100, 129 }, streamIds); TestHelper.WaitUntil(() => responses.Count == 3); Assert.AreEqual(3, responses.Count); } /// <summary> /// Gets a buffer containing 8 bytes for header and 4 bytes for the body. /// For result + void response message (protocol v2) /// </summary> private static byte[] GetResultBuffer(short streamId, ProtocolVersion version = ProtocolVersion.V2) { var header = (byte)((int)version | 0x80); if (version.Uses2BytesStreamIds()) { var bytes = BeConverter.GetBytes(streamId); return new byte[] { //header header, 0, bytes[0], bytes[1], ResultResponse.OpCode, 0, 0, 0, 4, //body 0, 0, 0, 1 }; } return new byte[] { //header header, 0, (byte)streamId, ResultResponse.OpCode, 0, 0, 0, 4, //body 0, 0, 0, 1 }; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using Newtonsoft.Json.Linq; using NuGet.Client.Installation; using NuGet.Client.Resolution; using NuGet.Versioning; using NuGet.VisualStudio; using NuGetConsole; using Resx = NuGet.Client.VisualStudio.UI.Resources; namespace NuGet.Client.VisualStudio.UI { /// <summary> /// Interaction logic for PackageManagerControl.xaml /// </summary> public partial class PackageManagerControl : UserControl { private const int PageSize = 10; // Copied from file Constants.cs in NuGet.Core: // This is temporary until we fix the gallery to have proper first class support for this. // The magic unpublished date is 1900-01-01T00:00:00 public static readonly DateTimeOffset Unpublished = new DateTimeOffset(1900, 1, 1, 0, 0, 0, TimeSpan.FromHours(-8)); private bool _initialized; // used to prevent starting new search when we update the package sources // list in response to PackageSourcesChanged event. private bool _dontStartNewSearch; private int _busyCount; public PackageManagerModel Model { get; private set; } public SourceRepositoryManager Sources { get { return Model.Sources; } } public InstallationTarget Target { get { return Model.Target; } } private IConsole _outputConsole; internal IUserInterfaceService UI { get; private set; } private PackageRestoreBar _restoreBar; private IPackageRestoreManager _packageRestoreManager; public PackageManagerControl(PackageManagerModel model, IUserInterfaceService ui) { UI = ui; Model = model; InitializeComponent(); _searchControl.Text = model.SearchText; _filter.Items.Add(Resx.Resources.Filter_All); _filter.Items.Add(Resx.Resources.Filter_Installed); _filter.Items.Add(Resx.Resources.Filter_UpdateAvailable); // TODO: Relocate to v3 API. _packageRestoreManager = ServiceLocator.GetInstance<IPackageRestoreManager>(); AddRestoreBar(); _packageDetail.Visibility = System.Windows.Visibility.Collapsed; _packageDetail.Control = this; _packageSolutionDetail.Visibility = System.Windows.Visibility.Collapsed; _packageSolutionDetail.Control = this; _busyCount = 0; if (Target.IsSolution) { _packageSolutionDetail.Visibility = System.Windows.Visibility.Visible; } else { _packageDetail.Visibility = System.Windows.Visibility.Visible; } var outputConsoleProvider = ServiceLocator.GetInstance<IOutputConsoleProvider>(); _outputConsole = outputConsoleProvider.CreateOutputConsole(requirePowerShellHost: false); InitSourceRepoList(); this.Unloaded += PackageManagerControl_Unloaded; _initialized = true; Model.Sources.PackageSourcesChanged += Sources_PackageSourcesChanged; } private void Sources_PackageSourcesChanged(object sender, EventArgs e) { // Set _dontStartNewSearch to true to prevent a new search started in // _sourceRepoList_SelectionChanged(). This method will start the new // search when needed by itself. _dontStartNewSearch = true; try { var oldActiveSource = _sourceRepoList.SelectedItem as PackageSource; var newSources = new List<PackageSource>(Sources.AvailableSources); // Update the source repo list with the new value. _sourceRepoList.Items.Clear(); foreach (var source in newSources) { _sourceRepoList.Items.Add(source); } if (oldActiveSource != null && newSources.Contains(oldActiveSource)) { // active source is not changed. Set _dontStartNewSearch to true // to prevent a new search when _sourceRepoList.SelectedItem is set. _sourceRepoList.SelectedItem = oldActiveSource; } else { // active source changed. _sourceRepoList.SelectedItem = newSources.Count > 0 ? newSources[0] : null; // start search explicitly. SearchPackageInActivePackageSource(); } } finally { _dontStartNewSearch = false; } } private void PackageManagerControl_Unloaded(object sender, RoutedEventArgs e) { RemoveRestoreBar(); } private void AddRestoreBar() { _restoreBar = new PackageRestoreBar(_packageRestoreManager); _root.Children.Add(_restoreBar); _packageRestoreManager.PackagesMissingStatusChanged += packageRestoreManager_PackagesMissingStatusChanged; } private void RemoveRestoreBar() { _restoreBar.CleanUp(); _packageRestoreManager.PackagesMissingStatusChanged -= packageRestoreManager_PackagesMissingStatusChanged; } private void packageRestoreManager_PackagesMissingStatusChanged(object sender, PackagesMissingStatusEventArgs e) { // PackageRestoreManager fires this event even when solution is closed. // Don't do anything if solution is closed. if (!Target.IsAvailable) { return; } if (!e.PackagesMissing) { // packages are restored. Update the UI if (Target.IsSolution) { // TODO: update UI here } else { // TODO: update UI here } } } private void InitSourceRepoList() { _label.Text = string.Format( CultureInfo.CurrentCulture, Resx.Resources.Label_PackageManager, Target.Name); // init source repo list _sourceRepoList.Items.Clear(); foreach (var source in Sources.AvailableSources) { _sourceRepoList.Items.Add(source); } if (Sources.ActiveRepository != null) { _sourceRepoList.SelectedItem = Sources.ActiveRepository.Source; } } private void SetBusy(bool busy) { if (busy) { _busyCount++; if (_busyCount > 0) { _busyControl.Visibility = System.Windows.Visibility.Visible; this.IsEnabled = false; } } else { _busyCount--; if (_busyCount <= 0) { _busyControl.Visibility = System.Windows.Visibility.Collapsed; this.IsEnabled = true; } } } private class PackageLoaderOption { public bool IncludePrerelease { get; set; } public bool ShowUpdatesAvailable { get; set; } } private class PackageLoader : ILoader { // where to get the package list private Func<int, CancellationToken, Task<IEnumerable<JObject>>> _loader; private InstallationTarget _target; private PackageLoaderOption _option; public PackageLoader( Func<int, CancellationToken, Task<IEnumerable<JObject>>> loader, InstallationTarget target, PackageLoaderOption option, string searchText) { _loader = loader; _target = target; _option = option; LoadingMessage = string.IsNullOrWhiteSpace(searchText) ? Resx.Resources.Text_Loading : string.Format( CultureInfo.CurrentCulture, Resx.Resources.Text_Searching, searchText); } public string LoadingMessage { get; private set; } private Task<List<JObject>> InternalLoadItems( int startIndex, CancellationToken ct, Func<int, CancellationToken, Task<IEnumerable<JObject>>> loader) { return Task.Factory.StartNew(() => { var r1 = _loader(startIndex, ct); return r1.Result.ToList(); }); } private UiDetailedPackage ToDetailedPackage(UiSearchResultPackage package) { var detailedPackage = new UiDetailedPackage(); detailedPackage.Id = package.Id; detailedPackage.Version = package.Version; detailedPackage.Summary = package.Summary; return detailedPackage; } public async Task<LoadResult> LoadItems(int startIndex, CancellationToken ct) { var results = await InternalLoadItems(startIndex, ct, _loader); List<UiSearchResultPackage> packages = new List<UiSearchResultPackage>(); foreach (var package in results) { ct.ThrowIfCancellationRequested(); // As a debugging aide, I am intentionally NOT using an object initializer -anurse var searchResultPackage = new UiSearchResultPackage(); searchResultPackage.Id = package.Value<string>(Properties.PackageId); searchResultPackage.Version = NuGetVersion.Parse(package.Value<string>(Properties.LatestVersion)); if (searchResultPackage.Version.IsPrerelease && !_option.IncludePrerelease) { // don't include prerelease version if includePrerelease is false continue; } searchResultPackage.IconUrl = GetUri(package, Properties.IconUrl); var allVersions = LoadVersions( package.Value<JArray>(Properties.Packages), searchResultPackage.Version); if (!allVersions.Select(v => v.Version).Contains(searchResultPackage.Version)) { // make sure allVersions contains searchResultPackage itself. allVersions.Add(ToDetailedPackage(searchResultPackage)); } searchResultPackage.AllVersions = allVersions; SetPackageStatus(searchResultPackage, _target); if (_option.ShowUpdatesAvailable && searchResultPackage.Status != PackageStatus.UpdateAvailable) { continue; } searchResultPackage.Summary = package.Value<string>(Properties.Summary); if (string.IsNullOrWhiteSpace(searchResultPackage.Summary)) { // summary is empty. Use its description instead. var self = searchResultPackage.AllVersions.FirstOrDefault(p => p.Version == searchResultPackage.Version); if (self != null) { searchResultPackage.Summary = self.Description; } } packages.Add(searchResultPackage); } ct.ThrowIfCancellationRequested(); return new LoadResult() { Items = packages, HasMoreItems = packages.Count == PageSize }; } // Get all versions of the package private List<UiDetailedPackage> LoadVersions(JArray versions, NuGetVersion searchResultVersion) { var retValue = new List<UiDetailedPackage>(); // If repo is AggregateRepository, the package duplicates can be returned by // FindPackagesById(), so Distinct is needed here to remove the duplicates. foreach (var token in versions) { Debug.Assert(token.Type == JTokenType.Object); JObject version = (JObject)token; var detailedPackage = new UiDetailedPackage(); detailedPackage.Id = version.Value<string>(Properties.PackageId); detailedPackage.Version = NuGetVersion.Parse(version.Value<string>(Properties.Version)); if (detailedPackage.Version.IsPrerelease && !_option.IncludePrerelease && detailedPackage.Version != searchResultVersion) { // don't include prerelease version if includePrerelease is false continue; } string publishedStr = version.Value<string>(Properties.Published); if (!String.IsNullOrEmpty(publishedStr)) { detailedPackage.Published = DateTime.Parse(publishedStr); if (detailedPackage.Published <= Unpublished && detailedPackage.Version != searchResultVersion) { // don't include unlisted package continue; } } detailedPackage.Summary = version.Value<string>(Properties.Summary); detailedPackage.Description = version.Value<string>(Properties.Description); detailedPackage.Authors = version.Value<string>(Properties.Authors); detailedPackage.Owners = version.Value<string>(Properties.Owners); detailedPackage.IconUrl = GetUri(version, Properties.IconUrl); detailedPackage.LicenseUrl = GetUri(version, Properties.LicenseUrl); detailedPackage.ProjectUrl = GetUri(version, Properties.ProjectUrl); detailedPackage.Tags = String.Join(" ", (version.Value<JArray>(Properties.Tags) ?? Enumerable.Empty<JToken>()).Select(t => t.ToString())); detailedPackage.DownloadCount = version.Value<int>(Properties.DownloadCount); detailedPackage.DependencySets = (version.Value<JArray>(Properties.DependencyGroups) ?? Enumerable.Empty<JToken>()).Select(obj => LoadDependencySet((JObject)obj)); detailedPackage.HasDependencies = detailedPackage.DependencySets.Any( set => set.Dependencies != null && set.Dependencies.Count > 0); retValue.Add(detailedPackage); } return retValue; } private Uri GetUri(JObject json, string property) { if (json[property] == null) { return null; } string str = json[property].ToString(); if (String.IsNullOrEmpty(str)) { return null; } return new Uri(str); } private UiPackageDependencySet LoadDependencySet(JObject set) { var fxName = set.Value<string>(Properties.TargetFramework); return new UiPackageDependencySet( String.IsNullOrEmpty(fxName) ? null : FrameworkNameHelper.ParsePossiblyShortenedFrameworkName(fxName), (set.Value<JArray>(Properties.Dependencies) ?? Enumerable.Empty<JToken>()).Select(obj => LoadDependency((JObject)obj))); } private UiPackageDependency LoadDependency(JObject dep) { var ver = dep.Value<string>(Properties.Range); return new UiPackageDependency( dep.Value<string>(Properties.PackageId), String.IsNullOrEmpty(ver) ? null : VersionRange.Parse(ver)); } private string StringCollectionToString(JArray v) { if (v == null) { return null; } string retValue = String.Join(", ", v.Select(t => t.ToString())); if (retValue == String.Empty) { return null; } return retValue; } } private bool ShowInstalled { get { return Resx.Resources.Filter_Installed.Equals(_filter.SelectedItem); } } private bool ShowUpdatesAvailable { get { return Resx.Resources.Filter_UpdateAvailable.Equals(_filter.SelectedItem); } } public bool IncludePrerelease { get { return _checkboxPrerelease.IsChecked == true; } } internal SourceRepository CreateActiveRepository() { var activeSource = _sourceRepoList.SelectedItem as PackageSource; if (activeSource == null) { return null; } return Sources.CreateSourceRepository(activeSource); } private void SearchPackageInActivePackageSource() { var searchText = _searchControl.Text; var supportedFrameworks = Target.GetSupportedFrameworks(); // search online var activeSource = _sourceRepoList.SelectedItem as PackageSource; var sourceRepository = Sources.CreateSourceRepository(activeSource); PackageLoaderOption option = new PackageLoaderOption() { IncludePrerelease = this.IncludePrerelease, ShowUpdatesAvailable = this.ShowUpdatesAvailable }; if (ShowInstalled || ShowUpdatesAvailable) { // search installed packages var loader = new PackageLoader( (startIndex, ct) => Target.SearchInstalled( sourceRepository, searchText, startIndex, PageSize, ct), Target, option, searchText); _packageList.Loader = loader; } else { // search in active package source if (activeSource == null) { var loader = new PackageLoader( (startIndex, ct) => { return Task.Factory.StartNew(() => { return Enumerable.Empty<JObject>(); }); }, Target, option, searchText); _packageList.Loader = loader; } else { var loader = new PackageLoader( (startIndex, ct) => sourceRepository.Search( searchText, new SearchFilter() { SupportedFrameworks = supportedFrameworks, IncludePrerelease = option.IncludePrerelease }, startIndex, PageSize, ct), Target, option, searchText); _packageList.Loader = loader; } } } private void SettingsButtonClick(object sender, RoutedEventArgs e) { UI.LaunchNuGetOptionsDialog(); } private void PackageList_SelectionChanged(object sender, SelectionChangedEventArgs e) { UpdateDetailPane(); } /// <summary> /// Updates the detail pane based on the selected package /// </summary> private void UpdateDetailPane() { var selectedPackage = _packageList.SelectedItem as UiSearchResultPackage; if (selectedPackage == null) { _packageDetail.DataContext = null; _packageSolutionDetail.DataContext = null; } else { if (!Target.IsSolution) { var installedPackage = Target.InstalledPackages.GetInstalledPackage(selectedPackage.Id); var installedVersion = installedPackage == null ? null : installedPackage.Identity.Version; _packageDetail.DataContext = new PackageDetailControlModel(selectedPackage, installedVersion); } else { _packageSolutionDetail.DataContext = new PackageSolutionDetailControlModel(selectedPackage, (VsSolution)Target); } } } private void _sourceRepoList_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (_dontStartNewSearch) { return; } var newSource = _sourceRepoList.SelectedItem as PackageSource; if (newSource != null) { Sources.ChangeActiveSource(newSource); } SearchPackageInActivePackageSource(); } private void _filter_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (_initialized) { SearchPackageInActivePackageSource(); } } internal void UpdatePackageStatus() { if (ShowInstalled || ShowUpdatesAvailable) { // refresh the whole package list _packageList.Reload(); } else { // in this case, we only need to update PackageStatus of // existing items in the package list foreach (var item in _packageList.Items) { var package = item as UiSearchResultPackage; if (package == null) { continue; } SetPackageStatus(package, Target); } } } // Set the PackageStatus property of the given package. private static void SetPackageStatus( UiSearchResultPackage package, InstallationTarget target) { var latestStableVersion = package.AllVersions .Where(p => !p.Version.IsPrerelease) .Max(p => p.Version); // Get the minimum version installed in any target project/solution var minimumInstalledPackage = target.GetAllTargetsRecursively() .Select(t => t.InstalledPackages.GetInstalledPackage(package.Id)) .Where(p => p != null) .OrderBy(r => r.Identity.Version) .FirstOrDefault(); PackageStatus status; if (minimumInstalledPackage != null) { if (minimumInstalledPackage.Identity.Version < latestStableVersion) { status = PackageStatus.UpdateAvailable; } else { status = PackageStatus.Installed; } } else { status = PackageStatus.NotInstalled; } package.Status = status; } public bool ShowLicenseAgreement(IEnumerable<PackageAction> operations) { var licensePackages = operations.Where(op => op.ActionType == PackageActionType.Install && op.Package.Value<bool>("requireLicenseAcceptance")); // display license window if necessary if (licensePackages.Any()) { // Hacky distinct without writing a custom comparer var licenseModels = licensePackages .GroupBy(a => Tuple.Create(a.Package["id"], a.Package["version"])) .Select(g => { dynamic p = g.First().Package; string licenseUrl = (string)p.licenseUrl; string id = (string)p.id; string authors = (string)p.authors; return new PackageLicenseInfo( id, licenseUrl == null ? null : new Uri(licenseUrl), authors); }) .Where(pli => pli.LicenseUrl != null); // Shouldn't get nulls, but just in case bool accepted = this.UI.PromptForLicenseAcceptance(licenseModels); if (!accepted) { return false; } } return true; } private void PreviewActions(IEnumerable<PackageAction> actions) { var w = new PreviewWindow(); w.DataContext = new PreviewWindowModel(actions, Target); w.ShowModal(); } // preview user selected action internal async void Preview(IDetailControl detailControl) { SetBusy(true); try { _outputConsole.Clear(); var actions = await detailControl.ResolveActionsAsync(); PreviewActions(actions); } catch (Exception ex) { var errorDialog = new ErrorReportingDialog( ex.Message, ex.ToString()); errorDialog.ShowModal(); } finally { SetBusy(false); } } // perform the user selected action internal async void PerformAction(IDetailControl detailControl) { SetBusy(true); _outputConsole.Clear(); var progressDialog = new ProgressDialog(_outputConsole); progressDialog.Owner = Window.GetWindow(this); progressDialog.WindowStartupLocation = WindowStartupLocation.CenterOwner; try { var actions = await detailControl.ResolveActionsAsync(); // show license agreeement bool acceptLicense = ShowLicenseAgreement(actions); if (!acceptLicense) { return; } // Create the executor and execute the actions progressDialog.FileConflictAction = detailControl.FileConflictAction; progressDialog.Show(); var executor = new ActionExecutor(); await executor.ExecuteActionsAsync(actions, logger: progressDialog, cancelToken: CancellationToken.None); UpdatePackageStatus(); detailControl.Refresh(); } catch (Exception ex) { var errorDialog = new ErrorReportingDialog( ex.Message, ex.ToString()); errorDialog.ShowModal(); } finally { progressDialog.RequestToClose(); SetBusy(false); } } private void _searchControl_SearchStart(object sender, EventArgs e) { if (!_initialized) { return; } SearchPackageInActivePackageSource(); } private void _checkboxPrerelease_CheckChanged(object sender, RoutedEventArgs e) { if (!_initialized) { return; } SearchPackageInActivePackageSource(); } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // 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 Jaroslaw Kowalski 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. // namespace NLog.UnitTests { using System; using System.Collections.Generic; using System.Threading; using NLog.Common; using Xunit; public class AsyncHelperTests : NLogTestBase { [Fact] public void OneTimeOnlyTest1() { var exceptions = new List<Exception>(); AsyncContinuation cont = exceptions.Add; cont = AsyncHelpers.PreventMultipleCalls(cont); // OneTimeOnly(OneTimeOnly(x)) == OneTimeOnly(x) var cont2 = AsyncHelpers.PreventMultipleCalls(cont); Assert.Same(cont, cont2); var sampleException = new ApplicationException("some message"); cont(null); cont(sampleException); cont(null); cont(sampleException); Assert.Single(exceptions); Assert.Null(exceptions[0]); } [Fact] public void OneTimeOnlyTest2() { var exceptions = new List<Exception>(); AsyncContinuation cont = exceptions.Add; cont = AsyncHelpers.PreventMultipleCalls(cont); var sampleException = new ApplicationException("some message"); cont(sampleException); cont(null); cont(sampleException); cont(null); Assert.Single(exceptions); Assert.Same(sampleException, exceptions[0]); } [Fact] public void OneTimeOnlyExceptionInHandlerTest() { using (new NoThrowNLogExceptions()) { var exceptions = new List<Exception>(); var sampleException = new ApplicationException("some message"); AsyncContinuation cont = ex => { exceptions.Add(ex); throw sampleException; }; cont = AsyncHelpers.PreventMultipleCalls(cont); cont(null); cont(null); cont(null); Assert.Single(exceptions); Assert.Null(exceptions[0]); } } [Fact] public void OneTimeOnlyExceptionInHandlerTest_RethrowExceptionEnabled() { LogManager.ThrowExceptions = true; var exceptions = new List<Exception>(); var sampleException = new ApplicationException("some message"); AsyncContinuation cont = ex => { exceptions.Add(ex); throw sampleException; }; cont = AsyncHelpers.PreventMultipleCalls(cont); try { cont(null); } catch { } try { cont(null); } catch { } try { cont(null); } catch { } Assert.Single(exceptions); Assert.Null(exceptions[0]); } [Fact] public void ContinuationTimeoutTest() { RetryingIntegrationTest(3, () => { var resetEvent = new ManualResetEvent(false); var exceptions = new List<Exception>(); // set up a timer to strike in 1 second var cont = AsyncHelpers.WithTimeout(ex => { exceptions.Add(ex); resetEvent.Set(); }, TimeSpan.FromMilliseconds(1)); resetEvent.WaitOne(TimeSpan.FromSeconds(1)); // make sure we got timeout exception Assert.Single(exceptions); Assert.IsType<TimeoutException>(exceptions[0]); Assert.Equal("Timeout.", exceptions[0].Message); // those will be ignored cont(null); cont(new ApplicationException("Some exception")); cont(null); cont(new ApplicationException("Some exception")); Assert.Single(exceptions); }); } [Fact] public void ContinuationTimeoutNotHitTest() { var exceptions = new List<Exception>(); // set up a timer to strike var cont = AsyncHelpers.WithTimeout(AsyncHelpers.PreventMultipleCalls(exceptions.Add), TimeSpan.FromMilliseconds(50)); // call success quickly, hopefully before the timer comes cont(null); // sleep to make sure timer event comes Thread.Sleep(100); // make sure we got success, not a timer exception Assert.Single(exceptions); Assert.Null(exceptions[0]); // those will be ignored cont(null); cont(new ApplicationException("Some exception")); cont(null); cont(new ApplicationException("Some exception")); Assert.Single(exceptions); Assert.Null(exceptions[0]); } [Fact] public void ContinuationErrorTimeoutNotHitTest() { var exceptions = new List<Exception>(); // set up a timer to strike var cont = AsyncHelpers.WithTimeout(AsyncHelpers.PreventMultipleCalls(exceptions.Add), TimeSpan.FromMilliseconds(50)); var exception = new ApplicationException("Foo"); // call success quickly, hopefully before the timer comes cont(exception); // sleep to make sure timer event comes Thread.Sleep(100); // make sure we got success, not a timer exception Assert.Single(exceptions); Assert.NotNull(exceptions[0]); Assert.Same(exception, exceptions[0]); // those will be ignored cont(null); cont(new ApplicationException("Some exception")); cont(null); cont(new ApplicationException("Some exception")); Assert.Single(exceptions); Assert.NotNull(exceptions[0]); } [Fact] public void RepeatTest1() { bool finalContinuationInvoked = false; Exception lastException = null; AsyncContinuation finalContinuation = ex => { finalContinuationInvoked = true; lastException = ex; }; int callCount = 0; AsyncHelpers.Repeat(10, finalContinuation, cont => { callCount++; cont(null); }); Assert.True(finalContinuationInvoked); Assert.Null(lastException); Assert.Equal(10, callCount); } [Fact] public void RepeatTest2() { bool finalContinuationInvoked = false; Exception lastException = null; Exception sampleException = new ApplicationException("Some message"); AsyncContinuation finalContinuation = ex => { finalContinuationInvoked = true; lastException = ex; }; int callCount = 0; AsyncHelpers.Repeat(10, finalContinuation, cont => { callCount++; cont(sampleException); cont(sampleException); }); Assert.True(finalContinuationInvoked); Assert.Same(sampleException, lastException); Assert.Equal(1, callCount); } [Fact] public void RepeatTest3() { using (new NoThrowNLogExceptions()) { bool finalContinuationInvoked = false; Exception lastException = null; Exception sampleException = new ApplicationException("Some message"); AsyncContinuation finalContinuation = ex => { finalContinuationInvoked = true; lastException = ex; }; int callCount = 0; AsyncHelpers.Repeat(10, finalContinuation, cont => { callCount++; throw sampleException; }); Assert.True(finalContinuationInvoked); Assert.Same(sampleException, lastException); Assert.Equal(1, callCount); } } [Fact] public void ForEachItemSequentiallyTest1() { bool finalContinuationInvoked = false; Exception lastException = null; AsyncContinuation finalContinuation = ex => { finalContinuationInvoked = true; lastException = ex; }; int sum = 0; var input = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, }; AsyncHelpers.ForEachItemSequentially(input, finalContinuation, (i, cont) => { sum += i; cont(null); cont(null); }); Assert.True(finalContinuationInvoked); Assert.Null(lastException); Assert.Equal(55, sum); } [Fact] public void ForEachItemSequentiallyTest2() { bool finalContinuationInvoked = false; Exception lastException = null; Exception sampleException = new ApplicationException("Some message"); AsyncContinuation finalContinuation = ex => { finalContinuationInvoked = true; lastException = ex; }; int sum = 0; var input = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, }; AsyncHelpers.ForEachItemSequentially(input, finalContinuation, (i, cont) => { sum += i; cont(sampleException); cont(sampleException); }); Assert.True(finalContinuationInvoked); Assert.Same(sampleException, lastException); Assert.Equal(1, sum); } [Fact] public void ForEachItemSequentiallyTest3() { using (new NoThrowNLogExceptions()) { bool finalContinuationInvoked = false; Exception lastException = null; Exception sampleException = new ApplicationException("Some message"); AsyncContinuation finalContinuation = ex => { finalContinuationInvoked = true; lastException = ex; }; int sum = 0; var input = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, }; AsyncHelpers.ForEachItemSequentially(input, finalContinuation, (i, cont) => { sum += i; throw sampleException; }); Assert.True(finalContinuationInvoked); Assert.Same(sampleException, lastException); Assert.Equal(1, sum); } } [Fact] public void ForEachItemInParallelEmptyTest() { int[] items = new int[0]; Exception lastException = null; bool finalContinuationInvoked = false; AsyncContinuation continuation = ex => { lastException = ex; finalContinuationInvoked = true; }; AsyncHelpers.ForEachItemInParallel(items, continuation, (i, cont) => { Assert.True(false, "Will not be reached"); }); Assert.True(finalContinuationInvoked); Assert.Null(lastException); } [Fact] public void ForEachItemInParallelTest() { var finalContinuationInvoked = new ManualResetEvent(false); Exception lastException = null; AsyncContinuation finalContinuation = ex => { lastException = ex; finalContinuationInvoked.Set(); }; int sum = 0; var input = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, }; AsyncHelpers.ForEachItemInParallel(input, finalContinuation, (i, cont) => { lock (input) { sum += i; } cont(null); cont(null); }); finalContinuationInvoked.WaitOne(); Assert.Null(lastException); Assert.Equal(55, sum); } [Fact] public void ForEachItemInParallelSingleFailureTest() { using (new InternalLoggerScope()) using (new NoThrowNLogExceptions()) { InternalLogger.LogLevel = LogLevel.Trace; var finalContinuationInvoked = new ManualResetEvent(false); Exception lastException = null; AsyncContinuation finalContinuation = ex => { lastException = ex; finalContinuationInvoked.Set(); }; int sum = 0; var input = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, }; AsyncHelpers.ForEachItemInParallel(input, finalContinuation, (i, cont) => { lock (input) { sum += i; } if (i == 7) { throw new ApplicationException("Some failure."); } cont(null); }); finalContinuationInvoked.WaitOne(); Assert.Equal(55, sum); Assert.NotNull(lastException); Assert.IsType<ApplicationException>(lastException); Assert.Equal("Some failure.", lastException.Message); } } [Fact] public void ForEachItemInParallelMultipleFailuresTest() { using (new NoThrowNLogExceptions()) { var finalContinuationInvoked = new ManualResetEvent(false); Exception lastException = null; AsyncContinuation finalContinuation = ex => { lastException = ex; finalContinuationInvoked.Set(); }; int sum = 0; var input = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, }; AsyncHelpers.ForEachItemInParallel(input, finalContinuation, (i, cont) => { lock (input) { sum += i; } throw new ApplicationException("Some failure."); }); finalContinuationInvoked.WaitOne(); Assert.Equal(55, sum); Assert.NotNull(lastException); Assert.IsType<NLogRuntimeException>(lastException); Assert.StartsWith("Got multiple exceptions:\r\n", lastException.Message); } } [Fact] public void PrecededByTest1() { int invokedCount1 = 0; int invokedCount2 = 0; int sequence = 7; int invokedCount1Sequence = 0; int invokedCount2Sequence = 0; AsyncContinuation originalContinuation = ex => { invokedCount1++; invokedCount1Sequence = sequence++; }; AsynchronousAction doSomethingElse = c => { invokedCount2++; invokedCount2Sequence = sequence++; c(null); c(null); }; AsyncContinuation cont = AsyncHelpers.PrecededBy(originalContinuation, doSomethingElse); cont(null); // make sure doSomethingElse was invoked first // then original continuation Assert.Equal(7, invokedCount2Sequence); Assert.Equal(8, invokedCount1Sequence); Assert.Equal(1, invokedCount1); Assert.Equal(1, invokedCount2); } [Fact] public void PrecededByTest2() { int invokedCount1 = 0; int invokedCount2 = 0; int sequence = 7; int invokedCount1Sequence = 0; int invokedCount2Sequence = 0; AsyncContinuation originalContinuation = ex => { invokedCount1++; invokedCount1Sequence = sequence++; }; AsynchronousAction doSomethingElse = c => { invokedCount2++; invokedCount2Sequence = sequence++; c(null); c(null); }; AsyncContinuation cont = AsyncHelpers.PrecededBy(originalContinuation, doSomethingElse); var sampleException = new ApplicationException("Some message."); cont(sampleException); // make sure doSomethingElse was not invoked Assert.Equal(0, invokedCount2Sequence); Assert.Equal(7, invokedCount1Sequence); Assert.Equal(1, invokedCount1); Assert.Equal(0, invokedCount2); } } }
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2015 FUJIWARA, Yusuke // // 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. // #endregion -- License Terms -- #if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT #define UNITY #endif using System; using System.Collections; using System.Runtime.Serialization; namespace MsgPack.Serialization.CollectionSerializers { /// <summary> /// Provides basic features for non-generic dictionary serializers. /// </summary> /// <typeparam name="TDictionary">The type of the dictionary.</typeparam> /// <remarks> /// This class provides framework to implement variable collection serializer, and this type seals some virtual members to maximize future backward compatibility. /// If you cannot use this class, you can implement your own serializer which inherits <see cref="MessagePackSerializer{T}"/> and implements <see cref="ICollectionInstanceFactory"/>. /// </remarks> public abstract class NonGenericDictionaryMessagePackSerializer<TDictionary> : MessagePackSerializer<TDictionary>, ICollectionInstanceFactory where TDictionary : IDictionary { private readonly IMessagePackSingleObjectSerializer _keySerializer; private readonly IMessagePackSingleObjectSerializer _valueSerializer; /// <summary> /// Initializes a new instance of the <see cref="NonGenericDictionaryMessagePackSerializer{TDictionary}"/> class. /// </summary> /// <param name="ownerContext">A <see cref="SerializationContext"/> which owns this serializer.</param> /// <param name="schema"> /// The schema for collection itself or its items for the member this instance will be used to. /// <c>null</c> will be considered as <see cref="PolymorphismSchema.Default"/>. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="ownerContext"/> is <c>null</c>. /// </exception> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by base .ctor" )] protected NonGenericDictionaryMessagePackSerializer( SerializationContext ownerContext, PolymorphismSchema schema ) : base( ownerContext ) { var safeSchema = schema ?? PolymorphismSchema.Default; this._keySerializer = ownerContext.GetSerializer( typeof( object ), safeSchema.KeySchema ); this._valueSerializer = ownerContext.GetSerializer( typeof( object ), safeSchema.ItemSchema ); } /// <summary> /// Serializes specified object with specified <see cref="Packer"/>. /// </summary> /// <param name="packer"><see cref="Packer"/> which packs values in <paramref name="objectTree"/>. This value will not be <c>null</c>.</param> /// <param name="objectTree">Object to be serialized.</param> /// <exception cref="SerializationException"> /// <typeparamref name="TDictionary"/> is not serializable etc. /// </exception> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "By design" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "By design" )] protected internal sealed override void PackToCore( Packer packer, TDictionary objectTree ) { packer.PackMapHeader( objectTree.Count ); foreach ( DictionaryEntry item in objectTree ) { this._keySerializer.PackTo( packer, item.Key ); this._valueSerializer.PackTo( packer, item.Value ); } } /// <summary> /// Deserializes object with specified <see cref="Unpacker"/>. /// </summary> /// <param name="unpacker"><see cref="Unpacker"/> which unpacks values of resulting object tree. This value will not be <c>null</c>.</param> /// <returns>Deserialized object.</returns> /// <exception cref="SerializationException"> /// Failed to deserialize object due to invalid unpacker state, stream content, or so. /// </exception> /// <exception cref="MessageTypeException"> /// Failed to deserialize object due to invalid unpacker state, stream content, or so. /// </exception> /// <exception cref="InvalidMessagePackStreamException"> /// Failed to deserialize object due to invalid unpacker state, stream content, or so. /// </exception> /// <exception cref="NotSupportedException"> /// <typeparamref name="TDictionary"/> is abstract type. /// </exception> /// <remarks> /// This method invokes <see cref="CreateInstance(int)"/>, and then fill deserialized items to resultong collection. /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )] protected internal sealed override TDictionary UnpackFromCore( Unpacker unpacker ) { if ( !unpacker.IsMapHeader ) { throw SerializationExceptions.NewIsNotArrayHeader(); } return this.InternalUnpackFromCore( unpacker ); } internal virtual TDictionary InternalUnpackFromCore( Unpacker unpacker ) { var itemsCount = UnpackHelpers.GetItemsCount( unpacker ); var collection = this.CreateInstance( itemsCount ); this.UnpackToCore( unpacker, collection, itemsCount ); return collection; } /// <summary> /// Creates a new collection instance with specified initial capacity. /// </summary> /// <param name="initialCapacity"> /// The initial capacy of creating collection. /// Note that this parameter may <c>0</c> for non-empty collection. /// </param> /// <returns> /// New collection instance. This value will not be <c>null</c>. /// </returns> /// <remarks> /// An author of <see cref="Unpacker" /> could implement unpacker for non-MessagePack format, /// so implementer of this interface should not rely on that <paramref name="initialCapacity" /> reflects actual items count. /// For example, JSON unpacker cannot supply collection items count efficiently. /// </remarks> /// <seealso cref="ICollectionInstanceFactory.CreateInstance"/> protected abstract TDictionary CreateInstance( int initialCapacity ); object ICollectionInstanceFactory.CreateInstance( int initialCapacity ) { return this.CreateInstance( initialCapacity ); } /// <summary> /// Deserializes collection items with specified <see cref="Unpacker"/> and stores them to <paramref name="collection"/>. /// </summary> /// <param name="unpacker"><see cref="Unpacker"/> which unpacks values of resulting object tree. This value will not be <c>null</c>.</param> /// <param name="collection">Collection that the items to be stored. This value will not be <c>null</c>.</param> /// <exception cref="SerializationException"> /// Failed to deserialize object due to invalid unpacker state, stream content, or so. /// </exception> /// <exception cref="NotSupportedException"> /// <typeparamref name="TDictionary"/> is not collection. /// </exception> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "By design" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "By design" )] protected internal sealed override void UnpackToCore( Unpacker unpacker, TDictionary collection ) { if ( !unpacker.IsMapHeader ) { throw SerializationExceptions.NewIsNotArrayHeader(); } this.UnpackToCore( unpacker, collection, UnpackHelpers.GetItemsCount( unpacker ) ); } private void UnpackToCore( Unpacker unpacker, TDictionary collection, int itemsCount ) { for ( int i = 0; i < itemsCount; i++ ) { if ( !unpacker.Read() ) { throw SerializationExceptions.NewMissingItem( i ); } object key; if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader ) { key = this._keySerializer.UnpackFrom( unpacker ); } else { using ( var subtreeUnpacker = unpacker.ReadSubtree() ) { key = this._keySerializer.UnpackFrom( subtreeUnpacker ); } } if ( !unpacker.Read() ) { throw SerializationExceptions.NewMissingItem( i ); } object value; if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader ) { value = this._valueSerializer.UnpackFrom( unpacker ); } else { using ( var subtreeUnpacker = unpacker.ReadSubtree() ) { value = this._valueSerializer.UnpackFrom( subtreeUnpacker ); } } collection.Add( key, value ); } } } #if UNITY internal abstract class UnityNonGenericDictionaryMessagePackSerializer : NonGenericMessagePackSerializer, ICollectionInstanceFactory { private readonly IMessagePackSingleObjectSerializer _keySerializer; private readonly IMessagePackSingleObjectSerializer _valueSerializer; protected UnityNonGenericDictionaryMessagePackSerializer( SerializationContext ownerContext, Type targetType, PolymorphismSchema schema ) : base( ownerContext, targetType ) { var safeSchema = schema ?? PolymorphismSchema.Default; this._keySerializer = ownerContext.GetSerializer( typeof( object ), safeSchema.KeySchema ); this._valueSerializer = ownerContext.GetSerializer( typeof( object ), safeSchema.ItemSchema ); } protected internal sealed override void PackToCore( Packer packer, object objectTree ) { var asDictionary = objectTree as IDictionary; // ReSharper disable once PossibleNullReferenceException packer.PackMapHeader( asDictionary.Count ); foreach ( DictionaryEntry item in asDictionary ) { this._keySerializer.PackTo( packer, item.Key ); this._valueSerializer.PackTo( packer, item.Value ); } } protected internal sealed override object UnpackFromCore( Unpacker unpacker ) { if ( !unpacker.IsMapHeader ) { throw SerializationExceptions.NewIsNotArrayHeader(); } return this.InternalUnpackFromCore( unpacker ); } internal virtual object InternalUnpackFromCore( Unpacker unpacker ) { var itemsCount = UnpackHelpers.GetItemsCount( unpacker ); var collection = this.CreateInstance( itemsCount ); this.UnpackToCore( unpacker, collection as IDictionary, itemsCount ); return collection; } protected abstract object CreateInstance( int initialCapacity ); object ICollectionInstanceFactory.CreateInstance( int initialCapacity ) { return this.CreateInstance( initialCapacity ); } protected internal sealed override void UnpackToCore( Unpacker unpacker, object collection ) { if ( !unpacker.IsMapHeader ) { throw SerializationExceptions.NewIsNotArrayHeader(); } this.UnpackToCore( unpacker, collection as IDictionary, UnpackHelpers.GetItemsCount( unpacker ) ); } private void UnpackToCore( Unpacker unpacker, IDictionary collection, int itemsCount ) { for ( int i = 0; i < itemsCount; i++ ) { if ( !unpacker.Read() ) { throw SerializationExceptions.NewMissingItem( i ); } object key; if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader ) { key = this._keySerializer.UnpackFrom( unpacker ); } else { using ( var subtreeUnpacker = unpacker.ReadSubtree() ) { key = this._keySerializer.UnpackFrom( subtreeUnpacker ); } } if ( !unpacker.Read() ) { throw SerializationExceptions.NewMissingItem( i ); } object value; if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader ) { value = this._valueSerializer.UnpackFrom( unpacker ); } else { using ( var subtreeUnpacker = unpacker.ReadSubtree() ) { value = this._valueSerializer.UnpackFrom( subtreeUnpacker ); } } collection.Add( key, value ); } } } #endif // UNITY }
using OpenKh.Engine.Extensions; using OpenKh.Engine.MonoGame; using OpenKh.Engine.Renderers; using OpenKh.Engine.Renders; using OpenKh.Game.Infrastructure; using OpenKh.Game.Menu; using OpenKh.Kh2; using System.Collections.Generic; using System.Linq; using OpenKh.Game.Debugging; using OpenKh.Engine.Input; namespace OpenKh.Game.States { public class MenuState : IMenuManager, IState { private Kernel _kernel; private IDataContent _content; private ArchiveManager _archiveManager; private KingdomShader _shader; private MonoSpriteDrawing _drawing; private Layout _campLayout; private LayoutRenderer _layoutRenderer; private List<ISpriteTexture> _textures = new List<ISpriteTexture>(); private Dictionary<ushort, byte[]> _cachedText = new Dictionary<ushort, byte[]>(); private IAnimatedSequence _backgroundSeq; private IAnimatedSequence _subMenuDescriptionSeq; private List<object> _subMenuDescriptionInfo = new List<object>(); private Kh2MessageRenderer _messageRenderer; private IMenu _subMenu; public IGameContext GameContext { get; } public AnimatedSequenceFactory SequenceFactory { get; private set; } public IInput Input { get; private set; } public bool IsMenuOpen { get; private set; } public MenuState(IGameContext gameContext) { GameContext = gameContext; } public void Initialize(StateInitDesc initDesc) { _kernel = initDesc.Kernel; _content = initDesc.DataContent; _archiveManager = initDesc.ArchiveManager; Input = initDesc.Input; var viewport = initDesc.GraphicsDevice.GraphicsDevice.Viewport; _shader = new KingdomShader(initDesc.ContentManager); _drawing = new MonoSpriteDrawing(initDesc.GraphicsDevice.GraphicsDevice, _shader); _drawing.SetProjection( viewport.Width, viewport.Height, Global.ResolutionWidth, Global.ResolutionHeight, 1.0f); initDesc.GraphicsDevice.GraphicsDevice.DepthStencilState = new Microsoft.Xna.Framework.Graphics.DepthStencilState { DepthBufferEnable = false, StencilEnable = false, }; var messageContext = _kernel.SystemMessageContext; _messageRenderer = new Kh2MessageRenderer(_drawing, messageContext); _archiveManager.LoadArchive($"menu/{_kernel.Region}/camp.2ld"); (_campLayout, _textures) = GetLayoutResources("camp", "camp"); _layoutRenderer = new LayoutRenderer(_campLayout, _drawing, _textures) { SelectedSequenceGroupIndex = 0 }; SequenceFactory = new AnimatedSequenceFactory( _drawing, initDesc.Kernel.MessageProvider, _messageRenderer, _kernel.SystemMessageContext.Encoder, _campLayout.SequenceItems[1], _textures.First()); _backgroundSeq = SequenceFactory.Create(new List<AnimatedSequenceDesc> { new AnimatedSequenceDesc { SequenceIndexStart = 107, SequenceIndexLoop = 108, SequenceIndexEnd = 109, }, new AnimatedSequenceDesc { SequenceIndexStart = 110, SequenceIndexLoop = 111, SequenceIndexEnd = 112, }, new AnimatedSequenceDesc { SequenceIndexStart = 113, SequenceIndexLoop = 114, SequenceIndexEnd = 115, } }); _subMenuDescriptionSeq = SequenceFactory.Create(new List<AnimatedSequenceDesc>()); } public void Destroy() { foreach (var texture in _textures) texture.Dispose(); _shader.Dispose(); _drawing.Dispose(); } public void OpenMenu() { _layoutRenderer.FrameIndex = 0; _layoutRenderer.SelectedSequenceGroupIndex = 0; _backgroundSeq.Begin(); _subMenu = new MainMenu(this); _subMenu.Open(); _subMenuDescriptionInfo.Clear(); _subMenuDescriptionSeq = SequenceFactory.Create(new List<AnimatedSequenceDesc>()); _subMenuDescriptionSeq.Begin(); IsMenuOpen = true; } public void CloseAllMenu() { _layoutRenderer.FrameIndex = 0; _layoutRenderer.SelectedSequenceGroupIndex = 2; _backgroundSeq.End(); _subMenuDescriptionSeq.End(); _subMenu.Close(); } public void PushSubMenuDescription(ushort messageId) { _subMenuDescriptionInfo.Add(messageId); SubMenuDescriptionInvalidateByPush(); } public void PushSubMenuDescription(string message) { _subMenuDescriptionInfo.Add(message); SubMenuDescriptionInvalidateByPush(); } private void SubMenuDescriptionInvalidateByPush() { var count = _subMenuDescriptionInfo.Count; _subMenuDescriptionSeq = SequenceFactory.Create(Enumerable.Range(0, count) .Select(i => new AnimatedSequenceDesc { SequenceIndexStart = i + 1 < count ? -1 : 75, SequenceIndexLoop = 76, SequenceIndexEnd = 77, StackIndex = i, StackWidth = AnimatedSequenceDesc.DefaultStacking, StackHeight = 0, MessageId = _subMenuDescriptionInfo[i] is ushort id ? id : (ushort)0, MessageText = _subMenuDescriptionInfo[i] as string, Flags = AnimationFlags.TextIgnoreColor | AnimationFlags.TextTranslateX | AnimationFlags.ChildStackHorizontally, TextAnchor = TextAnchor.BottomLeft, Children = new List<AnimatedSequenceDesc> { new AnimatedSequenceDesc { }, new AnimatedSequenceDesc { SequenceIndexStart = i + 1 < count ? -1 : 27, SequenceIndexLoop = 28, SequenceIndexEnd = 29, } } }) .ToList()); _subMenuDescriptionSeq.Begin(); } public void PopSubMenuDescription() { var count = _subMenuDescriptionInfo.Count; if (count == 0) return; _subMenuDescriptionSeq = SequenceFactory.Create(Enumerable.Range(0, count) .Select(i => new AnimatedSequenceDesc { SequenceIndexLoop = i + 1 < count ? 76 : -1, SequenceIndexEnd = 77, StackIndex = i, StackWidth = AnimatedSequenceDesc.DefaultStacking, StackHeight = 0, MessageId = _subMenuDescriptionInfo[i] is ushort id ? id : (ushort)0, MessageText = _subMenuDescriptionInfo[i] as string, Flags = AnimationFlags.TextIgnoreColor | AnimationFlags.TextTranslateX | AnimationFlags.ChildStackHorizontally, TextAnchor = TextAnchor.BottomLeft, Children = new List<AnimatedSequenceDesc> { new AnimatedSequenceDesc { }, new AnimatedSequenceDesc { SequenceIndexLoop = i + 1 < count ? 28 : -1, SequenceIndexEnd = 29, }, } }) .ToList()); _subMenuDescriptionSeq.Begin(); _subMenuDescriptionInfo.RemoveAt(_subMenuDescriptionInfo.Count - 1); } public void SetElementDescription(ushort messageId) { } public void Update(DeltaTimes deltaTimes) { var deltaTime = deltaTimes.DeltaTime; ProcessInput(Input); _layoutRenderer.FrameIndex++; _backgroundSeq.Update(deltaTime); _subMenuDescriptionSeq.Update(deltaTime); _subMenu.Update(deltaTime); } public void Draw(DeltaTimes deltaTimes) { switch (_layoutRenderer.SelectedSequenceGroupIndex) { case 0: if (_layoutRenderer.IsLastFrame) { _layoutRenderer.FrameIndex = 0; _layoutRenderer.SelectedSequenceGroupIndex = 1; } break; case 1: break; case 2: if (_layoutRenderer.IsLastFrame) { IsMenuOpen = false; } break; } if (_layoutRenderer.SelectedSequenceGroupIndex == 0 && _layoutRenderer.IsLastFrame) _layoutRenderer.SelectedSequenceGroupIndex = 1; _layoutRenderer.Draw(); _backgroundSeq.Draw(0, 0); _subMenuDescriptionSeq.Draw(0, 0); _subMenu.Draw(); _drawing.Flush(); } private void ProcessInput(IInput input) { if (input.Triggered.SpecialRight) CloseAllMenu(); } private (Layout layout, List<ISpriteTexture> textures) GetLayoutResources(string layoutResourceName, string imagesResourceName) { var layout = _archiveManager.Get<Layout>(layoutResourceName); _textures = _archiveManager.Get<Imgz>(imagesResourceName) ?.Images?.Select(x => _drawing.CreateSpriteTexture(x)).ToList(); return (layout, _textures); } } }
// // Copyright (C) DataStax Inc. // // 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 System.Net; using System.Threading.Tasks; using Cassandra.DataStax.Graph; using Cassandra.Metrics; namespace Cassandra { /// <summary> /// A session holds connections to a Cassandra cluster, allowing it to be queried. /// <para> /// Each session maintains multiple connections to the cluster nodes, /// provides policies to choose which node to use for each query (round-robin on /// all nodes of the cluster by default), and handles retries for failed query (when /// it makes sense), etc... /// </para> /// <para> /// Session instances are thread-safe and usually a single instance is enough /// per application. However, a given session can only be set to one keyspace /// at a time, so one instance per keyspace is necessary. /// </para> /// </summary> public interface ISession: IDisposable { /// <summary> /// Gets the Cassandra native binary protocol version /// </summary> int BinaryProtocolVersion { get; } /// <summary> /// Gets the cluster information and state /// </summary> ICluster Cluster { get; } /// <summary> /// Determines if the object has been disposed. /// </summary> bool IsDisposed { get; } /// <summary> /// Gets name of currently used keyspace. /// </summary> string Keyspace { get; } /// <summary> /// Gets the user defined type mappings /// </summary> UdtMappingDefinitions UserDefinedTypes { get; } /// <summary> /// Session name. This will be autogenerated if it is not set with <see cref="Builder.WithSessionName"/>. /// This is used as part of the metric bucket name, for example, which can be used to separate metric paths per session. /// </summary> string SessionName { get; } /// <summary> /// Begins asynchronous execute operation. /// </summary> IAsyncResult BeginExecute(IStatement statement, AsyncCallback callback, object state); /// <summary> /// Begins asynchronous execute operation /// </summary> IAsyncResult BeginExecute(string cqlQuery, ConsistencyLevel consistency, AsyncCallback callback, object state); /// <summary> /// Begins asynchronous prepare operation /// </summary> IAsyncResult BeginPrepare(string cqlQuery, AsyncCallback callback, object state); /// <summary> /// Switches to the specified keyspace. /// </summary> /// <param name="keyspaceName">Case-sensitive name of keyspace to be used.</param> /// <exception cref="InvalidQueryException">When keyspace does not exist</exception> void ChangeKeyspace(string keyspaceName); /// <summary> /// Creates new keyspace in current cluster. /// </summary> /// <param name="keyspaceName">Case-sensitive name of keyspace to be created.</param> /// <param name="replication"> /// Replication property for this keyspace. /// To set it, refer to the <see cref="ReplicationStrategies"/> class methods. /// It is a dictionary of replication property sub-options where key is a sub-option name and value is a value for that sub-option. /// <para>Default value is <c>SimpleStrategy</c> with <c>replication_factor = 1</c></para> /// </param> /// <param name="durableWrites">Whether to use the commit log for updates on this keyspace. Default is set to <c>true</c>.</param> void CreateKeyspace(string keyspaceName, Dictionary<string, string> replication = null, bool durableWrites = true); /// <summary> /// Creates new keyspace in current cluster. /// If keyspace with specified name already exists, then this method does nothing. /// </summary> /// <param name="keyspaceName">Case-sensitive name of keyspace to be created.</param> /// <param name="replication"> /// Replication property for this keyspace. /// To set it, refer to the <see cref="ReplicationStrategies"/> class methods. /// It is a dictionary of replication property sub-options where key is a sub-option name and value is a value for that sub-option. /// <para>Default value is <c>'SimpleStrategy'</c> with <c>'replication_factor' = 2</c></para> /// </param> /// <param name="durableWrites">Whether to use the commit log for updates on this keyspace. Default is set to <c>true</c>.</param> void CreateKeyspaceIfNotExists(string keyspaceName, Dictionary<string, string> replication = null, bool durableWrites = true); /// <summary> /// Deletes specified keyspace from current cluster. /// If keyspace with specified name does not exist, then exception will be thrown. /// </summary> /// <param name="keyspaceName">Name of keyspace to be deleted.</param> void DeleteKeyspace(string keyspaceName); /// <summary> /// Deletes specified keyspace from current cluster. /// If keyspace with specified name does not exist, then this method does nothing. /// </summary> /// <param name="keyspaceName">Name of keyspace to be deleted.</param> void DeleteKeyspaceIfExists(string keyspaceName); /// <summary> /// Ends asynchronous execute operation /// </summary> /// <param name="ar"></param> /// <returns></returns> RowSet EndExecute(IAsyncResult ar); /// <summary> /// Ends asynchronous prepare operation /// </summary> PreparedStatement EndPrepare(IAsyncResult ar); /// <summary> /// Executes the provided statement with the provided execution profile. /// The execution profile must have been added previously to the Cluster using <see cref="Builder.WithExecutionProfiles"/>. /// </summary> /// <param name="statement">Statement to execute.</param> /// <param name="executionProfileName">ExecutionProfile name to be used while executing the statement.</param> RowSet Execute(IStatement statement, string executionProfileName); /// <summary> /// Executes the provided query. /// </summary> RowSet Execute(IStatement statement); /// <summary> /// Executes the provided query. /// </summary> RowSet Execute(string cqlQuery); /// <summary> /// Executes the provided query with the provided execution profile. /// The execution profile must have been added previously to the Cluster using <see cref="Builder.WithExecutionProfiles"/>. /// </summary> /// <param name="cqlQuery">Query to execute.</param> /// <param name="executionProfileName">ExecutionProfile name to be used while executing the statement.</param> RowSet Execute(string cqlQuery, string executionProfileName); /// <summary> /// Executes the provided query. /// </summary> RowSet Execute(string cqlQuery, ConsistencyLevel consistency); /// <summary> /// Executes the provided query. /// </summary> RowSet Execute(string cqlQuery, int pageSize); /// <summary> /// Executes a query asynchronously /// </summary> /// <param name="statement">The statement to execute (simple, bound or batch statement)</param> /// <returns>A task representing the asynchronous operation.</returns> Task<RowSet> ExecuteAsync(IStatement statement); /// <summary> /// Executes a query asynchronously with the provided execution profile. /// The execution profile must have been added previously to the Cluster using <see cref="Builder.WithExecutionProfiles"/>. /// </summary> /// <param name="statement">The statement to execute (simple, bound or batch statement)</param> /// <param name="executionProfileName">ExecutionProfile name to be used while executing the statement.</param> /// <returns>A task representing the asynchronous operation.</returns> Task<RowSet> ExecuteAsync(IStatement statement, string executionProfileName); /// <summary> /// Prepares the provided query string. /// </summary> /// <param name="cqlQuery">cql query to prepare</param> PreparedStatement Prepare(string cqlQuery); /// <summary> /// Prepares the query string, sending the custom payload request. /// </summary> /// <param name="cqlQuery">cql query to prepare</param> /// <param name="customPayload">Custom outgoing payload to send with the prepare request</param> PreparedStatement Prepare(string cqlQuery, IDictionary<string, byte[]> customPayload); /// <summary> /// Prepares the query on the provided keyspace. /// </summary> /// <param name="cqlQuery">Cql query to prepare</param> /// <param name="keyspace">The keyspace to prepare this query with</param> /// <remarks>Setting the keyspace parameter is only available with protocol v5 (not supported by the driver yet) or DSE 6.0+.</remarks> PreparedStatement Prepare(string cqlQuery, string keyspace); /// <summary> /// Prepares the provided query string asynchronously on the provided keyspace, sending the custom payload /// as part of the request. /// </summary> /// <param name="cqlQuery">Cql query to prepare</param> /// <param name="keyspace">The keyspace to prepare this query with</param> /// <param name="customPayload">Custom outgoing payload to send with the prepare request</param> /// <remarks>Setting the keyspace parameter is only available with protocol v5 (not supported by the driver yet) or DSE 6.0+.</remarks> PreparedStatement Prepare(string cqlQuery, string keyspace, IDictionary<string, byte[]> customPayload); /// <summary> /// Prepares the provided query string asynchronously. /// </summary> /// <param name="cqlQuery">cql query to prepare</param> Task<PreparedStatement> PrepareAsync(string cqlQuery); /// <summary> /// Prepares the provided query string asynchronously, and sending the custom payload request. /// </summary> /// <param name="cqlQuery">cql query to prepare</param> /// <param name="customPayload">Custom outgoing payload to send with the prepare request</param> Task<PreparedStatement> PrepareAsync(string cqlQuery, IDictionary<string, byte[]> customPayload); /// <summary> /// Prepares the query asynchronously on the provided keyspace. /// </summary> /// <param name="cqlQuery">Cql query to prepare</param> /// <param name="keyspace">The keyspace to prepare this query with</param> /// <remarks>Setting the keyspace parameter is only available with protocol v5 (not supported by the driver yet) or DSE 6.0+.</remarks> Task<PreparedStatement> PrepareAsync(string cqlQuery, string keyspace); /// <summary> /// Prepares the provided query asynchronously on the provided keyspace, sending the custom payload /// as part of the request. /// </summary> /// <param name="cqlQuery">Cql query to prepare</param> /// <param name="keyspace">The keyspace to prepare this query with</param> /// <param name="customPayload">Custom outgoing payload to send with the prepare request</param> /// <remarks>Setting the keyspace parameter is only available with protocol v5 (not supported by the driver yet) or DSE 6.0+.</remarks> Task<PreparedStatement> PrepareAsync(string cqlQuery, string keyspace, IDictionary<string, byte[]> customPayload); /// <summary> /// Retrieves the driver metrics for this session. /// </summary> IDriverMetrics GetMetrics(); /// <summary> /// Executes a graph statement. /// </summary> /// <param name="statement">The graph statement containing the query</param> /// <example> /// <code> /// GraphResultSet rs = session.ExecuteGraph(new SimpleGraphStatement("g.V()")); /// </code> /// </example> GraphResultSet ExecuteGraph(IGraphStatement statement); /// <summary> /// Executes a graph statement. /// </summary> /// <param name="statement">The graph statement containing the query</param> /// <example> /// <code> /// Task&lt;GraphResultSet$gt; task = session.ExecuteGraphAsync(new SimpleGraphStatement("g.V()")); /// </code> /// </example> Task<GraphResultSet> ExecuteGraphAsync(IGraphStatement statement); /// <summary> /// Executes a graph statement with the provided execution profile. /// The execution profile must have been added previously to the Cluster /// using <see cref="Builder.WithExecutionProfiles"/>. /// </summary> /// <param name="statement">The graph statement containing the query</param> /// <param name="executionProfileName">The graph execution profile name to use while executing this statement.</param> /// <example> /// <code> /// GraphResultSet rs = session.ExecuteGraph(new SimpleGraphStatement("g.V()"), "graphProfile"); /// </code> /// </example> GraphResultSet ExecuteGraph(IGraphStatement statement, string executionProfileName); /// <summary> /// Executes a graph statement asynchronously with the provided graph execution profile. /// The graph execution profile must have been added previously to the Cluster /// using <see cref="Builder.WithExecutionProfiles"/>. /// </summary> /// <param name="statement">The graph statement containing the query</param> /// <param name="executionProfileName">The graph execution profile name to use while executing this statement.</param> /// <example> /// <code> /// Task&lt;GraphResultSet$gt; task = session.ExecuteGraphAsync(new SimpleGraphStatement("g.V()"), "graphProfile"); /// </code> /// </example> Task<GraphResultSet> ExecuteGraphAsync(IGraphStatement statement, string executionProfileName); /// <summary> /// Disposes the session asynchronously. /// </summary> Task ShutdownAsync(); [Obsolete("Method deprecated. The driver internally waits for schema agreement when there is an schema change. See ProtocolOptions.MaxSchemaAgreementWaitSeconds for more info.")] void WaitForSchemaAgreement(RowSet rs); [Obsolete("Method deprecated. The driver internally waits for schema agreement when there is an schema change. See ProtocolOptions.MaxSchemaAgreementWaitSeconds for more info.")] bool WaitForSchemaAgreement(IPEndPoint forHost); } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using TC.Unity.Composition.UnitTests.Dependencies; namespace Soloco.Composition.UnitTests.Generation.CompositionFactoryBuilderSpecifications { public class When_a_composition_is_created_given_an_interface_with_external_dependencies { [TestClass] public class as_property_type : CompositionFactoryBuilderSpecification<as_property_type.IComposition> { public interface IPart { SomeArgumentType Test { get; set; } } public interface IComposition : IPart { } private readonly SomeArgumentType _returnValue = new SomeArgumentType { SomeValue = "Some Value" }; private Mock<IPart> _partMock; protected override void Arrange() { base.Arrange(); _partMock = new Mock<IPart>(); CompositeParts.Add(typeof(IPart), _partMock.Object); _partMock .SetupGet(p => p.Test) .Returns(_returnValue); } [TestMethod] public void then_the_constucted_type_should_not_be_null() { VerifyResultNotNull(); } [TestMethod] public void then_the_property_should_be_gettable() { Assert.AreSame(_returnValue, Result.Test); _partMock.VerifyGet(p => p.Test); } [TestMethod] public void then_the_property_should_be_settable() { Result.Test = _returnValue; _partMock.VerifySet(p => p.Test = _returnValue); } } [TestClass] public class as_method_parameter_type : CompositionFactoryBuilderSpecification<as_method_parameter_type.IComposition> { public interface IPart { void Test(SomeArgumentType parameter); } public interface IComposition : IPart { } private readonly SomeArgumentType _returnValue = new SomeArgumentType { SomeValue = "Some Value" }; private Mock<IPart> _partMock; protected override void Arrange() { base.Arrange(); _partMock = new Mock<IPart>(); CompositeParts.Add(typeof(IPart), _partMock.Object); } [TestMethod] public void then_the_constucted_type_should_not_be_null() { VerifyResultNotNull(); } [TestMethod] public void then_the_method_should_be_callable() { Result.Test(_returnValue); _partMock.Verify(p => p.Test(_returnValue)); } } [TestClass] public class as_method_return_type : CompositionFactoryBuilderSpecification<as_method_return_type.IComposition> { public interface IPart { SomeArgumentType Test(); } public interface IComposition : IPart { } private readonly SomeArgumentType _returnValue = new SomeArgumentType { SomeValue = "Some Value" }; private Mock<IPart> _partMock; protected override void Arrange() { base.Arrange(); _partMock = new Mock<IPart>(); CompositeParts.Add(typeof(IPart), _partMock.Object); _partMock .Setup(p => p.Test()) .Returns(_returnValue); } [TestMethod] public void then_the_constucted_type_should_not_be_null() { VerifyResultNotNull(); } [TestMethod] public void then_the_method_should_be_callable() { Assert.AreSame(_returnValue, Result.Test()); _partMock.Verify(p => p.Test()); } } [TestClass] public class as_event_handler_type : CompositionFactoryBuilderSpecification<as_event_handler_type.IEventComposition> { public interface IEventPart { event SomeEventHandler SimpleEvent; } class EventPartMock : IEventPart { public event SomeEventHandler SimpleEvent { add { SimpleEventHandler = value; SimpleEventAdded = true; } remove { SimpleEventHandler = value; SimpleEventRemoved = true; } } public SomeEventHandler SimpleEventHandler { get; private set; } public bool SimpleEventAdded { get; private set; } public bool SimpleEventRemoved { get; private set; } internal void RaiseSimpleEvent() { if (SimpleEventHandler == null) { throw new InvalidOperationException("SimpleEventHandler == null"); } SimpleEventHandler(); } } public interface IEventComposition : IEventPart { } private EventPartMock _partMock; private bool _simpleEventRaised; protected override void Arrange() { base.Arrange(); _partMock = new EventPartMock(); CompositeParts.Add(typeof(IEventPart), _partMock); } [TestMethod] public void then_the_constucted_type_should_not_be_null() { VerifyResultNotNull(); } [TestMethod] public void then_the_simple_event_should_subscribable() { SomeEventHandler handler = Result_SimpleEvent; Result.SimpleEvent += handler; Assert.AreSame(handler, _partMock.SimpleEventHandler); Assert.IsTrue(_partMock.SimpleEventAdded); } [TestMethod] public void then_the_simple_event_should_unsubscribable() { SomeEventHandler handler = Result_SimpleEvent; Result.SimpleEvent -= handler; Assert.AreSame(handler, _partMock.SimpleEventHandler); Assert.IsTrue(_partMock.SimpleEventRemoved); } [TestMethod] public void then_subscriber_of_the_simple_event_should_called() { SomeEventHandler handler = Result_SimpleEvent; Result.SimpleEvent += handler; _partMock.RaiseSimpleEvent(); Assert.IsTrue(_simpleEventRaised); } void Result_SimpleEvent() { _simpleEventRaised = true; } } [TestClass] public class as_composition_part : CompositionFactoryBuilderSpecification<as_composition_part.IComposition> { public interface IComposition : ISomePart { } private Mock<ISomePart> _partMock; protected override void Arrange() { base.Arrange(); _partMock = new Mock<ISomePart>(); CompositeParts.Add(typeof(ISomePart), _partMock.Object); } [TestMethod] public void then_the_constucted_type_should_not_be_null() { VerifyResultNotNull(); } } [TestClass] public class as_composition_base_part : CompositionFactoryBuilderSpecification<as_composition_base_part.IComposition> { public interface IParentSomePart : ISomePart { } public interface IComposition : IParentSomePart { } private Mock<IParentSomePart> _partMock; protected override void Arrange() { base.Arrange(); _partMock = new Mock<IParentSomePart>(); CompositeParts.Add(typeof(IParentSomePart), _partMock.Object); } [TestMethod] public void then_the_constucted_type_should_not_be_null() { VerifyResultNotNull(); } } [TestClass] public class as_composition : CompositionFactoryBuilderSpecification<ISomeComposition> { private Mock<ISomePart> _partMock; protected override void Arrange() { base.Arrange(); _partMock = new Mock<ISomePart>(); CompositeParts.Add(typeof(ISomePart), _partMock.Object); } [TestMethod] public void then_the_constucted_type_should_not_be_null() { VerifyResultNotNull(); } } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Symbology.Forms.dll // Description: The Windows Forms user interface layer for the DotSpatial.Symbology library. // ******************************************************************************************************** // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 10/4/2009 10:42:27 AM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using DotSpatial.Data; namespace DotSpatial.Symbology.Forms { /// <summary> /// The bar graph, when given a rectangular frame to work in, calculates appropriate bins /// from values, and draws the various labels and bars necessary. /// </summary> public class BarGraph : IDisposable { #region Private Variables private int _axisTextHeight; private int[] _bins; private List<ColorRange> _colorRanges; private int _countTextWidth; private TextFont _font; private int _height; private bool _logY; private int _maxBinCount; private double _maximum; private double _mean; private int _minHeight; private double _minimum; private int _numColumns; private ColorRange _selectedRange; private bool _showMean; private bool _showStandardDeviation; private double _std; private string _title; private TextFont _titleFont; private int _titleHeight; private int _width; #endregion #region Constructors /// <summary> /// Creates a new instance of BarGraph /// </summary> public BarGraph(int width, int height) { _numColumns = 40; _font = new TextFont(); _titleFont = new TextFont(20f); _title = "Statistical Breaks:"; _countTextWidth = 15; _axisTextHeight = 30; _minHeight = 20; _width = width; _height = height; _minimum = 0; _maximum = 100; _colorRanges = new List<ColorRange>(); } #endregion #region Methods /// <summary> /// Gets the bounding rectangle for the actual graph itself /// </summary> public Rectangle GetGraphBounds() { return new Rectangle(_countTextWidth, _titleHeight + 5, _width - _countTextWidth - 10, _height - _axisTextHeight - 10 - _titleHeight); } #endregion #region Properties /// <summary> /// Gets or sets the array of integers that represent the positive integer value stored in /// each bar. /// </summary> public int[] Bins { get { return _bins; } set { _bins = value; } } /// <summary> /// Gets or sets the list of color ranges that control how the colors are drawn to the graph. /// </summary> public List<ColorRange> ColorRanges { get { return _colorRanges; } set { _colorRanges = value; } } /// <summary> /// Gets or sets the Font for text like the axis labels /// </summary> public TextFont Font { get { return _font; } set { _font = value; } } /// <summary> /// Gets or sets the integer height /// </summary> public int Height { get { return _height; } set { _height = value; } } /// <summary> /// Gets or sets a boolean that indicates whether or not count values should be drawn with /// heights that are proportional to the logarithm of the count, instead of the count itself. /// </summary> public bool LogY { get { return _logY; } set { _logY = value; } } /// <summary> /// Gets or sets the integer maximum from all of the current bins. /// </summary> public int MaxBinCount { get { return _maxBinCount; } set { _maxBinCount = value; } } /// <summary> /// This doesn't affect the statistical minimum or maximum, but rather the current view extents. /// </summary> public double Maximum { get { return _maximum; } set { _maximum = value; } } /// <summary> /// The mean line can be drawn if it is in the view range. This is the statistical mean /// for all the values, not just the values currently in view. /// </summary> public double Mean { get { return _mean; } set { _mean = value; } } /// <summary> /// Gets or sets the double standard deviation. If ShowStandardDeviation is true, then /// they will be represented by red lines on either side of the mean. /// </summary> public double StandardDeviation { get { return _std; } set { _std = value; } } /// <summary> /// Very small counts frequently dissappear next to big counts. One strategey is to use a /// minimum height, so that the difference between 0 and 1 is magnified on the columns. /// </summary> public int MinHeight { get { return _minHeight; } set { _minHeight = value; } } /// <summary> /// Gets or sets the maximum extent for this graph. This doesn't affect the numeric statistics, /// but only the current view of that statistics. /// </summary> public double Minimum { get { return _minimum; } set { _minimum = value; } } /// <summary> /// Gets or sets the number of columns. Setting this will recalculate the bins. /// </summary> public int NumColumns { get { return _numColumns; } set { if (value < 0) value = 0; _numColumns = value; } } /// <summary> /// Gets or sets the color range. /// </summary> public ColorRange SelectedRange { get { return _selectedRange; } set { _selectedRange = value; } } /// <summary> /// Boolean, if this is true, the mean will be shown as a blue dotted line. /// </summary> public bool ShowMean { get { return _showMean; } set { _showMean = value; } } /// <summary> /// Boolean, if this is true, the integral standard deviations from the mean will be drawn /// as red dotted lines. /// </summary> public bool ShowStandardDeviation { get { return _showStandardDeviation; } set { _showStandardDeviation = value; } } /// <summary> /// Gets or sets the title of the graph. /// </summary> public string Title { get { return _title; } set { _title = value; } } /// <summary> /// Gets or sets the font to use for the graph title /// </summary> public TextFont TitleFont { get { return _titleFont; } set { _titleFont = value; } } /// <summary> /// Gets or sets the width of this graph in pixels. /// </summary> public int Width { get { return _width; } set { _width = value; } } #endregion #region IDisposable Members /// <summary> /// Disposes the font and titlefont /// </summary> public void Dispose() { _font.Dispose(); _titleFont.Dispose(); } #endregion /// <summary> /// Draws the graph, the colored bins, selected region, and any text, but not any sliders. /// </summary> /// <param name="g"></param> /// <param name="clip"></param> public void Draw(Graphics g, Rectangle clip) { DrawText(g); Rectangle gb = GetGraphBounds(); DrawSelectionHighlight(g, clip, gb); DrawColumns(g, clip); g.DrawRectangle(Pens.Black, gb); if (_showMean) { Pen p = new Pen(Color.Blue); p.DashStyle = DashStyle.Dash; float x = GetPosition(_mean); if (x > -32000 && x < 32000) g.DrawLine(p, x, gb.Top, x, gb.Bottom); p.Dispose(); } if (_showStandardDeviation) { Pen p = new Pen(Color.Red); p.DashStyle = DashStyle.Dash; for (int i = 1; i < 6; i++) { double h = _mean + _std * i; double l = _mean - _std * i; if (h < _maximum && h > _minimum) { float x = GetPosition(h); if (x > -32000 && x < 32000) g.DrawLine(p, x, gb.Top, x, gb.Bottom); } if (l < _maximum && l > _minimum) { float x = GetPosition(l); if (x > -32000 && x < 32000) g.DrawLine(p, x, gb.Top, x, gb.Bottom); } } p.Dispose(); } } private void DrawColumns(Graphics g, Rectangle clip) { if (_numColumns == 0 || _maxBinCount == 0) return; Rectangle gb = GetGraphBounds(); float dX = (gb.Width) / (float)_numColumns; float dY = (gb.Height) / (float)_maxBinCount; if (_maxBinCount == 0) return; if (_logY) dY = (float)((gb.Height) / Math.Log(_maxBinCount)); for (int i = 0; i < _numColumns; i++) { if (_bins[i] == 0) continue; float h = dY * _bins[i]; if (_logY) h = (float)((dY) * Math.Log(_bins[i])); if (h < _minHeight) h = _minHeight; RectangleF rect = new RectangleF(dX * i + gb.X, gb.Height - h + gb.Y, dX, h); if (!clip.IntersectsWith(rect)) continue; Color light = Color.LightGray; Color dark = Color.DarkGray; double centerValue = CenterValue(i); if (_colorRanges != null) { foreach (ColorRange item in _colorRanges) { if (!item.Contains(centerValue)) continue; Color c = item.Color; light = c.Lighter(.2f); dark = c.Darker(.2f); break; } } LinearGradientBrush lgb = new LinearGradientBrush(rect, light, dark, LinearGradientMode.Horizontal); g.FillRectangle(lgb, rect.X, rect.Y, rect.Width, rect.Height); lgb.Dispose(); } } /// <summary> /// Given a double value, this returns the floating point position on this graph, /// based on the current minimum, maximum values. /// </summary> /// <param name="value">The double value to locate</param> /// <returns>A floating point X position</returns> public float GetPosition(double value) { Rectangle gb = GetGraphBounds(); return (float)(gb.Width * (value - _minimum) / (_maximum - _minimum) + gb.X); } /// <summary> /// Given a floating point X coordinate (relative to the control, not just the graph) /// this will return the double value represented by that location. /// </summary> /// <param name="position">The floating point position</param> /// <returns>The double value at the specified X coordinate</returns> public double GetValue(float position) { Rectangle gb = GetGraphBounds(); return ((position - gb.X) / gb.Width) * (_maximum - _minimum) + _minimum; } private void DrawSelectionHighlight(Graphics g, Rectangle clip, Rectangle gb) { if (_selectedRange == null) return; int index = _colorRanges.IndexOf(_selectedRange); if (index < 0) return; float left = gb.Left; if (_selectedRange.Range.Maximum < _minimum) return; if (_selectedRange.Range.Minimum > _maximum) return; if (_selectedRange.Range.Minimum != null) { float rangeLeft = GetPosition(_selectedRange.Range.Minimum.Value); if (rangeLeft > left) left = rangeLeft; } float right = gb.Right; if (_selectedRange.Range.Maximum != null) { float rangeRight = GetPosition(_selectedRange.Range.Maximum.Value); if (rangeRight < right) right = rangeRight; } Rectangle selectionRect = new Rectangle((int)left, gb.Top, (int)(right - left), gb.Height); if (!clip.IntersectsWith(selectionRect)) return; GraphicsPath gp = new GraphicsPath(); gp.AddRoundedRectangle(selectionRect, 2); if (selectionRect.Width != 0 && selectionRect.Height != 0) { LinearGradientBrush lgb = new LinearGradientBrush(selectionRect, Color.FromArgb(241, 248, 253), Color.FromArgb(213, 239, 252), LinearGradientMode.ForwardDiagonal); g.FillPath(lgb, gp); lgb.Dispose(); } gp.Dispose(); } /// <summary> /// Gets the real data value at the center of one of the bins. /// </summary> /// <param name="binIndex"></param> /// <returns></returns> public double CenterValue(int binIndex) { return _minimum + (_maximum - _minimum) * (binIndex + .5) / NumColumns; } private static string Format(double value) { if (Math.Abs(value) < 1) return value.ToString("E4"); if (value < 1E10) return value.ToString("#, ###"); return value.ToString("E4"); } /// <summary> /// Draws only the text for this bar graph. This will also calculate some critical /// font measurements to help size the internal part of the graph. /// </summary> /// <param name="g"></param> public void DrawText(Graphics g) { _titleHeight = (int)Math.Ceiling(g.MeasureString("My", _titleFont.GetFont()).Height); Font fnt = _font.GetFont(); string min = Format(_minimum); SizeF minSize = g.MeasureString(min, fnt); string max = Format(_maximum); SizeF maxSize = g.MeasureString(max, fnt); string mid = Format((_maximum + _minimum) / 2); SizeF midSize = g.MeasureString(mid, fnt); _axisTextHeight = (int)(Math.Ceiling(Math.Max(Math.Max(minSize.Height, maxSize.Height), midSize.Height))); _axisTextHeight += 10; const string one = "1"; SizeF oneSize = g.MeasureString(one, fnt); string count = Format(_maxBinCount); SizeF countSize = g.MeasureString(count, fnt); SizeF halfSize = new SizeF(0, 0); string halfCount = string.Empty; if (_maxBinCount > 1) { halfCount = Format(_maxBinCount / 2f); if (_logY) halfCount = Format(Math.Exp(Math.Log(_maxBinCount) / 2)); halfSize = g.MeasureString(halfCount, fnt); } _countTextWidth = (int)(Math.Ceiling(Math.Max(Math.Max(oneSize.Width, countSize.Width), halfSize.Width))); _countTextWidth += 20; Rectangle gb = GetGraphBounds(); _font.Draw(g, min, gb.X, gb.Bottom + 15); g.DrawLine(Pens.Black, gb.Left, gb.Bottom, gb.Left, gb.Bottom + 10); _font.Draw(g, max, gb.Right - maxSize.Width, gb.Bottom + 15); g.DrawLine(Pens.Black, gb.Left + gb.Width / 2, gb.Bottom, gb.Left + gb.Width / 2, gb.Bottom + 10); _font.Draw(g, mid, gb.X + gb.Width / 2 - midSize.Width / 2, gb.Bottom + 15); g.DrawLine(Pens.Black, gb.Right, gb.Bottom, gb.Right, gb.Bottom + 10); float dY; if (_maxBinCount == 0) { dY = _minHeight; } else { dY = (gb.Height) / (float)_maxBinCount; } float oneH = Math.Max(dY, _minHeight); _font.Draw(g, one, gb.Left - oneSize.Width - 15, gb.Bottom - oneSize.Height / 2 - oneH); g.DrawLine(Pens.Black, gb.Left - 10, gb.Bottom - oneH, gb.Left, gb.Bottom - oneH); if (_maxBinCount > 1) { _font.Draw(g, count, gb.Left - countSize.Width - 15, gb.Top); g.DrawLine(Pens.Black, gb.Left - 20, gb.Top, gb.Left, gb.Top); _font.Draw(g, halfCount, gb.Left - halfSize.Width - 15, gb.Top + gb.Height / 2 - halfSize.Height / 2); g.DrawLine(Pens.Black, gb.Left - 10, gb.Top + gb.Height / 2, gb.Left, gb.Top + gb.Height / 2); } SizeF titleSize = g.MeasureString(_title, _titleFont.GetFont()); _titleFont.Draw(g, _title, gb.X + gb.Width / 2 - titleSize.Width / 2, 2.5f); } } }
using System.Collections.Generic; using System.Reflection; using System.Reflection.Metadata; using ApiContractGenerator.Model; using ApiContractGenerator.Model.TypeReferences; namespace ApiContractGenerator.Source { public sealed partial class MetadataReaderSource { private abstract class ReaderClassBase : IMetadataType { protected readonly MetadataReader Reader; protected readonly TypeReferenceTypeProvider TypeProvider; protected readonly TypeDefinition Definition; protected ReaderClassBase(MetadataReader reader, TypeReferenceTypeProvider typeProvider, TypeDefinition definition) { Reader = reader; TypeProvider = typeProvider; Definition = definition; } private GenericContext? genericContext; protected GenericContext GenericContext { get { if (genericContext == null) genericContext = GenericContext.FromType(Reader, TypeProvider, Definition); return genericContext.Value; } } private string name; public string Name => name ?? (name = Reader.GetString(Definition.Name)); public string Comment => null; private IReadOnlyList<IMetadataAttribute> attributes; public IReadOnlyList<IMetadataAttribute> Attributes => attributes ?? (attributes = GetAttributes(Reader, TypeProvider, Definition.GetCustomAttributes(), GenericContext)); public MetadataVisibility Visibility { get { switch (Definition.Attributes & TypeAttributes.VisibilityMask) { case TypeAttributes.Public: case TypeAttributes.NestedPublic: return MetadataVisibility.Public; case TypeAttributes.NestedFamily: case TypeAttributes.NestedFamORAssem: return MetadataVisibility.Protected; default: return 0; } } } public IReadOnlyList<IMetadataGenericTypeParameter> GenericTypeParameters => GenericContext.TypeParameters; private MetadataTypeReference baseType; private bool isBaseTypeValid; public MetadataTypeReference BaseType { get { if (!isBaseTypeValid) { if (!Definition.BaseType.IsNil) baseType = GetTypeFromEntityHandle(Reader, TypeProvider, GenericContext, Definition.BaseType); isBaseTypeValid = true; } return baseType; } } private IReadOnlyList<MetadataTypeReference> interfaceImplementations; public IReadOnlyList<MetadataTypeReference> InterfaceImplementations { get { if (interfaceImplementations == null) { var handles = Definition.GetInterfaceImplementations(); var r = new List<MetadataTypeReference>(handles.Count); foreach (var handle in handles) { r.Add(GetTypeFromEntityHandle(Reader, TypeProvider, GenericContext, Reader.GetInterfaceImplementation(handle).Interface)); } interfaceImplementations = r; } return interfaceImplementations; } } private IReadOnlyList<IMetadataField> fields; public IReadOnlyList<IMetadataField> Fields { get { if (fields == null) { var r = new List<IMetadataField>(); foreach (var handle in Definition.GetFields()) { var definition = Reader.GetFieldDefinition(handle); switch (definition.Attributes & FieldAttributes.FieldAccessMask) { case FieldAttributes.Public: case FieldAttributes.Family: case FieldAttributes.FamORAssem: r.Add(new ReaderField(Reader, TypeProvider, definition, GenericContext)); break; } } fields = r; } return fields; } } private IReadOnlyList<IMetadataProperty> properties; public IReadOnlyList<IMetadataProperty> Properties { get { if (properties == null) { var r = new List<IMetadataProperty>(); foreach (var handle in Definition.GetProperties()) { var definition = Reader.GetPropertyDefinition(handle); var accessors = definition.GetAccessors(); var visibleGetter = accessors.Getter.IsNil ? null : GetVisibleMethod(accessors.Getter); var visibleSetter = accessors.Setter.IsNil ? null : GetVisibleMethod(accessors.Setter); if (visibleGetter == null && visibleSetter == null) continue; r.Add(new ReaderProperty(Reader,TypeProvider, definition, GenericContext, visibleGetter, visibleSetter)); } properties = r; } return properties; } } private IReadOnlyList<IMetadataEvent> events; public IReadOnlyList<IMetadataEvent> Events { get { if (events == null) { var r = new List<IMetadataEvent>(); foreach (var handle in Definition.GetEvents()) { var definition = Reader.GetEventDefinition(handle); var accessors = definition.GetAccessors(); var visibleAdder = accessors.Adder.IsNil ? null : GetVisibleMethod(accessors.Adder); var visibleRemover = accessors.Remover.IsNil ? null : GetVisibleMethod(accessors.Remover); var visibleRaiser = accessors.Raiser.IsNil ? null : GetVisibleMethod(accessors.Raiser); if (visibleAdder == null && visibleRemover == null && visibleRaiser == null) continue; r.Add(new ReaderEvent(Reader, TypeProvider, definition, GenericContext, visibleAdder, visibleRemover, visibleRaiser)); } events = r; } return events; } } private IMetadataMethod GetVisibleMethod(MethodDefinitionHandle handle) { var methods = Methods; var index = visibleMethodHandles.IndexOf(handle); return index == -1 ? null : methods[index]; } private List<MethodDefinitionHandle> visibleMethodHandles; private IReadOnlyList<IMetadataMethod> methods; public IReadOnlyList<IMetadataMethod> Methods { get { if (methods == null) { var r = new List<IMetadataMethod>(); visibleMethodHandles = new List<MethodDefinitionHandle>(); foreach (var handle in Definition.GetMethods()) { var definition = Reader.GetMethodDefinition(handle); switch (definition.Attributes & MethodAttributes.MemberAccessMask) { case MethodAttributes.Public: case MethodAttributes.Family: case MethodAttributes.FamORAssem: r.Add(new ReaderMethod(Reader, TypeProvider, definition, GenericContext)); visibleMethodHandles.Add(handle); break; } } methods = r; } return methods; } } private IReadOnlyList<IMetadataType> nestedTypes; public IReadOnlyList<IMetadataType> NestedTypes { get { if (nestedTypes == null) { var r = new List<IMetadataType>(); foreach (var handle in Definition.GetNestedTypes()) { var definition = Reader.GetTypeDefinition(handle); switch (definition.Attributes & TypeAttributes.VisibilityMask) { case TypeAttributes.NestedPublic: case TypeAttributes.NestedFamily: case TypeAttributes.NestedFamORAssem: r.Add(Create(Reader, TypeProvider, definition)); break; } } nestedTypes = r; } return nestedTypes; } } private static bool TryGetNonGenericTypeNamespaceAndName(MetadataReader reader, EntityHandle entity, out string @namespace, out string name) { switch (entity.Kind) { case HandleKind.TypeReference: var reference = reader.GetTypeReference((TypeReferenceHandle)entity); @namespace = reader.GetString(reference.Namespace); name = reader.GetString(reference.Name); return true; case HandleKind.TypeDefinition: var definition = reader.GetTypeDefinition((TypeDefinitionHandle)entity); @namespace = reader.GetString(definition.Namespace); name = reader.GetString(definition.Name); return true; default: @namespace = null; name = null; return false; } } public static ReaderClassBase Create(MetadataReader reader, TypeReferenceTypeProvider typeProvider, TypeDefinition typeDefinition) { if ((typeDefinition.Attributes & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Interface) { return new ReaderInterface(reader, typeProvider, typeDefinition); } if (!typeDefinition.BaseType.IsNil && TryGetNonGenericTypeNamespaceAndName(reader, typeDefinition.BaseType, out var baseTypeNamespace, out var baseTypeName)) { if (baseTypeName == "Enum" && baseTypeNamespace == "System") { return new ReaderEnum(reader, typeProvider, typeDefinition); } if (baseTypeName == "ValueType" && baseTypeNamespace == "System") { return new ReaderStruct(reader, typeProvider, typeDefinition); } if (baseTypeName == "MulticastDelegate" && baseTypeNamespace == "System") { return new ReaderDelegate(reader, typeProvider, typeDefinition); } } return new ReaderClass(reader, typeProvider, typeDefinition); } } } }
using System; using System.Collections.ObjectModel; using System.Linq; using System.Windows.Input; using EspaceClient.BackOffice.Domaine.Criterias; using EspaceClient.BackOffice.Domaine.Results; using EspaceClient.BackOffice.Silverlight.Business.Depots; using EspaceClient.BackOffice.Silverlight.Business.Interfaces; using EspaceClient.BackOffice.Silverlight.Business.Loader; using EspaceClient.BackOffice.Silverlight.ViewModels.Common.Modularity; using EspaceClient.BackOffice.Silverlight.ViewModels.Helper.GestionClient.ClientPM; using EspaceClient.BackOffice.Silverlight.ViewModels.Messages; using EspaceClient.BackOffice.Silverlight.ViewModels.ModelBuilders.GestionClient.ClientPM; using nRoute.Components; using nRoute.Components.Composition; using OGDC.Silverlight.Toolkit.DataGrid.Manager; using OGDC.Silverlight.Toolkit.Services.Services; namespace EspaceClient.BackOffice.Silverlight.ViewModels.GestionClient.ClientPM.Tabs { /// <summary> /// ViewModel de la vue <see cref="SearchView"/> /// </summary> public class SearchViewModel : TabBase { private readonly IResourceWrapper _resourceWrapper; private readonly IDepotSociete _societe; private readonly IMessenging _messengingService; private readonly IApplicationContext _applicationContext; private readonly ILoaderReferentiel _referentiel; private readonly IModelBuilderDetails _builderDetails; private ObservableCollection<ClientPMResult> _searchResult; private bool _searchOverflow; private ICommand _searchCommand; private ICommand _resetCommand; private ICommand _doubleClickCommand; private SearchClientPMCriteriasDto _criteres; private bool _isLoading; private DataGridColumnManager _manager; [ResolveConstructor] public SearchViewModel( IResourceWrapper resourceWrapper, IMessenging messengingService, IApplicationContext applicationContext, ILoaderReferentiel referentiel, IDepotSociete societe, IModelBuilderDetails builderDetails) : base(applicationContext, messengingService) { _resourceWrapper = resourceWrapper; _societe = societe; _messengingService = messengingService; _applicationContext = applicationContext; _referentiel = referentiel; _builderDetails = builderDetails; InitializeCommands(); InitializeUI(); } public DataGridColumnManager DataGridManager { get { return _manager; } set { if (_manager != value) { _manager = value; NotifyPropertyChanged(() => DataGridManager); } } } public ObservableCollection<ClientPMResult> SearchResult { get { return _searchResult; } set { if (_searchResult != value) { _searchResult = value; NotifyPropertyChanged(() => SearchResult); } } } public SearchClientPMCriteriasDto Criteres { get { return _criteres; } set { _criteres = value; NotifyPropertyChanged(() => Criteres); } } public bool SearchOverflow { get { return _searchOverflow; } set { if (_searchOverflow != value) { _searchOverflow = value; NotifyPropertyChanged(() => SearchOverflow); } } } public bool IsLoading { get { return _isLoading; } set { if (_isLoading != value) { _isLoading = value; NotifyPropertyChanged(() => IsLoading); } } } #region Commands /// <summary> /// Command de recherche des personnes. /// </summary> public ICommand SearchCommand { get { return _searchCommand; } } /// <summary> /// Command de recherche des personnes. /// </summary> public ICommand ResetCommand { get { return _resetCommand; } } public ICommand DoubleClickCommand { get { return _doubleClickCommand; } } #endregion private void InitializeCommands() { _searchCommand = new ActionCommand(OnSearch); _doubleClickCommand = new ActionCommand<ClientPMResult>(OnDoubleClickCommand); _resetCommand = new ActionCommand(OnReset); } private void OnReset() { InitializeUI(); } private void InitializeUI() { Criteres = new SearchClientPMCriteriasDto(); SearchResult = new ObservableCollection<ClientPMResult>(); SearchOverflow = false; IsLoading = false; DataGridManager = new DataGridColumnManager(); } private void OnSearch() { if (IsLoading) return; var limitValue = _referentiel.Referentiel.Parametres.Where(x => x.Code.Equals("SearchClientPMLimit")).Select(x => x.Valeur).FirstOrDefault(); var limit = Convert.ToInt32(limitValue); _societe.SearchClientPM(Criteres, r => { foreach (var P in r) SearchResult.Add(P); SearchOverflow = SearchResult.Count == limit; IsLoading = false; }, error => _messengingService.Publish(new ErrorMessage(error))); SearchResult.Clear(); IsLoading = true; } private void OnDoubleClickCommand(ClientPMResult selectedClientPM) { if (selectedClientPM != null) { ClientPMHelper.AddClientPMTab(selectedClientPM.ID, _messengingService, _societe, _builderDetails, _referentiel); } } public override void OnRefreshTab<EntityType>(long id, Action<EntityType> callback) { throw new NotImplementedException(); } protected override void OnRefreshTabCompleted(Action callback) { throw new NotImplementedException(); } } }
//----------------------------------------------------------------------- // <copyright file="DataPortal.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: https://cslanet.com // </copyright> // <summary>Implements the server-side DataPortal </summary> //----------------------------------------------------------------------- using System; using Csla.Configuration; #if NETFX_CORE using System.Reflection; using Csla.Reflection; #endif using System.Security.Principal; using System.Threading.Tasks; using Csla.Properties; using System.Collections.Generic; namespace Csla.Server { /// <summary> /// Implements the server-side DataPortal /// message router as discussed /// in Chapter 4. /// </summary> public class DataPortal : IDataPortalServer { /// <summary> /// Gets the data portal dashboard instance. /// </summary> public static Dashboard.IDashboard Dashboard { get; internal set; } static DataPortal() { Dashboard = Server.Dashboard.DashboardFactory.GetDashboard(); } #region Constructors /// <summary> /// Default constructor /// </summary> public DataPortal() : this("CslaAuthorizationProvider") { } /// <summary> /// This construcor accepts the App Setting name for the Csla Authorization Provider, /// therefore getting the provider type from configuration file /// </summary> /// <param name="cslaAuthorizationProviderAppSettingName"></param> protected DataPortal(string cslaAuthorizationProviderAppSettingName) : this(GetAuthProviderType(cslaAuthorizationProviderAppSettingName)) { } /// <summary> /// This constructor accepts the Authorization Provider Type as a parameter. /// </summary> /// <param name="authProviderType"></param> protected DataPortal(Type authProviderType) { if (null == authProviderType) throw new ArgumentNullException("authProviderType", Resources.CslaAuthenticationProviderNotSet); if (!typeof(IAuthorizeDataPortal).IsAssignableFrom(authProviderType)) throw new ArgumentException(Resources.AuthenticationProviderDoesNotImplementIAuthorizeDataPortal, "authProviderType"); //only construct the type if it was not constructed already if (null == _authorizer) { lock (_syncRoot) { if (null == _authorizer) _authorizer = (IAuthorizeDataPortal)Activator.CreateInstance(authProviderType); } } if (InterceptorType != null) { if (_interceptor == null) { lock (_syncRoot) { if (_interceptor == null) _interceptor = (IInterceptDataPortal)Activator.CreateInstance(InterceptorType); } } } } private static Type GetAuthProviderType(string cslaAuthorizationProviderAppSettingName) { if (cslaAuthorizationProviderAppSettingName == null) throw new ArgumentNullException("cslaAuthorizationProviderAppSettingName", Resources.AuthorizationProviderNameNotSpecified); if (null == _authorizer)//not yet instantiated { var authProvider = ConfigurationManager.AppSettings[cslaAuthorizationProviderAppSettingName]; return string.IsNullOrEmpty(authProvider) ? typeof(NullAuthorizer) : Type.GetType(authProvider, true); } else return _authorizer.GetType(); } #endregion #region Data Access #if !(ANDROID || IOS) && !NETFX_CORE && !MONO && !NETSTANDARD2_0 private IDataPortalServer GetServicedComponentPortal(TransactionalAttribute transactionalAttribute) { switch (transactionalAttribute.TransactionIsolationLevel) { case TransactionIsolationLevel.Serializable: return new ServicedDataPortalSerializable(); case TransactionIsolationLevel.RepeatableRead: return new ServicedDataPortalRepeatableRead(); case TransactionIsolationLevel.ReadCommitted: return new ServicedDataPortalReadCommitted(); case TransactionIsolationLevel.ReadUncommitted: return new ServicedDataPortalReadUncommitted(); default: throw new ArgumentOutOfRangeException("transactionalAttribute"); } } #endif /// <summary> /// Create a new business object. /// </summary> /// <param name="objectType">Type of business object to create.</param> /// <param name="criteria">Criteria object describing business object.</param> /// <param name="context"> /// <see cref="Server.DataPortalContext" /> object passed to the server. /// </param> /// <param name="isSync">True if the client-side proxy should synchronously invoke the server.</param> public async Task<DataPortalResult> Create( Type objectType, object criteria, DataPortalContext context, bool isSync) { try { SetContext(context); Initialize(new InterceptArgs { ObjectType = objectType, Parameter = criteria, Operation = DataPortalOperations.Create, IsSync = isSync }); AuthorizeRequest(new AuthorizeRequest(objectType, criteria, DataPortalOperations.Create)); DataPortalResult result; DataPortalMethodInfo method = DataPortalMethodCache.GetCreateMethod(objectType, criteria); IDataPortalServer portal; #if !(ANDROID || IOS) && !NETFX_CORE switch (method.TransactionalAttribute.TransactionType) { #if !MONO && !NETSTANDARD2_0 case TransactionalTypes.EnterpriseServices: portal = GetServicedComponentPortal(method.TransactionalAttribute); try { result = await portal.Create(objectType, criteria, context, isSync).ConfigureAwait(false); } finally { ((System.EnterpriseServices.ServicedComponent)portal).Dispose(); } break; #endif case TransactionalTypes.TransactionScope: portal = new TransactionalDataPortal(method.TransactionalAttribute); result = await portal.Create(objectType, criteria, context, isSync).ConfigureAwait(false); break; default: portal = new DataPortalBroker(); result = await portal.Create(objectType, criteria, context, isSync).ConfigureAwait(false); break; } #else portal = new DataPortalBroker(); result = await portal.Create(objectType, criteria, context, isSync).ConfigureAwait(false); #endif Complete(new InterceptArgs { ObjectType = objectType, Parameter = criteria, Result = result, Operation = DataPortalOperations.Create, IsSync = isSync }); return result; } catch (Csla.Server.DataPortalException ex) { Complete(new InterceptArgs { ObjectType = objectType, Parameter = criteria, Exception = ex, Operation = DataPortalOperations.Create, IsSync = isSync }); throw; } catch (AggregateException ex) { Exception error = null; if (ex.InnerExceptions.Count > 0) error = ex.InnerExceptions[0].InnerException; else error = ex; var fex = DataPortal.NewDataPortalException( "DataPortal.Create " + Resources.FailedOnServer, new DataPortalExceptionHandler().InspectException(objectType, criteria, "DataPortal.Create", error), null); Complete(new InterceptArgs { ObjectType = objectType, Parameter = criteria, Exception = fex, Operation = DataPortalOperations.Create, IsSync = isSync }); throw fex; } catch (Exception ex) { var fex = DataPortal.NewDataPortalException( "DataPortal.Create " + Resources.FailedOnServer, new DataPortalExceptionHandler().InspectException(objectType, criteria, "DataPortal.Create", ex), null); Complete(new InterceptArgs { ObjectType = objectType, Parameter = criteria, Exception = fex, Operation = DataPortalOperations.Create, IsSync = isSync }); throw fex; } finally { ClearContext(context); } } /// <summary> /// Get an existing business object. /// </summary> /// <param name="objectType">Type of business object to retrieve.</param> /// <param name="criteria">Criteria object describing business object.</param> /// <param name="context"> /// <see cref="Server.DataPortalContext" /> object passed to the server. /// </param> /// <param name="isSync">True if the client-side proxy should synchronously invoke the server.</param> public async Task<DataPortalResult> Fetch(Type objectType, object criteria, DataPortalContext context, bool isSync) { try { SetContext(context); Initialize(new InterceptArgs { ObjectType = objectType, Parameter = criteria, Operation = DataPortalOperations.Fetch, IsSync = isSync }); AuthorizeRequest(new AuthorizeRequest(objectType, criteria, DataPortalOperations.Fetch)); DataPortalResult result; DataPortalMethodInfo method = DataPortalMethodCache.GetFetchMethod(objectType, criteria); IDataPortalServer portal; #if !(ANDROID || IOS) && !NETFX_CORE switch (method.TransactionalAttribute.TransactionType) { #if !MONO && !NETSTANDARD2_0 case TransactionalTypes.EnterpriseServices: portal = GetServicedComponentPortal(method.TransactionalAttribute); try { result = await portal.Fetch(objectType, criteria, context, isSync).ConfigureAwait(false); } finally { ((System.EnterpriseServices.ServicedComponent)portal).Dispose(); } break; #endif case TransactionalTypes.TransactionScope: portal = new TransactionalDataPortal(method.TransactionalAttribute); result = await portal.Fetch(objectType, criteria, context, isSync).ConfigureAwait(false); break; default: portal = new DataPortalBroker(); result = await portal.Fetch(objectType, criteria, context, isSync).ConfigureAwait(false); break; } #else portal = new DataPortalBroker(); result = await portal.Fetch(objectType, criteria, context, isSync).ConfigureAwait(false); #endif Complete(new InterceptArgs { ObjectType = objectType, Parameter = criteria, Result = result, Operation = DataPortalOperations.Fetch, IsSync = isSync }); return result; } catch (Csla.Server.DataPortalException ex) { Complete(new InterceptArgs { ObjectType = objectType, Parameter = criteria, Exception = ex, Operation = DataPortalOperations.Fetch, IsSync = isSync }); throw; } catch (AggregateException ex) { Exception error = null; if (ex.InnerExceptions.Count > 0) error = ex.InnerExceptions[0].InnerException; else error = ex; var fex = DataPortal.NewDataPortalException( "DataPortal.Fetch " + Resources.FailedOnServer, new DataPortalExceptionHandler().InspectException(objectType, criteria, "DataPortal.Fetch", error), null); Complete(new InterceptArgs { ObjectType = objectType, Parameter = criteria, Exception = fex, Operation = DataPortalOperations.Fetch, IsSync = isSync }); throw fex; } catch (Exception ex) { var fex = DataPortal.NewDataPortalException( "DataPortal.Fetch " + Resources.FailedOnServer, new DataPortalExceptionHandler().InspectException(objectType, criteria, "DataPortal.Fetch", ex), null); Complete(new InterceptArgs { ObjectType = objectType, Parameter = criteria, Exception = fex, Operation = DataPortalOperations.Fetch, IsSync = isSync }); throw fex; } finally { ClearContext(context); } } /// <summary> /// Update a business object. /// </summary> /// <param name="obj">Business object to update.</param> /// <param name="context"> /// <see cref="Server.DataPortalContext" /> object passed to the server. /// </param> /// <param name="isSync">True if the client-side proxy should synchronously invoke the server.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public async Task<DataPortalResult> Update(object obj, DataPortalContext context, bool isSync) { Type objectType = null; DataPortalOperations operation = DataPortalOperations.Update; try { SetContext(context); objectType = obj.GetType(); if (obj is Core.ICommandObject) operation = DataPortalOperations.Execute; Initialize(new InterceptArgs { ObjectType = objectType, Parameter = obj, Operation = operation, IsSync = isSync }); AuthorizeRequest(new AuthorizeRequest(objectType, obj, operation)); DataPortalResult result; DataPortalMethodInfo method; var factoryInfo = ObjectFactoryAttribute.GetObjectFactoryAttribute(objectType); if (factoryInfo != null) { string methodName; var factoryType = FactoryDataPortal.FactoryLoader.GetFactoryType(factoryInfo.FactoryTypeName); var bbase = obj as Core.BusinessBase; if (bbase != null) { if (bbase.IsDeleted) methodName = factoryInfo.DeleteMethodName; else methodName = factoryInfo.UpdateMethodName; } else if (obj is Core.ICommandObject) methodName = factoryInfo.ExecuteMethodName; else methodName = factoryInfo.UpdateMethodName; method = Server.DataPortalMethodCache.GetMethodInfo(factoryType, methodName, new object[] { obj }); } else { string methodName; var bbase = obj as Core.BusinessBase; if (bbase != null) { if (bbase.IsDeleted) methodName = "DataPortal_DeleteSelf"; else if (bbase.IsNew) methodName = "DataPortal_Insert"; else methodName = "DataPortal_Update"; } else if (obj is Core.ICommandObject) methodName = "DataPortal_Execute"; else methodName = "DataPortal_Update"; method = DataPortalMethodCache.GetMethodInfo(obj.GetType(), methodName); } #if !(ANDROID || IOS) && !NETFX_CORE context.TransactionalType = method.TransactionalAttribute.TransactionType; #else context.TransactionalType = method.TransactionalType; #endif IDataPortalServer portal; #if !(ANDROID || IOS) && !NETFX_CORE switch (method.TransactionalAttribute.TransactionType) { #if !MONO && !NETSTANDARD2_0 case TransactionalTypes.EnterpriseServices: portal = GetServicedComponentPortal(method.TransactionalAttribute); try { result = await portal.Update(obj, context, isSync).ConfigureAwait(false); } finally { ((System.EnterpriseServices.ServicedComponent)portal).Dispose(); } break; #endif case TransactionalTypes.TransactionScope: portal = new TransactionalDataPortal(method.TransactionalAttribute); result = await portal.Update(obj, context, isSync).ConfigureAwait(false); break; default: portal = new DataPortalBroker(); result = await portal.Update(obj, context, isSync).ConfigureAwait(false); break; } #else portal = new DataPortalBroker(); result = await portal.Update(obj, context, isSync).ConfigureAwait(false); #endif Complete(new InterceptArgs { ObjectType = objectType, Parameter = obj, Result = result, Operation = operation, IsSync = isSync }); return result; } catch (Csla.Server.DataPortalException ex) { Complete(new InterceptArgs { ObjectType = objectType, Parameter = obj, Exception = ex, Operation = operation, IsSync = isSync }); throw; } catch (AggregateException ex) { Exception error = null; if (ex.InnerExceptions.Count > 0) error = ex.InnerExceptions[0].InnerException; else error = ex; var fex = DataPortal.NewDataPortalException( "DataPortal.Update " + Resources.FailedOnServer, new DataPortalExceptionHandler().InspectException(obj.GetType(), obj, null, "DataPortal.Update", error), obj); Complete(new InterceptArgs { ObjectType = objectType, Parameter = obj, Exception = fex, Operation = operation, IsSync = isSync }); throw fex; } catch (Exception ex) { var fex = DataPortal.NewDataPortalException( "DataPortal.Update " + Resources.FailedOnServer, new DataPortalExceptionHandler().InspectException(obj.GetType(), obj, null, "DataPortal.Update", ex), obj); Complete(new InterceptArgs { ObjectType = objectType, Parameter = obj, Exception = fex, Operation = operation, IsSync = isSync }); throw fex; } finally { ClearContext(context); } } /// <summary> /// Delete a business object. /// </summary> /// <param name="objectType">Type of business object to create.</param> /// <param name="criteria">Criteria object describing business object.</param> /// <param name="context"> /// <see cref="Server.DataPortalContext" /> object passed to the server. /// </param> /// <param name="isSync">True if the client-side proxy should synchronously invoke the server.</param> public async Task<DataPortalResult> Delete(Type objectType, object criteria, DataPortalContext context, bool isSync) { try { SetContext(context); Initialize(new InterceptArgs { ObjectType = objectType, Parameter = criteria, Operation = DataPortalOperations.Delete, IsSync = isSync }); AuthorizeRequest(new AuthorizeRequest(objectType, criteria, DataPortalOperations.Delete)); DataPortalResult result; DataPortalMethodInfo method; var factoryInfo = ObjectFactoryAttribute.GetObjectFactoryAttribute(objectType); if (factoryInfo != null) { var factoryType = FactoryDataPortal.FactoryLoader.GetFactoryType(factoryInfo.FactoryTypeName); string methodName = factoryInfo.DeleteMethodName; method = Server.DataPortalMethodCache.GetMethodInfo(factoryType, methodName, criteria); } else { method = DataPortalMethodCache.GetMethodInfo(objectType, "DataPortal_Delete", criteria); } IDataPortalServer portal; #if !(ANDROID || IOS) && !NETFX_CORE switch (method.TransactionalAttribute.TransactionType) { #if !MONO && !NETSTANDARD2_0 case TransactionalTypes.EnterpriseServices: portal = GetServicedComponentPortal(method.TransactionalAttribute); try { result = await portal.Delete(objectType, criteria, context, isSync).ConfigureAwait(false); } finally { ((System.EnterpriseServices.ServicedComponent)portal).Dispose(); } break; #endif case TransactionalTypes.TransactionScope: portal = new TransactionalDataPortal(method.TransactionalAttribute); result = await portal.Delete(objectType, criteria, context, isSync).ConfigureAwait(false); break; default: portal = new DataPortalBroker(); result = await portal.Delete(objectType, criteria, context, isSync).ConfigureAwait(false); break; } #else portal = new DataPortalBroker(); result = await portal.Delete(objectType, criteria, context, isSync).ConfigureAwait(false); #endif Complete(new InterceptArgs { ObjectType = objectType, Parameter = criteria, Result = result, Operation = DataPortalOperations.Delete, IsSync = isSync }); return result; } catch (Csla.Server.DataPortalException ex) { Complete(new InterceptArgs { ObjectType = objectType, Parameter = criteria, Exception = ex, Operation = DataPortalOperations.Delete, IsSync = isSync }); throw; } catch (AggregateException ex) { Exception error = null; if (ex.InnerExceptions.Count > 0) error = ex.InnerExceptions[0].InnerException; else error = ex; var fex = DataPortal.NewDataPortalException( "DataPortal.Delete " + Resources.FailedOnServer, new DataPortalExceptionHandler().InspectException(objectType, criteria, "DataPortal.Delete", error), null); Complete(new InterceptArgs { ObjectType = objectType, Parameter = criteria, Exception = fex, Operation = DataPortalOperations.Delete, IsSync = isSync }); throw fex; } catch (Exception ex) { var fex = DataPortal.NewDataPortalException( "DataPortal.Delete " + Resources.FailedOnServer, new DataPortalExceptionHandler().InspectException(objectType, criteria, "DataPortal.Delete", ex), null); Complete(new InterceptArgs { ObjectType = objectType, Parameter = criteria, Exception = fex, Operation = DataPortalOperations.Delete, IsSync = isSync }); throw fex; } finally { ClearContext(context); } } private IInterceptDataPortal _interceptor = null; private static Type _interceptorType = null; private static bool _InterceptorTypeSet = false; /// <summary> /// Gets or sets the type of interceptor invoked /// by the data portal for pre- and post-processing /// of each data portal invocation. /// </summary> public static Type InterceptorType { get { if (!_InterceptorTypeSet) { var typeName = ConfigurationManager.AppSettings["CslaDataPortalInterceptor"]; if (!string.IsNullOrWhiteSpace(typeName)) InterceptorType = Type.GetType(typeName); _InterceptorTypeSet = true; } return _interceptorType; } set { _interceptorType = value; _InterceptorTypeSet = true; } } internal void Complete(InterceptArgs e) { var startTime = (DateTimeOffset)ApplicationContext.ClientContext["__dataportaltimer"]; e.Runtime = DateTimeOffset.Now - startTime; Dashboard.CompleteCall(e); if (_interceptor != null) _interceptor.Complete(e); } internal void Initialize(InterceptArgs e) { ApplicationContext.ClientContext["__dataportaltimer"] = DateTimeOffset.Now; Dashboard.InitializeCall(e); if (_interceptor != null) _interceptor.Initialize(e); } #endregion #region Context ApplicationContext.LogicalExecutionLocations _oldLocation; private void SetContext(DataPortalContext context) { _oldLocation = Csla.ApplicationContext.LogicalExecutionLocation; ApplicationContext.SetLogicalExecutionLocation(ApplicationContext.LogicalExecutionLocations.Server); // if the dataportal is not remote then // do nothing if (!context.IsRemotePortal) return; // set the context value so everyone knows the // code is running on the server ApplicationContext.SetExecutionLocation(ApplicationContext.ExecutionLocations.Server); // set the app context to the value we got from the // client ApplicationContext.SetContext(context.ClientContext, context.GlobalContext); // set the thread's culture to match the client #if !PCL46 && !PCL259// rely on NuGet bait-and-switch for actual implementation #if NETCORE System.Globalization.CultureInfo.CurrentCulture = new System.Globalization.CultureInfo(context.ClientCulture); System.Globalization.CultureInfo.CurrentUICulture = new System.Globalization.CultureInfo(context.ClientUICulture); #elif NETFX_CORE var list = new System.Collections.ObjectModel.ReadOnlyCollection<string>(new List<string> { context.ClientUICulture }); Windows.ApplicationModel.Resources.Core.ResourceContext.GetForCurrentView().Languages = list; list = new System.Collections.ObjectModel.ReadOnlyCollection<string>(new List<string> { context.ClientCulture }); Windows.ApplicationModel.Resources.Core.ResourceContext.GetForCurrentView().Languages = list; #else System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(context.ClientCulture); System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(context.ClientUICulture); #endif #endif if (ApplicationContext.AuthenticationType == "Windows") { // When using integrated security, Principal must be null if (context.Principal != null) { Csla.Security.SecurityException ex = new Csla.Security.SecurityException(Resources.NoPrincipalAllowedException); //ex.Action = System.Security.Permissions.SecurityAction.Deny; throw ex; } #if !(ANDROID || IOS) && !NETFX_CORE // Set .NET to use integrated security AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal); #endif } else { // We expect the some Principal object if (context.Principal == null) { Csla.Security.SecurityException ex = new Csla.Security.SecurityException( Resources.BusinessPrincipalException + " Nothing"); //ex.Action = System.Security.Permissions.SecurityAction.Deny; throw ex; } ApplicationContext.User = context.Principal; } } private void ClearContext(DataPortalContext context) { ApplicationContext.SetLogicalExecutionLocation(_oldLocation); // if the dataportal is not remote then // do nothing if (!context.IsRemotePortal) return; ApplicationContext.Clear(); if (ApplicationContext.AuthenticationType != "Windows") ApplicationContext.User = null; } #endregion #region Authorize private static object _syncRoot = new object(); private static IAuthorizeDataPortal _authorizer = null; /// <summary> /// Gets or sets a reference to the current authorizer. /// </summary> protected static IAuthorizeDataPortal Authorizer { get { return _authorizer; } set { _authorizer = value; } } internal void Authorize(AuthorizeRequest clientRequest) { AuthorizeRequest(clientRequest); } private static void AuthorizeRequest(AuthorizeRequest clientRequest) { _authorizer.Authorize(clientRequest); } /// <summary> /// Default implementation of the authorizer that /// allows all data portal calls to pass. /// </summary> protected class NullAuthorizer : IAuthorizeDataPortal { /// <summary> /// Creates an instance of the type. /// </summary> /// <param name="clientRequest"> /// Client request information. /// </param> public void Authorize(AuthorizeRequest clientRequest) { /* default is to allow all requests */ } } #endregion internal static DataPortalException NewDataPortalException(string message, Exception innerException, object businessObject) { if (!ApplicationContext.DataPortalReturnObjectOnException) businessObject = null; throw new DataPortalException( message, innerException, new DataPortalResult(businessObject)); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: POGOProtos/Networking/Requests/Messages/AddFortModifierMessage.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 POGOProtos.Networking.Requests.Messages { /// <summary>Holder for reflection information generated from POGOProtos/Networking/Requests/Messages/AddFortModifierMessage.proto</summary> public static partial class AddFortModifierMessageReflection { #region Descriptor /// <summary>File descriptor for POGOProtos/Networking/Requests/Messages/AddFortModifierMessage.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static AddFortModifierMessageReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CkRQT0dPUHJvdG9zL05ldHdvcmtpbmcvUmVxdWVzdHMvTWVzc2FnZXMvQWRk", "Rm9ydE1vZGlmaWVyTWVzc2FnZS5wcm90bxInUE9HT1Byb3Rvcy5OZXR3b3Jr", "aW5nLlJlcXVlc3RzLk1lc3NhZ2VzGiZQT0dPUHJvdG9zL0ludmVudG9yeS9J", "dGVtL0l0ZW1JZC5wcm90byKWAQoWQWRkRm9ydE1vZGlmaWVyTWVzc2FnZRI4", "Cg1tb2RpZmllcl90eXBlGAEgASgOMiEuUE9HT1Byb3Rvcy5JbnZlbnRvcnku", "SXRlbS5JdGVtSWQSDwoHZm9ydF9pZBgCIAEoCRIXCg9wbGF5ZXJfbGF0aXR1", "ZGUYAyABKAESGAoQcGxheWVyX2xvbmdpdHVkZRgEIAEoAWIGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::POGOProtos.Inventory.Item.ItemIdReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Networking.Requests.Messages.AddFortModifierMessage), global::POGOProtos.Networking.Requests.Messages.AddFortModifierMessage.Parser, new[]{ "ModifierType", "FortId", "PlayerLatitude", "PlayerLongitude" }, null, null, null) })); } #endregion } #region Messages public sealed partial class AddFortModifierMessage : pb::IMessage<AddFortModifierMessage> { private static readonly pb::MessageParser<AddFortModifierMessage> _parser = new pb::MessageParser<AddFortModifierMessage>(() => new AddFortModifierMessage()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<AddFortModifierMessage> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::POGOProtos.Networking.Requests.Messages.AddFortModifierMessageReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public AddFortModifierMessage() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public AddFortModifierMessage(AddFortModifierMessage other) : this() { modifierType_ = other.modifierType_; fortId_ = other.fortId_; playerLatitude_ = other.playerLatitude_; playerLongitude_ = other.playerLongitude_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public AddFortModifierMessage Clone() { return new AddFortModifierMessage(this); } /// <summary>Field number for the "modifier_type" field.</summary> public const int ModifierTypeFieldNumber = 1; private global::POGOProtos.Inventory.Item.ItemId modifierType_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::POGOProtos.Inventory.Item.ItemId ModifierType { get { return modifierType_; } set { modifierType_ = value; } } /// <summary>Field number for the "fort_id" field.</summary> public const int FortIdFieldNumber = 2; private string fortId_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string FortId { get { return fortId_; } set { fortId_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "player_latitude" field.</summary> public const int PlayerLatitudeFieldNumber = 3; private double playerLatitude_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public double PlayerLatitude { get { return playerLatitude_; } set { playerLatitude_ = value; } } /// <summary>Field number for the "player_longitude" field.</summary> public const int PlayerLongitudeFieldNumber = 4; private double playerLongitude_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public double PlayerLongitude { get { return playerLongitude_; } set { playerLongitude_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as AddFortModifierMessage); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(AddFortModifierMessage other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (ModifierType != other.ModifierType) return false; if (FortId != other.FortId) return false; if (PlayerLatitude != other.PlayerLatitude) return false; if (PlayerLongitude != other.PlayerLongitude) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (ModifierType != 0) hash ^= ModifierType.GetHashCode(); if (FortId.Length != 0) hash ^= FortId.GetHashCode(); if (PlayerLatitude != 0D) hash ^= PlayerLatitude.GetHashCode(); if (PlayerLongitude != 0D) hash ^= PlayerLongitude.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 (ModifierType != 0) { output.WriteRawTag(8); output.WriteEnum((int) ModifierType); } if (FortId.Length != 0) { output.WriteRawTag(18); output.WriteString(FortId); } if (PlayerLatitude != 0D) { output.WriteRawTag(25); output.WriteDouble(PlayerLatitude); } if (PlayerLongitude != 0D) { output.WriteRawTag(33); output.WriteDouble(PlayerLongitude); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (ModifierType != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) ModifierType); } if (FortId.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(FortId); } if (PlayerLatitude != 0D) { size += 1 + 8; } if (PlayerLongitude != 0D) { size += 1 + 8; } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(AddFortModifierMessage other) { if (other == null) { return; } if (other.ModifierType != 0) { ModifierType = other.ModifierType; } if (other.FortId.Length != 0) { FortId = other.FortId; } if (other.PlayerLatitude != 0D) { PlayerLatitude = other.PlayerLatitude; } if (other.PlayerLongitude != 0D) { PlayerLongitude = other.PlayerLongitude; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { modifierType_ = (global::POGOProtos.Inventory.Item.ItemId) input.ReadEnum(); break; } case 18: { FortId = input.ReadString(); break; } case 25: { PlayerLatitude = input.ReadDouble(); break; } case 33: { PlayerLongitude = input.ReadDouble(); break; } } } } } #endregion } #endregion Designer generated code
using System; using UnityEngine; using UnityStandardAssets.CrossPlatformInput; namespace UnityStandardAssets.Characters.FirstPerson { [RequireComponent(typeof (Rigidbody))] [RequireComponent(typeof (CapsuleCollider))] public class RigidbodyFirstPersonController : MonoBehaviour { [Serializable] public class MovementSettings { public float ForwardSpeed = 8.0f; // Speed when walking forward public float BackwardSpeed = 4.0f; // Speed when walking backwards public float StrafeSpeed = 4.0f; // Speed when walking sideways public float RunMultiplier = 2.0f; // Speed when sprinting public KeyCode RunKey = KeyCode.LeftShift; public float JumpForce = 30f; public AnimationCurve SlopeCurveModifier = new AnimationCurve(new Keyframe(-90.0f, 1.0f), new Keyframe(0.0f, 1.0f), new Keyframe(90.0f, 0.0f)); [HideInInspector] public float CurrentTargetSpeed = 8f; #if !MOBILE_INPUT private bool m_Running; #endif public void UpdateDesiredTargetSpeed(Vector2 input) { if (input == Vector2.zero) return; if (input.x > 0 || input.x < 0) { //strafe CurrentTargetSpeed = StrafeSpeed; } if (input.y < 0) { //backwards CurrentTargetSpeed = BackwardSpeed; } if (input.y > 0) { //forwards //handled last as if strafing and moving forward at the same time forwards speed should take precedence CurrentTargetSpeed = ForwardSpeed; } #if !MOBILE_INPUT if (Input.GetKey(RunKey)) { CurrentTargetSpeed *= RunMultiplier; m_Running = true; } else { m_Running = false; } #endif } #if !MOBILE_INPUT public bool Running { get { return m_Running; } } #endif } [Serializable] public class AdvancedSettings { public float groundCheckDistance = 0.01f; // distance for checking if the controller is grounded ( 0.01f seems to work best for this ) public float stickToGroundHelperDistance = 0.5f; // stops the character public float slowDownRate = 20f; // rate at which the controller comes to a stop when there is no input public bool airControl; // can the user control the direction that is being moved in the air } public Camera cam; public MovementSettings movementSettings = new MovementSettings(); public MouseLook mouseLook = new MouseLook(); public AdvancedSettings advancedSettings = new AdvancedSettings(); private Rigidbody m_RigidBody; private CapsuleCollider m_Capsule; private float m_YRotation; private Vector3 m_GroundContactNormal; private bool m_Jump, m_PreviouslyGrounded, m_Jumping, m_IsGrounded; public Vector3 Velocity { get { return m_RigidBody.velocity; } } public bool Grounded { get { return m_IsGrounded; } } public bool Jumping { get { return m_Jumping; } } public bool Running { get { #if !MOBILE_INPUT return movementSettings.Running; #else return false; #endif } } private void Start() { m_RigidBody = GetComponent<Rigidbody>(); m_Capsule = GetComponent<CapsuleCollider>(); mouseLook.Init (transform, cam.transform); } private void Update() { RotateView(); if (CrossPlatformInputManager.GetButtonDown("Jump") && !m_Jump) { //jump disabled m_Jump = false;//true; } } private void FixedUpdate() { GroundCheck(); Vector2 input = GetInput(); if ((Mathf.Abs(input.x) > float.Epsilon || Mathf.Abs(input.y) > float.Epsilon) && (advancedSettings.airControl || m_IsGrounded)) { // always move along the camera forward as it is the direction that it being aimed at Vector3 desiredMove = cam.transform.forward*input.y + cam.transform.right*input.x; desiredMove = Vector3.ProjectOnPlane(desiredMove, m_GroundContactNormal).normalized; desiredMove.x = desiredMove.x*movementSettings.CurrentTargetSpeed; desiredMove.z = desiredMove.z*movementSettings.CurrentTargetSpeed; desiredMove.y = desiredMove.y*movementSettings.CurrentTargetSpeed; if (m_RigidBody.velocity.sqrMagnitude < (movementSettings.CurrentTargetSpeed*movementSettings.CurrentTargetSpeed)) { m_RigidBody.AddForce(desiredMove*SlopeMultiplier(), ForceMode.Impulse); } } if (m_IsGrounded) { m_RigidBody.drag = 5f; if (m_Jump) { m_RigidBody.drag = 0f; m_RigidBody.velocity = new Vector3(m_RigidBody.velocity.x, 0f, m_RigidBody.velocity.z); m_RigidBody.AddForce(new Vector3(0f, movementSettings.JumpForce, 0f), ForceMode.Impulse); m_Jumping = true; } if (!m_Jumping && Mathf.Abs(input.x) < float.Epsilon && Mathf.Abs(input.y) < float.Epsilon && m_RigidBody.velocity.magnitude < 1f) { m_RigidBody.Sleep(); } } else { m_RigidBody.drag = 0f; if (m_PreviouslyGrounded && !m_Jumping) { StickToGroundHelper(); } } m_Jump = false; } private float SlopeMultiplier() { float angle = Vector3.Angle(m_GroundContactNormal, Vector3.up); return movementSettings.SlopeCurveModifier.Evaluate(angle); } private void StickToGroundHelper() { RaycastHit hitInfo; if (Physics.SphereCast(transform.position, m_Capsule.radius, Vector3.down, out hitInfo, ((m_Capsule.height/2f) - m_Capsule.radius) + advancedSettings.stickToGroundHelperDistance)) { if (Mathf.Abs(Vector3.Angle(hitInfo.normal, Vector3.up)) < 85f) { m_RigidBody.velocity = Vector3.ProjectOnPlane(m_RigidBody.velocity, hitInfo.normal); } } } private Vector2 GetInput() { Vector2 input = new Vector2 { x = CrossPlatformInputManager.GetAxis("Horizontal"), y = CrossPlatformInputManager.GetAxis("Vertical") }; movementSettings.UpdateDesiredTargetSpeed(input); return input; } private void RotateView() { //avoids the mouse looking if the game is effectively paused if (Mathf.Abs(Time.timeScale) < float.Epsilon) return; // get the rotation before it's changed float oldYRotation = transform.eulerAngles.y; mouseLook.LookRotation (transform, cam.transform); if (m_IsGrounded || advancedSettings.airControl) { // Rotate the rigidbody velocity to match the new direction that the character is looking Quaternion velRotation = Quaternion.AngleAxis(transform.eulerAngles.y - oldYRotation, Vector3.up); m_RigidBody.velocity = velRotation*m_RigidBody.velocity; } } /// sphere cast down just beyond the bottom of the capsule to see if the capsule is colliding round the bottom private void GroundCheck() { m_PreviouslyGrounded = m_IsGrounded; RaycastHit hitInfo; if (Physics.SphereCast(transform.position, m_Capsule.radius, Vector3.down, out hitInfo, ((m_Capsule.height/2f) - m_Capsule.radius) + advancedSettings.groundCheckDistance)) { m_IsGrounded = true; m_GroundContactNormal = hitInfo.normal; } else { m_IsGrounded = false; m_GroundContactNormal = Vector3.up; } if (!m_PreviouslyGrounded && m_IsGrounded && m_Jumping) { m_Jumping = false; } } } }
using Lucene.Net.Index; using Lucene.Net.Support; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace Lucene.Net.Codecs.RAMOnly { using IBits = Lucene.Net.Util.IBits; using BytesRef = Lucene.Net.Util.BytesRef; /* * 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 DocsAndPositionsEnum = Lucene.Net.Index.DocsAndPositionsEnum; using DocsEnum = Lucene.Net.Index.DocsEnum; using FieldInfo = Lucene.Net.Index.FieldInfo; using IndexFileNames = Lucene.Net.Index.IndexFileNames; using IndexInput = Lucene.Net.Store.IndexInput; using IndexOptions = Lucene.Net.Index.IndexOptions; using IndexOutput = Lucene.Net.Store.IndexOutput; using IOUtils = Lucene.Net.Util.IOUtils; using RamUsageEstimator = Lucene.Net.Util.RamUsageEstimator; using SegmentReadState = Lucene.Net.Index.SegmentReadState; using SegmentWriteState = Lucene.Net.Index.SegmentWriteState; using Terms = Lucene.Net.Index.Terms; using TermsEnum = Lucene.Net.Index.TermsEnum; /// <summary> /// Stores all postings data in RAM, but writes a small /// token (header + single int) to identify which "slot" the /// index is using in RAM HashMap. /// /// NOTE: this codec sorts terms by reverse-unicode-order! /// </summary> [PostingsFormatName("RAMOnly")] // LUCENENET specific - using PostingsFormatName attribute to ensure the default name passed from subclasses is the same as this class name public sealed class RAMOnlyPostingsFormat : PostingsFormat { // For fun, test that we can override how terms are // sorted, and basic things still work -- this comparer // sorts in reversed unicode code point order: private static readonly IComparer<BytesRef> reverseUnicodeComparer = new ComparerAnonymousInnerClassHelper(); #pragma warning disable 659 // LUCENENET: Overrides Equals but not GetHashCode private class ComparerAnonymousInnerClassHelper : IComparer<BytesRef> #pragma warning restore 659 { public ComparerAnonymousInnerClassHelper() { } public virtual int Compare(BytesRef t1, BytesRef t2) { var b1 = t1.Bytes; var b2 = t2.Bytes; int b1Stop; int b1Upto = t1.Offset; int b2Upto = t2.Offset; if (t1.Length < t2.Length) { b1Stop = t1.Offset + t1.Length; } else { b1Stop = t1.Offset + t2.Length; } while (b1Upto < b1Stop) { int bb1 = b1[b1Upto++] & 0xff; int bb2 = b2[b2Upto++] & 0xff; if (bb1 != bb2) { //System.out.println("cmp 1=" + t1 + " 2=" + t2 + " return " + (bb2-bb1)); return bb2 - bb1; } } // One is prefix of another, or they are equal return t2.Length - t1.Length; } public override bool Equals(object other) { return this == other; } } public RAMOnlyPostingsFormat() : base() { } // Postings state: internal class RAMPostings : FieldsProducer { // LUCENENET specific: Use StringComparer.Ordinal to get the same ordering as Java internal readonly IDictionary<string, RAMField> FieldToTerms = new SortedDictionary<string, RAMField>(StringComparer.Ordinal); public override Terms GetTerms(string field) { RAMField result; FieldToTerms.TryGetValue(field, out result); return result; } public override int Count { get { return FieldToTerms.Count; } } public override IEnumerator<string> GetEnumerator() { return FieldToTerms.Keys.GetEnumerator(); } protected override void Dispose(bool disposing) { } public override long RamBytesUsed() { long sizeInBytes = 0; foreach (RAMField field in FieldToTerms.Values) { sizeInBytes += field.RamBytesUsed(); } return sizeInBytes; } public override void CheckIntegrity() { } } internal class RAMField : Terms { internal readonly string Field; // LUCENENET specific: Use StringComparer.Ordinal to get the same ordering as Java internal readonly SortedDictionary<string, RAMTerm> TermToDocs = new SortedDictionary<string, RAMTerm>(StringComparer.Ordinal); internal long SumTotalTermFreq_Renamed; internal long SumDocFreq_Renamed; internal int DocCount_Renamed; internal readonly FieldInfo Info; internal RAMField(string field, FieldInfo info) { this.Field = field; this.Info = info; } /// <summary> /// Returns approximate RAM bytes used </summary> public virtual long RamBytesUsed() { long sizeInBytes = 0; foreach (RAMTerm term in TermToDocs.Values) { sizeInBytes += term.RamBytesUsed(); } return sizeInBytes; } public override long Count { get { return TermToDocs.Count; } } public override long SumTotalTermFreq { get { return SumTotalTermFreq_Renamed; } } public override long SumDocFreq { get { return SumDocFreq_Renamed; } } public override int DocCount { get { return DocCount_Renamed; } } public override TermsEnum GetIterator(TermsEnum reuse) { return new RAMTermsEnum(this); } public override IComparer<BytesRef> Comparer { get { return reverseUnicodeComparer; } } public override bool HasFreqs { get { return Info.IndexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS) >= 0; } } public override bool HasOffsets { get { return Info.IndexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0; } } public override bool HasPositions { get { return Info.IndexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0; } } public override bool HasPayloads { get { return Info.HasPayloads; } } } internal class RAMTerm { internal readonly string Term; internal long TotalTermFreq; internal readonly IList<RAMDoc> Docs = new List<RAMDoc>(); public RAMTerm(string term) { this.Term = term; } /// <summary> /// Returns approximate RAM bytes used </summary> public virtual long RamBytesUsed() { long sizeInBytes = 0; foreach (RAMDoc rDoc in Docs) { sizeInBytes += rDoc.RamBytesUsed(); } return sizeInBytes; } } internal class RAMDoc { internal readonly int DocID; internal readonly int[] Positions; internal byte[][] Payloads; public RAMDoc(int docID, int freq) { this.DocID = docID; Positions = new int[freq]; } /// <summary> /// Returns approximate RAM bytes used </summary> public virtual long RamBytesUsed() { long sizeInBytes = 0; sizeInBytes += (Positions != null) ? RamUsageEstimator.SizeOf(Positions) : 0; if (Payloads != null) { foreach (var payload in Payloads) { sizeInBytes += (payload != null) ? RamUsageEstimator.SizeOf(payload) : 0; } } return sizeInBytes; } } // Classes for writing to the postings state private class RAMFieldsConsumer : FieldsConsumer { internal readonly RAMPostings Postings; internal readonly RAMTermsConsumer TermsConsumer = new RAMTermsConsumer(); public RAMFieldsConsumer(RAMPostings postings) { this.Postings = postings; } public override TermsConsumer AddField(FieldInfo field) { if (field.IndexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0) { throw new System.NotSupportedException("this codec cannot index offsets"); } RAMField ramField = new RAMField(field.Name, field); Postings.FieldToTerms[field.Name] = ramField; TermsConsumer.Reset(ramField); return TermsConsumer; } protected override void Dispose(bool disposing) { // TODO: finalize stuff } } private class RAMTermsConsumer : TermsConsumer { internal RAMField Field; internal readonly RAMPostingsWriterImpl PostingsWriter = new RAMPostingsWriterImpl(); internal RAMTerm Current; internal virtual void Reset(RAMField field) { this.Field = field; } public override PostingsConsumer StartTerm(BytesRef text) { string term = text.Utf8ToString(); Current = new RAMTerm(term); PostingsWriter.Reset(Current); return PostingsWriter; } public override IComparer<BytesRef> Comparer { get { return BytesRef.UTF8SortedAsUnicodeComparer; } } public override void FinishTerm(BytesRef text, TermStats stats) { Debug.Assert(stats.DocFreq > 0); Debug.Assert(stats.DocFreq == Current.Docs.Count); Current.TotalTermFreq = stats.TotalTermFreq; Field.TermToDocs[Current.Term] = Current; } public override void Finish(long sumTotalTermFreq, long sumDocFreq, int docCount) { Field.SumTotalTermFreq_Renamed = sumTotalTermFreq; Field.SumDocFreq_Renamed = sumDocFreq; Field.DocCount_Renamed = docCount; } } internal class RAMPostingsWriterImpl : PostingsConsumer { internal RAMTerm Term; internal RAMDoc Current; internal int PosUpto = 0; public virtual void Reset(RAMTerm term) { this.Term = term; } public override void StartDoc(int docID, int freq) { Current = new RAMDoc(docID, freq); Term.Docs.Add(Current); PosUpto = 0; } public override void AddPosition(int position, BytesRef payload, int startOffset, int endOffset) { Debug.Assert(startOffset == -1); Debug.Assert(endOffset == -1); Current.Positions[PosUpto] = position; if (payload != null && payload.Length > 0) { if (Current.Payloads == null) { Current.Payloads = new byte[Current.Positions.Length][]; } var bytes = Current.Payloads[PosUpto] = new byte[payload.Length]; Array.Copy(payload.Bytes, payload.Offset, bytes, 0, payload.Length); } PosUpto++; } public override void FinishDoc() { Debug.Assert(PosUpto == Current.Positions.Length); } } internal class RAMTermsEnum : TermsEnum { internal IEnumerator<string> It; internal string Current; internal readonly RAMField RamField; public RAMTermsEnum(RAMField field) { this.RamField = field; } public override IComparer<BytesRef> Comparer { get { return BytesRef.UTF8SortedAsUnicodeComparer; } } public override BytesRef Next() { if (It == null) { if (Current == null) { It = RamField.TermToDocs.Keys.GetEnumerator(); } else { //It = RamField.TermToDocs.tailMap(Current).Keys.GetEnumerator(); It = RamField.TermToDocs.Where(kvpair => String.Compare(kvpair.Key, Current) >= 0).ToDictionary(kvpair => kvpair.Key, kvpair => kvpair.Value).Keys.GetEnumerator(); } } if (It.MoveNext()) { Current = It.Current; return new BytesRef(Current); } else { return null; } } public override SeekStatus SeekCeil(BytesRef term) { Current = term.Utf8ToString(); It = null; if (RamField.TermToDocs.ContainsKey(Current)) { return SeekStatus.FOUND; } else { if (Current.CompareToOrdinal(RamField.TermToDocs.Last().Key) > 0) { return SeekStatus.END; } else { return SeekStatus.NOT_FOUND; } } } public override void SeekExact(long ord) { throw new System.NotSupportedException(); } public override long Ord { get { throw new System.NotSupportedException(); } } public override BytesRef Term { get { // TODO: reuse BytesRef return new BytesRef(Current); } } public override int DocFreq { get { return RamField.TermToDocs[Current].Docs.Count; } } public override long TotalTermFreq { get { return RamField.TermToDocs[Current].TotalTermFreq; } } public override DocsEnum Docs(IBits liveDocs, DocsEnum reuse, DocsFlags flags) { return new RAMDocsEnum(RamField.TermToDocs[Current], liveDocs); } public override DocsAndPositionsEnum DocsAndPositions(IBits liveDocs, DocsAndPositionsEnum reuse, DocsAndPositionsFlags flags) { return new RAMDocsAndPositionsEnum(RamField.TermToDocs[Current], liveDocs); } } private class RAMDocsEnum : DocsEnum { private readonly RAMTerm RamTerm; private readonly IBits LiveDocs; private RAMDoc Current; private int Upto = -1; #pragma warning disable 414 private int PosUpto = 0; // LUCENENET NOTE: Not used #pragma warning restore 414 public RAMDocsEnum(RAMTerm ramTerm, IBits liveDocs) { this.RamTerm = ramTerm; this.LiveDocs = liveDocs; } public override int Advance(int targetDocID) { return SlowAdvance(targetDocID); } // TODO: override bulk read, for better perf public override int NextDoc() { while (true) { Upto++; if (Upto < RamTerm.Docs.Count) { Current = RamTerm.Docs[Upto]; if (LiveDocs == null || LiveDocs.Get(Current.DocID)) { PosUpto = 0; return Current.DocID; } } else { return NO_MORE_DOCS; } } } public override int Freq { get { return Current.Positions.Length; } } public override int DocID { get { return Current.DocID; } } public override long GetCost() { return RamTerm.Docs.Count; } } private class RAMDocsAndPositionsEnum : DocsAndPositionsEnum { private readonly RAMTerm RamTerm; private readonly IBits LiveDocs; private RAMDoc Current; private int Upto = -1; private int PosUpto = 0; public RAMDocsAndPositionsEnum(RAMTerm ramTerm, IBits liveDocs) { this.RamTerm = ramTerm; this.LiveDocs = liveDocs; } public override int Advance(int targetDocID) { return SlowAdvance(targetDocID); } // TODO: override bulk read, for better perf public override int NextDoc() { while (true) { Upto++; if (Upto < RamTerm.Docs.Count) { Current = RamTerm.Docs[Upto]; if (LiveDocs == null || LiveDocs.Get(Current.DocID)) { PosUpto = 0; return Current.DocID; } } else { return NO_MORE_DOCS; } } } public override int Freq { get { return Current.Positions.Length; } } public override int DocID { get { return Current.DocID; } } public override int NextPosition() { return Current.Positions[PosUpto++]; } public override int StartOffset { get { return -1; } } public override int EndOffset { get { return -1; } } public override BytesRef GetPayload() { if (Current.Payloads != null && Current.Payloads[PosUpto - 1] != null) { return new BytesRef(Current.Payloads[PosUpto - 1]); } else { return null; } } public override long GetCost() { return RamTerm.Docs.Count; } } // Holds all indexes created, keyed by the ID assigned in fieldsConsumer private readonly IDictionary<int?, RAMPostings> State = new Dictionary<int?, RAMPostings>(); private readonly AtomicInt64 NextID = new AtomicInt64(); private readonly string RAM_ONLY_NAME = "RAMOnly"; private const int VERSION_START = 0; private const int VERSION_LATEST = VERSION_START; private const string ID_EXTENSION = "id"; public override FieldsConsumer FieldsConsumer(SegmentWriteState writeState) { int id = (int)NextID.GetAndIncrement(); // TODO -- ok to do this up front instead of // on close....? should be ok? // Write our ID: string idFileName = IndexFileNames.SegmentFileName(writeState.SegmentInfo.Name, writeState.SegmentSuffix, ID_EXTENSION); IndexOutput @out = writeState.Directory.CreateOutput(idFileName, writeState.Context); bool success = false; try { CodecUtil.WriteHeader(@out, RAM_ONLY_NAME, VERSION_LATEST); @out.WriteVInt32(id); success = true; } finally { if (!success) { IOUtils.DisposeWhileHandlingException(@out); } else { IOUtils.Dispose(@out); } } RAMPostings postings = new RAMPostings(); RAMFieldsConsumer consumer = new RAMFieldsConsumer(postings); lock (State) { State[id] = postings; } return consumer; } public override FieldsProducer FieldsProducer(SegmentReadState readState) { // Load our ID: string idFileName = IndexFileNames.SegmentFileName(readState.SegmentInfo.Name, readState.SegmentSuffix, ID_EXTENSION); IndexInput @in = readState.Directory.OpenInput(idFileName, readState.Context); bool success = false; int id; try { CodecUtil.CheckHeader(@in, RAM_ONLY_NAME, VERSION_START, VERSION_LATEST); id = @in.ReadVInt32(); success = true; } finally { if (!success) { IOUtils.DisposeWhileHandlingException(@in); } else { IOUtils.Dispose(@in); } } lock (State) { return State[id]; } } } }
/* * Copyright (c) .NET Foundation and Contributors * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. * * https://github.com/piranhacms/piranha.core * */ using System; using Piranha.Extend.Fields; using Piranha.Extend.Serializers; using Piranha.Runtime; using Xunit; namespace Piranha.Tests { public class Serializers { public enum ColorType { Red, Green, Blue } [Fact] public SerializerManager Register() { var manager = new SerializerManager(); manager.Register<TextField>(new StringFieldSerializer<TextField>()); return manager; } [Fact] public void GetSerializer() { var manager = Register(); var serializer = manager[typeof(TextField)]; Assert.NotNull(serializer); } [Fact] public void UnRegister() { var manager = Register(); manager.UnRegister<TextField>(); Assert.Null(manager[typeof(TextField)]); } [Fact] public void SerializeCheckBoxField() { var serializer = new CheckBoxFieldSerializer<CheckBoxField>(); var value = true; var str = serializer.Serialize(new CheckBoxField { Value = value }); Assert.Equal(value.ToString(), str); } [Fact] public void DeserializeCheckBoxField() { var serializer = new CheckBoxFieldSerializer<CheckBoxField>(); var value = true; var field = (CheckBoxField)serializer.Deserialize(value.ToString()); Assert.Equal(value, field.Value); } [Fact] public void WrongInputCheckBoxField() { var serializer = new CheckBoxFieldSerializer<CheckBoxField>(); Assert.Throws<ArgumentException>(() => serializer.Serialize(new DateField { Value = DateTime.Now })); } [Fact] public void SerializeDateField() { var serializer = new DateFieldSerializer(); var str = serializer.Serialize(new DateField { Value = new DateTime(2001, 1, 5, 16, 0, 0) }); Assert.Equal("2001-01-05", str); } [Fact] public void SerializeEmptyDateField() { var serializer = new DateFieldSerializer(); var str = serializer.Serialize(new DateField()); Assert.Null(str); } [Fact] public void DeserializeDateField() { var serializer = new DateFieldSerializer(); var date = new DateTime(2001, 1, 5, 16, 0, 0); var str = "2001-01-05 16:00:00"; var field = (DateField)serializer.Deserialize(str); Assert.NotNull(field); Assert.Equal(date, field.Value.Value); } [Fact] public void DeserializeEmptyDateField() { var serializer = new DateFieldSerializer(); var field = (DateField)serializer.Deserialize(null); Assert.False(field.Value.HasValue); } [Fact] public void WrongInputToDateField() { var serializer = new DateFieldSerializer(); Assert.Throws<ArgumentException>(() => serializer.Serialize(new StringField { Value = "Exception" })); } [Fact] public void SerializeImageField() { var serializer = new ImageFieldSerializer(); var id = Guid.NewGuid(); var str = serializer.Serialize(new ImageField { Id = id }); Assert.Equal(id.ToString(), str); } [Fact] public void DeserializeImageField() { var serializer = new ImageFieldSerializer(); var id = Guid.NewGuid(); var field = (ImageField)serializer.Deserialize(id.ToString()); Assert.Equal(id, field.Id.Value); } [Fact] public void DeserializeEmptyImageField() { var serializer = new ImageFieldSerializer(); var field = (ImageField)serializer.Deserialize(null); Assert.False(field.HasValue); } [Fact] public void WrongInputToImageField() { var serializer = new ImageFieldSerializer(); Assert.Throws<ArgumentException>(() => serializer.Serialize(new StringField { Value = "Exception" })); } [Fact] public void SerializeDocumentField() { var serializer = new DocumentFieldSerializer(); var id = Guid.NewGuid(); var str = serializer.Serialize(new DocumentField { Id = id }); Assert.Equal(id.ToString(), str); } [Fact] public void DeserializeDocumentField() { var serializer = new DocumentFieldSerializer(); var id = Guid.NewGuid(); var field = (DocumentField)serializer.Deserialize(id.ToString()); Assert.Equal(id, field.Id.Value); } [Fact] public void DeserializeEmptyDocumentField() { var serializer = new DocumentFieldSerializer(); var field = (DocumentField)serializer.Deserialize(null); Assert.False(field.HasValue); } [Fact] public void WrongInputToDocumentField() { var serializer = new DocumentFieldSerializer(); Assert.Throws<ArgumentException>(() => serializer.Serialize(new StringField { Value = "Exception" })); } [Fact] public void SerializeVideoField() { var serializer = new VideoFieldSerializer(); var id = Guid.NewGuid(); var str = serializer.Serialize(new VideoField { Id = id }); Assert.Equal(id.ToString(), str); } [Fact] public void DeserializeVideoField() { var serializer = new VideoFieldSerializer(); var id = Guid.NewGuid(); var field = (VideoField)serializer.Deserialize(id.ToString()); Assert.Equal(id, field.Id.Value); } [Fact] public void DeserializeEmptyVideoField() { var serializer = new VideoFieldSerializer(); var field = (VideoField)serializer.Deserialize(null); Assert.False(field.HasValue); } [Fact] public void WrongInputToVideoField() { var serializer = new VideoFieldSerializer(); Assert.Throws<ArgumentException>(() => serializer.Serialize(new StringField { Value = "Exception" })); } // START AUDIO [Fact] public void SerializeAudioField() { var serializer = new AudioFieldSerializer(); var id = Guid.NewGuid(); var str = serializer.Serialize(new AudioField { Id = id }); Assert.Equal(id.ToString(), str); } [Fact] public void DeserializeAudioField() { var serializer = new AudioFieldSerializer(); var id = Guid.NewGuid(); var field = (AudioField)serializer.Deserialize(id.ToString()); Assert.Equal(id, field.Id.Value); } [Fact] public void DeserializeEmptyAudioField() { var serializer = new AudioFieldSerializer(); var field = (AudioField)serializer.Deserialize(null); Assert.False(field.HasValue); } [Fact] public void WrongInputToAudioField() { var serializer = new AudioFieldSerializer(); Assert.Throws<ArgumentException>(() => serializer.Serialize(new StringField { Value = "Exception" })); } // END AUDIO [Fact] public void SerializeMediaField() { var serializer = new MediaFieldSerializer(); var id = Guid.NewGuid(); var str = serializer.Serialize(new MediaField { Id = id }); Assert.Equal(id.ToString(), str); } [Fact] public void DeserializeMediaField() { var serializer = new MediaFieldSerializer(); var id = Guid.NewGuid(); var field = (MediaField)serializer.Deserialize(id.ToString()); Assert.Equal(id, field.Id.Value); } [Fact] public void DeserializeEmptyMediaField() { var serializer = new MediaFieldSerializer(); var field = (MediaField)serializer.Deserialize(null); Assert.False(field.HasValue); } [Fact] public void WrongInputToMediaField() { var serializer = new MediaFieldSerializer(); Assert.Throws<ArgumentException>(() => serializer.Serialize(new StringField { Value = "Exception" })); } [Fact] public void SerializeNumberField() { var serializer = new IntegerFieldSerializer<NumberField>(); var str = serializer.Serialize(new NumberField { Value = 25 }); Assert.Equal("25", str); } [Fact] public void SerializeEmptyNumberField() { var serializer = new IntegerFieldSerializer<NumberField>(); var str = serializer.Serialize(new NumberField()); Assert.Null(str); } [Fact] public void DeserializeNumberField() { var serializer = new IntegerFieldSerializer<NumberField>(); var number = new NumberField { Value = 25 }; var str = "25"; var field = (NumberField)serializer.Deserialize(str); Assert.NotNull(field); Assert.Equal(number.Value, field.Value); } [Fact] public void DeserializeEmptyNumberField() { var serializer = new IntegerFieldSerializer<NumberField>(); var field = (NumberField)serializer.Deserialize(null); Assert.False(field.Value.HasValue); } [Fact] public void WrongInputToNumberField() { var serializer = new IntegerFieldSerializer<NumberField>(); Assert.Throws<ArgumentException>(() => serializer.Serialize(new StringField { Value = "Exception" })); } [Fact] public void SerializeStringField() { var serializer = new StringFieldSerializer<StringField>(); var ipsum = "Integer posuere erat a ante venenatis dapibus posuere velit aliquet."; var str = serializer.Serialize(new StringField { Value = ipsum }); Assert.Equal(ipsum, str); } [Fact] public void DeserializeStringField() { var serializer = new StringFieldSerializer<StringField>(); var ipsum = "Integer posuere erat a ante venenatis dapibus posuere velit aliquet."; var field = (StringField)serializer.Deserialize(ipsum); Assert.Equal(ipsum, field.Value); } [Fact] public void WrongInputStringField() { var serializer = new StringFieldSerializer<StringField>(); Assert.Throws<ArgumentException>(() => serializer.Serialize(new DateField { Value = DateTime.Now })); } [Fact] public void SerializePageField() { var serializer = new PageFieldSerializer(); var pageId = Guid.NewGuid(); var str = serializer.Serialize(new PageField { Id = pageId }); Assert.Equal(pageId.ToString(), str); } [Fact] public void DeserializePageField() { var serializer = new PageFieldSerializer(); var pageId = Guid.NewGuid(); var field = (PageField)serializer.Deserialize(pageId.ToString()); Assert.Equal(pageId, field.Id); } [Fact] public void WrongInputPageField() { var serializer = new PageFieldSerializer(); Assert.Throws<ArgumentException>(() => serializer.Serialize(new DateField { Value = DateTime.Now })); } [Fact] public void SerializePostField() { var serializer = new PostFieldSerializer(); var postId = Guid.NewGuid(); var str = serializer.Serialize(new PostField { Id = postId }); Assert.Equal(postId.ToString(), str); } [Fact] public void DeserializePostField() { var serializer = new PostFieldSerializer(); var postId = Guid.NewGuid(); var field = (PostField)serializer.Deserialize(postId.ToString()); Assert.Equal(postId, field.Id); } [Fact] public void WrongInputPostField() { var serializer = new PostFieldSerializer(); Assert.Throws<ArgumentException>(() => serializer.Serialize(new DateField { Value = DateTime.Now })); } [Fact] public void SerializeSelectField() { var serializer = new SelectFieldSerializer<SelectField<ColorType>>(); var str = serializer.Serialize(new SelectField<ColorType> { EnumValue = ColorType.Green.ToString() }); Assert.Equal("Green", str); } [Fact] public void DeserializeSelectField() { var serializer = new SelectFieldSerializer<SelectField<ColorType>>(); var field = (SelectField<ColorType>)serializer.Deserialize("Blue"); Assert.Equal(ColorType.Blue.ToString(), field.EnumValue); } [Fact] public void DeserializeEmptySelectField() { var serializer = new SelectFieldSerializer<SelectField<ColorType>>(); var field = (SelectField<ColorType>)serializer.Deserialize(null); // Default value of the enum sequence Assert.Equal("Red", field.EnumValue); } } }
// 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.IO; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Security; using Xunit; using System.Text; namespace System.IO.FileSystem.DriveInfoTests { public class DriveInfoWindowsTests { [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void TestConstructor() { string[] invalidInput = { ":\0", ":", "://", @":\", ":/", @":\\", "Az", "1", "a1", @"\\share", @"\\", "c ", string.Empty, " c" }; string[] variableInput = { "{0}", "{0}", "{0}:", "{0}:", @"{0}:\", @"{0}:\\", "{0}://" }; // Test Invalid input foreach (var input in invalidInput) { Assert.Throws<ArgumentException>(() => { new DriveInfo(input); }); } // Test Null Assert.Throws<ArgumentNullException>(() => { new DriveInfo(null); }); // Test Valid DriveLetter var validDriveLetter = GetValidDriveLettersOnMachine().First(); foreach (var input in variableInput) { string name = string.Format(input, validDriveLetter); DriveInfo dInfo = new DriveInfo(name); Assert.Equal(string.Format(@"{0}:\", validDriveLetter), dInfo.Name); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void TestGetDrives() { var validExpectedDrives = GetValidDriveLettersOnMachine(); var validActualDrives = DriveInfo.GetDrives(); // Test count Assert.Equal(validExpectedDrives.Count(), validActualDrives.Count()); for (int i = 0; i < validActualDrives.Count(); i++) { // Test if the driveletter is correct Assert.Contains(validActualDrives[i].Name[0], validExpectedDrives); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void TestDriveFormat() { var validDrive = DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.Fixed).First(); const int volNameLen = 50; StringBuilder volumeName = new StringBuilder(volNameLen); const int fileSystemNameLen = 50; StringBuilder fileSystemName = new StringBuilder(fileSystemNameLen); int serialNumber, maxFileNameLen, fileSystemFlags; bool r = GetVolumeInformation(validDrive.Name, volumeName, volNameLen, out serialNumber, out maxFileNameLen, out fileSystemFlags, fileSystemName, fileSystemNameLen); var fileSystem = fileSystemName.ToString(); if (r) { Assert.Equal(fileSystem, validDrive.DriveFormat); } else { Assert.Throws<IOException>(() => validDrive.DriveFormat); } // Test Invalid drive var invalidDrive = new DriveInfo(GetInvalidDriveLettersOnMachine().First().ToString()); Assert.Throws<DriveNotFoundException>(() => invalidDrive.DriveFormat); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void TestDriveType() { var validDrive = DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.Fixed).First(); var expectedDriveType = GetDriveType(validDrive.Name); Assert.Equal((DriveType)expectedDriveType, validDrive.DriveType); // Test Invalid drive var invalidDrive = new DriveInfo(GetInvalidDriveLettersOnMachine().First().ToString()); Assert.Equal(invalidDrive.DriveType, DriveType.NoRootDirectory); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void TestValidDiskSpaceProperties() { bool win32Result; long fbUser = -1; long tbUser; long fbTotal; DriveInfo drive; drive = DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.Fixed).First(); if (drive.IsReady) { win32Result = GetDiskFreeSpaceEx(drive.Name, out fbUser, out tbUser, out fbTotal); Assert.True(win32Result); if (fbUser != drive.AvailableFreeSpace) Assert.True(drive.AvailableFreeSpace >= 0); // valid property getters shouldn't throw string name = drive.Name; string format = drive.DriveFormat; Assert.Equal(name, drive.ToString()); // totalsize should not change for a fixed drive. Assert.Equal(tbUser, drive.TotalSize); if (fbTotal != drive.TotalFreeSpace) Assert.True(drive.TotalFreeSpace >= 0); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void TestInvalidDiskProperties() { string invalidDriveName = GetInvalidDriveLettersOnMachine().First().ToString(); var invalidDrive = new DriveInfo(invalidDriveName); Assert.Throws<DriveNotFoundException>(() => invalidDrive.AvailableFreeSpace); Assert.Throws<DriveNotFoundException>(() => invalidDrive.DriveFormat); Assert.Equal(DriveType.NoRootDirectory, invalidDrive.DriveType); Assert.False(invalidDrive.IsReady); Assert.Equal(invalidDriveName + ":\\", invalidDrive.Name); Assert.Equal(invalidDriveName + ":\\", invalidDrive.ToString()); Assert.Equal(invalidDriveName + ":\\", invalidDrive.RootDirectory.FullName); Assert.Throws<DriveNotFoundException>(() => invalidDrive.TotalFreeSpace); Assert.Throws<DriveNotFoundException>(() => invalidDrive.TotalSize); Assert.Throws<DriveNotFoundException>(() => invalidDrive.VolumeLabel); Assert.Throws<DriveNotFoundException>(() => invalidDrive.VolumeLabel = null); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void GetVolumeLabel_Returns_CorrectLabel() { void DoDriveCheck() { // Get Volume Label - valid drive int serialNumber, maxFileNameLen, fileSystemFlags; int volNameLen = 50; int fileNameLen = 50; StringBuilder volumeName = new StringBuilder(volNameLen); StringBuilder fileSystemName = new StringBuilder(fileNameLen); DriveInfo validDrive = DriveInfo.GetDrives().First(d => d.DriveType == DriveType.Fixed); bool volumeInformationSuccess = GetVolumeInformation(validDrive.Name, volumeName, volNameLen, out serialNumber, out maxFileNameLen, out fileSystemFlags, fileSystemName, fileNameLen); if (volumeInformationSuccess) { Assert.Equal(volumeName.ToString(), validDrive.VolumeLabel); } else // if we can't compare the volumeName, we should at least check that getting it doesn't throw { var name = validDrive.VolumeLabel; } }; if (PlatformDetection.IsWinRT) { Assert.Throws<UnauthorizedAccessException>(() => DoDriveCheck()); } else { DoDriveCheck(); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void SetVolumeLabel_Roundtrips() { DriveInfo drive = DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.Fixed).First(); string currentLabel = drive.VolumeLabel; try { drive.VolumeLabel = currentLabel; // shouldn't change the state of the drive regardless of success } catch (UnauthorizedAccessException) { } Assert.Equal(drive.VolumeLabel, currentLabel); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void VolumeLabelOnNetworkOrCdRom_Throws() { // Test setting the volume label on a Network or CD-ROM var noAccessDrive = DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.Network || d.DriveType == DriveType.CDRom); foreach (var adrive in noAccessDrive) { if (adrive.IsReady) { Exception e = Assert.ThrowsAny<Exception>(() => { adrive.VolumeLabel = null; }); Assert.True( e is UnauthorizedAccessException || e is IOException || e is SecurityException); } } } [DllImport("kernel32.dll", SetLastError = true)] internal static extern int GetLogicalDrives(); [DllImport("kernel32.dll", EntryPoint = "GetVolumeInformationW", CharSet = CharSet.Unicode, SetLastError = true, BestFitMapping = false)] internal static extern bool GetVolumeInformation(string drive, StringBuilder volumeName, int volumeNameBufLen, out int volSerialNumber, out int maxFileNameLen, out int fileSystemFlags, StringBuilder fileSystemName, int fileSystemNameBufLen); [DllImport("kernel32.dll", SetLastError = true, EntryPoint = "GetDriveTypeW", CharSet = CharSet.Unicode)] internal static extern int GetDriveType(string drive); [DllImport("kernel32.dll", SetLastError = true)] internal static extern bool GetDiskFreeSpaceEx(string drive, out long freeBytesForUser, out long totalBytes, out long freeBytes); private IEnumerable<char> GetValidDriveLettersOnMachine() { uint mask = (uint)GetLogicalDrives(); Assert.NotEqual<uint>(mask, 0); var bits = new BitArray(new int[] { (int)mask }); for (int i = 0; i < bits.Length; i++) { var letter = (char)('A' + i); if (bits[i]) yield return letter; } } private IEnumerable<char> GetInvalidDriveLettersOnMachine() { uint mask = (uint)GetLogicalDrives(); Assert.NotEqual<uint>(mask, 0); var bits = new BitArray(new int[] { (int)mask }); for (int i = 0; i < bits.Length; i++) { var letter = (char)('A' + i); if (!bits[i]) { if (char.IsLetter(letter)) yield return letter; } } } } }
namespace Watts.Azure.Common.DataFactory.Copy { using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading; using General; using Hyak.Common; using Interfaces.Security; using Microsoft.Azure; using Microsoft.Azure.Management.DataFactories; using Microsoft.Azure.Management.DataFactories.Common.Models; using Microsoft.Azure.Management.DataFactories.Models; using Storage.Objects; using Watts.Azure.Common.Interfaces.DataFactory; /// <summary> /// Azure Data Factory copy of data from one storage service to another /// </summary> public class AzureDataFactoryCopy { private readonly AzureDatasetHelper datasetHelper; private readonly LinkedServiceHelper linkedServiceHelper; private readonly AzureDataFactorySetup factorySetup; private readonly IAzureActiveDirectoryAuthentication authentication; private readonly CopySetup copySetup; private readonly Action<string> progressDelegate; private IAzureLinkedService sourceService; private IAzureLinkedService targetService; private CopySource source; private CopySink sink; private int authenticationRetries = 0; public AzureDataFactoryCopy(AzureDataFactorySetup factorySetup, CopySetup copySetup, IAzureActiveDirectoryAuthentication authentication, Action<string> progressDelegate = null) { this.datasetHelper = new AzureDatasetHelper(); this.linkedServiceHelper = new LinkedServiceHelper(progressDelegate); this.factorySetup = factorySetup; this.copySetup = copySetup; this.authentication = authentication; this.progressDelegate = progressDelegate; Uri resourceManagerUri = new Uri(Constants.ResourceManagerEndpoint); this.Client = new DataFactoryManagementClient(authentication.GetTokenCredentials(), resourceManagerUri); } public IAzureLinkedService SourceService { get => this.sourceService; set { this.sourceService = value; this.source = this.datasetHelper.GetCopySource(this.sourceService); } } public IAzureLinkedService TargetService { get => this.targetService; set { this.targetService = value; this.sink = this.datasetHelper.GetCopySink(this.targetService); } } public IDataFactoryManagementClient Client { get; private set; } /// <summary> /// Apply a filter query to the copy. /// </summary> /// <param name="queryString"></param> public void UsingSourceQuery(string queryString) { this.Report($"Will use source query {queryString}"); this.datasetHelper.SetSourceQuery(this.source, queryString); } /// <summary> /// Link a service to the copy (e.g. the source or the sink) /// </summary> /// <param name="service"></param> /// <param name="linkedServiceName"></param> /// <returns></returns> public bool LinkService(IAzureLinkedService service, string linkedServiceName) { this.Report($"Adding linked service {linkedServiceName}"); LinkedServiceTypeProperties serviceTypeProperties = this.linkedServiceHelper.GetLinkedServiceTypeProperties(service); var result = this.Client.LinkedServices.CreateOrUpdate( this.factorySetup.ResourceGroupName, this.factorySetup.Name, new LinkedServiceCreateOrUpdateParameters() { LinkedService = new LinkedService() { Name = linkedServiceName, Properties = new LinkedServiceProperties(serviceTypeProperties), } }); this.Report($"Result status {result.Status}"); return result.Status == OperationStatus.Succeeded; } /// <summary> /// Create the datasets for the source and sink. /// </summary> /// <param name="dataStructure"></param> /// <returns></returns> public bool CreateDatasets(DataStructure dataStructure) { var structure = dataStructure.DataElements; this.Report($"Creating source dataset with structure {string.Join(", ", structure.Select(p => p.Name))}"); var sourceResult = this.CreateSourceDataSet(structure); this.Report("Creating target dataset"); var targetResult = this.CreateTargetDataSet(structure); this.Report($"Source dataset creation status {sourceResult.Status}"); this.Report($"Target dataset creation status {targetResult.Status}"); return sourceResult.Status == OperationStatus.Succeeded && targetResult.Status == OperationStatus.Succeeded; } /// <summary> /// Get the pipeline if it exists, otherwise null. /// </summary> /// <returns></returns> public Pipeline PipelineExists() { if (!this.DataFactoryExists()) { return null; } this.Report("Checking if pipeline exists..."); PipelineListResponse pipeline = null; try { pipeline = this.Client.Pipelines.List(this.factorySetup.ResourceGroupName, this.factorySetup.Name); } catch (CloudException ex) { this.Report($"Exception when attempting to list pipelines. Assuming the pipeline does not exist... {ex}"); return null; } if (pipeline.Pipelines.Count > 0) { this.Report("Pipeline exists, returning first"); return pipeline.Pipelines.First(); } this.Report("No pipeline found"); return null; } public bool DataFactoryExists() { var dataFactories = this.Client.DataFactories.List(this.factorySetup.ResourceGroupName); return dataFactories.DataFactories.Any(p => p.Name == this.factorySetup.Name); } /// <summary> /// Create the copy data pipeline. /// </summary> /// <param name="pipelineActivePeriodStartTime"></param> /// <param name="pipelineActivePeriodEndTime"></param> public void CreatePipeline(DateTime pipelineActivePeriodStartTime, DateTime pipelineActivePeriodEndTime) { this.Report($"Creating pipeline {this.copySetup.SourceDatasetName} -> {this.copySetup.TargetDatasetName}..."); this.Client.Pipelines.CreateOrUpdate( this.factorySetup.ResourceGroupName, this.factorySetup.Name, new PipelineCreateOrUpdateParameters() { Pipeline = new Pipeline() { Name = this.copySetup.CopyPipelineName ?? Guid.NewGuid().ToString(), Properties = new PipelineProperties() { Description = "Pipeline for data transfer between two services", // Initial value for pipeline's active period. With this, you won't need to set slice status Start = pipelineActivePeriodStartTime, End = pipelineActivePeriodEndTime, Activities = new List<Activity>() { new Activity() { Name = Guid.NewGuid().ToString(), Inputs = new List<ActivityInput>() { new ActivityInput() { Name = this.copySetup.SourceDatasetName } }, Outputs = new List<ActivityOutput>() { new ActivityOutput() { Name = this.copySetup.TargetDatasetName, } }, TypeProperties = new CopyActivity() { Source = this.source, Sink = this.sink, CloudDataMovementUnits = 8, }, } }, } } }); } /// <summary> /// Monitor the status of the data copy, exiting when the copy either times out or is completed. /// </summary> /// <param name="destinationDatasetName"></param> /// <param name="pipelineActivePeriodStartTime"></param> /// <param name="pipelineActivePeriodEndTime"></param> public void MonitorStatusUntilDone(string destinationDatasetName, DateTime pipelineActivePeriodStartTime, DateTime pipelineActivePeriodEndTime) { DateTime start = DateTime.Now; bool done = false; while (DateTime.Now - start < TimeSpan.FromMinutes(this.copySetup.TimeoutInMinutes) && !done) { try { this.Report("Pulling the slice status"); // Wait before the next status check Thread.Sleep(1000 * 12); var datalistResponse = this.Client.DataSlices.List( this.factorySetup.ResourceGroupName, this.factorySetup.Name, destinationDatasetName, new DataSliceListParameters() { DataSliceRangeStartTime = pipelineActivePeriodStartTime.ConvertToISO8601DateTimeString(), DataSliceRangeEndTime = pipelineActivePeriodEndTime.ConvertToISO8601DateTimeString() }); done = true; foreach (DataSlice slice in datalistResponse.DataSlices) { if (slice.State == DataSliceState.Failed || slice.State == DataSliceState.Ready) { this.Report($"Slice execution is done with status: {slice.State}"); break; } else { this.Report($"Slice status is: {slice.State}"); done = false; } } // Reset the counter so we know that we're authenticated... this.authenticationRetries = 0; } catch (Exception) { this.Report("Exception occurred..."); if (this.authenticationRetries < 3) { this.Report("Could be a temporary disconnect, will attempt to re-authenticate..."); this.RetryAuthentication(); this.authenticationRetries++; } else { throw; } } } } /// <summary> /// Get a list of all error messages that occcured during the execution. /// </summary> /// <param name="pipelineActivePeriodStartTime"></param> /// <returns></returns> public List<string> GetErrors(DateTime pipelineActivePeriodStartTime) { List<string> retVal = new List<string>(); var datasliceRunListResponse = this.Client.DataSliceRuns.List( this.factorySetup.ResourceGroupName, this.factorySetup.Name, this.copySetup.TargetDatasetName, new DataSliceRunListParameters() { DataSliceStartTime = pipelineActivePeriodStartTime.ConvertToISO8601DateTimeString() }); retVal = datasliceRunListResponse.DataSliceRuns.Where(p => !string.IsNullOrEmpty(p.ErrorMessage)) .Select(q => q.ErrorMessage).ToList(); return retVal; } /// <summary> /// Print all details of the run (status, start time, end time, etc.) /// </summary> /// <param name="destinationDatasetName"></param> /// <param name="pipelineActivePeriodStartTime"></param> public void PrintRunDetails(string destinationDatasetName, DateTime pipelineActivePeriodStartTime) { var datasliceRunListResponse = this.Client.DataSliceRuns.List( this.factorySetup.ResourceGroupName, this.factorySetup.Name, destinationDatasetName, new DataSliceRunListParameters() { DataSliceStartTime = pipelineActivePeriodStartTime.ConvertToISO8601DateTimeString() }); foreach (DataSliceRun run in datasliceRunListResponse.DataSliceRuns) { this.Report($"Status: \t\t{run.Status}"); this.Report($"DataSliceStart: \t{run.DataSliceStart}"); this.Report($"DataSliceEnd: \t\t{run.DataSliceEnd}"); this.Report($"ActivityId: \t\t{run.ActivityName}"); this.Report($"ProcessingStartTime: \t{run.ProcessingStartTime}"); this.Report($"ProcessingEndTime: \t{run.ProcessingEndTime}"); this.Report($"ErrorMessage: \t{run.ErrorMessage}"); } } /// <summary> /// Delete the datafactory associated with the copy. /// </summary> /// <returns></returns> public bool Delete() { var response = this.Client.DataFactories.Delete(this.factorySetup.ResourceGroupName, this.factorySetup.Name); // If the status code is 200 or 204, the delete was successful (https://docs.microsoft.com/en-us/rest/api/datafactory/integrationruntimes/delete) return response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.NoContent; } /// <summary> /// Create the data factory /// </summary> internal void CreateDataFactory() { this.Report($"Creating datafactory {this.factorySetup.Name}..."); this.Client.DataFactories.CreateOrUpdate( this.factorySetup.ResourceGroupName, new DataFactoryCreateOrUpdateParameters() { DataFactory = new DataFactory() { Name = this.factorySetup.Name, Location = "northeurope", Properties = new DataFactoryProperties() { } } }); } /// <summary> /// Attempt to re-authenticate. /// </summary> internal void RetryAuthentication() { Console.WriteLine("Will re-authenticate with Azure"); Uri resourceManagerUri = new Uri(Constants.ResourceManagerEndpoint); this.Client = new DataFactoryManagementClient(this.authentication.GetTokenCredentials(), resourceManagerUri); } /// <summary> /// Report progress on the progress delegate if there is one. /// </summary> /// <param name="progress"></param> internal void Report(string progress) { this.progressDelegate?.Invoke(progress); } internal DatasetCreateOrUpdateResponse CreateTargetDataSet(List<DataElement> structure) { return this.Client.Datasets.CreateOrUpdate( this.factorySetup.ResourceGroupName, this.factorySetup.Name, new DatasetCreateOrUpdateParameters() { Dataset = new Dataset() { Name = this.copySetup.TargetDatasetName, Properties = new DatasetProperties() { LinkedServiceName = this.copySetup.TargetLinkedServiceName, TypeProperties = this.datasetHelper.GetTypeProperties(this.TargetService, this.copySetup.TargetDatasetName), Availability = new Availability() { Frequency = SchedulePeriod.Day, Interval = 1, }, Structure = structure }, } }); } internal DatasetCreateOrUpdateResponse CreateSourceDataSet(List<DataElement> structure) { return this.Client.Datasets.CreateOrUpdate( this.factorySetup.ResourceGroupName, this.factorySetup.Name, new DatasetCreateOrUpdateParameters() { Dataset = new Dataset() { Name = this.copySetup.SourceDatasetName, Properties = new DatasetProperties() { LinkedServiceName = this.copySetup.SourceLinkedServiceName, TypeProperties = this.datasetHelper.GetTypeProperties(this.SourceService), External = true, Availability = new Availability() { Frequency = SchedulePeriod.Day, Interval = 1, }, Policy = new Policy() { Validation = new ValidationPolicy() { MinimumRows = 1 } }, Structure = structure } } }); } } }
/* Copyright (c) Citrix Systems, 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. * * 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 HOLDER 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. */ using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using XenAPI; using XenAdmin.Actions; using XenAdmin.Network; using XenAdmin.Core; namespace XenAdmin.Dialogs { public partial class RoleElevationDialog : XenDialogBase { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); public Session elevatedSession; public string elevatedPassword; public string elevatedUsername; public string originalUsername; public string originalPassword; private List<Role> authorizedRoles; /// <summary> /// Displays a dialog informing the user they need a different role to complete the task, and offers the chance to switch user. Optionally logs /// out the elevated session. If successful exposes the elevated session, password and username as fields. /// </summary> /// <param name="connection">The current server connection with the role information</param> /// <param name="session">The session on which we have been denied access</param> /// <param name="authorizedRoles">A list of roles that are able to complete the task</param> /// <param name="actionTitle">A description of the current action, if null or empty will not be displayed</param> public RoleElevationDialog(IXenConnection connection, Session session, List<Role> authorizedRoles, string actionTitle) :base(connection) { InitializeComponent(); UserDetails ud = session.CurrentUserDetails; labelCurrentUserValue.Text = ud.UserDisplayName ?? ud.UserName ?? Messages.UNKNOWN_AD_USER; labelCurrentRoleValue.Text = Role.FriendlyCSVRoleList(session.Roles); authorizedRoles.Sort((r1, r2) => r2.CompareTo(r1)); labelRequiredRoleValue.Text = Role.FriendlyCSVRoleList(authorizedRoles); labelServerValue.Text = Helpers.GetName(connection); labelServer.Text = Helpers.IsPool(connection) ? Messages.POOL_COLON : Messages.SERVER_COLON; originalUsername = session.Connection.Username; originalPassword = session.Connection.Password; if (string.IsNullOrEmpty(actionTitle)) { labelCurrentAction.Visible = false; labelCurrentActionValue.Visible = false; } else { labelCurrentActionValue.Text = actionTitle; } this.authorizedRoles = authorizedRoles; } private void buttonAuthorize_Click(object sender, EventArgs e) { try { Exception delegateException = null; log.Debug("Testing logging in with the new credentials"); DelegatedAsyncAction loginAction = new DelegatedAsyncAction(connection, Messages.AUTHORIZING_USER, Messages.CREDENTIALS_CHECKING, Messages.CREDENTIALS_CHECK_COMPLETE, delegate { try { elevatedSession = connection.ElevatedSession(TextBoxUsername.Text.Trim(), TextBoxPassword.Text); } catch (Exception ex) { delegateException = ex; } }); using (var dlg = new ActionProgressDialog(loginAction, ProgressBarStyle.Marquee, false)) dlg.ShowDialog(this); // The exception would have been handled by the action progress dialog, just return the user to the sudo dialog if (loginAction.Exception != null) return; if(HandledAnyDelegateException(delegateException)) return; if (elevatedSession.IsLocalSuperuser || SessionAuthorized(elevatedSession)) { elevatedUsername = TextBoxUsername.Text.Trim(); elevatedPassword = TextBoxPassword.Text; DialogResult = DialogResult.OK; Close(); return; } ShowNotAuthorisedDialog(); } catch (Exception ex) { log.DebugFormat("Exception when attempting to sudo action: {0} ", ex); using (var dlg = new ErrorDialog(string.Format(Messages.USER_AUTHORIZATION_FAILED, TextBoxUsername.Text))) dlg.ShowDialog(Parent); TextBoxPassword.Focus(); TextBoxPassword.SelectAll(); } finally { // Check whether we have a successful elevated session and whether we have been asked to log it out // If non successful (most likely the new subject is not authorized) then log it out anyway. if (elevatedSession != null && DialogResult != DialogResult.OK) { elevatedSession.Connection.Logout(elevatedSession); elevatedSession = null; } } } private bool HandledAnyDelegateException(Exception delegateException) { if (delegateException != null) { Failure f = delegateException as Failure; if (f != null && f.ErrorDescription[0] == Failure.RBAC_PERMISSION_DENIED) { ShowNotAuthorisedDialog(); return true; } throw delegateException; } return false; } private void ShowNotAuthorisedDialog() { using (var dlg = new ErrorDialog(Messages.USER_NOT_AUTHORIZED) {WindowTitle = Messages.PERMISSION_DENIED}) { dlg.ShowDialog(this); } TextBoxPassword.Focus(); TextBoxPassword.SelectAll(); } private bool SessionAuthorized(Session s) { UserDetails ud = s.CurrentUserDetails; foreach (Role r in s.Roles) { if (authorizedRoles.Contains(r)) { log.DebugFormat("Subject '{0}' is authorized to complete the action", ud.UserDisplayName ?? ud.UserName ?? ud.UserSid); return true; } } log.DebugFormat("Subject '{0}' is not authorized to complete the action", ud.UserDisplayName ?? ud.UserName ?? ud.UserSid); return false; } private void buttonCancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; Close(); } private void UpdateButtons() { buttonAuthorize.Enabled = TextBoxUsername.Text.Trim() != "" && TextBoxPassword.Text != ""; } private void TextBoxUsername_TextChanged(object sender, EventArgs e) { UpdateButtons(); } private void TextBoxPassword_TextChanged(object sender, EventArgs e) { UpdateButtons(); } } }
using System; using System.Collections; using Server.Network; using Server.Mobiles; using Server.Items; using Server.Gumps; namespace Server.Items.Crops { public class HoublonSeed : BaseCrop { // return true to allow planting on Dirt Item (ItemID 0x32C9) // See CropHelper.cs for other overriddable types public override bool CanGrowGarden { get { return true; } } [Constructable] public HoublonSeed() : this(1) { } [Constructable] public HoublonSeed(int amount) : base(0xF27) { Stackable = true; Weight = .5; Hue = 0x5E2; Movable = true; Amount = amount; Name = AgriTxt.Seed + " de Houblon"; } public override void OnDoubleClick(Mobile from) { if (from.Mounted && !CropHelper.CanWorkMounted) { from.SendMessage(AgriTxt.CannotWorkMounted); return; } Point3D m_pnt = from.Location; Map m_map = from.Map; if (!IsChildOf(from.Backpack)) { from.SendLocalizedMessage(1042010); //You must have the object in your backpack to use it. return; } else if (!CropHelper.CheckCanGrow(this, m_map, m_pnt.X, m_pnt.Y)) { from.SendMessage(AgriTxt.CannotGrowHere); return; } //check for BaseCrop on this tile ArrayList cropshere = CropHelper.CheckCrop(m_pnt, m_map, 0); if (cropshere.Count > 0) { from.SendMessage(AgriTxt.AlreadyCrop); return; } //check for over planting prohibt if 4 maybe 3 neighboring crops ArrayList cropsnear = CropHelper.CheckCrop(m_pnt, m_map, 1); if ((cropsnear.Count > 3) || ((cropsnear.Count == 3) && Utility.RandomBool())) { from.SendMessage(AgriTxt.TooMuchCrops); return; } if (this.BumpZ) ++m_pnt.Z; if (!from.Mounted) from.Animate(32, 5, 1, true, false, 0); // Bow from.SendMessage(AgriTxt.CropPlanted); this.Consume(); Item item = new HoublonSeedling(from); item.Location = m_pnt; item.Map = m_map; } public HoublonSeed(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } } public class HoublonSeedling : BaseCrop { private static Mobile m_sower; public Timer thisTimer; [CommandProperty(AccessLevel.GameMaster)] public Mobile Sower { get { return m_sower; } set { m_sower = value; } } [Constructable] public HoublonSeedling(Mobile sower) : base(Utility.RandomList(0xC60, 0xC5E)) { Movable = false; Name = AgriTxt.Seedling + " de Houblon"; m_sower = sower; init(this); } public static void init(HoublonSeedling plant) { plant.thisTimer = new CropHelper.GrowTimer(plant, typeof(HoublonCrop), plant.Sower); plant.thisTimer.Start(); } public override void OnDoubleClick(Mobile from) { if (from.Mounted && !CropHelper.CanWorkMounted) { from.SendMessage(AgriTxt.CannotWorkMounted); return; } if ((Utility.RandomDouble() <= .25) && !(m_sower.AccessLevel > AccessLevel.Counselor)) { //25% Chance from.SendMessage(AgriTxt.PickCrop); thisTimer.Stop(); this.Delete(); } else from.SendMessage(AgriTxt.TooYoungCrop); } public HoublonSeedling(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); writer.Write(m_sower); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); m_sower = reader.ReadMobile(); init(this); } } public class HoublonCrop : BaseCrop { private const int max = 10; private int fullGraphic; private int pickedGraphic; private DateTime lastpicked; private Mobile m_sower; private int m_yield; public Timer regrowTimer; private DateTime m_lastvisit; [CommandProperty(AccessLevel.GameMaster)] public DateTime LastSowerVisit { get { return m_lastvisit; } } [CommandProperty(AccessLevel.GameMaster)] public bool Growing { get { return regrowTimer.Running; } } [CommandProperty(AccessLevel.GameMaster)] public Mobile Sower { get { return m_sower; } set { m_sower = value; } } [CommandProperty(AccessLevel.GameMaster)] public int Yield { get { return m_yield; } set { m_yield = value; } } public int Capacity { get { return max; } } public int FullGraphic { get { return fullGraphic; } set { fullGraphic = value; } } public int PickGraphic { get { return pickedGraphic; } set { pickedGraphic = value; } } public DateTime LastPick { get { return lastpicked; } set { lastpicked = value; } } [Constructable] public HoublonCrop(Mobile sower) : base(Utility.RandomList(0xC60, 0xC5E)) { Movable = false; Name = "Plant de Houblon"; m_sower = sower; m_lastvisit = DateTime.Now; init(this, false); } [Constructable] public HoublonCrop() : this(null) { } public static void init(HoublonCrop plant, bool full) { plant.PickGraphic = Utility.RandomList(0xC60, 0xC5E); plant.FullGraphic = Utility.RandomList(0x1A9E, 0x1A9F, 0x1AA0, 0x1AA1); plant.LastPick = DateTime.Now; plant.regrowTimer = new CropTimer(plant); if (full) { plant.Yield = plant.Capacity; ((Item)plant).ItemID = plant.FullGraphic; } else { plant.Yield = 0; ((Item)plant).ItemID = plant.PickGraphic; plant.regrowTimer.Start(); } } public void UpRoot(Mobile from) { from.SendMessage(AgriTxt.WitherCrop); if (regrowTimer.Running) regrowTimer.Stop(); this.Delete(); } public override void OnDoubleClick(Mobile from) { if (m_sower == null || m_sower.Deleted) m_sower = from; if (from.Mounted && !CropHelper.CanWorkMounted) { from.SendMessage(AgriTxt.CannotWorkMounted); return; } if (DateTime.Now > lastpicked.AddSeconds(3)) // 3 seconds between picking { lastpicked = DateTime.Now; int lumberValue = (int)from.Skills[SkillName.Lumberjacking].Value / 5; if (lumberValue == 0) { from.SendMessage(AgriTxt.DunnoHowTo); return; } if (from.InRange(this.GetWorldLocation(), 2)) { if (m_yield < 1) { from.SendMessage(AgriTxt.NoCrop); if (PlayerCanDestroy && !(m_sower.AccessLevel > AccessLevel.Counselor)) { UpRootGump g = new UpRootGump(from, this); from.SendGump(g); } } else //check skill and sower { from.Direction = from.GetDirectionTo(this); from.Animate(from.Mounted ? 29 : 32, 5, 1, true, false, 0); if (from == m_sower) { lumberValue *= 2; m_lastvisit = DateTime.Now; } if (lumberValue > m_yield) lumberValue = m_yield + 1; int pick = Utility.Random(lumberValue); if (pick == 0) { from.SendMessage(AgriTxt.ZeroPicked); return; } m_yield -= pick; from.SendMessage(AgriTxt.YouPick + " {0} houblon{1}!", pick, (pick == 1 ? "" : "s")); //PublicOverheadMessage( MessageType.Regular, 0x3BD, false, string.Format( "{0}", m_yield )); // use for debuging ((Item)this).ItemID = pickedGraphic; Hop crop = new Hop(pick); from.AddToBackpack(crop); if (SowerPickTime != TimeSpan.Zero && m_lastvisit + SowerPickTime < DateTime.Now && !(m_sower.AccessLevel > AccessLevel.Counselor)) { this.UpRoot(from); return; } if (!regrowTimer.Running) { regrowTimer.Start(); } } } else { from.SendMessage(AgriTxt.TooFar); } } } private class CropTimer : Timer { private HoublonCrop i_plant; public CropTimer(HoublonCrop plant) : base(TimeSpan.FromSeconds(600), TimeSpan.FromSeconds(15)) { Priority = TimerPriority.OneSecond; i_plant = plant; } protected override void OnTick() { if ((i_plant != null) && (!i_plant.Deleted)) { int current = i_plant.Yield; if (++current >= i_plant.Capacity) { current = i_plant.Capacity; ((Item)i_plant).ItemID = i_plant.FullGraphic; Stop(); } else if (current <= 0) current = 1; i_plant.Yield = current; //i_plant.PublicOverheadMessage( MessageType.Regular, 0x22, false, string.Format( "{0}", current )); // use for debuging } else Stop(); } } public HoublonCrop(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)1); writer.Write(m_lastvisit); writer.Write(m_sower); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); switch (version) { case 1: { m_lastvisit = reader.ReadDateTime(); goto case 0; } case 0: { m_sower = reader.ReadMobile(); break; } } if (version == 0) m_lastvisit = DateTime.Now; init(this, true); } } }
#if !NOT_UNITY3D using System; using System.IO; using UnityEditor; using UnityEngine; using ModestTree; using UnityEditor.SceneManagement; using System.Linq; using UnityEngine.SceneManagement; namespace Zenject { public static class ZenMenuItems { [MenuItem("Edit/Zenject/Validate Current Scenes #%v")] public static void ValidateCurrentScene() { ValidateCurrentSceneInternal(); } [MenuItem("Edit/Zenject/Validate Then Run #%r")] public static void ValidateCurrentSceneThenRun() { if (ValidateCurrentSceneInternal()) { EditorApplication.isPlaying = true; } } [MenuItem("Edit/Zenject/Help...")] public static void OpenDocumentation() { Application.OpenURL("https://github.com/modesttree/zenject"); } [MenuItem("GameObject/Zenject/Scene Context", false, 9)] public static void CreateSceneContext(MenuCommand menuCommand) { var root = new GameObject("SceneContext").AddComponent<SceneContext>(); Selection.activeGameObject = root.gameObject; EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene()); } [MenuItem("GameObject/Zenject/Decorator Context", false, 9)] public static void CreateDecoratorContext(MenuCommand menuCommand) { var root = new GameObject("DecoratorContext").AddComponent<SceneDecoratorContext>(); Selection.activeGameObject = root.gameObject; EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene()); } [MenuItem("GameObject/Zenject/Game Object Context", false, 9)] public static void CreateGameObjectContext(MenuCommand menuCommand) { var root = new GameObject("GameObjectContext").AddComponent<GameObjectContext>(); Selection.activeGameObject = root.gameObject; EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene()); } [MenuItem("Edit/Zenject/Create Project Context")] public static void CreateProjectContextInDefaultLocation() { var fullDirPath = Path.Combine(Application.dataPath, "Resources"); if (!Directory.Exists(fullDirPath)) { Directory.CreateDirectory(fullDirPath); } CreateProjectContextInternal("Assets/Resources"); } [MenuItem("Assets/Create/Zenject/Scriptable Object Installer", false, 1)] public static void CreateScriptableObjectInstaller() { AddCSharpClassTemplate("Scriptable Object Installer", "UntitledInstaller", false, "using UnityEngine;" + "\nusing Zenject;" + "\n" + "\n[CreateAssetMenu(fileName = \"CLASS_NAME\", menuName = \"Installers/CLASS_NAME\")]" + "\npublic class CLASS_NAME : ScriptableObjectInstaller<CLASS_NAME>" + "\n{" + "\n public override void InstallBindings()" + "\n {" + "\n }" + "\n}"); } [MenuItem("Assets/Create/Zenject/Mono Installer", false, 1)] public static void CreateMonoInstaller() { AddCSharpClassTemplate("Mono Installer", "UntitledInstaller", false, "using UnityEngine;" + "\nusing Zenject;" + "\n" + "\npublic class CLASS_NAME : MonoInstaller<CLASS_NAME>" + "\n{" + "\n public override void InstallBindings()" + "\n {" + "\n }" + "\n}"); } [MenuItem("Assets/Create/Zenject/Installer", false, 1)] public static void CreateInstaller() { AddCSharpClassTemplate("Installer", "UntitledInstaller", false, "using UnityEngine;" + "\nusing Zenject;" + "\n" + "\npublic class CLASS_NAME : Installer<CLASS_NAME>" + "\n{" + "\n public override void InstallBindings()" + "\n {" + "\n }" + "\n}"); } [MenuItem("Assets/Create/Zenject/Editor Window", false, 20)] public static void CreateEditorWindow() { AddCSharpClassTemplate("Editor Window", "UntitledEditorWindow", true, "using UnityEngine;" + "\nusing UnityEditor;" + "\nusing Zenject;" + "\n" + "\npublic class CLASS_NAME : ZenjectEditorWindow" + "\n{" + "\n [MenuItem(\"Window/CLASS_NAME\")]" + "\n public static CLASS_NAME GetOrCreateWindow()" + "\n {" + "\n var window = EditorWindow.GetWindow<CLASS_NAME>();" + "\n window.titleContent = new GUIContent(\"CLASS_NAME\");" + "\n return window;" + "\n }" + "\n" + "\n public override void InstallBindings()" + "\n {" + "\n // TODO" + "\n }" + "\n}"); } [MenuItem("Assets/Create/Zenject/Unit Test", false, 60)] public static void CreateUnitTest() { AddCSharpClassTemplate("Unit Test", "UntitledUnitTest", true, "using Zenject;" + "\nusing NUnit.Framework;" + "\n" + "\n[TestFixture]" + "\npublic class CLASS_NAME : ZenjectUnitTestFixture" + "\n{" + "\n [Test]" + "\n public void RunTest1()" + "\n {" + "\n // TODO" + "\n }" + "\n}"); } [MenuItem("Assets/Create/Zenject/Integration Test", false, 60)] public static void CreateIntegrationTest() { AddCSharpClassTemplate("Integration Test", "UntitledIntegrationTest", true, "using Zenject;" + "\nusing NUnit.Framework;" + "\n" + "\n[TestFixture]" + "\npublic class CLASS_NAME : ZenjectIntegrationTestFixture" + "\n{" + "\n [Test]" + "\n public void RunTest1()" + "\n {" + "\n // TODO: Add bindings" + "\n " + "\n Initialize();" + "\n " + "\n // TODO" + "\n }" + "\n}"); } [MenuItem("Assets/Create/Zenject/Project Context", false, 40)] public static void CreateProjectContext() { var absoluteDir = ZenUnityEditorUtil.TryGetSelectedFolderPathInProjectsTab(); if (absoluteDir == null) { EditorUtility.DisplayDialog("Error", "Could not find directory to place the '{0}.prefab' asset. Please try again by right clicking in the desired folder within the projects pane." .Fmt(ProjectContext.ProjectContextResourcePath), "Ok"); return; } var parentFolderName = Path.GetFileName(absoluteDir); if (parentFolderName != "Resources") { EditorUtility.DisplayDialog("Error", "'{0}.prefab' must be placed inside a directory named 'Resources'. Please try again by right clicking within the Project pane in a valid Resources folder." .Fmt(ProjectContext.ProjectContextResourcePath), "Ok"); return; } CreateProjectContextInternal(absoluteDir); } static void CreateProjectContextInternal(string absoluteDir) { var assetPath = ZenUnityEditorUtil.ConvertFullAbsolutePathToAssetPath(absoluteDir); var prefabPath = (Path.Combine(assetPath, ProjectContext.ProjectContextResourcePath) + ".prefab").Replace("\\", "/"); var emptyPrefab = PrefabUtility.CreateEmptyPrefab(prefabPath); var gameObject = new GameObject(); try { gameObject.AddComponent<ProjectContext>(); var prefabObj = PrefabUtility.ReplacePrefab(gameObject, emptyPrefab); Selection.activeObject = prefabObj; } finally { GameObject.DestroyImmediate(gameObject); } Debug.Log("Created new ProjectContext at '{0}'".Fmt(prefabPath)); } static void AddCSharpClassTemplate( string friendlyName, string defaultFileName, bool editorOnly, string templateStr) { var folderPath = ZenUnityEditorUtil.GetCurrentDirectoryAssetPathFromSelection(); if (editorOnly && !folderPath.Contains("/Editor")) { EditorUtility.DisplayDialog("Error", "Editor window classes must have a parent folder above them named 'Editor'. Please create or find an Editor folder and try again", "Ok"); return; } var absolutePath = EditorUtility.SaveFilePanel( "Choose name for " + friendlyName, folderPath, defaultFileName + ".cs", "cs"); if (absolutePath == "") { // Dialog was cancelled return; } if (!absolutePath.ToLower().EndsWith(".cs")) { absolutePath += ".cs"; } var className = Path.GetFileNameWithoutExtension(absolutePath); File.WriteAllText(absolutePath, templateStr.Replace("CLASS_NAME", className)); AssetDatabase.Refresh(); var assetPath = ZenUnityEditorUtil.ConvertFullAbsolutePathToAssetPath(absolutePath); EditorUtility.FocusProjectWindow(); Selection.activeObject = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(assetPath); } [MenuItem("Edit/Zenject/Validate All Active Scenes #%v")] public static void ValidateAllActiveScenes() { ValidateWrapper(() => { var numValidated = ZenUnityEditorUtil.ValidateAllActiveScenes(); Log.Info("Validated all '{0}' active scenes successfully", numValidated); }); } static bool ValidateWrapper(Action action) { if (EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo()) { var originalSceneSetup = EditorSceneManager.GetSceneManagerSetup(); try { action(); return true; } catch (Exception e) { Log.ErrorException(e); return false; } finally { EditorSceneManager.RestoreSceneManagerSetup(originalSceneSetup); } } else { Debug.Log("Validation cancelled - All scenes must be saved first for validation to take place"); return false; } } static bool ValidateCurrentSceneInternal() { return ValidateWrapper(() => { ZenUnityEditorUtil.ValidateCurrentSceneSetup(); Log.Info("All scenes validated successfully"); }); } } } #endif
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; using System.Runtime.InteropServices; // ERROR: Not supported in C#: OptionDeclaration using Microsoft.Win32; namespace _4PosBackOffice.NET { static class modUtilities { public const int REG_SZ = 1; public const int REG_DWORD = 4; public const int HKEY_CLASSES_ROOT = 0x80000000; public const int HKEY_CURRENT_USER = 0x80000001; public const int HKEY_LOCAL_MACHINE = 0x80000002; public const int HKEY_USERS = 0x80000003; public const short ERROR_NONE = 0; public const short ERROR_BADDB = 1; public const short ERROR_BADKEY = 2; public const short ERROR_CANTOPEN = 3; public const short ERROR_CANTREAD = 4; public const short ERROR_CANTWRITE = 5; public const short ERROR_OUTOFMEMORY = 6; public const short ERROR_ARENA_TRASHED = 7; public const short ERROR_ACCESS_DENIED = 8; public const short ERROR_INVALID_PARAMETERS = 87; public const short ERROR_NO_MORE_ITEMS = 259; public const int KEY_QUERY_VALUE = 0x1; public const int KEY_SET_VALUE = 0x2; public const int KEY_ALL_ACCESS = 0x3f; public const short REG_OPTION_NON_VOLATILE = 0; [DllImport("advapi32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] public static extern int RegCloseKey(int hkey); [DllImport("advapi32.dll", EntryPoint = "RegCreateKeyExA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] public static extern int RegCreateKeyEx(int hkey, string lpSubKey, int Reserved, string lpClass, int dwOptions, int samDesired, int lpSecurityAttributes, ref int phkResult, ref int lpdwDisposition); [DllImport("advapi32.dll", EntryPoint = "RegOpenKeyExA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] public static extern int RegOpenKeyEx(int hkey, string lpSubKey, int ulOptions, int samDesired, ref int phkResult); [DllImport("advapi32.dll", EntryPoint = "RegQueryValueExA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] public static extern int RegQueryValueExString(int hkey, string lpValueName, int lpReserved, ref int lpType, string lpData, ref int lpcbData); [DllImport("advapi32.dll", EntryPoint = "RegQueryValueExA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] public static extern int RegQueryValueExLong(int hkey, string lpValueName, int lpReserved, ref int lpType, ref int lpData, ref int lpcbData); [DllImport("advapi32.dll", EntryPoint = "RegQueryValueExA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] public static extern int RegQueryValueExNULL(int hkey, string lpValueName, int lpReserved, ref int lpType, int lpData, ref int lpcbData); [DllImport("advapi32.dll", EntryPoint = "RegSetValueExA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] public static extern int RegSetValueExString(int hkey, string lpValueName, int Reserved, int dwType, string lpValue, int cbData); [DllImport("advapi32.dll", EntryPoint = "RegSetValueExA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] public static extern int RegSetValueExLong(int hkey, string lpValueName, int Reserved, int dwType, ref int lpValue, int cbData); [DllImport("user32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] public static extern int SetForegroundWindow(int hwnd); [DllImport("user32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] private static extern int BringWindowToTop(int hwnd); [DllImport("user32", EntryPoint = "FindWindowA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] private static extern int FindWindow(object lpClassName, object lpWindowName); private const int LOCALE_SSHORTDATE = 0x1f; private const int WM_SETTINGCHANGE = 0x1a; private const int HWND_BROADCAST = 0xffff; [DllImport("kernel32", EntryPoint = "SetLocaleInfoA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] private static extern bool SetLocaleInfo(int Locale, int LCType, string lpLCData); [DllImport("user32", EntryPoint = "PostMessageA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] private static extern int PostMessage(int hwnd, int wMsg, int wParam, int lParam); [DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] private static extern int GetSystemDefaultLCID(); public static void setShortDateFormat() { int dwLCID = 0; dwLCID = GetSystemDefaultLCID(); if (SetLocaleInfo(dwLCID, LOCALE_SSHORTDATE, "yyyy/MM/dd") == false) { Interaction.MsgBox("Failed"); return; } PostMessage(HWND_BROADCAST, WM_SETTINGCHANGE, 0, 0); } public static void setApplicationFocus(ref string title) { int iret = 0; int lHandle = 0; lHandle = FindWindow(VariantType.Empty, title); if (lHandle == 0) { } else { iret = BringWindowToTop(lHandle); } } public static int SetValueEx(int hkey, ref string sValueName, ref int ltype, ref int vValue) { int functionReturnValue = 0; int lValue = 0; string sValue = null; switch (ltype) { case REG_SZ: sValue = vValue + Strings.Chr(0); functionReturnValue = RegSetValueExString(hkey, sValueName, 0, ltype, sValue, Strings.Len(sValue)); break; case REG_DWORD: lValue = vValue; functionReturnValue = RegSetValueExLong(hkey, sValueName, 0, ltype, ref lValue, 4); break; } return functionReturnValue; } public static int QueryValueEx(int lhKey, string szValueName, ref object vValue) { int functionReturnValue = 0; int cch = 0; int lrc = 0; int ltype = 0; int lValue = 0; string sValue = null; RegistryKey rkey = null; // ERROR: Not supported in C#: OnErrorStatement // Determine the size and type of data to be read rkey = Registry.LocalMachine.OpenSubKey(szValueName, true); lrc = RegQueryValueExNULL(lhKey, szValueName, 0, ref ltype, 0, ref cch); if (lrc != ERROR_NONE) // ERROR: Not supported in C#: ErrorStatement switch (ltype) { // For strings case REG_SZ: sValue = new string(Strings.Chr(0), cch); lrc = RegQueryValueExString(lhKey, szValueName, 0, ref ltype, sValue, ref cch); if (lrc == ERROR_NONE) { vValue = Strings.Left(sValue, cch - 1); } else { vValue = null; } break; // For DWORDS case REG_DWORD: lrc = RegQueryValueExLong(lhKey, szValueName, 0, ref ltype, ref lValue, ref cch); if (lrc == ERROR_NONE) vValue = lValue; break; default: //all other data types not supported lrc = -1; break; } QueryValueExExit: functionReturnValue = lrc; return functionReturnValue; QueryValueExError: // ERROR: Not supported in C#: ResumeStatement return functionReturnValue; } public static void MyGotFocus(ref object lControl) { short x = 0; if (lControl.Alignment == 1) { for (x = 1; x <= 10; x++) { if (Strings.Left(lControl.Text, 1) == "0") { lControl.Text = Strings.Mid(lControl.Text, 2); } if (string.IsNullOrEmpty(lControl.Text)) lControl.Text = "0"; } } lControl.SelStart = 0; lControl.SelLength = Strings.Len(lControl.Text); } public static void MyGotFocusNumeric(ref object lControl) { short x = 0; lControl.Text = Strings.Replace(lControl.Text, ",", ""); lControl.Text = Strings.Replace(lControl.Text, ".", ""); if (lControl.Alignment == 1) { for (x = 1; x <= 10; x++) { if (Strings.Left(lControl.Text, 1) == "0") { lControl.Text = Strings.Mid(lControl.Text, 2); } if (string.IsNullOrEmpty(lControl.Text)) lControl.Text = "0"; } } lControl.SelStart = 0; lControl.SelLength = Strings.Len(lControl.Text); } public static void MyGotFocusNumericMEAT(ref object lControl) { short x = 0; lControl.Text = Strings.Replace(lControl.Text, ",", ""); //lControl.Text = Replace(lControl.Text, ".", "") //If lControl.Alignment = 1 Then // For x = 1 To 10 // If Left(lControl.Text, 1) = "0" Then // lControl.Text = Mid(lControl.Text, 2) // End If if (string.IsNullOrEmpty(lControl.Text)) lControl.Text = "0"; // Next //End If lControl.SelStart = 0; lControl.SelLength = Strings.Len(lControl.Text); } public static void MyGotFocusNumericNew(ref object lControl) { short x = 0; lControl.Text = Strings.Replace(lControl.Text, ",", ""); if (string.IsNullOrEmpty(lControl.Text)) lControl.Text = "0"; lControl.SelStart = 0; lControl.SelLength = Strings.Len(lControl.Text); } public static void MyKeyPress(ref short KeyAscii) { switch (KeyAscii) { case Strings.Asc(Constants.vbCr): KeyAscii = 0; break; case 8: case 46: break; case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: break; default: KeyAscii = 0; break; } } public static void MyKeyPressInt(ref short KeyAscii) { switch (KeyAscii) { case Strings.Asc(Constants.vbCr): KeyAscii = 0; break; case 8: break; case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: break; default: KeyAscii = 0; break; } } public static void MyKeyPressNegative(ref object lControl, ref short KeyAscii) { object lCurrentX = null; switch (KeyAscii) { case 45: //- if (Strings.InStr(lControl.Text, "-")) { } else { lCurrentX = lControl.SelStart + 1; lControl.Text = "-" + lControl.Text; lControl.SelStart = lCurrentX; } KeyAscii = 0; break; case 43: //+ if (Strings.InStr(lControl.Text, "-")) { lCurrentX = lControl.SelStart - 1; lControl.Text = Strings.Right(lControl.Text, Strings.Len(lControl.Text) - 1); if (lCurrentX < 0) lCurrentX = 0; lControl.SelStart = lCurrentX; } KeyAscii = 0; break; case Strings.Asc(Constants.vbCr): KeyAscii = 0; break; case 8: case 46: break; case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: break; default: KeyAscii = 0; break; } } public static void MyLostFocus(ref TextBox lControl, ref decimal lDecimal) { if (string.IsNullOrEmpty(lControl.Text)) lControl.Text = 0; if (lDecimal) { lControl.Text = lControl.Text / 100; } lControl.Text = Strings.FormatNumber(lControl.Text, lDecimal); } public static void MyLostFocusNew(ref TextBox lControl, ref decimal lDecimal) { if (string.IsNullOrEmpty(lControl.Text)) lControl.Text = 0; lControl.Text = Strings.FormatNumber(lControl.Text, lDecimal); } //Public Sub ageCustomer(id As Long) // Dim rs As Recordset // Dim lAmount As Currency, current As Currency, days30 As Currency, days60 As Currency, days90 As Currency, days120 As Currency, days150 As Currency // // cnnDB.Execute "UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_Current = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" & id & ") AND ((Customer.Customer_Current) Is Null));" // cnnDB.Execute "UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_30Days = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" & id & ") AND ((Customer.Customer_30Days) Is Null));" // cnnDB.Execute "UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_60Days = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" & id & ") AND ((Customer.Customer_60Days) Is Null));" // cnnDB.Execute "UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_90Days = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" & id & ") AND ((Customer.Customer_90Days) Is Null));" // cnnDB.Execute "UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_120Days = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" & id & ") AND ((Customer.Customer_120Days) Is Null));" // cnnDB.Execute "UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_150Days = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" & id & ") AND ((Customer.Customer_150Days) Is Null));" // // Set rs = getRS("SELECT CustomerTransaction.CustomerTransaction_CustomerID, CustomerTransaction.CustomerTransaction_Amount, Customer.Customer_Current, Customer.Customer_30Days, Customer.Customer_60Days, Customer.Customer_90Days, Customer.Customer_120Days, Customer.Customer_150Days FROM Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID Where (((CustomerTransaction.CustomerTransaction_ReferenceID) = " & id & "));") // // Do While rs.EOF = False // amount = amount + rs("CustomerTransaction_Amount") // rs.MoveNext // Loop // // If rs.RecordCount Then // // 'Do While rs.EOF = False // // 'amount = rs("CustomerTransaction_Amount") // rs.MoveFirst // current = rs("Customer_Current") // days30 = rs("Customer_30Days") // days60 = rs("Customer_60Days") // days90 = rs("Customer_90Days") // days120 = rs("Customer_120Days") // days150 = rs("Customer_150Days") // If amount < 0 Then // days150 = days150 + amount // If (days150 < 0) Then // amount = days150 // days150 = 0 // Else // amount = 0 // End If // days120 = days120 + amount // If (days120 < 0) Then // amount = days120 // days120 = 0 // Else // amount = 0 // End If // days90 = days90 + amount // If (days90 < 0) Then // amount = days90 // days90 = 0 // Else // amount = 0 // End If // days60 = days60 + amount // If (days60 < 0) Then // amount = days60 // days60 = 0 // Else // amount = 0 // End If // days30 = days30 + amount // If (days30 < 0) Then // amount = days30 // days30 = 0 // Else // amount = 0 // End If // End If // current = current + amount // cnnDB.Execute "UPDATE Customer SET Customer.Customer_Current = " & current & ", Customer.Customer_30Days = " & days30 & ", Customer.Customer_60Days = " & days60 & ", Customer.Customer_90Days = " & days90 & ", Customer.Customer_120Days = " & days120 & ", Customer.Customer_150Days = 0" & days150 & " WHERE (((Customer.CustomerID)=" & rs("CustomerTransaction_CustomerID") & "));" // 'rs.MoveNext // 'Loop // End If //End Sub } }
// 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 AndNotSByte() { var test = new SimpleBinaryOpTest__AndNotSByte(); 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 works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } 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__AndNotSByte { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(SByte); private const int Op2ElementCount = VectorSize / sizeof(SByte); private const int RetElementCount = VectorSize / sizeof(SByte); private static SByte[] _data1 = new SByte[Op1ElementCount]; private static SByte[] _data2 = new SByte[Op2ElementCount]; private static Vector128<SByte> _clsVar1; private static Vector128<SByte> _clsVar2; private Vector128<SByte> _fld1; private Vector128<SByte> _fld2; private SimpleBinaryOpTest__DataTable<SByte, SByte, SByte> _dataTable; static SimpleBinaryOpTest__AndNotSByte() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__AndNotSByte() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<SByte, SByte, SByte>(_data1, _data2, new SByte[RetElementCount], VectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse2.AndNot( Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse2.AndNot( Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse2.AndNot( Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse2.AndNot( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr); var result = Sse2.AndNot(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr)); var result = Sse2.AndNot(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr)); var result = Sse2.AndNot(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__AndNotSByte(); var result = Sse2.AndNot(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse2.AndNot(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<SByte> left, Vector128<SByte> right, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "") { if ((sbyte)(~left[0] & right[0]) != result[0]) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((sbyte)(~left[i] & right[i]) != result[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.AndNot)}<SByte>(Vector128<SByte>, Vector128<SByte>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /*============================================================ ** ** ** ** ** ** Purpose: Exposes routines for enumerating through a ** directory. ** ** April 11,2000 ** ===========================================================*/ using System; using System.Collections; using System.Collections.Generic; using System.Security; #if FEATURE_MACL using System.Security.AccessControl; #endif using System.Security.Permissions; using Microsoft.Win32; using System.Text; using System.Runtime.InteropServices; using System.Globalization; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Diagnostics.Contracts; namespace System.IO { [Serializable] [ComVisible(true)] public sealed class DirectoryInfo : FileSystemInfo { private String[] demandDir; #if FEATURE_CORECLR // Migrating InheritanceDemands requires this default ctor, so we can annotate it. #if FEATURE_CORESYSTEM [System.Security.SecurityCritical] #else [System.Security.SecuritySafeCritical] #endif //FEATURE_CORESYSTEM private DirectoryInfo(){} [System.Security.SecurityCritical] public static DirectoryInfo UnsafeCreateDirectoryInfo(String path) { if (path == null) throw new ArgumentNullException("path"); Contract.EndContractBlock(); DirectoryInfo di = new DirectoryInfo(); di.Init(path, false); return di; } #endif [System.Security.SecuritySafeCritical] public DirectoryInfo(String path) { if (path==null) throw new ArgumentNullException("path"); Contract.EndContractBlock(); Init(path, true); } [System.Security.SecurityCritical] private void Init(String path, bool checkHost) { // Special case "<DriveLetter>:" to point to "<CurrentDirectory>" instead if ((path.Length == 2) && (path[1] == ':')) { OriginalPath = "."; } else { OriginalPath = path; } // Must fully qualify the path for the security check String fullPath = Path.GetFullPathInternal(path); demandDir = new String[] {Directory.GetDemandDir(fullPath, true)}; #if FEATURE_CORECLR if (checkHost) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, OriginalPath, fullPath); state.EnsureState(); } #else new FileIOPermission(FileIOPermissionAccess.Read, demandDir, false, false ).Demand(); #endif FullPath = fullPath; DisplayPath = GetDisplayName(OriginalPath, FullPath); } #if FEATURE_CORESYSTEM [System.Security.SecuritySafeCritical] #endif //FEATURE_CORESYSTEM internal DirectoryInfo(String fullPath, bool junk) { Contract.Assert(Path.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); demandDir = new String[] {Directory.GetDemandDir(fullPath, true)}; } [System.Security.SecurityCritical] // auto-generated private DirectoryInfo(SerializationInfo info, StreamingContext context) : base(info, context) { #if !FEATURE_CORECLR demandDir = new String[] {Directory.GetDemandDir(FullPath, true)}; new FileIOPermission(FileIOPermissionAccess.Read, demandDir, false, false ).Demand(); #endif DisplayPath = GetDisplayName(OriginalPath, FullPath); } public override String Name { get { #if FEATURE_CORECLR // DisplayPath is dir name for coreclr return DisplayPath; #else // Return just dir name return GetDirName(FullPath); #endif } } 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.EndsWith(Path.DirectorySeparatorChar)) s = FullPath.Substring(0, FullPath.Length - 1); parentName = Path.GetDirectoryName(s); if (parentName==null) return null; DirectoryInfo dir = new DirectoryInfo(parentName,false); #if FEATURE_CORECLR FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.PathDiscovery | FileSecurityStateAccess.Read, String.Empty, dir.demandDir[0]); state.EnsureState(); #else new FileIOPermission(FileIOPermissionAccess.PathDiscovery | FileIOPermissionAccess.Read, dir.demandDir, false, false).Demand(); #endif return dir; } } #if FEATURE_CORECLR [System.Security.SecuritySafeCritical] #endif public DirectoryInfo CreateSubdirectory(String path) { if (path == null) throw new ArgumentNullException("path"); Contract.EndContractBlock(); return CreateSubdirectory(path, null); } #if FEATURE_MACL [System.Security.SecuritySafeCritical] // auto-generated public DirectoryInfo CreateSubdirectory(String path, DirectorySecurity directorySecurity) { return CreateSubdirectoryHelper(path, directorySecurity); } #else // FEATURE_MACL #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif public DirectoryInfo CreateSubdirectory(String path, Object directorySecurity) { if (path == null) throw new ArgumentNullException("path"); Contract.EndContractBlock(); return CreateSubdirectoryHelper(path, directorySecurity); } #endif // FEATURE_MACL [System.Security.SecurityCritical] // auto-generated private DirectoryInfo CreateSubdirectoryHelper(String path, Object directorySecurity) { Contract.Requires(path != null); String newDirs = Path.InternalCombine(FullPath, path); String fullPath = Path.GetFullPathInternal(newDirs); if (0!=String.Compare(FullPath,0,fullPath,0, FullPath.Length,StringComparison.OrdinalIgnoreCase)) { String displayPath = __Error.GetDisplayablePath(DisplayPath, false); throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSubPath", path, displayPath)); } // Ensure we have permission to create this subdirectory. String demandDirForCreation = Directory.GetDemandDir(fullPath, true); #if FEATURE_CORECLR FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, OriginalPath, demandDirForCreation); state.EnsureState(); #else new FileIOPermission(FileIOPermissionAccess.Write, new String[] { demandDirForCreation }, false, false).Demand(); #endif Directory.InternalCreateDirectory(fullPath, path, directorySecurity); // Check for read permission to directory we hand back by calling this constructor. return new DirectoryInfo(fullPath); } public void Create() { Directory.InternalCreateDirectory(FullPath, OriginalPath, null, true); } #if FEATURE_MACL public void Create(DirectorySecurity directorySecurity) { Directory.InternalCreateDirectory(FullPath, OriginalPath, directorySecurity, true); } #endif // 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 { if (_dataInitialised == -1) Refresh(); if (_dataInitialised != 0) // Refresh was unable to initialise the data return false; return _data.fileAttributes != -1 && (_data.fileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY) != 0; } catch { return false; } } } #if FEATURE_MACL public DirectorySecurity GetAccessControl() { return Directory.GetAccessControl(FullPath, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group); } public DirectorySecurity GetAccessControl(AccessControlSections includeSections) { return Directory.GetAccessControl(FullPath, includeSections); } public void SetAccessControl(DirectorySecurity directorySecurity) { Directory.SetAccessControl(FullPath, directorySecurity); } #endif // Returns an array of Files in the current DirectoryInfo matching the // given search criteria (ie, "*.txt"). 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", Environment.GetResourceString("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 = FileSystemEnumerableFactory.CreateFileInfoIterator(FullPath, OriginalPath, searchPattern, searchOption); 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", Environment.GetResourceString("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> enble = FileSystemEnumerableFactory.CreateFileSystemInfoIterator(FullPath, OriginalPath, searchPattern, searchOption); List<FileSystemInfo> fileList = new List<FileSystemInfo>(enble); 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", Environment.GetResourceString("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> enble = FileSystemEnumerableFactory.CreateDirectoryInfoIterator(FullPath, OriginalPath, searchPattern, searchOption); List<DirectoryInfo> fileList = new List<DirectoryInfo>(enble); 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", Environment.GetResourceString("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 FileSystemEnumerableFactory.CreateDirectoryInfoIterator(FullPath, OriginalPath, searchPattern, searchOption); } 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", Environment.GetResourceString("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 FileSystemEnumerableFactory.CreateFileInfoIterator(FullPath, OriginalPath, searchPattern, searchOption); } 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", Environment.GetResourceString("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 FileSystemEnumerableFactory.CreateFileSystemInfoIterator(FullPath, OriginalPath, searchPattern, searchOption); } // 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 demandPath; int rootLength = Path.GetRootLength(FullPath); String rootPath = FullPath.Substring(0, rootLength); demandPath = Directory.GetDemandDir(rootPath, true); #if FEATURE_CORECLR FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, demandPath); sourceState.EnsureState(); #else new FileIOPermission(FileIOPermissionAccess.PathDiscovery, new String[] { demandPath }, false, false).Demand(); #endif 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(Environment.GetResourceString("Argument_EmptyFileName"), "destDirName"); Contract.EndContractBlock(); #if FEATURE_CORECLR FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Write | FileSecurityStateAccess.Read, DisplayPath, Directory.GetDemandDir(FullPath, true)); sourceState.EnsureState(); #else new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, demandDir, false, false).Demand(); #endif String fullDestDirName = Path.GetFullPathInternal(destDirName); String demandPath; if (!fullDestDirName.EndsWith(Path.DirectorySeparatorChar)) fullDestDirName = fullDestDirName + Path.DirectorySeparatorChar; demandPath = fullDestDirName + '.'; // Demand read & write permission to destination. The reason is // we hand back a DirectoryInfo to the destination that would allow // you to read a directory listing from that directory. Sure, you // had the ability to read the file contents in the old location, // but you technically also need read permissions to the new // location as well, and write is not a true superset of read. #if FEATURE_CORECLR FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destDirName, demandPath); destState.EnsureState(); #else new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, demandPath).Demand(); #endif String fullSourcePath; if (FullPath.EndsWith(Path.DirectorySeparatorChar)) fullSourcePath = FullPath; else fullSourcePath = FullPath + Path.DirectorySeparatorChar; if (String.Compare(fullSourcePath, fullDestDirName, StringComparison.OrdinalIgnoreCase) == 0) throw new IOException(Environment.GetResourceString("IO.IO_SourceDestMustBeDifferent")); String sourceRoot = Path.GetPathRoot(fullSourcePath); String destinationRoot = Path.GetPathRoot(fullDestDirName); if (String.Compare(sourceRoot, destinationRoot, StringComparison.OrdinalIgnoreCase) != 0) throw new IOException(Environment.GetResourceString("IO.IO_SourceDestMustHaveSameRoot")); if (!Win32Native.MoveFile(FullPath, destDirName)) { int hr = Marshal.GetLastWin32Error(); if (hr == Win32Native.ERROR_FILE_NOT_FOUND) // A dubious error code { hr = Win32Native.ERROR_PATH_NOT_FOUND; __Error.WinIOError(hr, DisplayPath); } if (hr == Win32Native.ERROR_ACCESS_DENIED) // We did this for Win9x. We can't change it for backcomp. throw new IOException(Environment.GetResourceString("UnauthorizedAccess_IODenied_Path", DisplayPath)); __Error.WinIOError(hr,String.Empty); } FullPath = fullDestDirName; OriginalPath = destDirName; DisplayPath = GetDisplayName(OriginalPath, FullPath); demandDir = new String[] { Directory.GetDemandDir(FullPath, true) }; // Flush any cached information about the directory. _dataInitialised = -1; } [System.Security.SecuritySafeCritical] public override void Delete() { Directory.Delete(FullPath, OriginalPath, false, true); } [System.Security.SecuritySafeCritical] public void Delete(bool recursive) { Directory.Delete(FullPath, OriginalPath, recursive, true); } // Returns the fully qualified path public override String ToString() { return DisplayPath; } private static String GetDisplayName(String originalPath, String fullPath) { Contract.Assert(originalPath != null); Contract.Assert(fullPath != null); String displayName = ""; // Special case "<DriveLetter>:" to point to "<CurrentDirectory>" instead if ((originalPath.Length == 2) && (originalPath[1] == ':')) { displayName = "."; } else { #if FEATURE_CORECLR displayName = GetDirName(fullPath); #else displayName = originalPath; #endif } return displayName; } private static String GetDirName(String fullPath) { Contract.Assert(fullPath != null); String dirName = null; if (fullPath.Length > 3) { String s = fullPath; if (fullPath.EndsWith(Path.DirectorySeparatorChar)) { s = fullPath.Substring(0, fullPath.Length - 1); } dirName = Path.GetFileName(s); } else { dirName = fullPath; // For rooted paths, like "c:\" } return dirName; } } }
// // RecipePrintPageRenderer.cs // // Author: Jeffrey Stedfast <jeff@xamarin.com> // // Copyright (c) 2011 Xamarin Inc. // // 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 CoreGraphics; using System.Collections; using System.Collections.Generic; using Foundation; using UIKit; using CoreFoundation; namespace RecipesAndPrinting { public class RecipePrintPageRenderer : UIPrintPageRenderer { const float RecipeInfoHeight = 150.0f; const float TitleSize = 24.0f; const float Padding = 10.0f; static UIFont SystemFont = UIFont.SystemFontOfSize (UIFont.SystemFontSize); Dictionary<UIPrintFormatter, Recipe> recipeFormatterMap = new Dictionary<UIPrintFormatter, Recipe> (); NSRange pageRange; Recipe[] recipes; public RecipePrintPageRenderer (Recipe[] recipes) { this.HeaderHeight = 20.0f; this.FooterHeight = 20.0f; this.recipes = recipes; } // Calculate the content area based on the printableRect, that is, the area in which // the printer can print content. a.k.a the imageable area of the paper. CGRect ContentArea { get { CGRect r = PrintableRect; r.Height -= HeaderHeight + FooterHeight; r.Y += HeaderHeight; return r; } } public override void PrepareForDrawingPages (NSRange range) { base.PrepareForDrawingPages (range); pageRange = range; } // This property must be overriden when doing custom drawing as we are. // Since our custom drawing is really only for the borders and we are // relying on a series of UIMarkupTextPrintFormatters to display the recipe // content, UIKit can calculate the number of pages based on informtation // provided by those formatters. // // Therefore, setup the formatters, and ask super to count the pages. // HACK: Changed overridden member int to nint public override nint NumberOfPages { get { SetupPrintFormatters (); return base.NumberOfPages; } } // Iterate through the recipes setting each of their html representations into // a UIMarkupTextPrintFormatter and add that formatter to the printing job. void SetupPrintFormatters () { CGRect contentArea = ContentArea; nfloat previousFormatterMaxY = contentArea.Top; nint page = 0; foreach (Recipe recipe in recipes) { string html = recipe.HtmlRepresentation; // ios9 calls NumberOfPages -> SetupPrintFormatters not from main thread, but UIMarkupTextPrintFormatter is UIKit class (must be accessed from main thread) DispatchQueue.MainQueue.DispatchSync (() => { var formatter = new UIMarkupTextPrintFormatter (html); recipeFormatterMap.Add (formatter, recipe); // Make room for the recipe info UIEdgeInsets contentInsets = UIEdgeInsets.Zero; contentInsets.Top = previousFormatterMaxY + RecipeInfoHeight; if (contentInsets.Top > contentArea.Bottom) { // Move to the next page contentInsets.Top = contentArea.Top + RecipeInfoHeight; page++; } formatter.ContentInsets = contentInsets; // Add the formatter to the renderer at the specified page AddPrintFormatter (formatter, page); page = formatter.StartPage + formatter.PageCount - 1; previousFormatterMaxY = formatter.RectangleForPage (page).Bottom; }); } } // Custom UIPrintPageRenderer's may override this class to draw a custom print page header. // To illustrate that, this class sets the date in the header. public override void DrawHeaderForPage (nint index, CGRect headerRect) { NSDateFormatter dateFormatter = new NSDateFormatter (); dateFormatter.DateFormat = "MMMM d, yyyy 'at' h:mm a"; NSString dateString = new NSString (dateFormatter.ToString (NSDate.Now)); dateFormatter.Dispose (); dateString.DrawString (headerRect, SystemFont, UILineBreakMode.Clip, UITextAlignment.Right); dateString.Dispose (); } public override void DrawFooterForPage (nint index, CGRect footerRect) { NSString footer = new NSString (string.Format ("Page {0} of {1}", index - pageRange.Location + 1, pageRange.Length)); footer.DrawString (footerRect, SystemFont, UILineBreakMode.Clip, UITextAlignment.Center); footer.Dispose (); } // To intermix custom drawing with the drawing performed by an associated print formatter, // this method is called for each print formatter associated with a given page. // // We do this to intermix/overlay our custom drawing onto the recipe presentation. // We draw the upper portion of the recipe presentation by hand (image, title, desc), // and the bottom portion is drawn via the UIMarkupTextPrintFormatter. public override void DrawPrintFormatterForPage (UIPrintFormatter printFormatter, nint page) { base.DrawPrintFormatterForPage (printFormatter, page); // To keep our custom drawing in sync with the printFormatter, base our drawing // on the formatters rect. CGRect rect = printFormatter.RectangleForPage (page); // Use a bezier path to draw the borders. // We may potentially choose not to draw either the top or bottom line // of the border depending on whether our recipe extended from the previous // page, or carries onto the subsequent page. UIBezierPath border = new UIBezierPath (); if (page == printFormatter.StartPage) { // For border drawing, get the rect that includes the formatter area plus the header area. // Move the formatter's rect up the size of the custom drawn recipe presentation // and essentially grow the rect's height by this amount. rect.Height += RecipeInfoHeight; rect.Y -= RecipeInfoHeight; border.MoveTo (rect.Location); border.AddLineTo (new CGPoint (rect.Right, rect.Top)); Recipe recipe = recipeFormatterMap[printFormatter]; // Run custom code to draw upper portion of the recipe presentation (image, title, desc) DrawRecipe (recipe, rect); } // Draw the left border border.MoveTo (rect.Location); border.AddLineTo (new CGPoint (rect.Left, rect.Bottom)); // Draw the right border border.MoveTo (new CGPoint (rect.Right, rect.Top)); border.AddLineTo (new CGPoint (rect.Right, rect.Bottom)); if (page == printFormatter.StartPage + printFormatter.PageCount - 1) border.AddLineTo (new CGPoint (rect.Left, rect.Bottom)); // Set the UIColor to be used by the current graphics context, and then stroke // stroke the current path that is defined by the border bezier path. UIColor.Black.SetColor (); border.Stroke (); } // Custom code to draw upper portion of the recipe presentation (image, title, desc). // The argument rect is the full size of the recipe presentation. void DrawRecipe (Recipe recipe, CGRect rect) { DrawRecipeImage (recipe.Image, rect); DrawRecipeName (recipe.Name, rect); DrawRecipeInfo (recipe.AggregatedInfo, rect); } void DrawRecipeImage (UIImage image, CGRect rect) { // Create a new rect based on the size of the header area CGRect imageRect = CGRect.Empty; // Scale the image to fit in the infoRect float maxImageDimension = RecipeInfoHeight - Padding * 2; // HACK: Change float to nfloat nfloat largestImageDimension = (nfloat)Math.Max (image.Size.Width, image.Size.Height); nfloat scale = maxImageDimension / largestImageDimension; imageRect.Size = new CGSize (image.Size.Width * scale, image.Size.Height * scale); // Place the image rect at the x,y defined by the argument rect imageRect.Location = new CGPoint (rect.Left + Padding, rect.Top + Padding); // Ask the image to draw in the image rect image.Draw (imageRect); } // Custom drawing code to put the recipe name in the title section of the recipe presentation's header. void DrawRecipeName (string name, CGRect rect) { CGRect nameRect = CGRect.Empty; nameRect.X = rect.Left + RecipeInfoHeight; nameRect.Y = rect.Top + Padding; nameRect.Width = rect.Width - RecipeInfoHeight; nameRect.Height = RecipeInfoHeight; using (UIFont font = UIFont.BoldSystemFontOfSize (TitleSize)) { using (NSString str = new NSString (name)) { str.DrawString (nameRect, font, UILineBreakMode.Clip, UITextAlignment.Left); } } } // Custom drawing code to put the recipe recipe description, and prep time // in the title section of the recipe presentation's header. void DrawRecipeInfo (string info, CGRect rect) { CGRect infoRect = CGRect.Empty; infoRect.X = rect.Left + RecipeInfoHeight; infoRect.Y = rect.Top + TitleSize * 2; infoRect.Width = rect.Width - RecipeInfoHeight; infoRect.Height = RecipeInfoHeight - TitleSize * 2; UIColor.DarkGray.SetColor (); using (NSString str = new NSString (info)) { str.DrawString (infoRect, SystemFont, UILineBreakMode.Clip, UITextAlignment.Left); } } } }
// DeflaterEngine.cs // // Copyright (C) 2001 Mike Krueger // Copyright (C) 2004 John Reilly // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 2001 Free Software Foundation, Inc. // // 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. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. // ************************************************************************* // // Name: DeflaterEngine.cs // // Created: 19-02-2008 SharedCache.com, rschuetz // Modified: 19-02-2008 SharedCache.com, rschuetz : Creation // ************************************************************************* using System; using SharedCache.WinServiceCommon.SharpZipLib.Checksum; namespace SharedCache.WinServiceCommon.SharpZipLib.Zip.Compression { /// <summary> /// Strategies for deflater /// </summary> public enum DeflateStrategy { /// <summary> /// The default strategy /// </summary> Default = 0, /// <summary> /// This strategy will only allow longer string repetitions. It is /// useful for random data with a small character set. /// </summary> Filtered = 1, /// <summary> /// This strategy will not look for string repetitions at all. It /// only encodes with Huffman trees (which means, that more common /// characters get a smaller encoding. /// </summary> HuffmanOnly = 2 } // DEFLATE ALGORITHM: // // The uncompressed stream is inserted into the window array. When // the window array is full the first half is thrown away and the // second half is copied to the beginning. // // The head array is a hash table. Three characters build a hash value // and they the value points to the corresponding index in window of // the last string with this hash. The prev array implements a // linked list of matches with the same hash: prev[index & WMASK] points // to the previous index with the same hash. // /// <summary> /// Low level compression engine for deflate algorithm which uses a 32K sliding window /// with secondary compression from Huffman/Shannon-Fano codes. /// </summary> public class DeflaterEngine : DeflaterConstants { #region Constants const int TooFar = 4096; #endregion #region Constructors /// <summary> /// Construct instance with pending buffer /// </summary> /// <param name="pending"> /// Pending buffer to use /// </param>> public DeflaterEngine(DeflaterPending pending) { this.pending = pending; huffman = new DeflaterHuffman(pending); adler = new Adler32(); window = new byte[2 * WSIZE]; head = new short[HASH_SIZE]; prev = new short[WSIZE]; // We start at index 1, to avoid an implementation deficiency, that // we cannot build a repeat pattern at index 0. blockStart = strstart = 1; } #endregion /// <summary> /// Deflate drives actual compression of data /// </summary> /// <param name="flush">True to flush input buffers</param> /// <param name="finish">Finish deflation with the current input.</param> /// <returns>Returns true if progress has been made.</returns> public bool Deflate(bool flush, bool finish) { bool progress; do { FillWindow(); bool canFlush = flush && (inputOff == inputEnd); #if DebugDeflation if (DeflaterConstants.DEBUGGING) { Console.WriteLine("window: [" + blockStart + "," + strstart + "," + lookahead + "], " + compressionFunction + "," + canFlush); } #endif switch (compressionFunction) { case DEFLATE_STORED: progress = DeflateStored(canFlush, finish); break; case DEFLATE_FAST: progress = DeflateFast(canFlush, finish); break; case DEFLATE_SLOW: progress = DeflateSlow(canFlush, finish); break; default: throw new InvalidOperationException("unknown compressionFunction"); } } while (pending.IsFlushed && progress); // repeat while we have no pending output and progress was made return progress; } /// <summary> /// Sets input data to be deflated. Should only be called when <code>NeedsInput()</code> /// returns true /// </summary> /// <param name="buffer">The buffer containing input data.</param> /// <param name="offset">The offset of the first byte of data.</param> /// <param name="count">The number of bytes of data to use as input.</param> public void SetInput(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset"); } if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if (inputOff < inputEnd) { throw new InvalidOperationException("Old input was not completely processed"); } int end = offset + count; /* We want to throw an ArrayIndexOutOfBoundsException early. The * check is very tricky: it also handles integer wrap around. */ if ((offset > end) || (end > buffer.Length)) { throw new ArgumentOutOfRangeException("count"); } inputBuf = buffer; inputOff = offset; inputEnd = end; } /// <summary> /// Determines if more <see cref="SetInput">input</see> is needed. /// </summary> /// <returns>Return true if input is needed via <see cref="SetInput">SetInput</see></returns> public bool NeedsInput() { return (inputEnd == inputOff); } /// <summary> /// Set compression dictionary /// </summary> /// <param name="buffer">The buffer containing the dictionary data</param> /// <param name="offset">The offset in the buffer for the first byte of data</param> /// <param name="length">The length of the dictionary data.</param> public void SetDictionary(byte[] buffer, int offset, int length) { #if DebugDeflation if (DeflaterConstants.DEBUGGING && (strstart != 1) ) { throw new InvalidOperationException("strstart not 1"); } #endif adler.Update(buffer, offset, length); if (length < MIN_MATCH) { return; } if (length > MAX_DIST) { offset += length - MAX_DIST; length = MAX_DIST; } System.Array.Copy(buffer, offset, window, strstart, length); UpdateHash(); --length; while (--length > 0) { InsertString(); strstart++; } strstart += 2; blockStart = strstart; } /// <summary> /// Reset internal state /// </summary> public void Reset() { huffman.Reset(); adler.Reset(); blockStart = strstart = 1; lookahead = 0; totalIn = 0; prevAvailable = false; matchLen = MIN_MATCH - 1; for (int i = 0; i < HASH_SIZE; i++) { head[i] = 0; } for (int i = 0; i < WSIZE; i++) { prev[i] = 0; } } /// <summary> /// Reset Adler checksum /// </summary> public void ResetAdler() { adler.Reset(); } /// <summary> /// Get current value of Adler checksum /// </summary> public int Adler { get { return unchecked((int)adler.Value); } } /// <summary> /// Total data processed /// </summary> public int TotalIn { get { return totalIn; } } /// <summary> /// Get/set the <see cref="DeflateStrategy">deflate strategy</see> /// </summary> public DeflateStrategy Strategy { get { return strategy; } set { strategy = value; } } /// <summary> /// Set the deflate level (0-9) /// </summary> /// <param name="level">The value to set the level to.</param> public void SetLevel(int level) { if ((level < 0) || (level > 9)) { throw new ArgumentOutOfRangeException("level"); } goodLength = DeflaterConstants.GOOD_LENGTH[level]; max_lazy = DeflaterConstants.MAX_LAZY[level]; niceLength = DeflaterConstants.NICE_LENGTH[level]; max_chain = DeflaterConstants.MAX_CHAIN[level]; if (DeflaterConstants.COMPR_FUNC[level] != compressionFunction) { #if DebugDeflation if (DeflaterConstants.DEBUGGING) { Console.WriteLine("Change from " + compressionFunction + " to " + DeflaterConstants.COMPR_FUNC[level]); } #endif switch (compressionFunction) { case DEFLATE_STORED: if (strstart > blockStart) { huffman.FlushStoredBlock(window, blockStart, strstart - blockStart, false); blockStart = strstart; } UpdateHash(); break; case DEFLATE_FAST: if (strstart > blockStart) { huffman.FlushBlock(window, blockStart, strstart - blockStart, false); blockStart = strstart; } break; case DEFLATE_SLOW: if (prevAvailable) { huffman.TallyLit(window[strstart - 1] & 0xff); } if (strstart > blockStart) { huffman.FlushBlock(window, blockStart, strstart - blockStart, false); blockStart = strstart; } prevAvailable = false; matchLen = MIN_MATCH - 1; break; } compressionFunction = COMPR_FUNC[level]; } } /// <summary> /// Fill the window /// </summary> public void FillWindow() { /* If the window is almost full and there is insufficient lookahead, * move the upper half to the lower one to make room in the upper half. */ if (strstart >= WSIZE + MAX_DIST) { SlideWindow(); } /* If there is not enough lookahead, but still some input left, * read in the input */ while (lookahead < DeflaterConstants.MIN_LOOKAHEAD && inputOff < inputEnd) { int more = 2 * WSIZE - lookahead - strstart; if (more > inputEnd - inputOff) { more = inputEnd - inputOff; } System.Array.Copy(inputBuf, inputOff, window, strstart + lookahead, more); adler.Update(inputBuf, inputOff, more); inputOff += more; totalIn += more; lookahead += more; } if (lookahead >= MIN_MATCH) { UpdateHash(); } } void UpdateHash() { /* if (DEBUGGING) { Console.WriteLine("updateHash: "+strstart); } */ ins_h = (window[strstart] << HASH_SHIFT) ^ window[strstart + 1]; } /// <summary> /// Inserts the current string in the head hash and returns the previous /// value for this hash. /// </summary> /// <returns>The previous hash value</returns> int InsertString() { short match; int hash = ((ins_h << HASH_SHIFT) ^ window[strstart + (MIN_MATCH - 1)]) & HASH_MASK; #if DebugDeflation if (DeflaterConstants.DEBUGGING) { if (hash != (((window[strstart] << (2*HASH_SHIFT)) ^ (window[strstart + 1] << HASH_SHIFT) ^ (window[strstart + 2])) & HASH_MASK)) { throw new SharpZipBaseException("hash inconsistent: " + hash + "/" +window[strstart] + "," +window[strstart + 1] + "," +window[strstart + 2] + "," + HASH_SHIFT); } } #endif prev[strstart & WMASK] = match = head[hash]; head[hash] = unchecked((short)strstart); ins_h = hash; return match & 0xffff; } void SlideWindow() { Array.Copy(window, WSIZE, window, 0, WSIZE); matchStart -= WSIZE; strstart -= WSIZE; blockStart -= WSIZE; // Slide the hash table (could be avoided with 32 bit values // at the expense of memory usage). for (int i = 0; i < HASH_SIZE; ++i) { int m = head[i] & 0xffff; head[i] = (short)(m >= WSIZE ? (m - WSIZE) : 0); } // Slide the prev table. for (int i = 0; i < WSIZE; i++) { int m = prev[i] & 0xffff; prev[i] = (short)(m >= WSIZE ? (m - WSIZE) : 0); } } /// <summary> /// Find the best (longest) string in the window matching the /// string starting at strstart. /// /// Preconditions: /// <code> /// strstart + MAX_MATCH &lt;= window.length.</code> /// </summary> /// <param name="curMatch"></param> /// <returns>True if a match greater than the minimum length is found</returns> bool FindLongestMatch(int curMatch) { int chainLength = this.max_chain; int niceLength = this.niceLength; short[] prev = this.prev; int scan = this.strstart; int match; int best_end = this.strstart + matchLen; int best_len = Math.Max(matchLen, MIN_MATCH - 1); int limit = Math.Max(strstart - MAX_DIST, 0); int strend = strstart + MAX_MATCH - 1; byte scan_end1 = window[best_end - 1]; byte scan_end = window[best_end]; // Do not waste too much time if we already have a good match: if (best_len >= this.goodLength) { chainLength >>= 2; } /* Do not look for matches beyond the end of the input. This is necessary * to make deflate deterministic. */ if (niceLength > lookahead) { niceLength = lookahead; } #if DebugDeflation if (DeflaterConstants.DEBUGGING && (strstart > 2 * WSIZE - MIN_LOOKAHEAD)) { throw new InvalidOperationException("need lookahead"); } #endif do { #if DebugDeflation if (DeflaterConstants.DEBUGGING && (curMatch >= strstart) ) { throw new InvalidOperationException("no future"); } #endif if (window[curMatch + best_len] != scan_end || window[curMatch + best_len - 1] != scan_end1 || window[curMatch] != window[scan] || window[curMatch + 1] != window[scan + 1]) { continue; } match = curMatch + 2; scan += 2; /* We check for insufficient lookahead only every 8th comparison; * the 256th check will be made at strstart + 258. */ while ( window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && (scan < strend)) { // Do nothing } if (scan > best_end) { #if DebugDeflation if (DeflaterConstants.DEBUGGING && (ins_h == 0) ) Console.Error.WriteLine("Found match: " + curMatch + "-" + (scan - strstart)); #endif matchStart = curMatch; best_end = scan; best_len = scan - strstart; if (best_len >= niceLength) { break; } scan_end1 = window[best_end - 1]; scan_end = window[best_end]; } scan = strstart; } while ((curMatch = (prev[curMatch & WMASK] & 0xffff)) > limit && --chainLength != 0); matchLen = Math.Min(best_len, lookahead); return matchLen >= MIN_MATCH; } bool DeflateStored(bool flush, bool finish) { if (!flush && (lookahead == 0)) { return false; } strstart += lookahead; lookahead = 0; int storedLength = strstart - blockStart; if ((storedLength >= DeflaterConstants.MAX_BLOCK_SIZE) || // Block is full (blockStart < WSIZE && storedLength >= MAX_DIST) || // Block may move out of window flush) { bool lastBlock = finish; if (storedLength > DeflaterConstants.MAX_BLOCK_SIZE) { storedLength = DeflaterConstants.MAX_BLOCK_SIZE; lastBlock = false; } #if DebugDeflation if (DeflaterConstants.DEBUGGING) { Console.WriteLine("storedBlock[" + storedLength + "," + lastBlock + "]"); } #endif huffman.FlushStoredBlock(window, blockStart, storedLength, lastBlock); blockStart += storedLength; return !lastBlock; } return true; } bool DeflateFast(bool flush, bool finish) { if (lookahead < MIN_LOOKAHEAD && !flush) { return false; } while (lookahead >= MIN_LOOKAHEAD || flush) { if (lookahead == 0) { // We are flushing everything huffman.FlushBlock(window, blockStart, strstart - blockStart, finish); blockStart = strstart; return false; } if (strstart > 2 * WSIZE - MIN_LOOKAHEAD) { /* slide window, as FindLongestMatch needs this. * This should only happen when flushing and the window * is almost full. */ SlideWindow(); } int hashHead; if (lookahead >= MIN_MATCH && (hashHead = InsertString()) != 0 && strategy != DeflateStrategy.HuffmanOnly && strstart - hashHead <= MAX_DIST && FindLongestMatch(hashHead)) { // longestMatch sets matchStart and matchLen #if DebugDeflation if (DeflaterConstants.DEBUGGING) { for (int i = 0 ; i < matchLen; i++) { if (window[strstart + i] != window[matchStart + i]) { throw new SharpZipBaseException("Match failure"); } } } #endif bool full = huffman.TallyDist(strstart - matchStart, matchLen); lookahead -= matchLen; if (matchLen <= max_lazy && lookahead >= MIN_MATCH) { while (--matchLen > 0) { ++strstart; InsertString(); } ++strstart; } else { strstart += matchLen; if (lookahead >= MIN_MATCH - 1) { UpdateHash(); } } matchLen = MIN_MATCH - 1; if (!full) { continue; } } else { // No match found huffman.TallyLit(window[strstart] & 0xff); ++strstart; --lookahead; } if (huffman.IsFull()) { bool lastBlock = finish && (lookahead == 0); huffman.FlushBlock(window, blockStart, strstart - blockStart, lastBlock); blockStart = strstart; return !lastBlock; } } return true; } bool DeflateSlow(bool flush, bool finish) { if (lookahead < MIN_LOOKAHEAD && !flush) { return false; } while (lookahead >= MIN_LOOKAHEAD || flush) { if (lookahead == 0) { if (prevAvailable) { huffman.TallyLit(window[strstart - 1] & 0xff); } prevAvailable = false; // We are flushing everything #if DebugDeflation if (DeflaterConstants.DEBUGGING && !flush) { throw new SharpZipBaseException("Not flushing, but no lookahead"); } #endif huffman.FlushBlock(window, blockStart, strstart - blockStart, finish); blockStart = strstart; return false; } if (strstart >= 2 * WSIZE - MIN_LOOKAHEAD) { /* slide window, as FindLongestMatch needs this. * This should only happen when flushing and the window * is almost full. */ SlideWindow(); } int prevMatch = matchStart; int prevLen = matchLen; if (lookahead >= MIN_MATCH) { int hashHead = InsertString(); if (strategy != DeflateStrategy.HuffmanOnly && hashHead != 0 && strstart - hashHead <= MAX_DIST && FindLongestMatch(hashHead)) { // longestMatch sets matchStart and matchLen // Discard match if too small and too far away if (matchLen <= 5 && (strategy == DeflateStrategy.Filtered || (matchLen == MIN_MATCH && strstart - matchStart > TooFar))) { matchLen = MIN_MATCH - 1; } } } // previous match was better if ((prevLen >= MIN_MATCH) && (matchLen <= prevLen)) { #if DebugDeflation if (DeflaterConstants.DEBUGGING) { for (int i = 0 ; i < matchLen; i++) { if (window[strstart-1+i] != window[prevMatch + i]) throw new SharpZipBaseException(); } } #endif huffman.TallyDist(strstart - 1 - prevMatch, prevLen); prevLen -= 2; do { strstart++; lookahead--; if (lookahead >= MIN_MATCH) { InsertString(); } } while (--prevLen > 0); strstart++; lookahead--; prevAvailable = false; matchLen = MIN_MATCH - 1; } else { if (prevAvailable) { huffman.TallyLit(window[strstart - 1] & 0xff); } prevAvailable = true; strstart++; lookahead--; } if (huffman.IsFull()) { int len = strstart - blockStart; if (prevAvailable) { len--; } bool lastBlock = (finish && (lookahead == 0) && !prevAvailable); huffman.FlushBlock(window, blockStart, len, lastBlock); blockStart += len; return !lastBlock; } } return true; } #region Instance Fields // Hash index of string to be inserted int ins_h; /// <summary> /// Hashtable, hashing three characters to an index for window, so /// that window[index]..window[index+2] have this hash code. /// Note that the array should really be unsigned short, so you need /// to and the values with 0xffff. /// </summary> short[] head; /// <summary> /// <code>prev[index &amp; WMASK]</code> points to the previous index that has the /// same hash code as the string starting at index. This way /// entries with the same hash code are in a linked list. /// Note that the array should really be unsigned short, so you need /// to and the values with 0xffff. /// </summary> short[] prev; int matchStart; // Length of best match int matchLen; // Set if previous match exists bool prevAvailable; int blockStart; /// <summary> /// Points to the current character in the window. /// </summary> int strstart; /// <summary> /// lookahead is the number of characters starting at strstart in /// window that are valid. /// So window[strstart] until window[strstart+lookahead-1] are valid /// characters. /// </summary> int lookahead; /// <summary> /// This array contains the part of the uncompressed stream that /// is of relevance. The current character is indexed by strstart. /// </summary> byte[] window; DeflateStrategy strategy; int max_chain, max_lazy, niceLength, goodLength; /// <summary> /// The current compression function. /// </summary> int compressionFunction; /// <summary> /// The input data for compression. /// </summary> byte[] inputBuf; /// <summary> /// The total bytes of input read. /// </summary> int totalIn; /// <summary> /// The offset into inputBuf, where input data starts. /// </summary> int inputOff; /// <summary> /// The end offset of the input data. /// </summary> int inputEnd; DeflaterPending pending; DeflaterHuffman huffman; /// <summary> /// The adler checksum /// </summary> Adler32 adler; #endregion } }
/* ==================================================================== 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 System.IO; using NPOI.HSSF.UserModel; using NPOI.OpenXml4Net.OPC; using NPOI.POIFS.FileSystem; using NPOI.Util; using NPOI.XSSF.UserModel; namespace NPOI.SS.UserModel { public enum ImportOption { NONE, /// <summary> /// Only Text and Formulas are imported. Pictures, Drawing, Styles etc. are all ignored. /// </summary> SheetContentOnly, /// <summary> /// Only Text, Comments and Formulas are imported. Pictures, Drawing, Styles etc. are all ignored. /// </summary> TextOnly, /// <summary> /// Everything is imported - this is the same as NONE. /// </summary> All, } /// <summary> /// Factory for creating the appropriate kind of Workbook /// (be it HSSFWorkbook or XSSFWorkbook), from the given input /// </summary> public class WorkbookFactory { /// <summary> /// Creates an HSSFWorkbook from the given POIFSFileSystem /// </summary> public static IWorkbook Create(POIFSFileSystem fs) { return new HSSFWorkbook(fs); } /** * Creates an HSSFWorkbook from the given NPOIFSFileSystem */ public static IWorkbook Create(NPOIFSFileSystem fs) { return new HSSFWorkbook(fs.Root, true); } /// <summary> /// Creates an XSSFWorkbook from the given OOXML Package /// </summary> public static IWorkbook Create(OPCPackage pkg) { return new XSSFWorkbook(pkg); } /// <summary> /// Creates the appropriate HSSFWorkbook / XSSFWorkbook from /// the given InputStream. The Stream is wraped inside a PushbackInputStream. /// </summary> /// <param name="inputStream">Input Stream of .xls or .xlsx file</param> /// <returns>IWorkbook depending on the input HSSFWorkbook or XSSFWorkbook is returned.</returns> // Your input stream MUST either support mark/reset, or // be wrapped as a {@link PushbackInputStream}! public static IWorkbook Create(Stream inputStream) { // If Clearly doesn't do mark/reset, wrap up //if (!inp.MarkSupported()) //{ // inp = new PushbackInputStream(inp, 8); //} inputStream = new PushbackStream(inputStream); if (POIFSFileSystem.HasPOIFSHeader(inputStream)) { return new HSSFWorkbook(inputStream); } inputStream.Position = 0; if (POIXMLDocument.HasOOXMLHeader(inputStream)) { return new XSSFWorkbook(OPCPackage.Open(inputStream)); } throw new ArgumentException("Your stream was neither an OLE2 stream, nor an OOXML stream."); } /** * Creates the appropriate HSSFWorkbook / XSSFWorkbook from * the given File, which must exist and be readable. */ public static IWorkbook Create(string file) { if (!File.Exists(file)) { throw new FileNotFoundException(file); } FileStream fStream = null; try { using (fStream = new FileStream(file, FileMode.Open, FileAccess.Read)) { IWorkbook wb = new HSSFWorkbook(fStream); return wb; } } catch (OfficeXmlFileException e) { using (fStream = new FileStream(file, FileMode.Open, FileAccess.Read)) { return new XSSFWorkbook(fStream); } } } /// <summary> /// Creates the appropriate HSSFWorkbook / XSSFWorkbook from /// the given InputStream. The Stream is wraped inside a PushbackInputStream. /// </summary> /// <param name="inputStream">Input Stream of .xls or .xlsx file</param> /// <param name="importOption">Customize the elements that are processed on the next import</param> /// <returns>IWorkbook depending on the input HSSFWorkbook or XSSFWorkbook is returned.</returns> public static IWorkbook Create(Stream inputStream, ImportOption importOption) { SetImportOption(importOption); IWorkbook workbook = Create(inputStream); return workbook; } /// <summary> /// Creates a specific FormulaEvaluator for the given workbook. /// </summary> public static IFormulaEvaluator CreateFormulaEvaluator(IWorkbook workbook) { if (typeof(HSSFWorkbook) == workbook.GetType()) { return new HSSFFormulaEvaluator(workbook as HSSFWorkbook); } else { return new XSSFFormulaEvaluator(workbook as XSSFWorkbook); } } /// <summary> /// Sets the import option when opening the next workbook. /// Works only for XSSF. For HSSF workbooks this option is ignored. /// </summary> /// <param name="importOption">Customize the elements that are processed on the next import</param> public static void SetImportOption(ImportOption importOption) { if (ImportOption.SheetContentOnly == importOption) { // Add XSSFRelation.AddRelation(XSSFRelation.WORKSHEET); XSSFRelation.AddRelation(XSSFRelation.SHARED_STRINGS); // Remove XSSFRelation.RemoveRelation(XSSFRelation.WORKBOOK); XSSFRelation.RemoveRelation(XSSFRelation.MACROS_WORKBOOK); XSSFRelation.RemoveRelation(XSSFRelation.TEMPLATE_WORKBOOK); XSSFRelation.RemoveRelation(XSSFRelation.MACRO_TEMPLATE_WORKBOOK); XSSFRelation.RemoveRelation(XSSFRelation.MACRO_ADDIN_WORKBOOK); XSSFRelation.RemoveRelation(XSSFRelation.CHARTSHEET); XSSFRelation.RemoveRelation(XSSFRelation.STYLES); XSSFRelation.RemoveRelation(XSSFRelation.DRAWINGS); XSSFRelation.RemoveRelation(XSSFRelation.CHART); XSSFRelation.RemoveRelation(XSSFRelation.VML_DRAWINGS); XSSFRelation.RemoveRelation(XSSFRelation.CUSTOM_XML_MAPPINGS); XSSFRelation.RemoveRelation(XSSFRelation.TABLE); XSSFRelation.RemoveRelation(XSSFRelation.IMAGES); XSSFRelation.RemoveRelation(XSSFRelation.IMAGE_EMF); XSSFRelation.RemoveRelation(XSSFRelation.IMAGE_WMF); XSSFRelation.RemoveRelation(XSSFRelation.IMAGE_PICT); XSSFRelation.RemoveRelation(XSSFRelation.IMAGE_JPEG); XSSFRelation.RemoveRelation(XSSFRelation.IMAGE_PNG); XSSFRelation.RemoveRelation(XSSFRelation.IMAGE_DIB); XSSFRelation.RemoveRelation(XSSFRelation.SHEET_COMMENTS); XSSFRelation.RemoveRelation(XSSFRelation.SHEET_HYPERLINKS); XSSFRelation.RemoveRelation(XSSFRelation.OLEEMBEDDINGS); XSSFRelation.RemoveRelation(XSSFRelation.PACKEMBEDDINGS); XSSFRelation.RemoveRelation(XSSFRelation.VBA_MACROS); XSSFRelation.RemoveRelation(XSSFRelation.ACTIVEX_CONTROLS); XSSFRelation.RemoveRelation(XSSFRelation.ACTIVEX_BINS); XSSFRelation.RemoveRelation(XSSFRelation.THEME); XSSFRelation.RemoveRelation(XSSFRelation.CALC_CHAIN); XSSFRelation.RemoveRelation(XSSFRelation.PRINTER_SETTINGS); } else if (ImportOption.TextOnly == importOption) { // Add XSSFRelation.AddRelation(XSSFRelation.WORKSHEET); XSSFRelation.AddRelation(XSSFRelation.SHARED_STRINGS); XSSFRelation.AddRelation(XSSFRelation.SHEET_COMMENTS); // Remove XSSFRelation.RemoveRelation(XSSFRelation.WORKBOOK); XSSFRelation.RemoveRelation(XSSFRelation.MACROS_WORKBOOK); XSSFRelation.RemoveRelation(XSSFRelation.TEMPLATE_WORKBOOK); XSSFRelation.RemoveRelation(XSSFRelation.MACRO_TEMPLATE_WORKBOOK); XSSFRelation.RemoveRelation(XSSFRelation.MACRO_ADDIN_WORKBOOK); XSSFRelation.RemoveRelation(XSSFRelation.CHARTSHEET); XSSFRelation.RemoveRelation(XSSFRelation.STYLES); XSSFRelation.RemoveRelation(XSSFRelation.DRAWINGS); XSSFRelation.RemoveRelation(XSSFRelation.CHART); XSSFRelation.RemoveRelation(XSSFRelation.VML_DRAWINGS); XSSFRelation.RemoveRelation(XSSFRelation.CUSTOM_XML_MAPPINGS); XSSFRelation.RemoveRelation(XSSFRelation.TABLE); XSSFRelation.RemoveRelation(XSSFRelation.IMAGES); XSSFRelation.RemoveRelation(XSSFRelation.IMAGE_EMF); XSSFRelation.RemoveRelation(XSSFRelation.IMAGE_WMF); XSSFRelation.RemoveRelation(XSSFRelation.IMAGE_PICT); XSSFRelation.RemoveRelation(XSSFRelation.IMAGE_JPEG); XSSFRelation.RemoveRelation(XSSFRelation.IMAGE_PNG); XSSFRelation.RemoveRelation(XSSFRelation.IMAGE_DIB); XSSFRelation.RemoveRelation(XSSFRelation.SHEET_HYPERLINKS); XSSFRelation.RemoveRelation(XSSFRelation.OLEEMBEDDINGS); XSSFRelation.RemoveRelation(XSSFRelation.PACKEMBEDDINGS); XSSFRelation.RemoveRelation(XSSFRelation.VBA_MACROS); XSSFRelation.RemoveRelation(XSSFRelation.ACTIVEX_CONTROLS); XSSFRelation.RemoveRelation(XSSFRelation.ACTIVEX_BINS); XSSFRelation.RemoveRelation(XSSFRelation.THEME); XSSFRelation.RemoveRelation(XSSFRelation.CALC_CHAIN); XSSFRelation.RemoveRelation(XSSFRelation.PRINTER_SETTINGS); } else { // NONE/All XSSFRelation.AddRelation(XSSFRelation.WORKBOOK); XSSFRelation.AddRelation(XSSFRelation.MACROS_WORKBOOK); XSSFRelation.AddRelation(XSSFRelation.TEMPLATE_WORKBOOK); XSSFRelation.AddRelation(XSSFRelation.MACRO_TEMPLATE_WORKBOOK); XSSFRelation.AddRelation(XSSFRelation.MACRO_ADDIN_WORKBOOK); XSSFRelation.AddRelation(XSSFRelation.WORKSHEET); XSSFRelation.AddRelation(XSSFRelation.CHARTSHEET); XSSFRelation.AddRelation(XSSFRelation.SHARED_STRINGS); XSSFRelation.AddRelation(XSSFRelation.STYLES); XSSFRelation.AddRelation(XSSFRelation.DRAWINGS); XSSFRelation.AddRelation(XSSFRelation.CHART); XSSFRelation.AddRelation(XSSFRelation.VML_DRAWINGS); XSSFRelation.AddRelation(XSSFRelation.CUSTOM_XML_MAPPINGS); XSSFRelation.AddRelation(XSSFRelation.TABLE); XSSFRelation.AddRelation(XSSFRelation.IMAGES); XSSFRelation.AddRelation(XSSFRelation.IMAGE_EMF); XSSFRelation.AddRelation(XSSFRelation.IMAGE_WMF); XSSFRelation.AddRelation(XSSFRelation.IMAGE_PICT); XSSFRelation.AddRelation(XSSFRelation.IMAGE_JPEG); XSSFRelation.AddRelation(XSSFRelation.IMAGE_PNG); XSSFRelation.AddRelation(XSSFRelation.IMAGE_DIB); XSSFRelation.AddRelation(XSSFRelation.SHEET_COMMENTS); XSSFRelation.AddRelation(XSSFRelation.SHEET_HYPERLINKS); XSSFRelation.AddRelation(XSSFRelation.OLEEMBEDDINGS); XSSFRelation.AddRelation(XSSFRelation.PACKEMBEDDINGS); XSSFRelation.AddRelation(XSSFRelation.VBA_MACROS); XSSFRelation.AddRelation(XSSFRelation.ACTIVEX_CONTROLS); XSSFRelation.AddRelation(XSSFRelation.ACTIVEX_BINS); XSSFRelation.AddRelation(XSSFRelation.THEME); XSSFRelation.AddRelation(XSSFRelation.CALC_CHAIN); XSSFRelation.AddRelation(XSSFRelation.PRINTER_SETTINGS); } } } }
using System; using Csla; using ParentLoad.DataAccess; using ParentLoad.DataAccess.ERCLevel; namespace ParentLoad.Business.ERCLevel { /// <summary> /// B08_Region (editable child object).<br/> /// This is a generated base class of <see cref="B08_Region"/> business object. /// </summary> /// <remarks> /// This class contains one child collection:<br/> /// - <see cref="B09_CityObjects"/> of type <see cref="B09_CityColl"/> (1:M relation to <see cref="B10_City"/>)<br/> /// This class is an item of <see cref="B07_RegionColl"/> collection. /// </remarks> [Serializable] public partial class B08_Region : BusinessBase<B08_Region> { #region Static Fields private static int _lastID; #endregion #region State Fields [NotUndoable] [NonSerialized] internal int parent_Country_ID = 0; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="Region_ID"/> property. /// </summary> public static readonly PropertyInfo<int> Region_IDProperty = RegisterProperty<int>(p => p.Region_ID, "Region ID"); /// <summary> /// Gets the Region ID. /// </summary> /// <value>The Region ID.</value> public int Region_ID { get { return GetProperty(Region_IDProperty); } } /// <summary> /// Maintains metadata about <see cref="Region_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Region_NameProperty = RegisterProperty<string>(p => p.Region_Name, "Region Name"); /// <summary> /// Gets or sets the Region Name. /// </summary> /// <value>The Region Name.</value> public string Region_Name { get { return GetProperty(Region_NameProperty); } set { SetProperty(Region_NameProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="B09_Region_SingleObject"/> property. /// </summary> public static readonly PropertyInfo<B09_Region_Child> B09_Region_SingleObjectProperty = RegisterProperty<B09_Region_Child>(p => p.B09_Region_SingleObject, "B09 Region Single Object", RelationshipTypes.Child); /// <summary> /// Gets the B09 Region Single Object ("parent load" child property). /// </summary> /// <value>The B09 Region Single Object.</value> public B09_Region_Child B09_Region_SingleObject { get { return GetProperty(B09_Region_SingleObjectProperty); } private set { LoadProperty(B09_Region_SingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="B09_Region_ASingleObject"/> property. /// </summary> public static readonly PropertyInfo<B09_Region_ReChild> B09_Region_ASingleObjectProperty = RegisterProperty<B09_Region_ReChild>(p => p.B09_Region_ASingleObject, "B09 Region ASingle Object", RelationshipTypes.Child); /// <summary> /// Gets the B09 Region ASingle Object ("parent load" child property). /// </summary> /// <value>The B09 Region ASingle Object.</value> public B09_Region_ReChild B09_Region_ASingleObject { get { return GetProperty(B09_Region_ASingleObjectProperty); } private set { LoadProperty(B09_Region_ASingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="B09_CityObjects"/> property. /// </summary> public static readonly PropertyInfo<B09_CityColl> B09_CityObjectsProperty = RegisterProperty<B09_CityColl>(p => p.B09_CityObjects, "B09 City Objects", RelationshipTypes.Child); /// <summary> /// Gets the B09 City Objects ("parent load" child property). /// </summary> /// <value>The B09 City Objects.</value> public B09_CityColl B09_CityObjects { get { return GetProperty(B09_CityObjectsProperty); } private set { LoadProperty(B09_CityObjectsProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="B08_Region"/> object. /// </summary> /// <returns>A reference to the created <see cref="B08_Region"/> object.</returns> internal static B08_Region NewB08_Region() { return DataPortal.CreateChild<B08_Region>(); } /// <summary> /// Factory method. Loads a <see cref="B08_Region"/> object from the given B08_RegionDto. /// </summary> /// <param name="data">The <see cref="B08_RegionDto"/>.</param> /// <returns>A reference to the fetched <see cref="B08_Region"/> object.</returns> internal static B08_Region GetB08_Region(B08_RegionDto data) { B08_Region obj = new B08_Region(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(data); obj.LoadProperty(B09_CityObjectsProperty, B09_CityColl.NewB09_CityColl()); obj.MarkOld(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="B08_Region"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public B08_Region() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="B08_Region"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { LoadProperty(Region_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID)); LoadProperty(B09_Region_SingleObjectProperty, DataPortal.CreateChild<B09_Region_Child>()); LoadProperty(B09_Region_ASingleObjectProperty, DataPortal.CreateChild<B09_Region_ReChild>()); LoadProperty(B09_CityObjectsProperty, DataPortal.CreateChild<B09_CityColl>()); var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="B08_Region"/> object from the given <see cref="B08_RegionDto"/>. /// </summary> /// <param name="data">The B08_RegionDto to use.</param> private void Fetch(B08_RegionDto data) { // Value properties LoadProperty(Region_IDProperty, data.Region_ID); LoadProperty(Region_NameProperty, data.Region_Name); // parent properties parent_Country_ID = data.Parent_Country_ID; var args = new DataPortalHookArgs(data); OnFetchRead(args); } /// <summary> /// Loads child <see cref="B09_Region_Child"/> object. /// </summary> /// <param name="child">The child object to load.</param> internal void LoadChild(B09_Region_Child child) { LoadProperty(B09_Region_SingleObjectProperty, child); } /// <summary> /// Loads child <see cref="B09_Region_ReChild"/> object. /// </summary> /// <param name="child">The child object to load.</param> internal void LoadChild(B09_Region_ReChild child) { LoadProperty(B09_Region_ASingleObjectProperty, child); } /// <summary> /// Inserts a new <see cref="B08_Region"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(B06_Country parent) { var dto = new B08_RegionDto(); dto.Parent_Country_ID = parent.Country_ID; dto.Region_Name = Region_Name; using (var dalManager = DalFactoryParentLoad.GetManager()) { var args = new DataPortalHookArgs(dto); OnInsertPre(args); var dal = dalManager.GetProvider<IB08_RegionDal>(); using (BypassPropertyChecks) { var resultDto = dal.Insert(dto); LoadProperty(Region_IDProperty, resultDto.Region_ID); args = new DataPortalHookArgs(resultDto); } OnInsertPost(args); // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Updates in the database all changes made to the <see cref="B08_Region"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update() { if (!IsDirty) return; var dto = new B08_RegionDto(); dto.Region_ID = Region_ID; dto.Region_Name = Region_Name; using (var dalManager = DalFactoryParentLoad.GetManager()) { var args = new DataPortalHookArgs(dto); OnUpdatePre(args); var dal = dalManager.GetProvider<IB08_RegionDal>(); using (BypassPropertyChecks) { var resultDto = dal.Update(dto); args = new DataPortalHookArgs(resultDto); } OnUpdatePost(args); // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Self deletes the <see cref="B08_Region"/> object from database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf() { using (var dalManager = DalFactoryParentLoad.GetManager()) { var args = new DataPortalHookArgs(); // flushes all pending data operations FieldManager.UpdateChildren(this); OnDeletePre(args); var dal = dalManager.GetProvider<IB08_RegionDal>(); using (BypassPropertyChecks) { dal.Delete(ReadProperty(Region_IDProperty)); } OnDeletePost(args); } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.InteropServices; using System.Text; using System.Threading; namespace System.Diagnostics { internal static partial class ProcessManager { /// <summary>Gets whether the process with the specified ID is currently running.</summary> /// <param name="processId">The process ID.</param> /// <returns>true if the process is running; otherwise, false.</returns> public static bool IsProcessRunning(int processId) { return IsProcessRunning(processId, GetProcessIds()); } /// <summary>Gets whether the process with the specified ID on the specified machine is currently running.</summary> /// <param name="processId">The process ID.</param> /// <param name="machineName">The machine name.</param> /// <returns>true if the process is running; otherwise, false.</returns> public static bool IsProcessRunning(int processId, string machineName) { return IsProcessRunning(processId, GetProcessIds(machineName)); } /// <summary>Gets the ProcessInfo for the specified process ID on the specified machine.</summary> /// <param name="processId">The process ID.</param> /// <param name="machineName">The machine name.</param> /// <returns>The ProcessInfo for the process if it could be found; otherwise, null.</returns> public static ProcessInfo GetProcessInfo(int processId, string machineName) { ProcessInfo[] processInfos = ProcessManager.GetProcessInfos(machineName); foreach (ProcessInfo processInfo in processInfos) { if (processInfo.ProcessId == processId) { return processInfo; } } return null; } /// <summary>Gets process infos for each process on the specified machine.</summary> /// <param name="machineName">The target machine.</param> /// <returns>An array of process infos, one per found process.</returns> public static ProcessInfo[] GetProcessInfos(string machineName) { return IsRemoteMachine(machineName) ? NtProcessManager.GetProcessInfos(machineName, true) : NtProcessInfoHelper.GetProcessInfos(); // Do not use performance counter for local machine } /// <summary>Gets the IDs of all processes on the specified machine.</summary> /// <param name="machineName">The machine to examine.</param> /// <returns>An array of process IDs from the specified machine.</returns> public static int[] GetProcessIds(string machineName) { // Due to the lack of support for EnumModules() on coresysserver, we rely // on PerformanceCounters to get the ProcessIds for both remote desktop // and the local machine, unlike Desktop on which we rely on PCs only for // remote machines. return IsRemoteMachine(machineName) ? NtProcessManager.GetProcessIds(machineName, true) : GetProcessIds(); } /// <summary>Gets the IDs of all processes on the current machine.</summary> public static int[] GetProcessIds() { return NtProcessManager.GetProcessIds(); } /// <summary>Gets the ID of a process from a handle to the process.</summary> /// <param name="processHandle">The handle.</param> /// <returns>The process ID.</returns> public static int GetProcessIdFromHandle(SafeProcessHandle processHandle) { return NtProcessManager.GetProcessIdFromHandle(processHandle); } /// <summary>Gets an array of module infos for the specified process.</summary> /// <param name="processId">The ID of the process whose modules should be enumerated.</param> /// <returns>The array of modules.</returns> public static ModuleInfo[] GetModuleInfos(int processId) { return NtProcessManager.GetModuleInfos(processId); } /// <summary>Gets whether the named machine is remote or local.</summary> /// <param name="machineName">The machine name.</param> /// <returns>true if the machine is remote; false if it's local.</returns> public static bool IsRemoteMachine(string machineName) { if (machineName == null) throw new ArgumentNullException("machineName"); if (machineName.Length == 0) throw new ArgumentException(SR.Format(SR.InvalidParameter, "machineName", machineName)); string baseName; if (machineName.StartsWith("\\", StringComparison.Ordinal)) baseName = machineName.Substring(2); else baseName = machineName; if (baseName.Equals(".")) return false; if (String.Compare(Interop.mincore.GetComputerName(), baseName, StringComparison.OrdinalIgnoreCase) == 0) return false; return true; } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- static ProcessManager() { // In order to query information (OpenProcess) on some protected processes // like csrss, we need SeDebugPrivilege privilege. // After removing the dependency on Performance Counter, we don't have a chance // to run the code in CLR performance counter to ask for this privilege. // So we will try to get the privilege here. // We could fail if the user account doesn't have right to do this, but that's fair. Interop.mincore.LUID luid = new Interop.mincore.LUID(); if (!Interop.mincore.LookupPrivilegeValue(null, Interop.mincore.SeDebugPrivilege, out luid)) { return; } SafeTokenHandle tokenHandle = null; try { if (!Interop.mincore.OpenProcessToken( Interop.mincore.GetCurrentProcess(), Interop.mincore.HandleOptions.TOKEN_ADJUST_PRIVILEGES, out tokenHandle)) { return; } Interop.mincore.TokenPrivileges tp = new Interop.mincore.TokenPrivileges(); tp.Luid = luid; tp.Attributes = Interop.mincore.SEPrivileges.SE_PRIVILEGE_ENABLED; // AdjustTokenPrivileges can return true even if it didn't succeed (when ERROR_NOT_ALL_ASSIGNED is returned). Interop.mincore.AdjustTokenPrivileges(tokenHandle, false, tp, 0, IntPtr.Zero, IntPtr.Zero); } finally { if (tokenHandle != null) { tokenHandle.Dispose(); } } } private static bool IsProcessRunning(int processId, int[] processIds) { return Array.IndexOf(processIds, processId) >= 0; } public static SafeProcessHandle OpenProcess(int processId, int access, bool throwIfExited) { SafeProcessHandle processHandle = Interop.mincore.OpenProcess(access, false, processId); int result = Marshal.GetLastWin32Error(); if (!processHandle.IsInvalid) { return processHandle; } if (processId == 0) { throw new Win32Exception(5); } // If the handle is invalid because the process has exited, only throw an exception if throwIfExited is true. if (!IsProcessRunning(processId)) { if (throwIfExited) { throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, processId.ToString(CultureInfo.CurrentCulture))); } else { return SafeProcessHandle.InvalidHandle; } } throw new Win32Exception(result); } public static SafeThreadHandle OpenThread(int threadId, int access) { SafeThreadHandle threadHandle = Interop.mincore.OpenThread(access, false, threadId); int result = Marshal.GetLastWin32Error(); if (threadHandle.IsInvalid) { if (result == Interop.mincore.Errors.ERROR_INVALID_PARAMETER) throw new InvalidOperationException(SR.Format(SR.ThreadExited, threadId.ToString(CultureInfo.CurrentCulture))); throw new Win32Exception(result); } return threadHandle; } } /// <devdoc> /// This static class provides the process api for the WinNt platform. /// We use the performance counter api to query process and thread /// information. Module information is obtained using PSAPI. /// </devdoc> /// <internalonly/> internal static class NtProcessManager { private const int ProcessPerfCounterId = 230; private const int ThreadPerfCounterId = 232; private const string PerfCounterQueryString = "230 232"; internal const int IdleProcessID = 0; private static Dictionary<String, ValueId> s_valueIds; static NtProcessManager() { s_valueIds = new Dictionary<String, ValueId>(); s_valueIds.Add("Pool Paged Bytes", ValueId.PoolPagedBytes); s_valueIds.Add("Pool Nonpaged Bytes", ValueId.PoolNonpagedBytes); s_valueIds.Add("Elapsed Time", ValueId.ElapsedTime); s_valueIds.Add("Virtual Bytes Peak", ValueId.VirtualBytesPeak); s_valueIds.Add("Virtual Bytes", ValueId.VirtualBytes); s_valueIds.Add("Private Bytes", ValueId.PrivateBytes); s_valueIds.Add("Page File Bytes", ValueId.PageFileBytes); s_valueIds.Add("Page File Bytes Peak", ValueId.PageFileBytesPeak); s_valueIds.Add("Working Set Peak", ValueId.WorkingSetPeak); s_valueIds.Add("Working Set", ValueId.WorkingSet); s_valueIds.Add("ID Thread", ValueId.ThreadId); s_valueIds.Add("ID Process", ValueId.ProcessId); s_valueIds.Add("Priority Base", ValueId.BasePriority); s_valueIds.Add("Priority Current", ValueId.CurrentPriority); s_valueIds.Add("% User Time", ValueId.UserTime); s_valueIds.Add("% Privileged Time", ValueId.PrivilegedTime); s_valueIds.Add("Start Address", ValueId.StartAddress); s_valueIds.Add("Thread State", ValueId.ThreadState); s_valueIds.Add("Thread Wait Reason", ValueId.ThreadWaitReason); } internal static int SystemProcessID { get { const int systemProcessIDOnXP = 4; return systemProcessIDOnXP; } } public static int[] GetProcessIds(string machineName, bool isRemoteMachine) { ProcessInfo[] infos = GetProcessInfos(machineName, isRemoteMachine); int[] ids = new int[infos.Length]; for (int i = 0; i < infos.Length; i++) ids[i] = infos[i].ProcessId; return ids; } public static int[] GetProcessIds() { int[] processIds = new int[256]; int size; for (; ; ) { if (!Interop.mincore.EnumProcesses(processIds, processIds.Length * 4, out size)) throw new Win32Exception(); if (size == processIds.Length * 4) { processIds = new int[processIds.Length * 2]; continue; } break; } int[] ids = new int[size / 4]; Array.Copy(processIds, 0, ids, 0, ids.Length); return ids; } public static ModuleInfo[] GetModuleInfos(int processId) { return GetModuleInfos(processId, false); } public static ModuleInfo GetFirstModuleInfo(int processId) { ModuleInfo[] moduleInfos = GetModuleInfos(processId, true); if (moduleInfos.Length == 0) { return null; } else { return moduleInfos[0]; } } private static ModuleInfo[] GetModuleInfos(int processId, bool firstModuleOnly) { // preserving Everett behavior. if (processId == SystemProcessID || processId == IdleProcessID) { // system process and idle process doesn't have any modules throw new Win32Exception(Interop.mincore.Errors.EFail, SR.EnumProcessModuleFailed); } SafeProcessHandle processHandle = SafeProcessHandle.InvalidHandle; try { processHandle = ProcessManager.OpenProcess(processId, Interop.mincore.ProcessOptions.PROCESS_QUERY_INFORMATION | Interop.mincore.ProcessOptions.PROCESS_VM_READ, true); IntPtr[] moduleHandles = new IntPtr[64]; GCHandle moduleHandlesArrayHandle = new GCHandle(); int moduleCount = 0; for (; ; ) { bool enumResult = false; try { moduleHandlesArrayHandle = GCHandle.Alloc(moduleHandles, GCHandleType.Pinned); enumResult = Interop.mincore.EnumProcessModules(processHandle, moduleHandlesArrayHandle.AddrOfPinnedObject(), moduleHandles.Length * IntPtr.Size, ref moduleCount); // The API we need to use to enumerate process modules differs on two factors: // 1) If our process is running in WOW64. // 2) The bitness of the process we wish to introspect. // // If we are not running in WOW64 or we ARE in WOW64 but want to inspect a 32 bit process // we can call psapi!EnumProcessModules. // // If we are running in WOW64 and we want to inspect the modules of a 64 bit process then // psapi!EnumProcessModules will return false with ERROR_PARTIAL_COPY (299). In this case we can't // do the enumeration at all. So we'll detect this case and bail out. // // Also, EnumProcessModules is not a reliable method to get the modules for a process. // If OS loader is touching module information, this method might fail and copy part of the data. // This is no easy solution to this problem. The only reliable way to fix this is to // suspend all the threads in target process. Of course we don't want to do this in Process class. // So we just to try avoid the race by calling the same method 50 (an arbitrary number) times. // if (!enumResult) { bool sourceProcessIsWow64 = false; bool targetProcessIsWow64 = false; SafeProcessHandle hCurProcess = SafeProcessHandle.InvalidHandle; try { hCurProcess = ProcessManager.OpenProcess(unchecked((int)Interop.mincore.GetCurrentProcessId()), Interop.mincore.ProcessOptions.PROCESS_QUERY_INFORMATION, true); bool wow64Ret; wow64Ret = Interop.mincore.IsWow64Process(hCurProcess, ref sourceProcessIsWow64); if (!wow64Ret) { throw new Win32Exception(); } wow64Ret = Interop.mincore.IsWow64Process(processHandle, ref targetProcessIsWow64); if (!wow64Ret) { throw new Win32Exception(); } if (sourceProcessIsWow64 && !targetProcessIsWow64) { // Wow64 isn't going to allow this to happen, the best we can do is give a descriptive error to the user. throw new Win32Exception(Interop.mincore.Errors.ERROR_PARTIAL_COPY, SR.EnumProcessModuleFailedDueToWow); } } finally { if (hCurProcess != SafeProcessHandle.InvalidHandle) { hCurProcess.Dispose(); } } // If the failure wasn't due to Wow64, try again. for (int i = 0; i < 50; i++) { enumResult = Interop.mincore.EnumProcessModules(processHandle, moduleHandlesArrayHandle.AddrOfPinnedObject(), moduleHandles.Length * IntPtr.Size, ref moduleCount); if (enumResult) { break; } Thread.Sleep(1); } } } finally { moduleHandlesArrayHandle.Free(); } if (!enumResult) { throw new Win32Exception(); } moduleCount /= IntPtr.Size; if (moduleCount <= moduleHandles.Length) break; moduleHandles = new IntPtr[moduleHandles.Length * 2]; } List<ModuleInfo> moduleInfos = new List<ModuleInfo>(firstModuleOnly ? 1 : moduleCount); StringBuilder baseName = new StringBuilder(1024); StringBuilder fileName = new StringBuilder(1024); for (int i = 0; i < moduleCount; i++) { if (i > 0) { // If the user is only interested in the main module, break now. // This avoid some waste of time. In addition, if the application unloads a DLL // we will not get an exception. if (firstModuleOnly) { break; } baseName.Clear(); fileName.Clear(); } IntPtr moduleHandle = moduleHandles[i]; Interop.mincore.NtModuleInfo ntModuleInfo = new Interop.mincore.NtModuleInfo(); if (!Interop.mincore.GetModuleInformation(processHandle, moduleHandle, ntModuleInfo, Marshal.SizeOf(ntModuleInfo))) { HandleError(); continue; } ModuleInfo moduleInfo = new ModuleInfo { _sizeOfImage = ntModuleInfo.SizeOfImage, _entryPoint = ntModuleInfo.EntryPoint, _baseOfDll = ntModuleInfo.BaseOfDll }; int ret = Interop.mincore.GetModuleBaseName(processHandle, moduleHandle, baseName, baseName.Capacity); if (ret == 0) { HandleError(); continue; } moduleInfo._baseName = baseName.ToString(); ret = Interop.mincore.GetModuleFileNameEx(processHandle, moduleHandle, fileName, fileName.Capacity); if (ret == 0) { HandleError(); continue; } moduleInfo._fileName = fileName.ToString(); if (moduleInfo._fileName != null && moduleInfo._fileName.Length >= 4 && moduleInfo._fileName.StartsWith(@"\\?\", StringComparison.Ordinal)) { moduleInfo._fileName = fileName.ToString(4, fileName.Length - 4); } moduleInfos.Add(moduleInfo); } return moduleInfos.ToArray(); } finally { #if FEATURE_TRACESWITCH Debug.WriteLineIf(Process._processTracing.TraceVerbose, "Process - CloseHandle(process)"); #endif if (!processHandle.IsInvalid) { processHandle.Dispose(); } } } private static void HandleError() { int lastError = Marshal.GetLastWin32Error(); switch (lastError) { case Interop.mincore.Errors.ERROR_INVALID_HANDLE: case Interop.mincore.Errors.ERROR_PARTIAL_COPY: // It's possible that another thread casued this module to become // unloaded (e.g FreeLibrary was called on the module). Ignore it and // move on. break; default: throw new Win32Exception(lastError); } } public static int GetProcessIdFromHandle(SafeProcessHandle processHandle) { Interop.NtDll.NtProcessBasicInfo info = new Interop.NtDll.NtProcessBasicInfo(); int status = Interop.NtDll.NtQueryInformationProcess(processHandle, Interop.NtDll.NtQueryProcessBasicInfo, info, (int)Marshal.SizeOf(info), null); if (status != 0) { throw new InvalidOperationException(SR.CantGetProcessId, new Win32Exception(status)); } // We should change the signature of this function and ID property in process class. return info.UniqueProcessId.ToInt32(); } public static ProcessInfo[] GetProcessInfos(string machineName, bool isRemoteMachine) { PerformanceCounterLib library = null; try { library = PerformanceCounterLib.GetPerformanceCounterLib(machineName, new CultureInfo("en")); return GetProcessInfos(library); } catch (Exception e) { if (isRemoteMachine) { throw new InvalidOperationException(SR.CouldntConnectToRemoteMachine, e); } else { throw e; } } // We don't want to call library.Close() here because that would cause us to unload all of the perflibs. // On the next call to GetProcessInfos, we'd have to load them all up again, which is SLOW! } static ProcessInfo[] GetProcessInfos(PerformanceCounterLib library) { ProcessInfo[] processInfos; int retryCount = 5; do { try { byte[] dataPtr = library.GetPerformanceData(PerfCounterQueryString); processInfos = GetProcessInfos(library, ProcessPerfCounterId, ThreadPerfCounterId, dataPtr); } catch (Exception e) { throw new InvalidOperationException(SR.CouldntGetProcessInfos, e); } --retryCount; } while (processInfos.Length == 0 && retryCount != 0); if (processInfos.Length == 0) throw new InvalidOperationException(SR.ProcessDisabled); return processInfos; } static ProcessInfo[] GetProcessInfos(PerformanceCounterLib library, int processIndex, int threadIndex, byte[] data) { #if FEATURE_TRACESWITCH Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos()"); #endif Dictionary<int, ProcessInfo> processInfos = new Dictionary<int, ProcessInfo>(); List<ThreadInfo> threadInfos = new List<ThreadInfo>(); GCHandle dataHandle = new GCHandle(); try { dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned); IntPtr dataBlockPtr = dataHandle.AddrOfPinnedObject(); Interop.mincore.PERF_DATA_BLOCK dataBlock = new Interop.mincore.PERF_DATA_BLOCK(); Marshal.PtrToStructure(dataBlockPtr, dataBlock); IntPtr typePtr = (IntPtr)((long)dataBlockPtr + dataBlock.HeaderLength); Interop.mincore.PERF_INSTANCE_DEFINITION instance = new Interop.mincore.PERF_INSTANCE_DEFINITION(); Interop.mincore.PERF_COUNTER_BLOCK counterBlock = new Interop.mincore.PERF_COUNTER_BLOCK(); for (int i = 0; i < dataBlock.NumObjectTypes; i++) { Interop.mincore.PERF_OBJECT_TYPE type = new Interop.mincore.PERF_OBJECT_TYPE(); Marshal.PtrToStructure(typePtr, type); IntPtr instancePtr = (IntPtr)((long)typePtr + type.DefinitionLength); IntPtr counterPtr = (IntPtr)((long)typePtr + type.HeaderLength); List<Interop.mincore.PERF_COUNTER_DEFINITION> counterList = new List<Interop.mincore.PERF_COUNTER_DEFINITION>(); for (int j = 0; j < type.NumCounters; j++) { Interop.mincore.PERF_COUNTER_DEFINITION counter = new Interop.mincore.PERF_COUNTER_DEFINITION(); Marshal.PtrToStructure(counterPtr, counter); string counterName = library.GetCounterName(counter.CounterNameTitleIndex); if (type.ObjectNameTitleIndex == processIndex) counter.CounterNameTitlePtr = (int)GetValueId(counterName); else if (type.ObjectNameTitleIndex == threadIndex) counter.CounterNameTitlePtr = (int)GetValueId(counterName); counterList.Add(counter); counterPtr = (IntPtr)((long)counterPtr + counter.ByteLength); } Interop.mincore.PERF_COUNTER_DEFINITION[] counters = counterList.ToArray(); for (int j = 0; j < type.NumInstances; j++) { Marshal.PtrToStructure(instancePtr, instance); IntPtr namePtr = (IntPtr)((long)instancePtr + instance.NameOffset); string instanceName = Marshal.PtrToStringUni(namePtr); if (instanceName.Equals("_Total")) continue; IntPtr counterBlockPtr = (IntPtr)((long)instancePtr + instance.ByteLength); Marshal.PtrToStructure(counterBlockPtr, counterBlock); if (type.ObjectNameTitleIndex == processIndex) { ProcessInfo processInfo = GetProcessInfo(type, (IntPtr)((long)instancePtr + instance.ByteLength), counters); if (processInfo.ProcessId == 0 && string.Compare(instanceName, "Idle", StringComparison.OrdinalIgnoreCase) != 0) { // Sometimes we'll get a process structure that is not completely filled in. // We can catch some of these by looking for non-"idle" processes that have id 0 // and ignoring those. #if FEATURE_TRACESWITCH Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos() - found a non-idle process with id 0; ignoring."); #endif } else { if (processInfos.ContainsKey(processInfo.ProcessId)) { // We've found two entries in the perfcounters that claim to be the // same process. We throw an exception. Is this really going to be // helpfull to the user? Should we just ignore? #if FEATURE_TRACESWITCH Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos() - found a duplicate process id"); #endif } else { // the performance counters keep a 15 character prefix of the exe name, and then delete the ".exe", // if it's in the first 15. The problem is that sometimes that will leave us with part of ".exe" // at the end. If instanceName ends in ".", ".e", or ".ex" we remove it. string processName = instanceName; if (processName.Length == 15) { if (instanceName.EndsWith(".", StringComparison.Ordinal)) processName = instanceName.Substring(0, 14); else if (instanceName.EndsWith(".e", StringComparison.Ordinal)) processName = instanceName.Substring(0, 13); else if (instanceName.EndsWith(".ex", StringComparison.Ordinal)) processName = instanceName.Substring(0, 12); } processInfo.ProcessName = processName; processInfos.Add(processInfo.ProcessId, processInfo); } } } else if (type.ObjectNameTitleIndex == threadIndex) { ThreadInfo threadInfo = GetThreadInfo(type, (IntPtr)((long)instancePtr + instance.ByteLength), counters); if (threadInfo._threadId != 0) threadInfos.Add(threadInfo); } instancePtr = (IntPtr)((long)instancePtr + instance.ByteLength + counterBlock.ByteLength); } typePtr = (IntPtr)((long)typePtr + type.TotalByteLength); } } finally { if (dataHandle.IsAllocated) dataHandle.Free(); } for (int i = 0; i < threadInfos.Count; i++) { ThreadInfo threadInfo = (ThreadInfo)threadInfos[i]; ProcessInfo processInfo; if (processInfos.TryGetValue(threadInfo._processId, out processInfo)) { processInfo._threadInfoList.Add(threadInfo); } } ProcessInfo[] temp = new ProcessInfo[processInfos.Values.Count]; processInfos.Values.CopyTo(temp, 0); return temp; } static ThreadInfo GetThreadInfo(Interop.mincore.PERF_OBJECT_TYPE type, IntPtr instancePtr, Interop.mincore.PERF_COUNTER_DEFINITION[] counters) { ThreadInfo threadInfo = new ThreadInfo(); for (int i = 0; i < counters.Length; i++) { Interop.mincore.PERF_COUNTER_DEFINITION counter = counters[i]; long value = ReadCounterValue(counter.CounterType, (IntPtr)((long)instancePtr + counter.CounterOffset)); switch ((ValueId)counter.CounterNameTitlePtr) { case ValueId.ProcessId: threadInfo._processId = (int)value; break; case ValueId.ThreadId: threadInfo._threadId = (ulong)value; break; case ValueId.BasePriority: threadInfo._basePriority = (int)value; break; case ValueId.CurrentPriority: threadInfo._currentPriority = (int)value; break; case ValueId.StartAddress: threadInfo._startAddress = (IntPtr)value; break; case ValueId.ThreadState: threadInfo._threadState = (ThreadState)value; break; case ValueId.ThreadWaitReason: threadInfo._threadWaitReason = GetThreadWaitReason((int)value); break; } } return threadInfo; } internal static ThreadWaitReason GetThreadWaitReason(int value) { switch (value) { case 0: case 7: return ThreadWaitReason.Executive; case 1: case 8: return ThreadWaitReason.FreePage; case 2: case 9: return ThreadWaitReason.PageIn; case 3: case 10: return ThreadWaitReason.SystemAllocation; case 4: case 11: return ThreadWaitReason.ExecutionDelay; case 5: case 12: return ThreadWaitReason.Suspended; case 6: case 13: return ThreadWaitReason.UserRequest; case 14: return ThreadWaitReason.EventPairHigh; ; case 15: return ThreadWaitReason.EventPairLow; case 16: return ThreadWaitReason.LpcReceive; case 17: return ThreadWaitReason.LpcReply; case 18: return ThreadWaitReason.VirtualMemory; case 19: return ThreadWaitReason.PageOut; default: return ThreadWaitReason.Unknown; } } static ProcessInfo GetProcessInfo(Interop.mincore.PERF_OBJECT_TYPE type, IntPtr instancePtr, Interop.mincore.PERF_COUNTER_DEFINITION[] counters) { ProcessInfo processInfo = new ProcessInfo(); for (int i = 0; i < counters.Length; i++) { Interop.mincore.PERF_COUNTER_DEFINITION counter = counters[i]; long value = ReadCounterValue(counter.CounterType, (IntPtr)((long)instancePtr + counter.CounterOffset)); switch ((ValueId)counter.CounterNameTitlePtr) { case ValueId.ProcessId: processInfo.ProcessId = (int)value; break; case ValueId.PoolPagedBytes: processInfo.PoolPagedBytes = value; break; case ValueId.PoolNonpagedBytes: processInfo.PoolNonPagedBytes = value; break; case ValueId.VirtualBytes: processInfo.VirtualBytes = value; break; case ValueId.VirtualBytesPeak: processInfo.VirtualBytesPeak = value; break; case ValueId.WorkingSetPeak: processInfo.WorkingSetPeak = value; break; case ValueId.WorkingSet: processInfo.WorkingSet = value; break; case ValueId.PageFileBytesPeak: processInfo.PageFileBytesPeak = value; break; case ValueId.PageFileBytes: processInfo.PageFileBytes = value; break; case ValueId.PrivateBytes: processInfo.PrivateBytes = value; break; case ValueId.BasePriority: processInfo.BasePriority = (int)value; break; } } return processInfo; } static ValueId GetValueId(string counterName) { if (counterName != null) { ValueId id; if (s_valueIds.TryGetValue(counterName, out id)) return id; } return ValueId.Unknown; } static long ReadCounterValue(int counterType, IntPtr dataPtr) { if ((counterType & Interop.mincore.PerfCounterOptions.NtPerfCounterSizeLarge) != 0) return Marshal.ReadInt64(dataPtr); else return (long)Marshal.ReadInt32(dataPtr); } enum ValueId { Unknown = -1, PoolPagedBytes, PoolNonpagedBytes, ElapsedTime, VirtualBytesPeak, VirtualBytes, PrivateBytes, PageFileBytes, PageFileBytesPeak, WorkingSetPeak, WorkingSet, ThreadId, ProcessId, BasePriority, CurrentPriority, UserTime, PrivilegedTime, StartAddress, ThreadState, ThreadWaitReason } } internal static class NtProcessInfoHelper { private static int GetNewBufferSize(int existingBufferSize, int requiredSize) { if (requiredSize == 0) { // // On some old OS like win2000, requiredSize will not be set if the buffer // passed to NtQuerySystemInformation is not enough. // int newSize = existingBufferSize * 2; if (newSize < existingBufferSize) { // In reality, we should never overflow. // Adding the code here just in case it happens. throw new OutOfMemoryException(); } return newSize; } else { // allocating a few more kilo bytes just in case there are some new process // kicked in since new call to NtQuerySystemInformation int newSize = requiredSize + 1024 * 10; if (newSize < requiredSize) { throw new OutOfMemoryException(); } return newSize; } } public static ProcessInfo[] GetProcessInfos() { int requiredSize = 0; int status; ProcessInfo[] processInfos; GCHandle bufferHandle = new GCHandle(); // Start with the default buffer size. int bufferSize = DefaultCachedBufferSize; // Get the cached buffer. long[] buffer = Interlocked.Exchange(ref CachedBuffer, null); try { do { if (buffer == null) { // Allocate buffer of longs since some platforms require the buffer to be 64-bit aligned. buffer = new long[(bufferSize + 7) / 8]; } else { // If we have cached buffer, set the size properly. bufferSize = buffer.Length * sizeof(long); } bufferHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned); status = Interop.NtDll.NtQuerySystemInformation( Interop.NtDll.NtQuerySystemProcessInformation, bufferHandle.AddrOfPinnedObject(), bufferSize, out requiredSize); if ((uint)status == Interop.NtDll.STATUS_INFO_LENGTH_MISMATCH) { if (bufferHandle.IsAllocated) bufferHandle.Free(); buffer = null; bufferSize = GetNewBufferSize(bufferSize, requiredSize); } } while ((uint)status == Interop.NtDll.STATUS_INFO_LENGTH_MISMATCH); if (status < 0) { // see definition of NT_SUCCESS(Status) in SDK throw new InvalidOperationException(SR.CouldntGetProcessInfos, new Win32Exception(status)); } // Parse the data block to get process information processInfos = GetProcessInfos(bufferHandle.AddrOfPinnedObject()); } finally { // Cache the final buffer for use on the next call. Interlocked.Exchange(ref CachedBuffer, buffer); if (bufferHandle.IsAllocated) bufferHandle.Free(); } return processInfos; } // Use a smaller buffer size on debug to ensure we hit the retry path. #if DEBUG private const int DefaultCachedBufferSize = 1024; #else private const int DefaultCachedBufferSize = 128 * 1024; #endif // Cache a single buffer for use in GetProcessInfos(). private static long[] CachedBuffer; static ProcessInfo[] GetProcessInfos(IntPtr dataPtr) { // 60 is a reasonable number for processes on a normal machine. Dictionary<int, ProcessInfo> processInfos = new Dictionary<int, ProcessInfo>(60); long totalOffset = 0; while (true) { IntPtr currentPtr = (IntPtr)((long)dataPtr + totalOffset); SystemProcessInformation pi = new SystemProcessInformation(); Marshal.PtrToStructure(currentPtr, pi); // get information for a process ProcessInfo processInfo = new ProcessInfo(); // Process ID shouldn't overflow. OS API GetCurrentProcessID returns DWORD. processInfo.ProcessId = pi.UniqueProcessId.ToInt32(); processInfo.SessionId = (int)pi.SessionId; processInfo.PoolPagedBytes = (long)pi.QuotaPagedPoolUsage; ; processInfo.PoolNonPagedBytes = (long)pi.QuotaNonPagedPoolUsage; processInfo.VirtualBytes = (long)pi.VirtualSize; processInfo.VirtualBytesPeak = (long)pi.PeakVirtualSize; processInfo.WorkingSetPeak = (long)pi.PeakWorkingSetSize; processInfo.WorkingSet = (long)pi.WorkingSetSize; processInfo.PageFileBytesPeak = (long)pi.PeakPagefileUsage; processInfo.PageFileBytes = (long)pi.PagefileUsage; processInfo.PrivateBytes = (long)pi.PrivatePageCount; processInfo.BasePriority = pi.BasePriority; if (pi.NamePtr == IntPtr.Zero) { if (processInfo.ProcessId == NtProcessManager.SystemProcessID) { processInfo.ProcessName = "System"; } else if (processInfo.ProcessId == NtProcessManager.IdleProcessID) { processInfo.ProcessName = "Idle"; } else { // for normal process without name, using the process ID. processInfo.ProcessName = processInfo.ProcessId.ToString(CultureInfo.InvariantCulture); } } else { string processName = GetProcessShortName(Marshal.PtrToStringUni(pi.NamePtr, pi.NameLength / sizeof(char))); processInfo.ProcessName = processName; } // get the threads for current process processInfos[processInfo.ProcessId] = processInfo; currentPtr = (IntPtr)((long)currentPtr + Marshal.SizeOf(pi)); int i = 0; while (i < pi.NumberOfThreads) { SystemThreadInformation ti = new SystemThreadInformation(); Marshal.PtrToStructure(currentPtr, ti); ThreadInfo threadInfo = new ThreadInfo(); threadInfo._processId = (int)ti.UniqueProcess; threadInfo._threadId = (ulong)ti.UniqueThread; threadInfo._basePriority = ti.BasePriority; threadInfo._currentPriority = ti.Priority; threadInfo._startAddress = ti.StartAddress; threadInfo._threadState = (ThreadState)ti.ThreadState; threadInfo._threadWaitReason = NtProcessManager.GetThreadWaitReason((int)ti.WaitReason); processInfo._threadInfoList.Add(threadInfo); currentPtr = (IntPtr)((long)currentPtr + Marshal.SizeOf(ti)); i++; } if (pi.NextEntryOffset == 0) { break; } totalOffset += pi.NextEntryOffset; } ProcessInfo[] temp = new ProcessInfo[processInfos.Values.Count]; processInfos.Values.CopyTo(temp, 0); return temp; } // This function generates the short form of process name. // // This is from GetProcessShortName in NT code base. // Check base\screg\winreg\perfdlls\process\perfsprc.c for details. internal static string GetProcessShortName(String name) { if (String.IsNullOrEmpty(name)) { #if FEATURE_TRACESWITCH Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos() - unexpected blank ProcessName"); #endif return String.Empty; } int slash = -1; int period = -1; for (int i = 0; i < name.Length; i++) { if (name[i] == '\\') slash = i; else if (name[i] == '.') period = i; } if (period == -1) period = name.Length - 1; // set to end of string else { // if a period was found, then see if the extension is // .EXE, if so drop it, if not, then use end of string // (i.e. include extension in name) String extension = name.Substring(period); if (String.Equals(".exe", extension, StringComparison.OrdinalIgnoreCase)) period--; // point to character before period else period = name.Length - 1; // set to end of string } if (slash == -1) slash = 0; // set to start of string else slash++; // point to character next to slash // copy characters between period (or end of string) and // slash (or start of string) to make image name return name.Substring(slash, period - slash + 1); } // native struct defined in ntexapi.h [StructLayout(LayoutKind.Sequential)] internal class SystemProcessInformation { internal uint NextEntryOffset; internal uint NumberOfThreads; private long _SpareLi1; private long _SpareLi2; private long _SpareLi3; private long _CreateTime; private long _UserTime; private long _KernelTime; internal ushort NameLength; // UNICODE_STRING internal ushort MaximumNameLength; internal IntPtr NamePtr; // This will point into the data block returned by NtQuerySystemInformation internal int BasePriority; internal IntPtr UniqueProcessId; internal IntPtr InheritedFromUniqueProcessId; internal uint HandleCount; internal uint SessionId; internal UIntPtr PageDirectoryBase; internal UIntPtr PeakVirtualSize; // SIZE_T internal UIntPtr VirtualSize; internal uint PageFaultCount; internal UIntPtr PeakWorkingSetSize; internal UIntPtr WorkingSetSize; internal UIntPtr QuotaPeakPagedPoolUsage; internal UIntPtr QuotaPagedPoolUsage; internal UIntPtr QuotaPeakNonPagedPoolUsage; internal UIntPtr QuotaNonPagedPoolUsage; internal UIntPtr PagefileUsage; internal UIntPtr PeakPagefileUsage; internal UIntPtr PrivatePageCount; private long _ReadOperationCount; private long _WriteOperationCount; private long _OtherOperationCount; private long _ReadTransferCount; private long _WriteTransferCount; private long _OtherTransferCount; } [StructLayout(LayoutKind.Sequential)] internal class SystemThreadInformation { private long _KernelTime; private long _UserTime; private long _CreateTime; private uint _WaitTime; internal IntPtr StartAddress; internal IntPtr UniqueProcess; internal IntPtr UniqueThread; internal int Priority; internal int BasePriority; internal uint ContextSwitches; internal uint ThreadState; internal uint WaitReason; } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Umbraco.Core { /// <summary> /// A utility class for type checking, this provides internal caching so that calls to these methods will be faster /// than doing a manual type check in c# /// </summary> internal static class TypeHelper { private static readonly ConcurrentDictionary<Type, FieldInfo[]> GetFieldsCache = new ConcurrentDictionary<Type, FieldInfo[]>(); private static readonly ConcurrentDictionary<Tuple<Type, bool, bool, bool>, PropertyInfo[]> GetPropertiesCache = new ConcurrentDictionary<Tuple<Type, bool, bool, bool>, PropertyInfo[]>(); /// <summary> /// Find all assembly references that are referencing the assignTypeFrom Type's assembly found in the assemblyList /// </summary> /// <param name="assignTypeFrom"></param> /// <param name="assemblies"></param> /// <returns></returns> /// <remarks> /// If the assembly of the assignTypeFrom Type is in the App_Code assembly, then we return nothing since things cannot /// reference that assembly, same with the global.asax assembly. /// </remarks> public static Assembly[] GetReferencedAssemblies(Type assignTypeFrom, IEnumerable<Assembly> assemblies) { //check if it is the app_code assembly. //check if it is App_global.asax assembly if (assignTypeFrom.Assembly.IsAppCodeAssembly() || assignTypeFrom.Assembly.IsGlobalAsaxAssembly()) { return Enumerable.Empty<Assembly>().ToArray(); } //find all assembly references that are referencing the current type's assembly since we //should only be scanning those assemblies because any other assembly will definitely not //contain sub type's of the one we're currently looking for return assemblies .Where(assembly => assembly == assignTypeFrom.Assembly || HasReferenceToAssemblyWithName(assembly, assignTypeFrom.Assembly.GetName().Name)) .ToArray(); } /// <summary> /// checks if the assembly has a reference with the same name as the expected assembly name. /// </summary> /// <param name="assembly"></param> /// <param name="expectedAssemblyName"></param> /// <returns></returns> private static bool HasReferenceToAssemblyWithName(Assembly assembly, string expectedAssemblyName) { return assembly .GetReferencedAssemblies() .Select(a => a.Name) .Contains(expectedAssemblyName, StringComparer.Ordinal); } /// <summary> /// Returns true if the type is a class and is not static /// </summary> /// <param name="t"></param> /// <returns></returns> public static bool IsNonStaticClass(Type t) { return t.IsClass && IsStaticClass(t) == false; } /// <summary> /// Returns true if the type is a static class /// </summary> /// <param name="type"></param> /// <returns></returns> /// <remarks> /// In IL a static class is abstract and sealed /// see: http://stackoverflow.com/questions/1175888/determine-if-a-type-is-static /// </remarks> public static bool IsStaticClass(Type type) { return type.IsAbstract && type.IsSealed; } /// <summary> /// Finds a lowest base class amongst a collection of types /// </summary> /// <param name="types"></param> /// <returns></returns> /// <remarks> /// The term 'lowest' refers to the most base class of the type collection. /// If a base type is not found amongst the type collection then an invalid attempt is returned. /// </remarks> public static Attempt<Type> GetLowestBaseType(params Type[] types) { if (types.Length == 0) { return Attempt<Type>.False; } if (types.Length == 1) { return new Attempt<Type>(true, types[0]); } foreach (var curr in types) { var others = types.Except(new[] {curr}); //is the curr type a common denominator for all others ? var isBase = others.All(curr.IsAssignableFrom); //if this type is the base for all others if (isBase) { return new Attempt<Type>(true, curr); } } return Attempt<Type>.False; } /// <summary> /// Determines whether the type <paramref name="implementation"/> is assignable from the specified implementation <typeparamref name="TContract"/>, /// and caches the result across the application using a <see cref="ConcurrentDictionary{TKey,TValue}"/>. /// </summary> /// <param name="contract">The type of the contract.</param> /// <param name="implementation">The implementation.</param> /// <returns> /// <c>true</c> if [is type assignable from] [the specified contract]; otherwise, <c>false</c>. /// </returns> public static bool IsTypeAssignableFrom(Type contract, Type implementation) { return contract.IsAssignableFrom(implementation); } /// <summary> /// Determines whether the type <paramref name="implementation"/> is assignable from the specified implementation <typeparamref name="TContract"/>, /// and caches the result across the application using a <see cref="ConcurrentDictionary{TKey,TValue}"/>. /// </summary> /// <typeparam name="TContract">The type of the contract.</typeparam> /// <param name="implementation">The implementation.</param> public static bool IsTypeAssignableFrom<TContract>(Type implementation) { return IsTypeAssignableFrom(typeof(TContract), implementation); } /// <summary> /// A cached method to determine whether <paramref name="implementation"/> represents a value type. /// </summary> /// <param name="implementation">The implementation.</param> public static bool IsValueType(Type implementation) { return implementation.IsValueType || implementation.IsPrimitive; } /// <summary> /// A cached method to determine whether <paramref name="implementation"/> is an implied value type (<see cref="Type.IsValueType"/>, <see cref="Type.IsEnum"/> or a string). /// </summary> /// <param name="implementation">The implementation.</param> public static bool IsImplicitValueType(Type implementation) { return IsValueType(implementation) || implementation.IsEnum || implementation == typeof (string); } public static bool IsTypeAssignableFrom<TContract>(object implementation) { if (implementation == null) throw new ArgumentNullException("implementation"); return IsTypeAssignableFrom<TContract>(implementation.GetType()); } /// <summary> /// Returns a PropertyInfo from a type /// </summary> /// <param name="type"></param> /// <param name="name"></param> /// <param name="mustRead"></param> /// <param name="mustWrite"></param> /// <param name="includeIndexed"></param> /// <param name="caseSensitive"> </param> /// <returns></returns> public static PropertyInfo GetProperty(Type type, string name, bool mustRead = true, bool mustWrite = true, bool includeIndexed = false, bool caseSensitive = true) { return CachedDiscoverableProperties(type, mustRead, mustWrite, includeIndexed) .FirstOrDefault(x => { if (caseSensitive) return x.Name == name; return x.Name.InvariantEquals(name); }); } /// <summary> /// Gets (and caches) <see cref="FieldInfo"/> discoverable in the current <see cref="AppDomain"/> for a given <paramref name="type"/>. /// </summary> /// <param name="type">The source.</param> /// <returns></returns> public static FieldInfo[] CachedDiscoverableFields(Type type) { return GetFieldsCache.GetOrAdd( type, x => type .GetFields(BindingFlags.Public | BindingFlags.Instance) .Where(y => !y.IsInitOnly) .ToArray()); } /// <summary> /// Gets (and caches) <see cref="PropertyInfo"/> discoverable in the current <see cref="AppDomain"/> for a given <paramref name="type"/>. /// </summary> /// <param name="type">The source.</param> /// <param name="mustRead">true if the properties discovered are readable</param> /// <param name="mustWrite">true if the properties discovered are writable</param> /// <param name="includeIndexed">true if the properties discovered are indexable</param> /// <returns></returns> public static PropertyInfo[] CachedDiscoverableProperties(Type type, bool mustRead = true, bool mustWrite = true, bool includeIndexed = false) { return GetPropertiesCache.GetOrAdd( new Tuple<Type, bool, bool, bool>(type, mustRead, mustWrite, includeIndexed), x => type .GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(y => (!mustRead || y.CanRead) && (!mustWrite || y.CanWrite) && (includeIndexed || !y.GetIndexParameters().Any())) .ToArray()); } } }
// 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; using System.Collections.Specialized; using Xunit; namespace System.Diagnostics.Tests { [SkipOnTargetFramework(TargetFrameworkMonikers.Uap)] // In appcontainer, cannot write to perf counters public static class PerformanceCounterTests { [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounter_CreateCounter_EmptyCounter() { using (PerformanceCounter counterSample = new PerformanceCounter()) { Assert.Equal(".", counterSample.MachineName); Assert.Equal(string.Empty, counterSample.CategoryName); Assert.Equal(string.Empty, counterSample.CounterName); Assert.Equal(string.Empty, counterSample.InstanceName); Assert.True(counterSample.ReadOnly); } } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounter_CreateCounter_Count0() { var name = nameof(PerformanceCounter_CreateCounter_Count0) + "_Counter"; using (PerformanceCounter counterSample = CreateCounterWithCategory(name, false, PerformanceCounterCategoryType.SingleInstance)) { counterSample.RawValue = 0; Assert.Equal(0, counterSample.RawValue); Helpers.DeleteCategory(name); } } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounter_CreateCounter_ProcessorCounter() { using (PerformanceCounter counterSample = new PerformanceCounter("Processor", "Interrupts/sec", "0", ".")) { Assert.Equal(0, Helpers.RetryOnAllPlatforms(() => counterSample.NextValue())); Assert.True(counterSample.RawValue > 0); } } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounter_CreateCounter_MultiInstanceReadOnly() { var name = nameof(PerformanceCounter_CreateCounter_MultiInstanceReadOnly) + "_Counter"; var instance = name + "_Instance"; var category = Helpers.CreateCategory(name, PerformanceCounterCategoryType.MultiInstance); using (PerformanceCounter counterSample = Helpers.RetryOnAllPlatforms(() => new PerformanceCounter(category, name, instance))) { Assert.Equal(name, counterSample.CounterName); Assert.Equal(category, counterSample.CategoryName); Assert.Equal(instance, counterSample.InstanceName); Assert.Equal("counter description", Helpers.RetryOnAllPlatforms(() => counterSample.CounterHelp)); Assert.True(counterSample.ReadOnly); Helpers.DeleteCategory(name); } } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounter_CreateCounter_SetReadOnly() { var name = nameof(PerformanceCounter_CreateCounter_SetReadOnly) + "_Counter"; var category = Helpers.CreateCategory(name, PerformanceCounterCategoryType.SingleInstance); using (PerformanceCounter counterSample = Helpers.RetryOnAllPlatforms(() => new PerformanceCounter(category, name))) { counterSample.ReadOnly = false; Assert.False(counterSample.ReadOnly); } Helpers.DeleteCategory(name); } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounter_SetProperties_Null() { using (PerformanceCounter counterSample = new PerformanceCounter()) { Assert.Throws<ArgumentNullException>(() => counterSample.CategoryName = null); Assert.Throws<ArgumentNullException>(() => counterSample.CounterName = null); Assert.Throws<ArgumentException>(() => counterSample.MachineName = null); } } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounter_SetRawValue_ReadOnly() { using (PerformanceCounter counterSample = new PerformanceCounter()) { Assert.Throws<InvalidOperationException>(() => counterSample.RawValue = 10); } } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounter_GetRawValue_EmptyCategoryName() { var name = nameof(PerformanceCounter_GetRawValue_EmptyCategoryName) + "_Counter"; using (PerformanceCounter counterSample = new PerformanceCounter()) { counterSample.ReadOnly = false; counterSample.CounterName = name; Assert.Throws<InvalidOperationException>(() => counterSample.RawValue); } } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounter_GetRawValue_EmptyCounterName() { var name = nameof(PerformanceCounter_GetRawValue_EmptyCounterName) + "_Counter"; using (PerformanceCounter counterSample = new PerformanceCounter()) { counterSample.ReadOnly = false; counterSample.CategoryName = name + "_Category"; Assert.Throws<InvalidOperationException>(() => counterSample.RawValue); } } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounter_GetRawValue_CounterDoesNotExist() { var name = nameof(PerformanceCounter_GetRawValue_CounterDoesNotExist) + "_Counter"; using (PerformanceCounter counterSample = new PerformanceCounter()) { counterSample.ReadOnly = false; counterSample.CounterName = name; counterSample.CategoryName = name + "_Category"; Assert.Throws<InvalidOperationException>(() => counterSample.RawValue); } } [ActiveIssue(38180)] [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounter_NextValue_ProcessorCounter() { using (PerformanceCounter counterSample = new PerformanceCounter("Processor", "Interrupts/sec", "0", ".")) { Helpers.RetryOnAllPlatforms(() => counterSample.NextValue()); System.Threading.Thread.Sleep(30); Assert.True(Helpers.RetryOnAllPlatforms(() => counterSample.NextValue()) > 0); } } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounter_BeginInit_ProcessorCounter() { using (PerformanceCounter counterSample = new PerformanceCounter("Processor", "Interrupts/sec", "0", ".")) { counterSample.BeginInit(); Assert.NotNull(counterSample); } } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounter_BeginInitEndInit_ProcessorCounter() { using (PerformanceCounter counterSample = new PerformanceCounter("Processor", "Interrupts/sec", "0", ".")) { counterSample.BeginInit(); counterSample.EndInit(); Assert.NotNull(counterSample); } } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounter_Decrement() { var name = nameof(PerformanceCounter_Decrement) + "_Counter"; using (PerformanceCounter counterSample = CreateCounterWithCategory(name, false, PerformanceCounterCategoryType.SingleInstance)) { counterSample.RawValue = 10; Helpers.RetryOnAllPlatforms(() => counterSample.Decrement()); Assert.Equal(9, counterSample.RawValue); Helpers.DeleteCategory(name); } } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounter_Increment() { var name = nameof(PerformanceCounter_Increment) + "_Counter"; using (PerformanceCounter counterSample = CreateCounterWithCategory(name, false, PerformanceCounterCategoryType.SingleInstance)) { counterSample.RawValue = 10; Helpers.RetryOnAllPlatforms(() => counterSample.Increment()); Assert.Equal(11, Helpers.RetryOnAllPlatforms(() => counterSample.NextSample().RawValue)); Helpers.DeleteCategory(name); } } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounter_IncrementBy_IncrementBy2() { var name = nameof(PerformanceCounter_IncrementBy_IncrementBy2) + "_Counter"; using (PerformanceCounter counterSample = CreateCounterWithCategory(name, false, PerformanceCounterCategoryType.SingleInstance)) { counterSample.RawValue = 10; Helpers.RetryOnAllPlatforms(() => counterSample.IncrementBy(2)); Assert.Equal(12, counterSample.RawValue); Helpers.DeleteCategory(name); } } [ActiveIssue(25349)] [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounter_IncrementBy_IncrementByReadOnly() { var name = nameof(PerformanceCounter_IncrementBy_IncrementByReadOnly) + "_Counter"; using (PerformanceCounter counterSample = CreateCounterWithCategory(name, true, PerformanceCounterCategoryType.SingleInstance)) { Assert.Throws<InvalidOperationException>(() => counterSample.IncrementBy(2)); Helpers.DeleteCategory(name); } } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounter_Increment_IncrementReadOnly() { var name = nameof(PerformanceCounter_Increment_IncrementReadOnly) + "_Counter"; using (PerformanceCounter counterSample = CreateCounterWithCategory(name, true, PerformanceCounterCategoryType.SingleInstance)) { Assert.Throws<InvalidOperationException>(() => counterSample.Increment()); Helpers.DeleteCategory(name); } } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounter_Decrement_DecrementReadOnly() { var name = nameof(PerformanceCounter_Decrement_DecrementReadOnly) + "_Counter"; using (PerformanceCounter counterSample = CreateCounterWithCategory(name, true, PerformanceCounterCategoryType.SingleInstance)) { Assert.Throws<InvalidOperationException>(() => counterSample.Decrement()); Helpers.DeleteCategory(name); } } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounter_RemoveInstance() { var name = nameof(PerformanceCounter_RemoveInstance) + "_Counter"; using (PerformanceCounter counterSample = CreateCounterWithCategory(name, false, PerformanceCounterCategoryType.SingleInstance)) { counterSample.RawValue = 100; counterSample.RemoveInstance(); counterSample.Close(); Assert.NotNull(counterSample); Helpers.DeleteCategory(name); } } [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndCanWriteToPerfCounters))] public static void PerformanceCounter_NextSample_MultiInstance() { var name = nameof(PerformanceCounter_NextSample_MultiInstance) + "_Counter"; var instance = name + "_Instance"; var category = Helpers.CreateCategory(name, PerformanceCounterCategoryType.MultiInstance); using (PerformanceCounter counterSample = new PerformanceCounter(category, name, instance, false)) { counterSample.RawValue = 10; Helpers.RetryOnAllPlatforms(() => counterSample.Decrement()); Assert.Equal(9, counterSample.RawValue); Helpers.DeleteCategory(name); } } public static PerformanceCounter CreateCounterWithCategory(string name, bool readOnly, PerformanceCounterCategoryType categoryType ) { var category = Helpers.CreateCategory(name, categoryType); PerformanceCounter counterSample = Helpers.RetryOnAllPlatforms(() => new PerformanceCounter(category, name, readOnly)); return counterSample; } } }
namespace Fixtures.SwaggerBatHttp { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; /// <summary> /// Test Infrastructure for AutoRest /// </summary> public partial interface IMultipleResponses { /// <summary> /// Send a 200 response with valid payload: {'statusCode': '200'} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<A>> Get200Model204NoModelDefaultError200ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 204 response with no payload /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<A>> Get200Model204NoModelDefaultError204ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 201 response with valid payload: {'statusCode': '201'} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<A>> Get200Model204NoModelDefaultError201InvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 202 response with no payload: /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<A>> Get200Model204NoModelDefaultError202NoneWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 400 response with valid error payload: {'status': 400, /// 'message': 'client error'} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<A>> Get200Model204NoModelDefaultError400ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with valid payload: {'statusCode': '200'} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<A>> Get200Model201ModelDefaultError200ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 201 response with valid payload: {'statusCode': '201', /// 'textStatusCode': 'Created'} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<A>> Get200Model201ModelDefaultError201ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 400 response with valid payload: {'code': '400', 'message': /// 'client error'} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<A>> Get200Model201ModelDefaultError400ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with valid payload: {'statusCode': '200'} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<object>> Get200ModelA201ModelC404ModelDDefaultError200ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with valid payload: {'httpCode': '201'} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<object>> Get200ModelA201ModelC404ModelDDefaultError201ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with valid payload: {'httpStatusCode': '404'} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<object>> Get200ModelA201ModelC404ModelDDefaultError404ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 400 response with valid payload: {'code': '400', 'message': /// 'client error'} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<object>> Get200ModelA201ModelC404ModelDDefaultError400ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 202 response with no payload /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse> Get202None204NoneDefaultError202NoneWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 204 response with no payload /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse> Get202None204NoneDefaultError204NoneWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 400 response with valid payload: {'code': '400', 'message': /// 'client error'} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse> Get202None204NoneDefaultError400ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 202 response with an unexpected payload {'property': /// 'value'} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse> Get202None204NoneDefaultNone202InvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 204 response with no payload /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse> Get202None204NoneDefaultNone204NoneWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 400 response with no payload /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse> Get202None204NoneDefaultNone400NoneWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 400 response with an unexpected payload {'property': /// 'value'} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse> Get202None204NoneDefaultNone400InvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with valid payload: {'statusCode': '200'} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<A>> GetDefaultModelA200ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with no payload /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<A>> GetDefaultModelA200NoneWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 400 response with valid payload: {'statusCode': '400'} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<A>> GetDefaultModelA400ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 400 response with no payload /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<A>> GetDefaultModelA400NoneWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with invalid payload: {'statusCode': '200'} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse> GetDefaultNone200InvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with no payload /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse> GetDefaultNone200NoneWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 400 response with valid payload: {'statusCode': '400'} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse> GetDefaultNone400InvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 400 response with no payload /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse> GetDefaultNone400NoneWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with no payload, when a payload is expected - /// client should return a null object of thde type for model A /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<A>> Get200ModelA200NoneWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with payload {'statusCode': '200'} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<A>> Get200ModelA200ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with invalid payload {'statusCodeInvalid': /// '200'} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<A>> Get200ModelA200InvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 400 response with no payload client should treat as an http /// error with no error model /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<A>> Get200ModelA400NoneWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with payload {'statusCode': '400'} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<A>> Get200ModelA400ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with invalid payload {'statusCodeInvalid': /// '400'} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<A>> Get200ModelA400InvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 202 response with payload {'statusCode': '202'} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<A>> Get200ModelA202ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
namespace UsbApp { partial class Sniffer { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form 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.components = new System.ComponentModel.Container(); this.lb_recieved = new System.Windows.Forms.Label(); this.btn_send = new System.Windows.Forms.Button(); this.tb_send = new System.Windows.Forms.TextBox(); this.lb_vendor = new System.Windows.Forms.Label(); this.btn_ok = new System.Windows.Forms.Button(); this.lb_product = new System.Windows.Forms.Label(); this.lb_senddata = new System.Windows.Forms.Label(); this.lb_messages = new System.Windows.Forms.Label(); this.tb_vendor = new System.Windows.Forms.TextBox(); this.tb_product = new System.Windows.Forms.TextBox(); this.gb_filter = new System.Windows.Forms.GroupBox(); this.lb_message = new System.Windows.Forms.ListBox(); this.gb_details = new System.Windows.Forms.GroupBox(); this.lb_read = new System.Windows.Forms.ListBox(); this.usb = new UsbLibrary.UsbHidPort(this.components); this.gb_filter.SuspendLayout(); this.gb_details.SuspendLayout(); this.SuspendLayout(); // // lb_recieved // this.lb_recieved.AutoSize = true; this.lb_recieved.Location = new System.Drawing.Point(229, 16); this.lb_recieved.Name = "lb_recieved"; this.lb_recieved.Size = new System.Drawing.Size(82, 13); this.lb_recieved.TabIndex = 4; this.lb_recieved.Text = "Recieved Data:"; // // btn_send // this.btn_send.Location = new System.Drawing.Point(364, 263); this.btn_send.Name = "btn_send"; this.btn_send.Size = new System.Drawing.Size(48, 23); this.btn_send.TabIndex = 3; this.btn_send.Text = "Send"; this.btn_send.UseVisualStyleBackColor = true; this.btn_send.Click += new System.EventHandler(this.btn_send_Click); // // tb_send // this.tb_send.Location = new System.Drawing.Point(229, 263); this.tb_send.Name = "tb_send"; this.tb_send.Size = new System.Drawing.Size(132, 20); this.tb_send.TabIndex = 2; // // lb_vendor // this.lb_vendor.AutoSize = true; this.lb_vendor.Location = new System.Drawing.Point(9, 22); this.lb_vendor.Name = "lb_vendor"; this.lb_vendor.Size = new System.Drawing.Size(95, 13); this.lb_vendor.TabIndex = 5; this.lb_vendor.Text = "Device Vendor ID:"; // // btn_ok // this.btn_ok.Location = new System.Drawing.Point(322, 43); this.btn_ok.Name = "btn_ok"; this.btn_ok.Size = new System.Drawing.Size(75, 23); this.btn_ok.TabIndex = 7; this.btn_ok.Text = "OK"; this.btn_ok.UseVisualStyleBackColor = true; this.btn_ok.Click += new System.EventHandler(this.btn_ok_Click); // // lb_product // this.lb_product.AutoSize = true; this.lb_product.Location = new System.Drawing.Point(9, 48); this.lb_product.Name = "lb_product"; this.lb_product.Size = new System.Drawing.Size(98, 13); this.lb_product.TabIndex = 6; this.lb_product.Text = "Device Product ID:"; // // lb_senddata // this.lb_senddata.AutoSize = true; this.lb_senddata.Location = new System.Drawing.Point(229, 247); this.lb_senddata.Name = "lb_senddata"; this.lb_senddata.Size = new System.Drawing.Size(61, 13); this.lb_senddata.TabIndex = 5; this.lb_senddata.Text = "Send Data:"; // // lb_messages // this.lb_messages.AutoSize = true; this.lb_messages.Location = new System.Drawing.Point(8, 16); this.lb_messages.Name = "lb_messages"; this.lb_messages.Size = new System.Drawing.Size(80, 13); this.lb_messages.TabIndex = 7; this.lb_messages.Text = "Usb Messages:"; // // tb_vendor // this.tb_vendor.Location = new System.Drawing.Point(114, 19); this.tb_vendor.Name = "tb_vendor"; this.tb_vendor.Size = new System.Drawing.Size(189, 20); this.tb_vendor.TabIndex = 1; this.tb_vendor.Text = "05F3"; // // tb_product // this.tb_product.Location = new System.Drawing.Point(114, 45); this.tb_product.Name = "tb_product"; this.tb_product.Size = new System.Drawing.Size(189, 20); this.tb_product.TabIndex = 2; this.tb_product.Text = "00FF"; // // gb_filter // this.gb_filter.Controls.Add(this.btn_ok); this.gb_filter.Controls.Add(this.lb_product); this.gb_filter.Controls.Add(this.lb_vendor); this.gb_filter.Controls.Add(this.tb_vendor); this.gb_filter.Controls.Add(this.tb_product); this.gb_filter.ForeColor = System.Drawing.Color.White; this.gb_filter.Location = new System.Drawing.Point(12, 12); this.gb_filter.Name = "gb_filter"; this.gb_filter.Size = new System.Drawing.Size(428, 80); this.gb_filter.TabIndex = 5; this.gb_filter.TabStop = false; this.gb_filter.Text = "Filter for Device:"; // // lb_message // this.lb_message.FormattingEnabled = true; this.lb_message.Location = new System.Drawing.Point(11, 32); this.lb_message.Name = "lb_message"; this.lb_message.Size = new System.Drawing.Size(212, 251); this.lb_message.TabIndex = 6; // // gb_details // this.gb_details.Controls.Add(this.lb_read); this.gb_details.Controls.Add(this.lb_messages); this.gb_details.Controls.Add(this.lb_message); this.gb_details.Controls.Add(this.lb_senddata); this.gb_details.Controls.Add(this.lb_recieved); this.gb_details.Controls.Add(this.btn_send); this.gb_details.Controls.Add(this.tb_send); this.gb_details.ForeColor = System.Drawing.Color.White; this.gb_details.Location = new System.Drawing.Point(12, 98); this.gb_details.Name = "gb_details"; this.gb_details.Size = new System.Drawing.Size(428, 291); this.gb_details.TabIndex = 6; this.gb_details.TabStop = false; this.gb_details.Text = "Device Details:"; // // lb_read // this.lb_read.FormattingEnabled = true; this.lb_read.Location = new System.Drawing.Point(232, 32); this.lb_read.Name = "lb_read"; this.lb_read.Size = new System.Drawing.Size(180, 212); this.lb_read.TabIndex = 8; // // usb // this.usb.ProductId = 81; this.usb.VendorId = 1105; this.usb.OnSpecifiedDeviceRemoved += new System.EventHandler(this.usb_OnSpecifiedDeviceRemoved); this.usb.OnDeviceArrived += new System.EventHandler(this.usb_OnDeviceArrived); this.usb.OnDeviceRemoved += new System.EventHandler(this.usb_OnDeviceRemoved); this.usb.OnDataRecieved += new UsbLibrary.DataRecievedEventHandler(this.usb_OnDataRecieved); this.usb.OnSpecifiedDeviceArrived += new System.EventHandler(this.usb_OnSpecifiedDeviceArrived); this.usb.OnDataSend += new System.EventHandler(this.usb_OnDataSend); // // Sniffer // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.Desktop; this.ClientSize = new System.Drawing.Size(453, 401); this.Controls.Add(this.gb_filter); this.Controls.Add(this.gb_details); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Name = "Sniffer"; this.Text = "Sniffer"; this.gb_filter.ResumeLayout(false); this.gb_filter.PerformLayout(); this.gb_details.ResumeLayout(false); this.gb_details.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Label lb_recieved; private System.Windows.Forms.Button btn_send; private System.Windows.Forms.TextBox tb_send; private System.Windows.Forms.Label lb_vendor; private System.Windows.Forms.Button btn_ok; private System.Windows.Forms.Label lb_product; private System.Windows.Forms.Label lb_senddata; private System.Windows.Forms.Label lb_messages; private System.Windows.Forms.TextBox tb_vendor; private System.Windows.Forms.TextBox tb_product; private System.Windows.Forms.GroupBox gb_filter; private System.Windows.Forms.ListBox lb_message; private System.Windows.Forms.GroupBox gb_details; private UsbLibrary.UsbHidPort usb; private System.Windows.Forms.ListBox lb_read; } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; using Amazon; using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.DataModel; using Amazon.DynamoDBv2.DocumentModel; using Amazon.DynamoDBv2.Model; using Amazon.Util; using AspNetCore.Identity.DynamoDB.Extensions; namespace AspNetCore.Identity.DynamoDB { public class DynamoRoleUsersStore<TRole, TUser> where TRole : DynamoIdentityRole where TUser : DynamoIdentityUser { private IAmazonDynamoDB _client; private IDynamoDBContext _context; public async Task AddToRoleAsync(TUser user, string normalisedRoleName, CancellationToken cancellationToken) { if (user == null) { throw new ArgumentNullException(nameof(user)); } cancellationToken.ThrowIfCancellationRequested(); if (!await IsInRoleAsync(user, normalisedRoleName, cancellationToken)) { var roleUser = new DynamoIdentityRoleUser(normalisedRoleName, user.Id); await _context.SaveAsync(roleUser, cancellationToken); } } public async Task RemoveFromRoleAsync(TUser user, string normalisedRoleName, CancellationToken cancellationToken) { if (user == null) { throw new ArgumentNullException(nameof(user)); } cancellationToken.ThrowIfCancellationRequested(); var roleUsers = await QueryRoleUsers(normalisedRoleName, user.Id, cancellationToken); foreach (var roleUser in roleUsers) { await _context.DeleteAsync(roleUser, cancellationToken); } } public async Task<IList<string>> GetRolesAsync(TUser user, CancellationToken cancellationToken) { if (user == null) { throw new ArgumentNullException(nameof(user)); } cancellationToken.ThrowIfCancellationRequested(); var roleUser = await QueryRoleUsers(null, user.Id, cancellationToken); return roleUser.Select(r => r.NormalizedRoleName).Distinct().ToList(); } public async Task<bool> IsInRoleAsync(TUser user, string normalisedRoleName, CancellationToken cancellationToken) { if (user == null) { throw new ArgumentNullException(nameof(user)); } cancellationToken.ThrowIfCancellationRequested(); var roleUser = await QueryRoleUsers(normalisedRoleName, user.Id, cancellationToken); return roleUser.Count != 0; } public async Task<IList<string>> GetUserIdsInRoleAsync(string normalisedRoleName, CancellationToken cancellationToken) { var roleUsers = await QueryRoleUsers(normalisedRoleName, null, cancellationToken); return roleUsers.Select(r => r.UserId).Distinct().ToList(); } internal async Task<IList<DynamoIdentityRoleUser>> QueryRoleUsers(string normalisedRoleName, string userId, CancellationToken cancellationToken) { if (normalisedRoleName == null && userId == null) { throw new ArgumentNullException(nameof(normalisedRoleName)); } cancellationToken.ThrowIfCancellationRequested(); var expressions = new List<string>(); var index = "UserId-NormalizedRoleName-index"; var values = new Dictionary<string, DynamoDBEntry>(); if (normalisedRoleName != null) { index = "NormalizedRoleName-UserId-index"; expressions.Add("NormalizedRoleName = :normalizedRoleName"); values.Add(":normalizedRoleName", normalisedRoleName); } if (userId != null) { expressions.Add("UserId = :userId"); values.Add(":userId", userId); } var expression = string.Join(" AND ", expressions); var search = _context.FromQueryAsync<DynamoIdentityRoleUser>(new QueryOperationConfig { IndexName = index, KeyExpression = new Expression { ExpressionStatement = expression, ExpressionAttributeValues = values } }); return await search.GetRemainingAsync(cancellationToken); } public Task EnsureInitializedAsync(IAmazonDynamoDB client, IDynamoDBContext context, string roleUsersTableName = Constants.DefaultRoleUsersTableName) { if (client == null) { throw new ArgumentNullException(nameof(client)); } if (context == null) { throw new ArgumentNullException(nameof(context)); } _context = context; _client = client; if (roleUsersTableName != Constants.DefaultRoleUsersTableName) { AWSConfigsDynamoDB.Context.AddAlias(new TableAlias(roleUsersTableName, Constants.DefaultRoleUsersTableName)); } return EnsureInitializedImplAsync(client, roleUsersTableName); } private async Task EnsureInitializedImplAsync(IAmazonDynamoDB client, string roleUsersTableName) { var defaultProvisionThroughput = new ProvisionedThroughput { ReadCapacityUnits = 5, WriteCapacityUnits = 5 }; var globalSecondaryIndexes = new List<GlobalSecondaryIndex> { new GlobalSecondaryIndex { IndexName = "NormalizedRoleName-UserId-index", KeySchema = new List<KeySchemaElement> { new KeySchemaElement("NormalizedRoleName", KeyType.HASH), new KeySchemaElement("UserId", KeyType.RANGE) }, ProvisionedThroughput = defaultProvisionThroughput, Projection = new Projection { ProjectionType = ProjectionType.ALL } }, new GlobalSecondaryIndex { IndexName = "UserId-NormalizedRoleName-index", KeySchema = new List<KeySchemaElement> { new KeySchemaElement("UserId", KeyType.HASH), new KeySchemaElement("NormalizedRoleName", KeyType.RANGE) }, ProvisionedThroughput = defaultProvisionThroughput, Projection = new Projection { ProjectionType = ProjectionType.ALL } } }; var tableNames = await client.ListAllTablesAsync(); if (!tableNames.Contains(roleUsersTableName)) { await CreateTableAsync(client, roleUsersTableName, defaultProvisionThroughput, globalSecondaryIndexes); return; } var response = await client.DescribeTableAsync(new DescribeTableRequest {TableName = roleUsersTableName}); var table = response.Table; var indexesToAdd = globalSecondaryIndexes.Where( g => !table.GlobalSecondaryIndexes.Exists(gd => gd.IndexName.Equals(g.IndexName))); var indexUpdates = indexesToAdd.Select(index => new GlobalSecondaryIndexUpdate { Create = new CreateGlobalSecondaryIndexAction { IndexName = index.IndexName, KeySchema = index.KeySchema, ProvisionedThroughput = index.ProvisionedThroughput, Projection = index.Projection } }).ToList(); if (indexUpdates.Count > 0) { await UpdateTableAsync(client, roleUsersTableName, indexUpdates); } } private async Task CreateTableAsync(IAmazonDynamoDB client, string roleUsersTableName, ProvisionedThroughput provisionedThroughput, List<GlobalSecondaryIndex> globalSecondaryIndexes) { var response = await client.CreateTableAsync(new CreateTableRequest { TableName = roleUsersTableName, ProvisionedThroughput = provisionedThroughput, KeySchema = new List<KeySchemaElement> { new KeySchemaElement { AttributeName = "Id", KeyType = KeyType.HASH } }, AttributeDefinitions = new List<AttributeDefinition> { new AttributeDefinition { AttributeName = "Id", AttributeType = ScalarAttributeType.S }, new AttributeDefinition { AttributeName = "NormalizedRoleName", AttributeType = ScalarAttributeType.S }, new AttributeDefinition { AttributeName = "UserId", AttributeType = ScalarAttributeType.S } }, GlobalSecondaryIndexes = globalSecondaryIndexes }); if (response.HttpStatusCode != HttpStatusCode.OK) { throw new Exception($"Couldn't create table {roleUsersTableName}"); } await DynamoUtils.WaitForActiveTableAsync(client, roleUsersTableName); } private async Task UpdateTableAsync(IAmazonDynamoDB client, string roleUsersTableName, List<GlobalSecondaryIndexUpdate> indexUpdates) { await client.UpdateTableAsync(new UpdateTableRequest { TableName = roleUsersTableName, GlobalSecondaryIndexUpdates = indexUpdates }); await DynamoUtils.WaitForActiveTableAsync(client, roleUsersTableName); } } }
using System; using System.Globalization; using Scientia.HtmlRenderer.Core.Parse; using Scientia.HtmlRenderer.Core.Utils; namespace Scientia.HtmlRenderer.Core.Dom { /// <summary> /// Represents and gets info about a CSS Length /// </summary> /// <remarks> /// http://www.w3.org/TR/CSS21/syndata.html#length-units /// </remarks> internal sealed class CssLength { #region Fields private readonly double _Number; private readonly bool _IsRelative; private readonly CssUnit _Unit; private readonly string _Length; private readonly bool _IsPercentage; private readonly bool _HasError; #endregion /// <summary> /// Creates a new CssLength from a length specified on a CSS style sheet or fragment /// </summary> /// <param name="length">Length as specified in the Style Sheet or style fragment</param> public CssLength(string length) { this._Length = length; this._Number = 0f; this._Unit = CssUnit.None; this._IsPercentage = false; // Return zero if no length specified, zero specified if (string.IsNullOrEmpty(length) || length == "0") return; // If percentage, use ParseNumber if (length.EndsWith("%")) { this._Number = CssValueParser.ParseNumber(length, 1); this._IsPercentage = true; return; } // If no units, has error if (length.Length < 3) { double.TryParse(length, out this._Number); this._HasError = true; return; } // Get units of the length string u = length.Substring(length.Length - 2, 2); // Number of the length string number = length.Substring(0, length.Length - 2); // TODO: Units behave different in paper and in screen! switch (u) { case CssConstants.Em: this._Unit = CssUnit.Ems; this._IsRelative = true; break; case CssConstants.Ex: this._Unit = CssUnit.Ex; this._IsRelative = true; break; case CssConstants.Px: this._Unit = CssUnit.Pixels; this._IsRelative = true; break; case CssConstants.Mm: this._Unit = CssUnit.Milimeters; break; case CssConstants.Cm: this._Unit = CssUnit.Centimeters; break; case CssConstants.In: this._Unit = CssUnit.Inches; break; case CssConstants.Pt: this._Unit = CssUnit.Points; break; case CssConstants.Pc: this._Unit = CssUnit.Picas; break; default: this._HasError = true; return; } if (!double.TryParse(number, NumberStyles.Number, NumberFormatInfo.InvariantInfo, out this._Number)) { this._HasError = true; } } #region Props /// <summary> /// Gets the number in the length /// </summary> public double Number { get { return this._Number; } } /// <summary> /// Gets if the length has some parsing error /// </summary> public bool HasError { get { return this._HasError; } } /// <summary> /// Gets if the length represents a precentage (not actually a length) /// </summary> public bool IsPercentage { get { return this._IsPercentage; } } /// <summary> /// Gets if the length is specified in relative units /// </summary> public bool IsRelative { get { return this._IsRelative; } } /// <summary> /// Gets the unit of the length /// </summary> public CssUnit Unit { get { return this._Unit; } } /// <summary> /// Gets the length as specified in the string /// </summary> public string Length { get { return this._Length; } } #endregion #region Methods /// <summary> /// If length is in Ems, returns its value in points /// </summary> /// <param name="emSize">Em size factor to multiply</param> /// <returns>Points size of this em</returns> /// <exception cref="InvalidOperationException">If length has an error or isn't in ems</exception> public CssLength ConvertEmToPoints(double emSize) { if (this.HasError) throw new InvalidOperationException("Invalid length"); if (this.Unit != CssUnit.Ems) throw new InvalidOperationException("Length is not in ems"); return new CssLength(string.Format("{0}pt", Convert.ToSingle(this.Number * emSize).ToString("0.0", NumberFormatInfo.InvariantInfo))); } /// <summary> /// If length is in Ems, returns its value in pixels /// </summary> /// <param name="pixelFactor">Pixel size factor to multiply</param> /// <returns>Pixels size of this em</returns> /// <exception cref="InvalidOperationException">If length has an error or isn't in ems</exception> public CssLength ConvertEmToPixels(double pixelFactor) { if (this.HasError) throw new InvalidOperationException("Invalid length"); if (this.Unit != CssUnit.Ems) throw new InvalidOperationException("Length is not in ems"); return new CssLength(string.Format("{0}px", Convert.ToSingle(this.Number * pixelFactor).ToString("0.0", NumberFormatInfo.InvariantInfo))); } /// <summary> /// Returns the length formatted ready for CSS interpreting. /// </summary> /// <returns></returns> public override string ToString() { if (this.HasError) { return string.Empty; } else if (this.IsPercentage) { return string.Format(NumberFormatInfo.InvariantInfo, "{0}%", this.Number); } else { string u = string.Empty; switch (this.Unit) { case CssUnit.None: break; case CssUnit.Ems: u = "em"; break; case CssUnit.Pixels: u = "px"; break; case CssUnit.Ex: u = "ex"; break; case CssUnit.Inches: u = "in"; break; case CssUnit.Centimeters: u = "cm"; break; case CssUnit.Milimeters: u = "mm"; break; case CssUnit.Points: u = "pt"; break; case CssUnit.Picas: u = "pc"; break; } return string.Format(NumberFormatInfo.InvariantInfo, "{0}{1}", this.Number, u); } } #endregion } }
using System; using System.Collections.Generic; using Newtonsoft.Json; /* * AvaTax API Client Library * * (c) 2004-2018 Avalara, Inc. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @author Ted Spence * @author Zhenya Frolov * @author Greg Hester */ namespace Avalara.AvaTax.RestClient { /// <summary> /// One line item on this transaction. /// </summary> public class TransactionLineModel { /// <summary> /// The unique ID number of this transaction line item. /// </summary> public Int64? id { get; set; } /// <summary> /// The unique ID number of the transaction to which this line item belongs. /// </summary> public Int64? transactionId { get; set; } /// <summary> /// The line number or code indicating the line on this invoice or receipt or document. /// </summary> public String lineNumber { get; set; } /// <summary> /// The unique ID number of the boundary override applied to this line item. /// </summary> public Int32? boundaryOverrideId { get; set; } /// <summary> /// DEPRECATED - The customer usage type for this line item. Usage type often affects taxability rules. /// Please use entityUseCode instead. /// </summary> public String customerUsageType { get; set; } /// <summary> /// The entity use code for this line item. Usage type often affects taxability rules. /// </summary> public String entityUseCode { get; set; } /// <summary> /// A description of the item or service represented by this line. /// </summary> public String description { get; set; } /// <summary> /// The unique ID number of the destination address where this line was delivered or sold. /// In the case of a point-of-sale transaction, the destination address and origin address will be the same. /// In the case of a shipped transaction, they will be different. /// </summary> public Int64? destinationAddressId { get; set; } /// <summary> /// The unique ID number of the origin address where this line was delivered or sold. /// In the case of a point-of-sale transaction, the origin address and destination address will be the same. /// In the case of a shipped transaction, they will be different. /// </summary> public Int64? originAddressId { get; set; } /// <summary> /// The amount of discount that was applied to this line item. This represents the difference between list price and sale price of the item. /// In general, a discount represents money that did not change hands; tax is calculated on only the amount of money that changed hands. /// </summary> public Decimal? discountAmount { get; set; } /// <summary> /// The type of discount, if any, that was applied to this line item. /// </summary> public Int32? discountTypeId { get; set; } /// <summary> /// The amount of this line item that was exempt. /// </summary> public Decimal? exemptAmount { get; set; } /// <summary> /// The unique ID number of the exemption certificate that applied to this line item. It is the calc_id associated with a certificate in CertCapture. /// </summary> public Int32? exemptCertId { get; set; } /// <summary> /// The CertCapture Certificate ID /// </summary> public String certificateId { get; set; } /// <summary> /// The customer Tax Id Number (tax_number) associated with a certificate - Sales tax calculation requests first determine if there is an applicable /// ECMS entry available, and will utilize it for exemption processing. If no applicable ECMS entry is available, the AvaTax service /// will determine if an Exemption Number field is populated or an Entity/Use Code is included in the sales tax calculation request, /// and will perform exemption processing using either of those two options. /// </summary> public String exemptNo { get; set; } /// <summary> /// True if this item is taxable. /// </summary> public Boolean? isItemTaxable { get; set; } /// <summary> /// True if this item is a Streamlined Sales Tax line item. /// </summary> public Boolean? isSSTP { get; set; } /// <summary> /// The code string of the item represented by this line item. /// </summary> public String itemCode { get; set; } /// <summary> /// The total amount of the transaction, including both taxable and exempt. This is the total price for all items. /// To determine the individual item price, divide this by quantity. /// </summary> public Decimal? lineAmount { get; set; } /// <summary> /// The quantity of products sold on this line item. /// </summary> public Decimal? quantity { get; set; } /// <summary> /// A user-defined reference identifier for this transaction line item. /// </summary> public String ref1 { get; set; } /// <summary> /// A user-defined reference identifier for this transaction line item. /// </summary> public String ref2 { get; set; } /// <summary> /// The date when this transaction should be reported. By default, all transactions are reported on the date when the actual transaction took place. /// In some cases, line items may be reported later due to delayed shipments or other business reasons. /// </summary> public DateTime? reportingDate { get; set; } /// <summary> /// The revenue account number for this line item. /// </summary> public String revAccount { get; set; } /// <summary> /// Indicates whether this line item was taxed according to the origin or destination. /// </summary> public Sourcing? sourcing { get; set; } /// <summary> /// The tax for this line in this transaction. /// /// If you used a `taxOverride` of type `taxAmount` for this line, this value /// will represent the amount of your override. AvaTax will still attempt to calculate the correct tax /// for this line and will store that calculated value in the `taxCalculated` field. /// /// You can compare the `tax` and `taxCalculated` fields to check for any discrepancies /// between an external tax calculation provider and the calculation performed by AvaTax. /// </summary> public Decimal? tax { get; set; } /// <summary> /// The taxable amount of this line item. /// </summary> public Decimal? taxableAmount { get; set; } /// <summary> /// The amount of tax that AvaTax calculated for the transaction. /// /// If you used a `taxOverride` of type `taxAmount` for this line, there will be a difference between /// the `tax` field which represents your override, and the `taxCalculated` field which represents the /// amount of tax that AvaTax calculated for this line. /// /// You can compare the `tax` and `taxCalculated` fields to check for any discrepancies /// between an external tax calculation provider and the calculation performed by AvaTax. /// </summary> public Decimal? taxCalculated { get; set; } /// <summary> /// The code string for the tax code that was used to calculate this line item. /// </summary> public String taxCode { get; set; } /// <summary> /// The unique ID number for the tax code that was used to calculate this line item. /// </summary> public Int32? taxCodeId { get; set; } /// <summary> /// The date that was used for calculating tax amounts for this line item. By default, this date should be the same as the document date. /// In some cases, for example when a consumer returns a product purchased previously, line items may be calculated using a tax date in the past /// so that the consumer can receive a refund for the correct tax amount that was charged when the item was originally purchased. /// </summary> public DateTime? taxDate { get; set; } /// <summary> /// The tax engine identifier that was used to calculate this line item. /// </summary> public String taxEngine { get; set; } /// <summary> /// If a tax override was specified, this indicates the type of tax override. /// </summary> public TaxOverrideType? taxOverrideType { get; set; } /// <summary> /// VAT business identification number used for this transaction. /// </summary> public String businessIdentificationNo { get; set; } /// <summary> /// If a tax override was specified, this indicates the amount of tax that was requested. /// </summary> public Decimal? taxOverrideAmount { get; set; } /// <summary> /// If a tax override was specified, represents the reason for the tax override. /// </summary> public String taxOverrideReason { get; set; } /// <summary> /// Indicates whether the `amount` for this line already includes tax. /// /// If this value is `true`, the final price of this line including tax will equal the value in `amount`. /// /// If this value is `null` or `false`, the final price will equal `amount` plus whatever taxes apply to this line. /// </summary> public Boolean? taxIncluded { get; set; } /// <summary> /// Optional: A list of tax details for this line item. /// /// Tax details represent taxes being charged by various tax authorities. Taxes that appear in the `details` collection are intended to be /// displayed to the customer and charged as a 'tax' on the invoice. /// /// To fetch this list, add the query string `?$include=Details` to your URL. /// </summary> public List<TransactionLineDetailModel> details { get; set; } /// <summary> /// Optional: A list of non-passthrough tax details for this line item. /// /// Tax details represent taxes being charged by various tax authorities. Taxes that appear in the `nonPassthroughDetails` collection are /// taxes that must be paid directly by the company and not shown to the customer. /// </summary> public List<TransactionLineDetailModel> nonPassthroughDetails { get; set; } /// <summary> /// Optional: A list of location types for this line item. To fetch this list, add the query string "?$include=LineLocationTypes" to your URL. /// </summary> public List<TransactionLineLocationTypeModel> lineLocationTypes { get; set; } /// <summary> /// Contains a list of extra parameters that were set when the transaction was created. /// </summary> public Dictionary<string, string> parameters { get; set; } /// <summary> /// The cross-border harmonized system code (HSCode) used to calculate tariffs and duties for this line item. /// For a full list of HS codes, see `ListCrossBorderCodes()`. /// </summary> public String hsCode { get; set; } /// <summary> /// Indicates the cost of insurance and freight for this line. /// </summary> public Decimal? costInsuranceFreight { get; set; } /// <summary> /// Indicates the VAT code for this line item. /// </summary> public String vatCode { get; set; } /// <summary> /// Indicates the VAT number type for this line item. /// </summary> public Int32? vatNumberTypeId { get; set; } /// <summary> /// Convert this object to a JSON string of itself /// </summary> /// <returns>A JSON string of this object</returns> public override string ToString() { return JsonConvert.SerializeObject(this, new JsonSerializerSettings() { Formatting = Formatting.Indented }); } } }
// // TreeNode.cs // // Author: // Lluis Sanchez Gual // // Copyright (C) 2007 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Text; using System.Collections; using Mono.Addins.Description; namespace Mono.Addins { class TreeNode { ArrayList childrenList; TreeNodeCollection children; ExtensionNode extensionNode; bool childrenLoaded; string id; TreeNode parent; ExtensionNodeSet nodeTypes; ExtensionPoint extensionPoint; BaseCondition condition; protected AddinEngine addinEngine; public TreeNode (AddinEngine addinEngine, string id) { this.id = id; this.addinEngine = addinEngine; // Root node if (id.Length == 0) childrenLoaded = true; } public AddinEngine AddinEngine { get { return addinEngine; } } internal void AttachExtensionNode (ExtensionNode enode) { this.extensionNode = enode; if (extensionNode != null) extensionNode.SetTreeNode (this); } public string Id { get { return id; } } public ExtensionNode ExtensionNode { get { if (extensionNode == null && extensionPoint != null) { extensionNode = new ExtensionNode (); extensionNode.SetData (addinEngine, extensionPoint.RootAddin, null, null); AttachExtensionNode (extensionNode); } return extensionNode; } } public ExtensionPoint ExtensionPoint { get { return extensionPoint; } set { extensionPoint = value; } } public ExtensionNodeSet ExtensionNodeSet { get { return nodeTypes; } set { nodeTypes = value; } } public TreeNode Parent { get { return parent; } } public BaseCondition Condition { get { return condition; } set { condition = value; } } public virtual ExtensionContext Context { get { if (parent != null) return parent.Context; else return null; } } public bool IsEnabled { get { if (condition == null) return true; ExtensionContext ctx = Context; if (ctx == null) return true; else return condition.Evaluate (ctx); } } public bool ChildrenLoaded { get { return childrenLoaded; } } public void AddChildNode (TreeNode node) { node.parent = this; if (childrenList == null) childrenList = new ArrayList (); childrenList.Add (node); } public void InsertChildNode (int n, TreeNode node) { node.parent = this; if (childrenList == null) childrenList = new ArrayList (); childrenList.Insert (n, node); // Dont call NotifyChildrenChanged here. It is called by ExtensionTree, // after inserting all children of the node. } internal int ChildCount { get { return childrenList == null ? 0 : childrenList.Count; } } public ExtensionNode GetExtensionNode (string path, string childId) { TreeNode node = GetNode (path, childId); return node != null ? node.ExtensionNode : null; } public ExtensionNode GetExtensionNode (string path) { TreeNode node = GetNode (path); return node != null ? node.ExtensionNode : null; } public TreeNode GetNode (string path, string childId) { if (childId == null || childId.Length == 0) return GetNode (path); else return GetNode (path + "/" + childId); } public TreeNode GetNode (string path) { return GetNode (path, false); } public TreeNode GetNode (string path, bool buildPath) { if (path.StartsWith ("/")) path = path.Substring (1); string[] parts = path.Split ('/'); TreeNode curNode = this; foreach (string part in parts) { int i = curNode.Children.IndexOfNode (part); if (i != -1) { curNode = curNode.Children [i]; continue; } if (buildPath) { TreeNode newNode = new TreeNode (addinEngine, part); curNode.AddChildNode (newNode); curNode = newNode; } else return null; } return curNode; } public TreeNodeCollection Children { get { if (!childrenLoaded) { childrenLoaded = true; if (extensionPoint != null) Context.LoadExtensions (GetPath ()); // We have to keep the relation info, since add-ins may be loaded/unloaded } if (childrenList == null) return TreeNodeCollection.Empty; if (children == null) children = new TreeNodeCollection (childrenList); return children; } } public string GetPath () { int num=0; TreeNode node = this; while (node != null) { num++; node = node.parent; } string[] ids = new string [num]; node = this; while (node != null) { ids [--num] = node.id; node = node.parent; } return string.Join ("/", ids); } public void NotifyAddinLoaded (RuntimeAddin ad, bool recursive) { if (extensionNode != null && extensionNode.AddinId == ad.Addin.Id) extensionNode.OnAddinLoaded (); if (recursive && childrenLoaded) { foreach (TreeNode node in Children.Clone ()) node.NotifyAddinLoaded (ad, true); } } public ExtensionPoint FindLoadedExtensionPoint (string path) { if (path.StartsWith ("/")) path = path.Substring (1); string[] parts = path.Split ('/'); TreeNode curNode = this; foreach (string part in parts) { int i = curNode.Children.IndexOfNode (part); if (i != -1) { curNode = curNode.Children [i]; if (!curNode.ChildrenLoaded) return null; if (curNode.ExtensionPoint != null) return curNode.ExtensionPoint; continue; } return null; } return null; } public void FindAddinNodes (string id, ArrayList nodes) { if (id != null && extensionPoint != null && extensionPoint.RootAddin == id) { // It is an extension point created by the add-in. All nodes below this // extension point will be added to the list, even if they come from other add-ins. id = null; } if (childrenLoaded) { // Deep-first search, to make sure children are removed before the parent. foreach (TreeNode node in Children) node.FindAddinNodes (id, nodes); } if (id == null || (ExtensionNode != null && ExtensionNode.AddinId == id)) nodes.Add (this); } public bool FindExtensionPathByType (IProgressStatus monitor, Type type, string nodeName, out string path, out string pathNodeName) { if (extensionPoint != null) { foreach (ExtensionNodeType nt in extensionPoint.NodeSet.NodeTypes) { if (nt.ObjectTypeName.Length > 0 && (nodeName.Length == 0 || nodeName == nt.Id)) { RuntimeAddin addin = addinEngine.GetAddin (extensionPoint.RootAddin); Type ot = addin.GetType (nt.ObjectTypeName); if (ot != null) { if (ot.IsAssignableFrom (type)) { path = extensionPoint.Path; pathNodeName = nt.Id; return true; } } else monitor.ReportError ("Type '" + nt.ObjectTypeName + "' not found in add-in '" + Id + "'", null); } } } else { foreach (TreeNode node in Children) { if (node.FindExtensionPathByType (monitor, type, nodeName, out path, out pathNodeName)) return true; } } path = null; pathNodeName = null; return false; } public void Remove () { if (parent != null) { if (Condition != null) Context.UnregisterNodeCondition (this, Condition); parent.childrenList.Remove (this); parent.NotifyChildrenChanged (); } } public bool NotifyChildrenChanged () { if (extensionNode != null) return extensionNode.NotifyChildChanged (); else return false; } public void ResetCachedData () { if (extensionPoint != null) { string aid = Addin.GetIdName (extensionPoint.ParentAddinDescription.AddinId); RuntimeAddin ad = addinEngine.GetAddin (aid); if (ad != null) extensionPoint = ad.Addin.Description.ExtensionPoints [GetPath ()]; } if (childrenList != null) { foreach (TreeNode cn in childrenList) cn.ResetCachedData (); } } } }
// 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.Net.Security; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; namespace System.Net.Http { // This implementation uses the System.Net.Http.WinHttpHandler class on Windows. Other platforms will need to use // their own platform specific implementation. public partial class HttpClientHandler : HttpMessageHandler { private readonly WinHttpHandler _winHttpHandler; private readonly SocketsHttpHandler _socketsHttpHandler; private readonly DiagnosticsHandler _diagnosticsHandler; private bool _useProxy; public HttpClientHandler() : this(UseSocketsHttpHandler) { } private HttpClientHandler(bool useSocketsHttpHandler) // used by parameterless ctor and as hook for testing { if (useSocketsHttpHandler) { _socketsHttpHandler = new SocketsHttpHandler(); _diagnosticsHandler = new DiagnosticsHandler(_socketsHttpHandler); } else { _winHttpHandler = new WinHttpHandler(); _diagnosticsHandler = new DiagnosticsHandler(_winHttpHandler); // Adjust defaults to match current .NET Desktop HttpClientHandler (based on HWR stack). AllowAutoRedirect = true; AutomaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression; UseProxy = true; UseCookies = true; CookieContainer = new CookieContainer(); _winHttpHandler.DefaultProxyCredentials = null; _winHttpHandler.ServerCredentials = null; // The existing .NET Desktop HttpClientHandler based on the HWR stack uses only WinINet registry // settings for the proxy. This also includes supporting the "Automatic Detect a proxy" using // WPAD protocol and PAC file. So, for app-compat, we will do the same for the default proxy setting. _winHttpHandler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy; _winHttpHandler.Proxy = null; // Since the granular WinHttpHandler timeout properties are not exposed via the HttpClientHandler API, // we need to set them to infinite and allow the HttpClient.Timeout property to have precedence. _winHttpHandler.ReceiveHeadersTimeout = Timeout.InfiniteTimeSpan; _winHttpHandler.ReceiveDataTimeout = Timeout.InfiniteTimeSpan; _winHttpHandler.SendTimeout = Timeout.InfiniteTimeSpan; } } protected override void Dispose(bool disposing) { if (disposing && !_disposed) { _disposed = true; ((HttpMessageHandler)_winHttpHandler ?? _socketsHttpHandler).Dispose(); } base.Dispose(disposing); } public virtual bool SupportsAutomaticDecompression => true; public virtual bool SupportsProxy => true; public virtual bool SupportsRedirectConfiguration => true; public bool UseCookies { get => _winHttpHandler != null ? _winHttpHandler.CookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer : _socketsHttpHandler.UseCookies; set { if (_winHttpHandler != null) { _winHttpHandler.CookieUsePolicy = value ? CookieUsePolicy.UseSpecifiedCookieContainer : CookieUsePolicy.IgnoreCookies; } else { _socketsHttpHandler.UseCookies = value; } } } public CookieContainer CookieContainer { get => _winHttpHandler != null ? _winHttpHandler.CookieContainer : _socketsHttpHandler.CookieContainer; set { if (_winHttpHandler != null) { _winHttpHandler.CookieContainer = value; } else { _socketsHttpHandler.CookieContainer = value; } } } public DecompressionMethods AutomaticDecompression { get => _winHttpHandler != null ? _winHttpHandler.AutomaticDecompression : _socketsHttpHandler.AutomaticDecompression; set { if (_winHttpHandler != null) { _winHttpHandler.AutomaticDecompression = value; } else { _socketsHttpHandler.AutomaticDecompression = value; } } } public bool UseProxy { get => _winHttpHandler != null ? _useProxy : _socketsHttpHandler.UseProxy; set { if (_winHttpHandler != null) { _useProxy = value; } else { _socketsHttpHandler.UseProxy = value; } } } public IWebProxy Proxy { get => _winHttpHandler != null ? _winHttpHandler.Proxy : _socketsHttpHandler.Proxy; set { if (_winHttpHandler != null) { _winHttpHandler.Proxy = value; } else { _socketsHttpHandler.Proxy = value; } } } public ICredentials DefaultProxyCredentials { get => _winHttpHandler != null ? _winHttpHandler.DefaultProxyCredentials : _socketsHttpHandler.DefaultProxyCredentials; set { if (_winHttpHandler != null) { _winHttpHandler.DefaultProxyCredentials = value; } else { _socketsHttpHandler.DefaultProxyCredentials = value; } } } public bool PreAuthenticate { get => _winHttpHandler != null ? _winHttpHandler.PreAuthenticate : _socketsHttpHandler.PreAuthenticate; set { if (_winHttpHandler != null) { _winHttpHandler.PreAuthenticate = value; } else { _socketsHttpHandler.PreAuthenticate = value; } } } public bool UseDefaultCredentials { // WinHttpHandler doesn't have a separate UseDefaultCredentials property. There // is just a ServerCredentials property. So, we need to map the behavior. // // This property only affect .ServerCredentials and not .DefaultProxyCredentials. get => _winHttpHandler != null ? _winHttpHandler.ServerCredentials == CredentialCache.DefaultCredentials : false; set { if (_winHttpHandler != null) { if (value) { _winHttpHandler.ServerCredentials = CredentialCache.DefaultCredentials; } else { if (_winHttpHandler.ServerCredentials == CredentialCache.DefaultCredentials) { // Only clear out the ServerCredentials property if it was a DefaultCredentials. _winHttpHandler.ServerCredentials = null; } } } } } public ICredentials Credentials { get => _winHttpHandler != null ? _winHttpHandler.ServerCredentials : _socketsHttpHandler.Credentials; set { if (_winHttpHandler != null) { _winHttpHandler.ServerCredentials = value; } else { _socketsHttpHandler.Credentials = value; } } } public bool AllowAutoRedirect { get => _winHttpHandler != null ? _winHttpHandler.AutomaticRedirection : _socketsHttpHandler.AllowAutoRedirect; set { if (_winHttpHandler != null) { _winHttpHandler.AutomaticRedirection = value; } else { _socketsHttpHandler.AllowAutoRedirect = value; } } } public int MaxAutomaticRedirections { get => _winHttpHandler != null ? _winHttpHandler.MaxAutomaticRedirections : _socketsHttpHandler.MaxAutomaticRedirections; set { if (_winHttpHandler != null) { _winHttpHandler.MaxAutomaticRedirections = value; } else { _socketsHttpHandler.MaxAutomaticRedirections = value; } } } public int MaxConnectionsPerServer { get => _winHttpHandler != null ? _winHttpHandler.MaxConnectionsPerServer : _socketsHttpHandler.MaxConnectionsPerServer; set { if (_winHttpHandler != null) { _winHttpHandler.MaxConnectionsPerServer = value; } else { _socketsHttpHandler.MaxConnectionsPerServer = value; } } } public int MaxResponseHeadersLength { get => _winHttpHandler != null ? _winHttpHandler.MaxResponseHeadersLength : _socketsHttpHandler.MaxResponseHeadersLength; set { if (_winHttpHandler != null) { _winHttpHandler.MaxResponseHeadersLength = value; } else { _socketsHttpHandler.MaxResponseHeadersLength = value; } } } public ClientCertificateOption ClientCertificateOptions { get { if (_winHttpHandler != null) { return _winHttpHandler.ClientCertificateOption; } else { return _socketsHttpHandler.SslOptions.LocalCertificateSelectionCallback != null ? ClientCertificateOption.Automatic : ClientCertificateOption.Manual; } } set { if (_winHttpHandler != null) { _winHttpHandler.ClientCertificateOption = value; } else { switch (value) { case ClientCertificateOption.Manual: ThrowForModifiedManagedSslOptionsIfStarted(); _socketsHttpHandler.SslOptions.LocalCertificateSelectionCallback = null; break; case ClientCertificateOption.Automatic: ThrowForModifiedManagedSslOptionsIfStarted(); _socketsHttpHandler.SslOptions.LocalCertificateSelectionCallback = (sender, targetHost, localCertificates, remoteCertificate, acceptableIssuers) => CertificateHelper.GetEligibleClientCertificate(); break; default: throw new ArgumentOutOfRangeException(nameof(value)); } } } } public X509CertificateCollection ClientCertificates { get { if (_winHttpHandler != null) { return _winHttpHandler.ClientCertificates; } else { if (ClientCertificateOptions != ClientCertificateOption.Manual) { throw new InvalidOperationException(SR.Format(SR.net_http_invalid_enable_first, nameof(ClientCertificateOptions), nameof(ClientCertificateOption.Manual))); } return _socketsHttpHandler.SslOptions.ClientCertificates ?? (_socketsHttpHandler.SslOptions.ClientCertificates = new X509CertificateCollection()); } } } public Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> ServerCertificateCustomValidationCallback { get { return _winHttpHandler != null ? _winHttpHandler.ServerCertificateValidationCallback : (_socketsHttpHandler.SslOptions.RemoteCertificateValidationCallback?.Target as ConnectHelper.CertificateCallbackMapper)?.FromHttpClientHandler; } set { if (_winHttpHandler != null) { _winHttpHandler.ServerCertificateValidationCallback = value; } else { ThrowForModifiedManagedSslOptionsIfStarted(); _socketsHttpHandler.SslOptions.RemoteCertificateValidationCallback = value != null ? new ConnectHelper.CertificateCallbackMapper(value).ForSocketsHttpHandler : null; } } } public bool CheckCertificateRevocationList { get => _winHttpHandler != null ? _winHttpHandler.CheckCertificateRevocationList : _socketsHttpHandler.SslOptions.CertificateRevocationCheckMode == X509RevocationMode.Online; set { if (_winHttpHandler != null) { _winHttpHandler.CheckCertificateRevocationList = value; } else { ThrowForModifiedManagedSslOptionsIfStarted(); _socketsHttpHandler.SslOptions.CertificateRevocationCheckMode = value ? X509RevocationMode.Online : X509RevocationMode.NoCheck; } } } public SslProtocols SslProtocols { get => _winHttpHandler != null ? _winHttpHandler.SslProtocols : _socketsHttpHandler.SslOptions.EnabledSslProtocols; set { if (_winHttpHandler != null) { _winHttpHandler.SslProtocols = value; } else { SecurityProtocol.ThrowOnNotAllowed(value, allowNone: true); ThrowForModifiedManagedSslOptionsIfStarted(); _socketsHttpHandler.SslOptions.EnabledSslProtocols = value; } } } public IDictionary<string, object> Properties => _winHttpHandler != null ? _winHttpHandler.Properties : _socketsHttpHandler.Properties; protected internal override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { if (_winHttpHandler != null) { // Get current value of WindowsProxyUsePolicy. Only call its WinHttpHandler // property setter if the value needs to change. var oldProxyUsePolicy = _winHttpHandler.WindowsProxyUsePolicy; if (_useProxy) { if (_winHttpHandler.Proxy == null) { if (oldProxyUsePolicy != WindowsProxyUsePolicy.UseWinInetProxy) { _winHttpHandler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy; } } else { if (oldProxyUsePolicy != WindowsProxyUsePolicy.UseCustomProxy) { _winHttpHandler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseCustomProxy; } } } else { if (oldProxyUsePolicy != WindowsProxyUsePolicy.DoNotUseProxy) { _winHttpHandler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.DoNotUseProxy; } } return DiagnosticsHandler.IsEnabled() ? _diagnosticsHandler.SendAsync(request, cancellationToken) : _winHttpHandler.SendAsync(request, cancellationToken); } else { return DiagnosticsHandler.IsEnabled() ? _diagnosticsHandler.SendAsync(request, cancellationToken) : _socketsHttpHandler.SendAsync(request, cancellationToken); } } } }