content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
#pragma warning disable CS1591 using System; using System.Runtime.InteropServices; using System.Collections.Generic; using System.Linq; using System.ComponentModel; namespace Efl { namespace Ui { ///<summary>Event argument wrapper for event <see cref="Efl.Ui.ImageZoomable.DownloadProgressEvt"/>.</summary> public class ImageZoomableDownloadProgressEvt_Args : EventArgs { ///<summary>Actual event payload.</summary> public Elm.Photocam.Progress arg { get; set; } } ///<summary>Event argument wrapper for event <see cref="Efl.Ui.ImageZoomable.DownloadErrorEvt"/>.</summary> public class ImageZoomableDownloadErrorEvt_Args : EventArgs { ///<summary>Actual event payload.</summary> public Elm.Photocam.Error arg { get; set; } } /// <summary>Elementary Image Zoomable class</summary> [ImageZoomableNativeInherit] public class ImageZoomable : Efl.Ui.Image, Efl.Eo.IWrapper,Efl.Ui.IScrollable,Efl.Ui.IScrollableInteractive,Efl.Ui.IScrollbar,Efl.Ui.IZoom { ///<summary>Pointer to the native class description.</summary> public override System.IntPtr NativeClass { get { if (((object)this).GetType() == typeof (ImageZoomable)) return Efl.Ui.ImageZoomableNativeInherit.GetEflClassStatic(); else return Efl.Eo.ClassRegister.klassFromType[((object)this).GetType()]; } } [System.Runtime.InteropServices.DllImport(efl.Libs.Elementary)] internal static extern System.IntPtr efl_ui_image_zoomable_class_get(); ///<summary>Creates a new instance.</summary> ///<param name="parent">Parent instance.</param> ///<param name="style">The widget style to use. See <see cref="Efl.Ui.Widget.SetStyle"/></param> public ImageZoomable(Efl.Object parent , System.String style = null) : base(efl_ui_image_zoomable_class_get(), typeof(ImageZoomable), parent) { if (Efl.Eo.Globals.ParamHelperCheck(style)) SetStyle(Efl.Eo.Globals.GetParamHelper(style)); FinishInstantiation(); } ///<summary>Internal usage: Constructs an instance from a native pointer. This is used when interacting with C code and should not be used directly.</summary> protected ImageZoomable(System.IntPtr raw) : base(raw) { RegisterEventProxies(); } ///<summary>Internal usage: Constructor to forward the wrapper initialization to the root class that interfaces with native code. Should not be used directly.</summary> protected ImageZoomable(IntPtr base_klass, System.Type managed_type, Efl.Object parent) : base(base_klass, managed_type, parent) {} ///<summary>Verifies if the given object is equal to this one.</summary> public override bool Equals(object obj) { var other = obj as Efl.Object; if (other == null) return false; return this.NativeHandle == other.NativeHandle; } ///<summary>Gets the hash code for this object based on the native pointer it points to.</summary> public override int GetHashCode() { return this.NativeHandle.ToInt32(); } ///<summary>Turns the native pointer into a string representation.</summary> public override String ToString() { return $"{this.GetType().Name}@[{this.NativeHandle.ToInt32():x}]"; } private static object PressEvtKey = new object(); /// <summary>Called when photocam got pressed</summary> public event EventHandler PressEvt { add { lock (eventLock) { string key = "_EFL_UI_IMAGE_ZOOMABLE_EVENT_PRESS"; if (AddNativeEventHandler(efl.Libs.Elementary, key, this.evt_PressEvt_delegate)) { eventHandlers.AddHandler(PressEvtKey , value); } else Eina.Log.Error($"Error adding proxy for event {key}"); } } remove { lock (eventLock) { string key = "_EFL_UI_IMAGE_ZOOMABLE_EVENT_PRESS"; if (RemoveNativeEventHandler(key, this.evt_PressEvt_delegate)) { eventHandlers.RemoveHandler(PressEvtKey , value); } else Eina.Log.Error($"Error removing proxy for event {key}"); } } } ///<summary>Method to raise event PressEvt.</summary> public void On_PressEvt(EventArgs e) { EventHandler evt; lock (eventLock) { evt = (EventHandler)eventHandlers[PressEvtKey]; } evt?.Invoke(this, e); } Efl.EventCb evt_PressEvt_delegate; private void on_PressEvt_NativeCallback(System.IntPtr data, ref Efl.Event.NativeStruct evt) { EventArgs args = EventArgs.Empty; try { On_PressEvt(args); } catch (Exception e) { Eina.Log.Error(e.ToString()); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } private static object LoadEvtKey = new object(); /// <summary>Called when photocam loading started</summary> public event EventHandler LoadEvt { add { lock (eventLock) { string key = "_EFL_UI_IMAGE_ZOOMABLE_EVENT_LOAD"; if (AddNativeEventHandler(efl.Libs.Elementary, key, this.evt_LoadEvt_delegate)) { eventHandlers.AddHandler(LoadEvtKey , value); } else Eina.Log.Error($"Error adding proxy for event {key}"); } } remove { lock (eventLock) { string key = "_EFL_UI_IMAGE_ZOOMABLE_EVENT_LOAD"; if (RemoveNativeEventHandler(key, this.evt_LoadEvt_delegate)) { eventHandlers.RemoveHandler(LoadEvtKey , value); } else Eina.Log.Error($"Error removing proxy for event {key}"); } } } ///<summary>Method to raise event LoadEvt.</summary> public void On_LoadEvt(EventArgs e) { EventHandler evt; lock (eventLock) { evt = (EventHandler)eventHandlers[LoadEvtKey]; } evt?.Invoke(this, e); } Efl.EventCb evt_LoadEvt_delegate; private void on_LoadEvt_NativeCallback(System.IntPtr data, ref Efl.Event.NativeStruct evt) { EventArgs args = EventArgs.Empty; try { On_LoadEvt(args); } catch (Exception e) { Eina.Log.Error(e.ToString()); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } private static object LoadedEvtKey = new object(); /// <summary>Called when photocam loading finished</summary> public event EventHandler LoadedEvt { add { lock (eventLock) { string key = "_EFL_UI_IMAGE_ZOOMABLE_EVENT_LOADED"; if (AddNativeEventHandler(efl.Libs.Elementary, key, this.evt_LoadedEvt_delegate)) { eventHandlers.AddHandler(LoadedEvtKey , value); } else Eina.Log.Error($"Error adding proxy for event {key}"); } } remove { lock (eventLock) { string key = "_EFL_UI_IMAGE_ZOOMABLE_EVENT_LOADED"; if (RemoveNativeEventHandler(key, this.evt_LoadedEvt_delegate)) { eventHandlers.RemoveHandler(LoadedEvtKey , value); } else Eina.Log.Error($"Error removing proxy for event {key}"); } } } ///<summary>Method to raise event LoadedEvt.</summary> public void On_LoadedEvt(EventArgs e) { EventHandler evt; lock (eventLock) { evt = (EventHandler)eventHandlers[LoadedEvtKey]; } evt?.Invoke(this, e); } Efl.EventCb evt_LoadedEvt_delegate; private void on_LoadedEvt_NativeCallback(System.IntPtr data, ref Efl.Event.NativeStruct evt) { EventArgs args = EventArgs.Empty; try { On_LoadedEvt(args); } catch (Exception e) { Eina.Log.Error(e.ToString()); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } private static object LoadDetailEvtKey = new object(); /// <summary>Called when photocal detail loading started</summary> public event EventHandler LoadDetailEvt { add { lock (eventLock) { string key = "_EFL_UI_IMAGE_ZOOMABLE_EVENT_LOAD_DETAIL"; if (AddNativeEventHandler(efl.Libs.Elementary, key, this.evt_LoadDetailEvt_delegate)) { eventHandlers.AddHandler(LoadDetailEvtKey , value); } else Eina.Log.Error($"Error adding proxy for event {key}"); } } remove { lock (eventLock) { string key = "_EFL_UI_IMAGE_ZOOMABLE_EVENT_LOAD_DETAIL"; if (RemoveNativeEventHandler(key, this.evt_LoadDetailEvt_delegate)) { eventHandlers.RemoveHandler(LoadDetailEvtKey , value); } else Eina.Log.Error($"Error removing proxy for event {key}"); } } } ///<summary>Method to raise event LoadDetailEvt.</summary> public void On_LoadDetailEvt(EventArgs e) { EventHandler evt; lock (eventLock) { evt = (EventHandler)eventHandlers[LoadDetailEvtKey]; } evt?.Invoke(this, e); } Efl.EventCb evt_LoadDetailEvt_delegate; private void on_LoadDetailEvt_NativeCallback(System.IntPtr data, ref Efl.Event.NativeStruct evt) { EventArgs args = EventArgs.Empty; try { On_LoadDetailEvt(args); } catch (Exception e) { Eina.Log.Error(e.ToString()); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } private static object LoadedDetailEvtKey = new object(); /// <summary>Called when photocam detail loading finished</summary> public event EventHandler LoadedDetailEvt { add { lock (eventLock) { string key = "_EFL_UI_IMAGE_ZOOMABLE_EVENT_LOADED_DETAIL"; if (AddNativeEventHandler(efl.Libs.Elementary, key, this.evt_LoadedDetailEvt_delegate)) { eventHandlers.AddHandler(LoadedDetailEvtKey , value); } else Eina.Log.Error($"Error adding proxy for event {key}"); } } remove { lock (eventLock) { string key = "_EFL_UI_IMAGE_ZOOMABLE_EVENT_LOADED_DETAIL"; if (RemoveNativeEventHandler(key, this.evt_LoadedDetailEvt_delegate)) { eventHandlers.RemoveHandler(LoadedDetailEvtKey , value); } else Eina.Log.Error($"Error removing proxy for event {key}"); } } } ///<summary>Method to raise event LoadedDetailEvt.</summary> public void On_LoadedDetailEvt(EventArgs e) { EventHandler evt; lock (eventLock) { evt = (EventHandler)eventHandlers[LoadedDetailEvtKey]; } evt?.Invoke(this, e); } Efl.EventCb evt_LoadedDetailEvt_delegate; private void on_LoadedDetailEvt_NativeCallback(System.IntPtr data, ref Efl.Event.NativeStruct evt) { EventArgs args = EventArgs.Empty; try { On_LoadedDetailEvt(args); } catch (Exception e) { Eina.Log.Error(e.ToString()); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } private static object DownloadStartEvtKey = new object(); /// <summary>Called when photocam download started</summary> public event EventHandler DownloadStartEvt { add { lock (eventLock) { string key = "_EFL_UI_IMAGE_ZOOMABLE_EVENT_DOWNLOAD_START"; if (AddNativeEventHandler(efl.Libs.Elementary, key, this.evt_DownloadStartEvt_delegate)) { eventHandlers.AddHandler(DownloadStartEvtKey , value); } else Eina.Log.Error($"Error adding proxy for event {key}"); } } remove { lock (eventLock) { string key = "_EFL_UI_IMAGE_ZOOMABLE_EVENT_DOWNLOAD_START"; if (RemoveNativeEventHandler(key, this.evt_DownloadStartEvt_delegate)) { eventHandlers.RemoveHandler(DownloadStartEvtKey , value); } else Eina.Log.Error($"Error removing proxy for event {key}"); } } } ///<summary>Method to raise event DownloadStartEvt.</summary> public void On_DownloadStartEvt(EventArgs e) { EventHandler evt; lock (eventLock) { evt = (EventHandler)eventHandlers[DownloadStartEvtKey]; } evt?.Invoke(this, e); } Efl.EventCb evt_DownloadStartEvt_delegate; private void on_DownloadStartEvt_NativeCallback(System.IntPtr data, ref Efl.Event.NativeStruct evt) { EventArgs args = EventArgs.Empty; try { On_DownloadStartEvt(args); } catch (Exception e) { Eina.Log.Error(e.ToString()); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } private static object DownloadProgressEvtKey = new object(); /// <summary>Called when photocam download progress updated</summary> public event EventHandler<Efl.Ui.ImageZoomableDownloadProgressEvt_Args> DownloadProgressEvt { add { lock (eventLock) { string key = "_EFL_UI_IMAGE_ZOOMABLE_EVENT_DOWNLOAD_PROGRESS"; if (AddNativeEventHandler(efl.Libs.Elementary, key, this.evt_DownloadProgressEvt_delegate)) { eventHandlers.AddHandler(DownloadProgressEvtKey , value); } else Eina.Log.Error($"Error adding proxy for event {key}"); } } remove { lock (eventLock) { string key = "_EFL_UI_IMAGE_ZOOMABLE_EVENT_DOWNLOAD_PROGRESS"; if (RemoveNativeEventHandler(key, this.evt_DownloadProgressEvt_delegate)) { eventHandlers.RemoveHandler(DownloadProgressEvtKey , value); } else Eina.Log.Error($"Error removing proxy for event {key}"); } } } ///<summary>Method to raise event DownloadProgressEvt.</summary> public void On_DownloadProgressEvt(Efl.Ui.ImageZoomableDownloadProgressEvt_Args e) { EventHandler<Efl.Ui.ImageZoomableDownloadProgressEvt_Args> evt; lock (eventLock) { evt = (EventHandler<Efl.Ui.ImageZoomableDownloadProgressEvt_Args>)eventHandlers[DownloadProgressEvtKey]; } evt?.Invoke(this, e); } Efl.EventCb evt_DownloadProgressEvt_delegate; private void on_DownloadProgressEvt_NativeCallback(System.IntPtr data, ref Efl.Event.NativeStruct evt) { Efl.Ui.ImageZoomableDownloadProgressEvt_Args args = new Efl.Ui.ImageZoomableDownloadProgressEvt_Args(); args.arg = default(Elm.Photocam.Progress); try { On_DownloadProgressEvt(args); } catch (Exception e) { Eina.Log.Error(e.ToString()); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } private static object DownloadDoneEvtKey = new object(); /// <summary>Called when photocam download finished</summary> public event EventHandler DownloadDoneEvt { add { lock (eventLock) { string key = "_EFL_UI_IMAGE_ZOOMABLE_EVENT_DOWNLOAD_DONE"; if (AddNativeEventHandler(efl.Libs.Elementary, key, this.evt_DownloadDoneEvt_delegate)) { eventHandlers.AddHandler(DownloadDoneEvtKey , value); } else Eina.Log.Error($"Error adding proxy for event {key}"); } } remove { lock (eventLock) { string key = "_EFL_UI_IMAGE_ZOOMABLE_EVENT_DOWNLOAD_DONE"; if (RemoveNativeEventHandler(key, this.evt_DownloadDoneEvt_delegate)) { eventHandlers.RemoveHandler(DownloadDoneEvtKey , value); } else Eina.Log.Error($"Error removing proxy for event {key}"); } } } ///<summary>Method to raise event DownloadDoneEvt.</summary> public void On_DownloadDoneEvt(EventArgs e) { EventHandler evt; lock (eventLock) { evt = (EventHandler)eventHandlers[DownloadDoneEvtKey]; } evt?.Invoke(this, e); } Efl.EventCb evt_DownloadDoneEvt_delegate; private void on_DownloadDoneEvt_NativeCallback(System.IntPtr data, ref Efl.Event.NativeStruct evt) { EventArgs args = EventArgs.Empty; try { On_DownloadDoneEvt(args); } catch (Exception e) { Eina.Log.Error(e.ToString()); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } private static object DownloadErrorEvtKey = new object(); /// <summary>Called when photocam download failed</summary> public event EventHandler<Efl.Ui.ImageZoomableDownloadErrorEvt_Args> DownloadErrorEvt { add { lock (eventLock) { string key = "_EFL_UI_IMAGE_ZOOMABLE_EVENT_DOWNLOAD_ERROR"; if (AddNativeEventHandler(efl.Libs.Elementary, key, this.evt_DownloadErrorEvt_delegate)) { eventHandlers.AddHandler(DownloadErrorEvtKey , value); } else Eina.Log.Error($"Error adding proxy for event {key}"); } } remove { lock (eventLock) { string key = "_EFL_UI_IMAGE_ZOOMABLE_EVENT_DOWNLOAD_ERROR"; if (RemoveNativeEventHandler(key, this.evt_DownloadErrorEvt_delegate)) { eventHandlers.RemoveHandler(DownloadErrorEvtKey , value); } else Eina.Log.Error($"Error removing proxy for event {key}"); } } } ///<summary>Method to raise event DownloadErrorEvt.</summary> public void On_DownloadErrorEvt(Efl.Ui.ImageZoomableDownloadErrorEvt_Args e) { EventHandler<Efl.Ui.ImageZoomableDownloadErrorEvt_Args> evt; lock (eventLock) { evt = (EventHandler<Efl.Ui.ImageZoomableDownloadErrorEvt_Args>)eventHandlers[DownloadErrorEvtKey]; } evt?.Invoke(this, e); } Efl.EventCb evt_DownloadErrorEvt_delegate; private void on_DownloadErrorEvt_NativeCallback(System.IntPtr data, ref Efl.Event.NativeStruct evt) { Efl.Ui.ImageZoomableDownloadErrorEvt_Args args = new Efl.Ui.ImageZoomableDownloadErrorEvt_Args(); args.arg = default(Elm.Photocam.Error); try { On_DownloadErrorEvt(args); } catch (Exception e) { Eina.Log.Error(e.ToString()); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } private static object ScrollStartEvtKey = new object(); /// <summary>Called when scroll operation starts</summary> public event EventHandler ScrollStartEvt { add { lock (eventLock) { string key = "_EFL_UI_EVENT_SCROLL_START"; if (AddNativeEventHandler(efl.Libs.Efl, key, this.evt_ScrollStartEvt_delegate)) { eventHandlers.AddHandler(ScrollStartEvtKey , value); } else Eina.Log.Error($"Error adding proxy for event {key}"); } } remove { lock (eventLock) { string key = "_EFL_UI_EVENT_SCROLL_START"; if (RemoveNativeEventHandler(key, this.evt_ScrollStartEvt_delegate)) { eventHandlers.RemoveHandler(ScrollStartEvtKey , value); } else Eina.Log.Error($"Error removing proxy for event {key}"); } } } ///<summary>Method to raise event ScrollStartEvt.</summary> public void On_ScrollStartEvt(EventArgs e) { EventHandler evt; lock (eventLock) { evt = (EventHandler)eventHandlers[ScrollStartEvtKey]; } evt?.Invoke(this, e); } Efl.EventCb evt_ScrollStartEvt_delegate; private void on_ScrollStartEvt_NativeCallback(System.IntPtr data, ref Efl.Event.NativeStruct evt) { EventArgs args = EventArgs.Empty; try { On_ScrollStartEvt(args); } catch (Exception e) { Eina.Log.Error(e.ToString()); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } private static object ScrollEvtKey = new object(); /// <summary>Called when scrolling</summary> public event EventHandler ScrollEvt { add { lock (eventLock) { string key = "_EFL_UI_EVENT_SCROLL"; if (AddNativeEventHandler(efl.Libs.Efl, key, this.evt_ScrollEvt_delegate)) { eventHandlers.AddHandler(ScrollEvtKey , value); } else Eina.Log.Error($"Error adding proxy for event {key}"); } } remove { lock (eventLock) { string key = "_EFL_UI_EVENT_SCROLL"; if (RemoveNativeEventHandler(key, this.evt_ScrollEvt_delegate)) { eventHandlers.RemoveHandler(ScrollEvtKey , value); } else Eina.Log.Error($"Error removing proxy for event {key}"); } } } ///<summary>Method to raise event ScrollEvt.</summary> public void On_ScrollEvt(EventArgs e) { EventHandler evt; lock (eventLock) { evt = (EventHandler)eventHandlers[ScrollEvtKey]; } evt?.Invoke(this, e); } Efl.EventCb evt_ScrollEvt_delegate; private void on_ScrollEvt_NativeCallback(System.IntPtr data, ref Efl.Event.NativeStruct evt) { EventArgs args = EventArgs.Empty; try { On_ScrollEvt(args); } catch (Exception e) { Eina.Log.Error(e.ToString()); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } private static object ScrollStopEvtKey = new object(); /// <summary>Called when scroll operation stops</summary> public event EventHandler ScrollStopEvt { add { lock (eventLock) { string key = "_EFL_UI_EVENT_SCROLL_STOP"; if (AddNativeEventHandler(efl.Libs.Efl, key, this.evt_ScrollStopEvt_delegate)) { eventHandlers.AddHandler(ScrollStopEvtKey , value); } else Eina.Log.Error($"Error adding proxy for event {key}"); } } remove { lock (eventLock) { string key = "_EFL_UI_EVENT_SCROLL_STOP"; if (RemoveNativeEventHandler(key, this.evt_ScrollStopEvt_delegate)) { eventHandlers.RemoveHandler(ScrollStopEvtKey , value); } else Eina.Log.Error($"Error removing proxy for event {key}"); } } } ///<summary>Method to raise event ScrollStopEvt.</summary> public void On_ScrollStopEvt(EventArgs e) { EventHandler evt; lock (eventLock) { evt = (EventHandler)eventHandlers[ScrollStopEvtKey]; } evt?.Invoke(this, e); } Efl.EventCb evt_ScrollStopEvt_delegate; private void on_ScrollStopEvt_NativeCallback(System.IntPtr data, ref Efl.Event.NativeStruct evt) { EventArgs args = EventArgs.Empty; try { On_ScrollStopEvt(args); } catch (Exception e) { Eina.Log.Error(e.ToString()); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } private static object ScrollUpEvtKey = new object(); /// <summary>Called when scrolling upwards</summary> public event EventHandler ScrollUpEvt { add { lock (eventLock) { string key = "_EFL_UI_EVENT_SCROLL_UP"; if (AddNativeEventHandler(efl.Libs.Efl, key, this.evt_ScrollUpEvt_delegate)) { eventHandlers.AddHandler(ScrollUpEvtKey , value); } else Eina.Log.Error($"Error adding proxy for event {key}"); } } remove { lock (eventLock) { string key = "_EFL_UI_EVENT_SCROLL_UP"; if (RemoveNativeEventHandler(key, this.evt_ScrollUpEvt_delegate)) { eventHandlers.RemoveHandler(ScrollUpEvtKey , value); } else Eina.Log.Error($"Error removing proxy for event {key}"); } } } ///<summary>Method to raise event ScrollUpEvt.</summary> public void On_ScrollUpEvt(EventArgs e) { EventHandler evt; lock (eventLock) { evt = (EventHandler)eventHandlers[ScrollUpEvtKey]; } evt?.Invoke(this, e); } Efl.EventCb evt_ScrollUpEvt_delegate; private void on_ScrollUpEvt_NativeCallback(System.IntPtr data, ref Efl.Event.NativeStruct evt) { EventArgs args = EventArgs.Empty; try { On_ScrollUpEvt(args); } catch (Exception e) { Eina.Log.Error(e.ToString()); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } private static object ScrollDownEvtKey = new object(); /// <summary>Called when scrolling downwards</summary> public event EventHandler ScrollDownEvt { add { lock (eventLock) { string key = "_EFL_UI_EVENT_SCROLL_DOWN"; if (AddNativeEventHandler(efl.Libs.Efl, key, this.evt_ScrollDownEvt_delegate)) { eventHandlers.AddHandler(ScrollDownEvtKey , value); } else Eina.Log.Error($"Error adding proxy for event {key}"); } } remove { lock (eventLock) { string key = "_EFL_UI_EVENT_SCROLL_DOWN"; if (RemoveNativeEventHandler(key, this.evt_ScrollDownEvt_delegate)) { eventHandlers.RemoveHandler(ScrollDownEvtKey , value); } else Eina.Log.Error($"Error removing proxy for event {key}"); } } } ///<summary>Method to raise event ScrollDownEvt.</summary> public void On_ScrollDownEvt(EventArgs e) { EventHandler evt; lock (eventLock) { evt = (EventHandler)eventHandlers[ScrollDownEvtKey]; } evt?.Invoke(this, e); } Efl.EventCb evt_ScrollDownEvt_delegate; private void on_ScrollDownEvt_NativeCallback(System.IntPtr data, ref Efl.Event.NativeStruct evt) { EventArgs args = EventArgs.Empty; try { On_ScrollDownEvt(args); } catch (Exception e) { Eina.Log.Error(e.ToString()); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } private static object ScrollLeftEvtKey = new object(); /// <summary>Called when scrolling left</summary> public event EventHandler ScrollLeftEvt { add { lock (eventLock) { string key = "_EFL_UI_EVENT_SCROLL_LEFT"; if (AddNativeEventHandler(efl.Libs.Efl, key, this.evt_ScrollLeftEvt_delegate)) { eventHandlers.AddHandler(ScrollLeftEvtKey , value); } else Eina.Log.Error($"Error adding proxy for event {key}"); } } remove { lock (eventLock) { string key = "_EFL_UI_EVENT_SCROLL_LEFT"; if (RemoveNativeEventHandler(key, this.evt_ScrollLeftEvt_delegate)) { eventHandlers.RemoveHandler(ScrollLeftEvtKey , value); } else Eina.Log.Error($"Error removing proxy for event {key}"); } } } ///<summary>Method to raise event ScrollLeftEvt.</summary> public void On_ScrollLeftEvt(EventArgs e) { EventHandler evt; lock (eventLock) { evt = (EventHandler)eventHandlers[ScrollLeftEvtKey]; } evt?.Invoke(this, e); } Efl.EventCb evt_ScrollLeftEvt_delegate; private void on_ScrollLeftEvt_NativeCallback(System.IntPtr data, ref Efl.Event.NativeStruct evt) { EventArgs args = EventArgs.Empty; try { On_ScrollLeftEvt(args); } catch (Exception e) { Eina.Log.Error(e.ToString()); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } private static object ScrollRightEvtKey = new object(); /// <summary>Called when scrolling right</summary> public event EventHandler ScrollRightEvt { add { lock (eventLock) { string key = "_EFL_UI_EVENT_SCROLL_RIGHT"; if (AddNativeEventHandler(efl.Libs.Efl, key, this.evt_ScrollRightEvt_delegate)) { eventHandlers.AddHandler(ScrollRightEvtKey , value); } else Eina.Log.Error($"Error adding proxy for event {key}"); } } remove { lock (eventLock) { string key = "_EFL_UI_EVENT_SCROLL_RIGHT"; if (RemoveNativeEventHandler(key, this.evt_ScrollRightEvt_delegate)) { eventHandlers.RemoveHandler(ScrollRightEvtKey , value); } else Eina.Log.Error($"Error removing proxy for event {key}"); } } } ///<summary>Method to raise event ScrollRightEvt.</summary> public void On_ScrollRightEvt(EventArgs e) { EventHandler evt; lock (eventLock) { evt = (EventHandler)eventHandlers[ScrollRightEvtKey]; } evt?.Invoke(this, e); } Efl.EventCb evt_ScrollRightEvt_delegate; private void on_ScrollRightEvt_NativeCallback(System.IntPtr data, ref Efl.Event.NativeStruct evt) { EventArgs args = EventArgs.Empty; try { On_ScrollRightEvt(args); } catch (Exception e) { Eina.Log.Error(e.ToString()); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } private static object EdgeUpEvtKey = new object(); /// <summary>Called when hitting the top edge</summary> public event EventHandler EdgeUpEvt { add { lock (eventLock) { string key = "_EFL_UI_EVENT_EDGE_UP"; if (AddNativeEventHandler(efl.Libs.Efl, key, this.evt_EdgeUpEvt_delegate)) { eventHandlers.AddHandler(EdgeUpEvtKey , value); } else Eina.Log.Error($"Error adding proxy for event {key}"); } } remove { lock (eventLock) { string key = "_EFL_UI_EVENT_EDGE_UP"; if (RemoveNativeEventHandler(key, this.evt_EdgeUpEvt_delegate)) { eventHandlers.RemoveHandler(EdgeUpEvtKey , value); } else Eina.Log.Error($"Error removing proxy for event {key}"); } } } ///<summary>Method to raise event EdgeUpEvt.</summary> public void On_EdgeUpEvt(EventArgs e) { EventHandler evt; lock (eventLock) { evt = (EventHandler)eventHandlers[EdgeUpEvtKey]; } evt?.Invoke(this, e); } Efl.EventCb evt_EdgeUpEvt_delegate; private void on_EdgeUpEvt_NativeCallback(System.IntPtr data, ref Efl.Event.NativeStruct evt) { EventArgs args = EventArgs.Empty; try { On_EdgeUpEvt(args); } catch (Exception e) { Eina.Log.Error(e.ToString()); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } private static object EdgeDownEvtKey = new object(); /// <summary>Called when hitting the bottom edge</summary> public event EventHandler EdgeDownEvt { add { lock (eventLock) { string key = "_EFL_UI_EVENT_EDGE_DOWN"; if (AddNativeEventHandler(efl.Libs.Efl, key, this.evt_EdgeDownEvt_delegate)) { eventHandlers.AddHandler(EdgeDownEvtKey , value); } else Eina.Log.Error($"Error adding proxy for event {key}"); } } remove { lock (eventLock) { string key = "_EFL_UI_EVENT_EDGE_DOWN"; if (RemoveNativeEventHandler(key, this.evt_EdgeDownEvt_delegate)) { eventHandlers.RemoveHandler(EdgeDownEvtKey , value); } else Eina.Log.Error($"Error removing proxy for event {key}"); } } } ///<summary>Method to raise event EdgeDownEvt.</summary> public void On_EdgeDownEvt(EventArgs e) { EventHandler evt; lock (eventLock) { evt = (EventHandler)eventHandlers[EdgeDownEvtKey]; } evt?.Invoke(this, e); } Efl.EventCb evt_EdgeDownEvt_delegate; private void on_EdgeDownEvt_NativeCallback(System.IntPtr data, ref Efl.Event.NativeStruct evt) { EventArgs args = EventArgs.Empty; try { On_EdgeDownEvt(args); } catch (Exception e) { Eina.Log.Error(e.ToString()); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } private static object EdgeLeftEvtKey = new object(); /// <summary>Called when hitting the left edge</summary> public event EventHandler EdgeLeftEvt { add { lock (eventLock) { string key = "_EFL_UI_EVENT_EDGE_LEFT"; if (AddNativeEventHandler(efl.Libs.Efl, key, this.evt_EdgeLeftEvt_delegate)) { eventHandlers.AddHandler(EdgeLeftEvtKey , value); } else Eina.Log.Error($"Error adding proxy for event {key}"); } } remove { lock (eventLock) { string key = "_EFL_UI_EVENT_EDGE_LEFT"; if (RemoveNativeEventHandler(key, this.evt_EdgeLeftEvt_delegate)) { eventHandlers.RemoveHandler(EdgeLeftEvtKey , value); } else Eina.Log.Error($"Error removing proxy for event {key}"); } } } ///<summary>Method to raise event EdgeLeftEvt.</summary> public void On_EdgeLeftEvt(EventArgs e) { EventHandler evt; lock (eventLock) { evt = (EventHandler)eventHandlers[EdgeLeftEvtKey]; } evt?.Invoke(this, e); } Efl.EventCb evt_EdgeLeftEvt_delegate; private void on_EdgeLeftEvt_NativeCallback(System.IntPtr data, ref Efl.Event.NativeStruct evt) { EventArgs args = EventArgs.Empty; try { On_EdgeLeftEvt(args); } catch (Exception e) { Eina.Log.Error(e.ToString()); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } private static object EdgeRightEvtKey = new object(); /// <summary>Called when hitting the right edge</summary> public event EventHandler EdgeRightEvt { add { lock (eventLock) { string key = "_EFL_UI_EVENT_EDGE_RIGHT"; if (AddNativeEventHandler(efl.Libs.Efl, key, this.evt_EdgeRightEvt_delegate)) { eventHandlers.AddHandler(EdgeRightEvtKey , value); } else Eina.Log.Error($"Error adding proxy for event {key}"); } } remove { lock (eventLock) { string key = "_EFL_UI_EVENT_EDGE_RIGHT"; if (RemoveNativeEventHandler(key, this.evt_EdgeRightEvt_delegate)) { eventHandlers.RemoveHandler(EdgeRightEvtKey , value); } else Eina.Log.Error($"Error removing proxy for event {key}"); } } } ///<summary>Method to raise event EdgeRightEvt.</summary> public void On_EdgeRightEvt(EventArgs e) { EventHandler evt; lock (eventLock) { evt = (EventHandler)eventHandlers[EdgeRightEvtKey]; } evt?.Invoke(this, e); } Efl.EventCb evt_EdgeRightEvt_delegate; private void on_EdgeRightEvt_NativeCallback(System.IntPtr data, ref Efl.Event.NativeStruct evt) { EventArgs args = EventArgs.Empty; try { On_EdgeRightEvt(args); } catch (Exception e) { Eina.Log.Error(e.ToString()); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } private static object ScrollAnimStartEvtKey = new object(); /// <summary>Called when scroll animation starts</summary> public event EventHandler ScrollAnimStartEvt { add { lock (eventLock) { string key = "_EFL_UI_EVENT_SCROLL_ANIM_START"; if (AddNativeEventHandler(efl.Libs.Efl, key, this.evt_ScrollAnimStartEvt_delegate)) { eventHandlers.AddHandler(ScrollAnimStartEvtKey , value); } else Eina.Log.Error($"Error adding proxy for event {key}"); } } remove { lock (eventLock) { string key = "_EFL_UI_EVENT_SCROLL_ANIM_START"; if (RemoveNativeEventHandler(key, this.evt_ScrollAnimStartEvt_delegate)) { eventHandlers.RemoveHandler(ScrollAnimStartEvtKey , value); } else Eina.Log.Error($"Error removing proxy for event {key}"); } } } ///<summary>Method to raise event ScrollAnimStartEvt.</summary> public void On_ScrollAnimStartEvt(EventArgs e) { EventHandler evt; lock (eventLock) { evt = (EventHandler)eventHandlers[ScrollAnimStartEvtKey]; } evt?.Invoke(this, e); } Efl.EventCb evt_ScrollAnimStartEvt_delegate; private void on_ScrollAnimStartEvt_NativeCallback(System.IntPtr data, ref Efl.Event.NativeStruct evt) { EventArgs args = EventArgs.Empty; try { On_ScrollAnimStartEvt(args); } catch (Exception e) { Eina.Log.Error(e.ToString()); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } private static object ScrollAnimStopEvtKey = new object(); /// <summary>Called when scroll animation stopps</summary> public event EventHandler ScrollAnimStopEvt { add { lock (eventLock) { string key = "_EFL_UI_EVENT_SCROLL_ANIM_STOP"; if (AddNativeEventHandler(efl.Libs.Efl, key, this.evt_ScrollAnimStopEvt_delegate)) { eventHandlers.AddHandler(ScrollAnimStopEvtKey , value); } else Eina.Log.Error($"Error adding proxy for event {key}"); } } remove { lock (eventLock) { string key = "_EFL_UI_EVENT_SCROLL_ANIM_STOP"; if (RemoveNativeEventHandler(key, this.evt_ScrollAnimStopEvt_delegate)) { eventHandlers.RemoveHandler(ScrollAnimStopEvtKey , value); } else Eina.Log.Error($"Error removing proxy for event {key}"); } } } ///<summary>Method to raise event ScrollAnimStopEvt.</summary> public void On_ScrollAnimStopEvt(EventArgs e) { EventHandler evt; lock (eventLock) { evt = (EventHandler)eventHandlers[ScrollAnimStopEvtKey]; } evt?.Invoke(this, e); } Efl.EventCb evt_ScrollAnimStopEvt_delegate; private void on_ScrollAnimStopEvt_NativeCallback(System.IntPtr data, ref Efl.Event.NativeStruct evt) { EventArgs args = EventArgs.Empty; try { On_ScrollAnimStopEvt(args); } catch (Exception e) { Eina.Log.Error(e.ToString()); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } private static object ScrollDragStartEvtKey = new object(); /// <summary>Called when scroll drag starts</summary> public event EventHandler ScrollDragStartEvt { add { lock (eventLock) { string key = "_EFL_UI_EVENT_SCROLL_DRAG_START"; if (AddNativeEventHandler(efl.Libs.Efl, key, this.evt_ScrollDragStartEvt_delegate)) { eventHandlers.AddHandler(ScrollDragStartEvtKey , value); } else Eina.Log.Error($"Error adding proxy for event {key}"); } } remove { lock (eventLock) { string key = "_EFL_UI_EVENT_SCROLL_DRAG_START"; if (RemoveNativeEventHandler(key, this.evt_ScrollDragStartEvt_delegate)) { eventHandlers.RemoveHandler(ScrollDragStartEvtKey , value); } else Eina.Log.Error($"Error removing proxy for event {key}"); } } } ///<summary>Method to raise event ScrollDragStartEvt.</summary> public void On_ScrollDragStartEvt(EventArgs e) { EventHandler evt; lock (eventLock) { evt = (EventHandler)eventHandlers[ScrollDragStartEvtKey]; } evt?.Invoke(this, e); } Efl.EventCb evt_ScrollDragStartEvt_delegate; private void on_ScrollDragStartEvt_NativeCallback(System.IntPtr data, ref Efl.Event.NativeStruct evt) { EventArgs args = EventArgs.Empty; try { On_ScrollDragStartEvt(args); } catch (Exception e) { Eina.Log.Error(e.ToString()); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } private static object ScrollDragStopEvtKey = new object(); /// <summary>Called when scroll drag stops</summary> public event EventHandler ScrollDragStopEvt { add { lock (eventLock) { string key = "_EFL_UI_EVENT_SCROLL_DRAG_STOP"; if (AddNativeEventHandler(efl.Libs.Efl, key, this.evt_ScrollDragStopEvt_delegate)) { eventHandlers.AddHandler(ScrollDragStopEvtKey , value); } else Eina.Log.Error($"Error adding proxy for event {key}"); } } remove { lock (eventLock) { string key = "_EFL_UI_EVENT_SCROLL_DRAG_STOP"; if (RemoveNativeEventHandler(key, this.evt_ScrollDragStopEvt_delegate)) { eventHandlers.RemoveHandler(ScrollDragStopEvtKey , value); } else Eina.Log.Error($"Error removing proxy for event {key}"); } } } ///<summary>Method to raise event ScrollDragStopEvt.</summary> public void On_ScrollDragStopEvt(EventArgs e) { EventHandler evt; lock (eventLock) { evt = (EventHandler)eventHandlers[ScrollDragStopEvtKey]; } evt?.Invoke(this, e); } Efl.EventCb evt_ScrollDragStopEvt_delegate; private void on_ScrollDragStopEvt_NativeCallback(System.IntPtr data, ref Efl.Event.NativeStruct evt) { EventArgs args = EventArgs.Empty; try { On_ScrollDragStopEvt(args); } catch (Exception e) { Eina.Log.Error(e.ToString()); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } private static object BarPressEvtKey = new object(); /// <summary>Called when bar is pressed</summary> public event EventHandler<Efl.Ui.IScrollbarBarPressEvt_Args> BarPressEvt { add { lock (eventLock) { string key = "_EFL_UI_SCROLLBAR_EVENT_BAR_PRESS"; if (AddNativeEventHandler(efl.Libs.Efl, key, this.evt_BarPressEvt_delegate)) { eventHandlers.AddHandler(BarPressEvtKey , value); } else Eina.Log.Error($"Error adding proxy for event {key}"); } } remove { lock (eventLock) { string key = "_EFL_UI_SCROLLBAR_EVENT_BAR_PRESS"; if (RemoveNativeEventHandler(key, this.evt_BarPressEvt_delegate)) { eventHandlers.RemoveHandler(BarPressEvtKey , value); } else Eina.Log.Error($"Error removing proxy for event {key}"); } } } ///<summary>Method to raise event BarPressEvt.</summary> public void On_BarPressEvt(Efl.Ui.IScrollbarBarPressEvt_Args e) { EventHandler<Efl.Ui.IScrollbarBarPressEvt_Args> evt; lock (eventLock) { evt = (EventHandler<Efl.Ui.IScrollbarBarPressEvt_Args>)eventHandlers[BarPressEvtKey]; } evt?.Invoke(this, e); } Efl.EventCb evt_BarPressEvt_delegate; private void on_BarPressEvt_NativeCallback(System.IntPtr data, ref Efl.Event.NativeStruct evt) { Efl.Ui.IScrollbarBarPressEvt_Args args = new Efl.Ui.IScrollbarBarPressEvt_Args(); args.arg = default(Efl.Ui.ScrollbarDirection); try { On_BarPressEvt(args); } catch (Exception e) { Eina.Log.Error(e.ToString()); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } private static object BarUnpressEvtKey = new object(); /// <summary>Called when bar is unpressed</summary> public event EventHandler<Efl.Ui.IScrollbarBarUnpressEvt_Args> BarUnpressEvt { add { lock (eventLock) { string key = "_EFL_UI_SCROLLBAR_EVENT_BAR_UNPRESS"; if (AddNativeEventHandler(efl.Libs.Efl, key, this.evt_BarUnpressEvt_delegate)) { eventHandlers.AddHandler(BarUnpressEvtKey , value); } else Eina.Log.Error($"Error adding proxy for event {key}"); } } remove { lock (eventLock) { string key = "_EFL_UI_SCROLLBAR_EVENT_BAR_UNPRESS"; if (RemoveNativeEventHandler(key, this.evt_BarUnpressEvt_delegate)) { eventHandlers.RemoveHandler(BarUnpressEvtKey , value); } else Eina.Log.Error($"Error removing proxy for event {key}"); } } } ///<summary>Method to raise event BarUnpressEvt.</summary> public void On_BarUnpressEvt(Efl.Ui.IScrollbarBarUnpressEvt_Args e) { EventHandler<Efl.Ui.IScrollbarBarUnpressEvt_Args> evt; lock (eventLock) { evt = (EventHandler<Efl.Ui.IScrollbarBarUnpressEvt_Args>)eventHandlers[BarUnpressEvtKey]; } evt?.Invoke(this, e); } Efl.EventCb evt_BarUnpressEvt_delegate; private void on_BarUnpressEvt_NativeCallback(System.IntPtr data, ref Efl.Event.NativeStruct evt) { Efl.Ui.IScrollbarBarUnpressEvt_Args args = new Efl.Ui.IScrollbarBarUnpressEvt_Args(); args.arg = default(Efl.Ui.ScrollbarDirection); try { On_BarUnpressEvt(args); } catch (Exception e) { Eina.Log.Error(e.ToString()); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } private static object BarDragEvtKey = new object(); /// <summary>Called when bar is dragged</summary> public event EventHandler<Efl.Ui.IScrollbarBarDragEvt_Args> BarDragEvt { add { lock (eventLock) { string key = "_EFL_UI_SCROLLBAR_EVENT_BAR_DRAG"; if (AddNativeEventHandler(efl.Libs.Efl, key, this.evt_BarDragEvt_delegate)) { eventHandlers.AddHandler(BarDragEvtKey , value); } else Eina.Log.Error($"Error adding proxy for event {key}"); } } remove { lock (eventLock) { string key = "_EFL_UI_SCROLLBAR_EVENT_BAR_DRAG"; if (RemoveNativeEventHandler(key, this.evt_BarDragEvt_delegate)) { eventHandlers.RemoveHandler(BarDragEvtKey , value); } else Eina.Log.Error($"Error removing proxy for event {key}"); } } } ///<summary>Method to raise event BarDragEvt.</summary> public void On_BarDragEvt(Efl.Ui.IScrollbarBarDragEvt_Args e) { EventHandler<Efl.Ui.IScrollbarBarDragEvt_Args> evt; lock (eventLock) { evt = (EventHandler<Efl.Ui.IScrollbarBarDragEvt_Args>)eventHandlers[BarDragEvtKey]; } evt?.Invoke(this, e); } Efl.EventCb evt_BarDragEvt_delegate; private void on_BarDragEvt_NativeCallback(System.IntPtr data, ref Efl.Event.NativeStruct evt) { Efl.Ui.IScrollbarBarDragEvt_Args args = new Efl.Ui.IScrollbarBarDragEvt_Args(); args.arg = default(Efl.Ui.ScrollbarDirection); try { On_BarDragEvt(args); } catch (Exception e) { Eina.Log.Error(e.ToString()); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } private static object BarSizeChangedEvtKey = new object(); /// <summary>Called when bar size is changed</summary> public event EventHandler BarSizeChangedEvt { add { lock (eventLock) { string key = "_EFL_UI_SCROLLBAR_EVENT_BAR_SIZE_CHANGED"; if (AddNativeEventHandler(efl.Libs.Efl, key, this.evt_BarSizeChangedEvt_delegate)) { eventHandlers.AddHandler(BarSizeChangedEvtKey , value); } else Eina.Log.Error($"Error adding proxy for event {key}"); } } remove { lock (eventLock) { string key = "_EFL_UI_SCROLLBAR_EVENT_BAR_SIZE_CHANGED"; if (RemoveNativeEventHandler(key, this.evt_BarSizeChangedEvt_delegate)) { eventHandlers.RemoveHandler(BarSizeChangedEvtKey , value); } else Eina.Log.Error($"Error removing proxy for event {key}"); } } } ///<summary>Method to raise event BarSizeChangedEvt.</summary> public void On_BarSizeChangedEvt(EventArgs e) { EventHandler evt; lock (eventLock) { evt = (EventHandler)eventHandlers[BarSizeChangedEvtKey]; } evt?.Invoke(this, e); } Efl.EventCb evt_BarSizeChangedEvt_delegate; private void on_BarSizeChangedEvt_NativeCallback(System.IntPtr data, ref Efl.Event.NativeStruct evt) { EventArgs args = EventArgs.Empty; try { On_BarSizeChangedEvt(args); } catch (Exception e) { Eina.Log.Error(e.ToString()); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } private static object BarPosChangedEvtKey = new object(); /// <summary>Called when bar position is changed</summary> public event EventHandler BarPosChangedEvt { add { lock (eventLock) { string key = "_EFL_UI_SCROLLBAR_EVENT_BAR_POS_CHANGED"; if (AddNativeEventHandler(efl.Libs.Efl, key, this.evt_BarPosChangedEvt_delegate)) { eventHandlers.AddHandler(BarPosChangedEvtKey , value); } else Eina.Log.Error($"Error adding proxy for event {key}"); } } remove { lock (eventLock) { string key = "_EFL_UI_SCROLLBAR_EVENT_BAR_POS_CHANGED"; if (RemoveNativeEventHandler(key, this.evt_BarPosChangedEvt_delegate)) { eventHandlers.RemoveHandler(BarPosChangedEvtKey , value); } else Eina.Log.Error($"Error removing proxy for event {key}"); } } } ///<summary>Method to raise event BarPosChangedEvt.</summary> public void On_BarPosChangedEvt(EventArgs e) { EventHandler evt; lock (eventLock) { evt = (EventHandler)eventHandlers[BarPosChangedEvtKey]; } evt?.Invoke(this, e); } Efl.EventCb evt_BarPosChangedEvt_delegate; private void on_BarPosChangedEvt_NativeCallback(System.IntPtr data, ref Efl.Event.NativeStruct evt) { EventArgs args = EventArgs.Empty; try { On_BarPosChangedEvt(args); } catch (Exception e) { Eina.Log.Error(e.ToString()); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } private static object BarShowEvtKey = new object(); /// <summary>Callend when bar is shown</summary> public event EventHandler<Efl.Ui.IScrollbarBarShowEvt_Args> BarShowEvt { add { lock (eventLock) { string key = "_EFL_UI_SCROLLBAR_EVENT_BAR_SHOW"; if (AddNativeEventHandler(efl.Libs.Efl, key, this.evt_BarShowEvt_delegate)) { eventHandlers.AddHandler(BarShowEvtKey , value); } else Eina.Log.Error($"Error adding proxy for event {key}"); } } remove { lock (eventLock) { string key = "_EFL_UI_SCROLLBAR_EVENT_BAR_SHOW"; if (RemoveNativeEventHandler(key, this.evt_BarShowEvt_delegate)) { eventHandlers.RemoveHandler(BarShowEvtKey , value); } else Eina.Log.Error($"Error removing proxy for event {key}"); } } } ///<summary>Method to raise event BarShowEvt.</summary> public void On_BarShowEvt(Efl.Ui.IScrollbarBarShowEvt_Args e) { EventHandler<Efl.Ui.IScrollbarBarShowEvt_Args> evt; lock (eventLock) { evt = (EventHandler<Efl.Ui.IScrollbarBarShowEvt_Args>)eventHandlers[BarShowEvtKey]; } evt?.Invoke(this, e); } Efl.EventCb evt_BarShowEvt_delegate; private void on_BarShowEvt_NativeCallback(System.IntPtr data, ref Efl.Event.NativeStruct evt) { Efl.Ui.IScrollbarBarShowEvt_Args args = new Efl.Ui.IScrollbarBarShowEvt_Args(); args.arg = default(Efl.Ui.ScrollbarDirection); try { On_BarShowEvt(args); } catch (Exception e) { Eina.Log.Error(e.ToString()); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } private static object BarHideEvtKey = new object(); /// <summary>Called when bar is hidden</summary> public event EventHandler<Efl.Ui.IScrollbarBarHideEvt_Args> BarHideEvt { add { lock (eventLock) { string key = "_EFL_UI_SCROLLBAR_EVENT_BAR_HIDE"; if (AddNativeEventHandler(efl.Libs.Efl, key, this.evt_BarHideEvt_delegate)) { eventHandlers.AddHandler(BarHideEvtKey , value); } else Eina.Log.Error($"Error adding proxy for event {key}"); } } remove { lock (eventLock) { string key = "_EFL_UI_SCROLLBAR_EVENT_BAR_HIDE"; if (RemoveNativeEventHandler(key, this.evt_BarHideEvt_delegate)) { eventHandlers.RemoveHandler(BarHideEvtKey , value); } else Eina.Log.Error($"Error removing proxy for event {key}"); } } } ///<summary>Method to raise event BarHideEvt.</summary> public void On_BarHideEvt(Efl.Ui.IScrollbarBarHideEvt_Args e) { EventHandler<Efl.Ui.IScrollbarBarHideEvt_Args> evt; lock (eventLock) { evt = (EventHandler<Efl.Ui.IScrollbarBarHideEvt_Args>)eventHandlers[BarHideEvtKey]; } evt?.Invoke(this, e); } Efl.EventCb evt_BarHideEvt_delegate; private void on_BarHideEvt_NativeCallback(System.IntPtr data, ref Efl.Event.NativeStruct evt) { Efl.Ui.IScrollbarBarHideEvt_Args args = new Efl.Ui.IScrollbarBarHideEvt_Args(); args.arg = default(Efl.Ui.ScrollbarDirection); try { On_BarHideEvt(args); } catch (Exception e) { Eina.Log.Error(e.ToString()); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } private static object ZoomStartEvtKey = new object(); /// <summary>Called when zooming started</summary> public event EventHandler ZoomStartEvt { add { lock (eventLock) { string key = "_EFL_UI_EVENT_ZOOM_START"; if (AddNativeEventHandler(efl.Libs.Efl, key, this.evt_ZoomStartEvt_delegate)) { eventHandlers.AddHandler(ZoomStartEvtKey , value); } else Eina.Log.Error($"Error adding proxy for event {key}"); } } remove { lock (eventLock) { string key = "_EFL_UI_EVENT_ZOOM_START"; if (RemoveNativeEventHandler(key, this.evt_ZoomStartEvt_delegate)) { eventHandlers.RemoveHandler(ZoomStartEvtKey , value); } else Eina.Log.Error($"Error removing proxy for event {key}"); } } } ///<summary>Method to raise event ZoomStartEvt.</summary> public void On_ZoomStartEvt(EventArgs e) { EventHandler evt; lock (eventLock) { evt = (EventHandler)eventHandlers[ZoomStartEvtKey]; } evt?.Invoke(this, e); } Efl.EventCb evt_ZoomStartEvt_delegate; private void on_ZoomStartEvt_NativeCallback(System.IntPtr data, ref Efl.Event.NativeStruct evt) { EventArgs args = EventArgs.Empty; try { On_ZoomStartEvt(args); } catch (Exception e) { Eina.Log.Error(e.ToString()); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } private static object ZoomStopEvtKey = new object(); /// <summary>Called when zooming stopped</summary> public event EventHandler ZoomStopEvt { add { lock (eventLock) { string key = "_EFL_UI_EVENT_ZOOM_STOP"; if (AddNativeEventHandler(efl.Libs.Efl, key, this.evt_ZoomStopEvt_delegate)) { eventHandlers.AddHandler(ZoomStopEvtKey , value); } else Eina.Log.Error($"Error adding proxy for event {key}"); } } remove { lock (eventLock) { string key = "_EFL_UI_EVENT_ZOOM_STOP"; if (RemoveNativeEventHandler(key, this.evt_ZoomStopEvt_delegate)) { eventHandlers.RemoveHandler(ZoomStopEvtKey , value); } else Eina.Log.Error($"Error removing proxy for event {key}"); } } } ///<summary>Method to raise event ZoomStopEvt.</summary> public void On_ZoomStopEvt(EventArgs e) { EventHandler evt; lock (eventLock) { evt = (EventHandler)eventHandlers[ZoomStopEvtKey]; } evt?.Invoke(this, e); } Efl.EventCb evt_ZoomStopEvt_delegate; private void on_ZoomStopEvt_NativeCallback(System.IntPtr data, ref Efl.Event.NativeStruct evt) { EventArgs args = EventArgs.Empty; try { On_ZoomStopEvt(args); } catch (Exception e) { Eina.Log.Error(e.ToString()); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } private static object ZoomChangeEvtKey = new object(); /// <summary>Called when zooming changed</summary> public event EventHandler ZoomChangeEvt { add { lock (eventLock) { string key = "_EFL_UI_EVENT_ZOOM_CHANGE"; if (AddNativeEventHandler(efl.Libs.Efl, key, this.evt_ZoomChangeEvt_delegate)) { eventHandlers.AddHandler(ZoomChangeEvtKey , value); } else Eina.Log.Error($"Error adding proxy for event {key}"); } } remove { lock (eventLock) { string key = "_EFL_UI_EVENT_ZOOM_CHANGE"; if (RemoveNativeEventHandler(key, this.evt_ZoomChangeEvt_delegate)) { eventHandlers.RemoveHandler(ZoomChangeEvtKey , value); } else Eina.Log.Error($"Error removing proxy for event {key}"); } } } ///<summary>Method to raise event ZoomChangeEvt.</summary> public void On_ZoomChangeEvt(EventArgs e) { EventHandler evt; lock (eventLock) { evt = (EventHandler)eventHandlers[ZoomChangeEvtKey]; } evt?.Invoke(this, e); } Efl.EventCb evt_ZoomChangeEvt_delegate; private void on_ZoomChangeEvt_NativeCallback(System.IntPtr data, ref Efl.Event.NativeStruct evt) { EventArgs args = EventArgs.Empty; try { On_ZoomChangeEvt(args); } catch (Exception e) { Eina.Log.Error(e.ToString()); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } ///<summary>Register the Eo event wrappers making the bridge to C# events. Internal usage only.</summary> protected override void RegisterEventProxies() { base.RegisterEventProxies(); evt_PressEvt_delegate = new Efl.EventCb(on_PressEvt_NativeCallback); evt_LoadEvt_delegate = new Efl.EventCb(on_LoadEvt_NativeCallback); evt_LoadedEvt_delegate = new Efl.EventCb(on_LoadedEvt_NativeCallback); evt_LoadDetailEvt_delegate = new Efl.EventCb(on_LoadDetailEvt_NativeCallback); evt_LoadedDetailEvt_delegate = new Efl.EventCb(on_LoadedDetailEvt_NativeCallback); evt_DownloadStartEvt_delegate = new Efl.EventCb(on_DownloadStartEvt_NativeCallback); evt_DownloadProgressEvt_delegate = new Efl.EventCb(on_DownloadProgressEvt_NativeCallback); evt_DownloadDoneEvt_delegate = new Efl.EventCb(on_DownloadDoneEvt_NativeCallback); evt_DownloadErrorEvt_delegate = new Efl.EventCb(on_DownloadErrorEvt_NativeCallback); evt_ScrollStartEvt_delegate = new Efl.EventCb(on_ScrollStartEvt_NativeCallback); evt_ScrollEvt_delegate = new Efl.EventCb(on_ScrollEvt_NativeCallback); evt_ScrollStopEvt_delegate = new Efl.EventCb(on_ScrollStopEvt_NativeCallback); evt_ScrollUpEvt_delegate = new Efl.EventCb(on_ScrollUpEvt_NativeCallback); evt_ScrollDownEvt_delegate = new Efl.EventCb(on_ScrollDownEvt_NativeCallback); evt_ScrollLeftEvt_delegate = new Efl.EventCb(on_ScrollLeftEvt_NativeCallback); evt_ScrollRightEvt_delegate = new Efl.EventCb(on_ScrollRightEvt_NativeCallback); evt_EdgeUpEvt_delegate = new Efl.EventCb(on_EdgeUpEvt_NativeCallback); evt_EdgeDownEvt_delegate = new Efl.EventCb(on_EdgeDownEvt_NativeCallback); evt_EdgeLeftEvt_delegate = new Efl.EventCb(on_EdgeLeftEvt_NativeCallback); evt_EdgeRightEvt_delegate = new Efl.EventCb(on_EdgeRightEvt_NativeCallback); evt_ScrollAnimStartEvt_delegate = new Efl.EventCb(on_ScrollAnimStartEvt_NativeCallback); evt_ScrollAnimStopEvt_delegate = new Efl.EventCb(on_ScrollAnimStopEvt_NativeCallback); evt_ScrollDragStartEvt_delegate = new Efl.EventCb(on_ScrollDragStartEvt_NativeCallback); evt_ScrollDragStopEvt_delegate = new Efl.EventCb(on_ScrollDragStopEvt_NativeCallback); evt_BarPressEvt_delegate = new Efl.EventCb(on_BarPressEvt_NativeCallback); evt_BarUnpressEvt_delegate = new Efl.EventCb(on_BarUnpressEvt_NativeCallback); evt_BarDragEvt_delegate = new Efl.EventCb(on_BarDragEvt_NativeCallback); evt_BarSizeChangedEvt_delegate = new Efl.EventCb(on_BarSizeChangedEvt_NativeCallback); evt_BarPosChangedEvt_delegate = new Efl.EventCb(on_BarPosChangedEvt_NativeCallback); evt_BarShowEvt_delegate = new Efl.EventCb(on_BarShowEvt_NativeCallback); evt_BarHideEvt_delegate = new Efl.EventCb(on_BarHideEvt_NativeCallback); evt_ZoomStartEvt_delegate = new Efl.EventCb(on_ZoomStartEvt_NativeCallback); evt_ZoomStopEvt_delegate = new Efl.EventCb(on_ZoomStopEvt_NativeCallback); evt_ZoomChangeEvt_delegate = new Efl.EventCb(on_ZoomChangeEvt_NativeCallback); } /// <summary>Get the gesture state for photocam. /// This gets the current gesture state for the photocam object.</summary> /// <returns>The gesture state.</returns> virtual public bool GetGestureEnabled() { var _ret_var = Efl.Ui.ImageZoomableNativeInherit.efl_ui_image_zoomable_gesture_enabled_get_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle)); Eina.Error.RaiseIfUnhandledException(); return _ret_var; } /// <summary>Set the gesture state for photocam. /// This sets the gesture state to on or off for photocam. The default is off. This will start multi touch zooming.</summary> /// <param name="gesture">The gesture state.</param> /// <returns></returns> virtual public void SetGestureEnabled( bool gesture) { Efl.Ui.ImageZoomableNativeInherit.efl_ui_image_zoomable_gesture_enabled_set_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle), gesture); Eina.Error.RaiseIfUnhandledException(); } /// <summary>Get the region of the image that is currently shown /// See also <see cref="Efl.Ui.ImageZoomable.SetImageRegion"/>.</summary> /// <returns>The region in the original image pixels.</returns> virtual public Eina.Rect GetImageRegion() { var _ret_var = Efl.Ui.ImageZoomableNativeInherit.efl_ui_image_zoomable_image_region_get_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle)); Eina.Error.RaiseIfUnhandledException(); return _ret_var; } /// <summary>Set the viewed region of the image /// This shows the region of the image without using animation.</summary> /// <param name="region">The region in the original image pixels.</param> /// <returns></returns> virtual public void SetImageRegion( Eina.Rect region) { Eina.Rect.NativeStruct _in_region = region; Efl.Ui.ImageZoomableNativeInherit.efl_ui_image_zoomable_image_region_set_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle), _in_region); Eina.Error.RaiseIfUnhandledException(); } /// <summary>The content position</summary> /// <returns>The position is virtual value, (0, 0) starting at the top-left.</returns> virtual public Eina.Position2D GetContentPos() { var _ret_var = Efl.Ui.IScrollableInteractiveNativeInherit.efl_ui_scrollable_content_pos_get_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle)); Eina.Error.RaiseIfUnhandledException(); return _ret_var; } /// <summary>The content position</summary> /// <param name="pos">The position is virtual value, (0, 0) starting at the top-left.</param> /// <returns></returns> virtual public void SetContentPos( Eina.Position2D pos) { Eina.Position2D.NativeStruct _in_pos = pos; Efl.Ui.IScrollableInteractiveNativeInherit.efl_ui_scrollable_content_pos_set_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle), _in_pos); Eina.Error.RaiseIfUnhandledException(); } /// <summary>The content size</summary> /// <returns>The content size in pixels.</returns> virtual public Eina.Size2D GetContentSize() { var _ret_var = Efl.Ui.IScrollableInteractiveNativeInherit.efl_ui_scrollable_content_size_get_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle)); Eina.Error.RaiseIfUnhandledException(); return _ret_var; } /// <summary>The viewport geometry</summary> /// <returns>It is absolute geometry.</returns> virtual public Eina.Rect GetViewportGeometry() { var _ret_var = Efl.Ui.IScrollableInteractiveNativeInherit.efl_ui_scrollable_viewport_geometry_get_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle)); Eina.Error.RaiseIfUnhandledException(); return _ret_var; } /// <summary>Bouncing behavior /// When scrolling, the scroller may &quot;bounce&quot; when reaching the edge of the content object. This is a visual way to indicate the end has been reached. This is enabled by default for both axes. This API will determine if it&apos;s enabled for the given axis with the boolean parameters for each one.</summary> /// <param name="horiz">Horizontal bounce policy.</param> /// <param name="vert">Vertical bounce policy.</param> /// <returns></returns> virtual public void GetBounceEnabled( out bool horiz, out bool vert) { Efl.Ui.IScrollableInteractiveNativeInherit.efl_ui_scrollable_bounce_enabled_get_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle), out horiz, out vert); Eina.Error.RaiseIfUnhandledException(); } /// <summary>Bouncing behavior /// When scrolling, the scroller may &quot;bounce&quot; when reaching the edge of the content object. This is a visual way to indicate the end has been reached. This is enabled by default for both axes. This API will determine if it&apos;s enabled for the given axis with the boolean parameters for each one.</summary> /// <param name="horiz">Horizontal bounce policy.</param> /// <param name="vert">Vertical bounce policy.</param> /// <returns></returns> virtual public void SetBounceEnabled( bool horiz, bool vert) { Efl.Ui.IScrollableInteractiveNativeInherit.efl_ui_scrollable_bounce_enabled_set_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle), horiz, vert); Eina.Error.RaiseIfUnhandledException(); } /// <summary>Freeze property This function will freeze scrolling movement (by input of a user). Unlike efl_ui_scrollable_movement_block_set, this function freezes bidirectionally. If you want to freeze in only one direction, See <see cref="Efl.Ui.IScrollableInteractive.SetMovementBlock"/>.</summary> /// <returns><c>true</c> if freeze, <c>false</c> otherwise</returns> virtual public bool GetScrollFreeze() { var _ret_var = Efl.Ui.IScrollableInteractiveNativeInherit.efl_ui_scrollable_scroll_freeze_get_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle)); Eina.Error.RaiseIfUnhandledException(); return _ret_var; } /// <summary>Freeze property This function will freeze scrolling movement (by input of a user). Unlike efl_ui_scrollable_movement_block_set, this function freezes bidirectionally. If you want to freeze in only one direction, See <see cref="Efl.Ui.IScrollableInteractive.SetMovementBlock"/>.</summary> /// <param name="freeze"><c>true</c> if freeze, <c>false</c> otherwise</param> /// <returns></returns> virtual public void SetScrollFreeze( bool freeze) { Efl.Ui.IScrollableInteractiveNativeInherit.efl_ui_scrollable_scroll_freeze_set_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle), freeze); Eina.Error.RaiseIfUnhandledException(); } /// <summary>Hold property When hold turns on, it only scrolls by holding action.</summary> /// <returns><c>true</c> if hold, <c>false</c> otherwise</returns> virtual public bool GetScrollHold() { var _ret_var = Efl.Ui.IScrollableInteractiveNativeInherit.efl_ui_scrollable_scroll_hold_get_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle)); Eina.Error.RaiseIfUnhandledException(); return _ret_var; } /// <summary>Hold property When hold turns on, it only scrolls by holding action.</summary> /// <param name="hold"><c>true</c> if hold, <c>false</c> otherwise</param> /// <returns></returns> virtual public void SetScrollHold( bool hold) { Efl.Ui.IScrollableInteractiveNativeInherit.efl_ui_scrollable_scroll_hold_set_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle), hold); Eina.Error.RaiseIfUnhandledException(); } /// <summary>Controls an infinite loop for a scroller.</summary> /// <param name="loop_h">The scrolling horizontal loop</param> /// <param name="loop_v">The Scrolling vertical loop</param> /// <returns></returns> virtual public void GetLooping( out bool loop_h, out bool loop_v) { Efl.Ui.IScrollableInteractiveNativeInherit.efl_ui_scrollable_looping_get_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle), out loop_h, out loop_v); Eina.Error.RaiseIfUnhandledException(); } /// <summary>Controls an infinite loop for a scroller.</summary> /// <param name="loop_h">The scrolling horizontal loop</param> /// <param name="loop_v">The Scrolling vertical loop</param> /// <returns></returns> virtual public void SetLooping( bool loop_h, bool loop_v) { Efl.Ui.IScrollableInteractiveNativeInherit.efl_ui_scrollable_looping_set_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle), loop_h, loop_v); Eina.Error.RaiseIfUnhandledException(); } /// <summary>Blocking of scrolling (per axis) /// This function will block scrolling movement (by input of a user) in a given direction. You can disable movements in the X axis, the Y axis or both. The default value is <c>none</c>, where movements are allowed in both directions.</summary> /// <returns>Which axis (or axes) to block</returns> virtual public Efl.Ui.ScrollBlock GetMovementBlock() { var _ret_var = Efl.Ui.IScrollableInteractiveNativeInherit.efl_ui_scrollable_movement_block_get_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle)); Eina.Error.RaiseIfUnhandledException(); return _ret_var; } /// <summary>Blocking of scrolling (per axis) /// This function will block scrolling movement (by input of a user) in a given direction. You can disable movements in the X axis, the Y axis or both. The default value is <c>none</c>, where movements are allowed in both directions.</summary> /// <param name="block">Which axis (or axes) to block</param> /// <returns></returns> virtual public void SetMovementBlock( Efl.Ui.ScrollBlock block) { Efl.Ui.IScrollableInteractiveNativeInherit.efl_ui_scrollable_movement_block_set_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle), block); Eina.Error.RaiseIfUnhandledException(); } /// <summary>Control scrolling gravity on the scrollable /// The gravity defines how the scroller will adjust its view when the size of the scroller contents increases. /// /// The scroller will adjust the view to glue itself as follows. /// /// x=0.0, for staying where it is relative to the left edge of the content x=1.0, for staying where it is relative to the right edge of the content y=0.0, for staying where it is relative to the top edge of the content y=1.0, for staying where it is relative to the bottom edge of the content /// /// Default values for x and y are 0.0</summary> /// <param name="x">Horizontal scrolling gravity</param> /// <param name="y">Vertical scrolling gravity</param> /// <returns></returns> virtual public void GetGravity( out double x, out double y) { Efl.Ui.IScrollableInteractiveNativeInherit.efl_ui_scrollable_gravity_get_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle), out x, out y); Eina.Error.RaiseIfUnhandledException(); } /// <summary>Control scrolling gravity on the scrollable /// The gravity defines how the scroller will adjust its view when the size of the scroller contents increases. /// /// The scroller will adjust the view to glue itself as follows. /// /// x=0.0, for staying where it is relative to the left edge of the content x=1.0, for staying where it is relative to the right edge of the content y=0.0, for staying where it is relative to the top edge of the content y=1.0, for staying where it is relative to the bottom edge of the content /// /// Default values for x and y are 0.0</summary> /// <param name="x">Horizontal scrolling gravity</param> /// <param name="y">Vertical scrolling gravity</param> /// <returns></returns> virtual public void SetGravity( double x, double y) { Efl.Ui.IScrollableInteractiveNativeInherit.efl_ui_scrollable_gravity_set_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle), x, y); Eina.Error.RaiseIfUnhandledException(); } /// <summary>Prevent the scrollable from being smaller than the minimum size of the content. /// By default the scroller will be as small as its design allows, irrespective of its content. This will make the scroller minimum size the right size horizontally and/or vertically to perfectly fit its content in that direction.</summary> /// <param name="w">Whether to limit the minimum horizontal size</param> /// <param name="h">Whether to limit the minimum vertical size</param> /// <returns></returns> virtual public void SetMatchContent( bool w, bool h) { Efl.Ui.IScrollableInteractiveNativeInherit.efl_ui_scrollable_match_content_set_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle), w, h); Eina.Error.RaiseIfUnhandledException(); } /// <summary>Control the step size /// Use this call to set step size. This value is used when scroller scroll by arrow key event.</summary> /// <returns>The step size in pixels</returns> virtual public Eina.Position2D GetStepSize() { var _ret_var = Efl.Ui.IScrollableInteractiveNativeInherit.efl_ui_scrollable_step_size_get_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle)); Eina.Error.RaiseIfUnhandledException(); return _ret_var; } /// <summary>Control the step size /// Use this call to set step size. This value is used when scroller scroll by arrow key event.</summary> /// <param name="step">The step size in pixels</param> /// <returns></returns> virtual public void SetStepSize( Eina.Position2D step) { Eina.Position2D.NativeStruct _in_step = step; Efl.Ui.IScrollableInteractiveNativeInherit.efl_ui_scrollable_step_size_set_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle), _in_step); Eina.Error.RaiseIfUnhandledException(); } /// <summary>Show a specific virtual region within the scroller content object. /// This will ensure all (or part if it does not fit) of the designated region in the virtual content object (0, 0 starting at the top-left of the virtual content object) is shown within the scroller. This allows the scroller to &quot;smoothly slide&quot; to this location (if configuration in general calls for transitions). It may not jump immediately to the new location and make take a while and show other content along the way.</summary> /// <param name="rect">The position where to scroll. and The size user want to see</param> /// <param name="animation">Whether to scroll with animation or not</param> /// <returns></returns> virtual public void Scroll( Eina.Rect rect, bool animation) { Eina.Rect.NativeStruct _in_rect = rect; Efl.Ui.IScrollableInteractiveNativeInherit.efl_ui_scrollable_scroll_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle), _in_rect, animation); Eina.Error.RaiseIfUnhandledException(); } /// <summary>Scrollbar visibility policy</summary> /// <param name="hbar">Horizontal scrollbar</param> /// <param name="vbar">Vertical scrollbar</param> /// <returns></returns> virtual public void GetBarMode( out Efl.Ui.ScrollbarMode hbar, out Efl.Ui.ScrollbarMode vbar) { Efl.Ui.IScrollbarNativeInherit.efl_ui_scrollbar_bar_mode_get_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle), out hbar, out vbar); Eina.Error.RaiseIfUnhandledException(); } /// <summary>Scrollbar visibility policy</summary> /// <param name="hbar">Horizontal scrollbar</param> /// <param name="vbar">Vertical scrollbar</param> /// <returns></returns> virtual public void SetBarMode( Efl.Ui.ScrollbarMode hbar, Efl.Ui.ScrollbarMode vbar) { Efl.Ui.IScrollbarNativeInherit.efl_ui_scrollbar_bar_mode_set_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle), hbar, vbar); Eina.Error.RaiseIfUnhandledException(); } /// <summary>Scrollbar size. It is calculated based on viewport size-content sizes.</summary> /// <param name="width">Value between 0.0 and 1.0</param> /// <param name="height">Value between 0.0 and 1.0</param> /// <returns></returns> virtual public void GetBarSize( out double width, out double height) { Efl.Ui.IScrollbarNativeInherit.efl_ui_scrollbar_bar_size_get_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle), out width, out height); Eina.Error.RaiseIfUnhandledException(); } /// <summary>Scrollbar position. It is calculated based on current position-maximum positions.</summary> /// <param name="posx">Value between 0.0 and 1.0</param> /// <param name="posy">Value between 0.0 and 1.0</param> /// <returns></returns> virtual public void GetBarPosition( out double posx, out double posy) { Efl.Ui.IScrollbarNativeInherit.efl_ui_scrollbar_bar_position_get_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle), out posx, out posy); Eina.Error.RaiseIfUnhandledException(); } /// <summary>Scrollbar position. It is calculated based on current position-maximum positions.</summary> /// <param name="posx">Value between 0.0 and 1.0</param> /// <param name="posy">Value between 0.0 and 1.0</param> /// <returns></returns> virtual public void SetBarPosition( double posx, double posy) { Efl.Ui.IScrollbarNativeInherit.efl_ui_scrollbar_bar_position_set_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle), posx, posy); Eina.Error.RaiseIfUnhandledException(); } /// <summary>Update bar visibility. /// The object will call this function whenever the bar need to be shown or hidden.</summary> /// <returns></returns> virtual public void UpdateBarVisibility() { Efl.Ui.IScrollbarNativeInherit.efl_ui_scrollbar_bar_visibility_update_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle)); Eina.Error.RaiseIfUnhandledException(); } /// <summary>This sets the zoom animation state to on or off for zoomable. The default is off. When <c>paused</c> is <c>true</c>, it will stop zooming using animation on zoom level changes and change instantly, stopping any existing animations that are running.</summary> /// <returns>The paused state.</returns> virtual public bool GetZoomAnimation() { var _ret_var = Efl.Ui.IZoomNativeInherit.efl_ui_zoom_animation_get_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle)); Eina.Error.RaiseIfUnhandledException(); return _ret_var; } /// <summary>This sets the zoom animation state to on or off for zoomable. The default is off. When <c>paused</c> is <c>true</c>, it will stop zooming using animation on zoom level changes and change instantly, stopping any existing animations that are running.</summary> /// <param name="paused">The paused state.</param> /// <returns></returns> virtual public void SetZoomAnimation( bool paused) { Efl.Ui.IZoomNativeInherit.efl_ui_zoom_animation_set_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle), paused); Eina.Error.RaiseIfUnhandledException(); } /// <summary>Get the zoom level of the photo /// This returns the current zoom level of the zoomable object. Note that if you set the fill mode to other than #EFL_UI_ZOOM_MODE_MANUAL (which is the default), the zoom level may be changed at any time by the zoomable object itself to account for photo size and zoomable viewport size.</summary> /// <returns>The zoom level to set</returns> virtual public double GetZoomLevel() { var _ret_var = Efl.Ui.IZoomNativeInherit.efl_ui_zoom_level_get_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle)); Eina.Error.RaiseIfUnhandledException(); return _ret_var; } /// <summary>Set the zoom level of the photo /// This sets the zoom level. If <c>zoom</c> is 1, it means no zoom. If it&apos;s smaller than 1, it means zoom in. If it&apos;s bigger than 1, it means zoom out. For example, <c>zoom</c> 1 will be 1:1 pixel for pixel. <c>zoom</c> 2 will be 2:1 (that is 2x2 photo pixels will display as 1 on-screen pixel) which is a zoom out. 4:1 will be 4x4 photo pixels as 1 screen pixel, and so on. The <c>zoom</c> parameter must be greater than 0. It is suggested to stick to powers of 2. (1, 2, 4, 8, 16, 32, etc.).</summary> /// <param name="zoom">The zoom level to set</param> /// <returns></returns> virtual public void SetZoomLevel( double zoom) { Efl.Ui.IZoomNativeInherit.efl_ui_zoom_level_set_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle), zoom); Eina.Error.RaiseIfUnhandledException(); } /// <summary>Get the zoom mode /// This gets the current zoom mode of the zoomable object.</summary> /// <returns>The zoom mode.</returns> virtual public Efl.Ui.ZoomMode GetZoomMode() { var _ret_var = Efl.Ui.IZoomNativeInherit.efl_ui_zoom_mode_get_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle)); Eina.Error.RaiseIfUnhandledException(); return _ret_var; } /// <summary>Set the zoom mode /// This sets the zoom mode to manual or one of several automatic levels. Manual (EFL_UI_ZOOM_MODE_MANUAL) means that zoom is set manually by <see cref="Efl.Ui.IZoom.SetZoomLevel"/> and will stay at that level until changed by code or until zoom mode is changed. This is the default mode. The Automatic modes will allow the zoomable object to automatically adjust zoom mode based on properties. /// /// #EFL_UI_ZOOM_MODE_AUTO_FIT) will adjust zoom so the photo fits EXACTLY inside the scroll frame with no pixels outside this region. #EFL_UI_ZOOM_MODE_AUTO_FILL will be similar but ensure no pixels within the frame are left unfilled.</summary> /// <param name="mode">The zoom mode.</param> /// <returns></returns> virtual public void SetZoomMode( Efl.Ui.ZoomMode mode) { Efl.Ui.IZoomNativeInherit.efl_ui_zoom_mode_set_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle), mode); Eina.Error.RaiseIfUnhandledException(); } /// <summary>Get the gesture state for photocam. /// This gets the current gesture state for the photocam object.</summary> /// <value>The gesture state.</value> public bool GestureEnabled { get { return GetGestureEnabled(); } set { SetGestureEnabled( value); } } /// <summary>Get the region of the image that is currently shown /// See also <see cref="Efl.Ui.ImageZoomable.SetImageRegion"/>.</summary> /// <value>The region in the original image pixels.</value> public Eina.Rect ImageRegion { get { return GetImageRegion(); } set { SetImageRegion( value); } } /// <summary>The content position</summary> /// <value>The position is virtual value, (0, 0) starting at the top-left.</value> public Eina.Position2D ContentPos { get { return GetContentPos(); } set { SetContentPos( value); } } /// <summary>The content size</summary> /// <value>The content size in pixels.</value> public Eina.Size2D ContentSize { get { return GetContentSize(); } } /// <summary>The viewport geometry</summary> /// <value>It is absolute geometry.</value> public Eina.Rect ViewportGeometry { get { return GetViewportGeometry(); } } /// <summary>Freeze property This function will freeze scrolling movement (by input of a user). Unlike efl_ui_scrollable_movement_block_set, this function freezes bidirectionally. If you want to freeze in only one direction, See <see cref="Efl.Ui.IScrollableInteractive.SetMovementBlock"/>.</summary> /// <value><c>true</c> if freeze, <c>false</c> otherwise</value> public bool ScrollFreeze { get { return GetScrollFreeze(); } set { SetScrollFreeze( value); } } /// <summary>Hold property When hold turns on, it only scrolls by holding action.</summary> /// <value><c>true</c> if hold, <c>false</c> otherwise</value> public bool ScrollHold { get { return GetScrollHold(); } set { SetScrollHold( value); } } /// <summary>Blocking of scrolling (per axis) /// This function will block scrolling movement (by input of a user) in a given direction. You can disable movements in the X axis, the Y axis or both. The default value is <c>none</c>, where movements are allowed in both directions.</summary> /// <value>Which axis (or axes) to block</value> public Efl.Ui.ScrollBlock MovementBlock { get { return GetMovementBlock(); } set { SetMovementBlock( value); } } /// <summary>Control the step size /// Use this call to set step size. This value is used when scroller scroll by arrow key event.</summary> /// <value>The step size in pixels</value> public Eina.Position2D StepSize { get { return GetStepSize(); } set { SetStepSize( value); } } /// <summary>This sets the zoom animation state to on or off for zoomable. The default is off. When <c>paused</c> is <c>true</c>, it will stop zooming using animation on zoom level changes and change instantly, stopping any existing animations that are running.</summary> /// <value>The paused state.</value> public bool ZoomAnimation { get { return GetZoomAnimation(); } set { SetZoomAnimation( value); } } /// <summary>Get the zoom level of the photo /// This returns the current zoom level of the zoomable object. Note that if you set the fill mode to other than #EFL_UI_ZOOM_MODE_MANUAL (which is the default), the zoom level may be changed at any time by the zoomable object itself to account for photo size and zoomable viewport size.</summary> /// <value>The zoom level to set</value> public double ZoomLevel { get { return GetZoomLevel(); } set { SetZoomLevel( value); } } /// <summary>Get the zoom mode /// This gets the current zoom mode of the zoomable object.</summary> /// <value>The zoom mode.</value> public Efl.Ui.ZoomMode ZoomMode { get { return GetZoomMode(); } set { SetZoomMode( value); } } private static IntPtr GetEflClassStatic() { return Efl.Ui.ImageZoomable.efl_ui_image_zoomable_class_get(); } } public class ImageZoomableNativeInherit : Efl.Ui.ImageNativeInherit{ public new static Efl.Eo.NativeModule _Module = new Efl.Eo.NativeModule(efl.Libs.Elementary); public override System.Collections.Generic.List<Efl_Op_Description> GetEoOps(System.Type type) { var descs = new System.Collections.Generic.List<Efl_Op_Description>(); var methods = Efl.Eo.Globals.GetUserMethods(type); if (efl_ui_image_zoomable_gesture_enabled_get_static_delegate == null) efl_ui_image_zoomable_gesture_enabled_get_static_delegate = new efl_ui_image_zoomable_gesture_enabled_get_delegate(gesture_enabled_get); if (methods.FirstOrDefault(m => m.Name == "GetGestureEnabled") != null) descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(_Module.Module, "efl_ui_image_zoomable_gesture_enabled_get"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_image_zoomable_gesture_enabled_get_static_delegate)}); if (efl_ui_image_zoomable_gesture_enabled_set_static_delegate == null) efl_ui_image_zoomable_gesture_enabled_set_static_delegate = new efl_ui_image_zoomable_gesture_enabled_set_delegate(gesture_enabled_set); if (methods.FirstOrDefault(m => m.Name == "SetGestureEnabled") != null) descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(_Module.Module, "efl_ui_image_zoomable_gesture_enabled_set"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_image_zoomable_gesture_enabled_set_static_delegate)}); if (efl_ui_image_zoomable_image_region_get_static_delegate == null) efl_ui_image_zoomable_image_region_get_static_delegate = new efl_ui_image_zoomable_image_region_get_delegate(image_region_get); if (methods.FirstOrDefault(m => m.Name == "GetImageRegion") != null) descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(_Module.Module, "efl_ui_image_zoomable_image_region_get"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_image_zoomable_image_region_get_static_delegate)}); if (efl_ui_image_zoomable_image_region_set_static_delegate == null) efl_ui_image_zoomable_image_region_set_static_delegate = new efl_ui_image_zoomable_image_region_set_delegate(image_region_set); if (methods.FirstOrDefault(m => m.Name == "SetImageRegion") != null) descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(_Module.Module, "efl_ui_image_zoomable_image_region_set"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_image_zoomable_image_region_set_static_delegate)}); if (efl_ui_scrollable_content_pos_get_static_delegate == null) efl_ui_scrollable_content_pos_get_static_delegate = new efl_ui_scrollable_content_pos_get_delegate(content_pos_get); if (methods.FirstOrDefault(m => m.Name == "GetContentPos") != null) descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(_Module.Module, "efl_ui_scrollable_content_pos_get"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_scrollable_content_pos_get_static_delegate)}); if (efl_ui_scrollable_content_pos_set_static_delegate == null) efl_ui_scrollable_content_pos_set_static_delegate = new efl_ui_scrollable_content_pos_set_delegate(content_pos_set); if (methods.FirstOrDefault(m => m.Name == "SetContentPos") != null) descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(_Module.Module, "efl_ui_scrollable_content_pos_set"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_scrollable_content_pos_set_static_delegate)}); if (efl_ui_scrollable_content_size_get_static_delegate == null) efl_ui_scrollable_content_size_get_static_delegate = new efl_ui_scrollable_content_size_get_delegate(content_size_get); if (methods.FirstOrDefault(m => m.Name == "GetContentSize") != null) descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(_Module.Module, "efl_ui_scrollable_content_size_get"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_scrollable_content_size_get_static_delegate)}); if (efl_ui_scrollable_viewport_geometry_get_static_delegate == null) efl_ui_scrollable_viewport_geometry_get_static_delegate = new efl_ui_scrollable_viewport_geometry_get_delegate(viewport_geometry_get); if (methods.FirstOrDefault(m => m.Name == "GetViewportGeometry") != null) descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(_Module.Module, "efl_ui_scrollable_viewport_geometry_get"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_scrollable_viewport_geometry_get_static_delegate)}); if (efl_ui_scrollable_bounce_enabled_get_static_delegate == null) efl_ui_scrollable_bounce_enabled_get_static_delegate = new efl_ui_scrollable_bounce_enabled_get_delegate(bounce_enabled_get); if (methods.FirstOrDefault(m => m.Name == "GetBounceEnabled") != null) descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(_Module.Module, "efl_ui_scrollable_bounce_enabled_get"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_scrollable_bounce_enabled_get_static_delegate)}); if (efl_ui_scrollable_bounce_enabled_set_static_delegate == null) efl_ui_scrollable_bounce_enabled_set_static_delegate = new efl_ui_scrollable_bounce_enabled_set_delegate(bounce_enabled_set); if (methods.FirstOrDefault(m => m.Name == "SetBounceEnabled") != null) descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(_Module.Module, "efl_ui_scrollable_bounce_enabled_set"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_scrollable_bounce_enabled_set_static_delegate)}); if (efl_ui_scrollable_scroll_freeze_get_static_delegate == null) efl_ui_scrollable_scroll_freeze_get_static_delegate = new efl_ui_scrollable_scroll_freeze_get_delegate(scroll_freeze_get); if (methods.FirstOrDefault(m => m.Name == "GetScrollFreeze") != null) descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(_Module.Module, "efl_ui_scrollable_scroll_freeze_get"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_scrollable_scroll_freeze_get_static_delegate)}); if (efl_ui_scrollable_scroll_freeze_set_static_delegate == null) efl_ui_scrollable_scroll_freeze_set_static_delegate = new efl_ui_scrollable_scroll_freeze_set_delegate(scroll_freeze_set); if (methods.FirstOrDefault(m => m.Name == "SetScrollFreeze") != null) descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(_Module.Module, "efl_ui_scrollable_scroll_freeze_set"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_scrollable_scroll_freeze_set_static_delegate)}); if (efl_ui_scrollable_scroll_hold_get_static_delegate == null) efl_ui_scrollable_scroll_hold_get_static_delegate = new efl_ui_scrollable_scroll_hold_get_delegate(scroll_hold_get); if (methods.FirstOrDefault(m => m.Name == "GetScrollHold") != null) descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(_Module.Module, "efl_ui_scrollable_scroll_hold_get"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_scrollable_scroll_hold_get_static_delegate)}); if (efl_ui_scrollable_scroll_hold_set_static_delegate == null) efl_ui_scrollable_scroll_hold_set_static_delegate = new efl_ui_scrollable_scroll_hold_set_delegate(scroll_hold_set); if (methods.FirstOrDefault(m => m.Name == "SetScrollHold") != null) descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(_Module.Module, "efl_ui_scrollable_scroll_hold_set"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_scrollable_scroll_hold_set_static_delegate)}); if (efl_ui_scrollable_looping_get_static_delegate == null) efl_ui_scrollable_looping_get_static_delegate = new efl_ui_scrollable_looping_get_delegate(looping_get); if (methods.FirstOrDefault(m => m.Name == "GetLooping") != null) descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(_Module.Module, "efl_ui_scrollable_looping_get"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_scrollable_looping_get_static_delegate)}); if (efl_ui_scrollable_looping_set_static_delegate == null) efl_ui_scrollable_looping_set_static_delegate = new efl_ui_scrollable_looping_set_delegate(looping_set); if (methods.FirstOrDefault(m => m.Name == "SetLooping") != null) descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(_Module.Module, "efl_ui_scrollable_looping_set"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_scrollable_looping_set_static_delegate)}); if (efl_ui_scrollable_movement_block_get_static_delegate == null) efl_ui_scrollable_movement_block_get_static_delegate = new efl_ui_scrollable_movement_block_get_delegate(movement_block_get); if (methods.FirstOrDefault(m => m.Name == "GetMovementBlock") != null) descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(_Module.Module, "efl_ui_scrollable_movement_block_get"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_scrollable_movement_block_get_static_delegate)}); if (efl_ui_scrollable_movement_block_set_static_delegate == null) efl_ui_scrollable_movement_block_set_static_delegate = new efl_ui_scrollable_movement_block_set_delegate(movement_block_set); if (methods.FirstOrDefault(m => m.Name == "SetMovementBlock") != null) descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(_Module.Module, "efl_ui_scrollable_movement_block_set"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_scrollable_movement_block_set_static_delegate)}); if (efl_ui_scrollable_gravity_get_static_delegate == null) efl_ui_scrollable_gravity_get_static_delegate = new efl_ui_scrollable_gravity_get_delegate(gravity_get); if (methods.FirstOrDefault(m => m.Name == "GetGravity") != null) descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(_Module.Module, "efl_ui_scrollable_gravity_get"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_scrollable_gravity_get_static_delegate)}); if (efl_ui_scrollable_gravity_set_static_delegate == null) efl_ui_scrollable_gravity_set_static_delegate = new efl_ui_scrollable_gravity_set_delegate(gravity_set); if (methods.FirstOrDefault(m => m.Name == "SetGravity") != null) descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(_Module.Module, "efl_ui_scrollable_gravity_set"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_scrollable_gravity_set_static_delegate)}); if (efl_ui_scrollable_match_content_set_static_delegate == null) efl_ui_scrollable_match_content_set_static_delegate = new efl_ui_scrollable_match_content_set_delegate(match_content_set); if (methods.FirstOrDefault(m => m.Name == "SetMatchContent") != null) descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(_Module.Module, "efl_ui_scrollable_match_content_set"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_scrollable_match_content_set_static_delegate)}); if (efl_ui_scrollable_step_size_get_static_delegate == null) efl_ui_scrollable_step_size_get_static_delegate = new efl_ui_scrollable_step_size_get_delegate(step_size_get); if (methods.FirstOrDefault(m => m.Name == "GetStepSize") != null) descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(_Module.Module, "efl_ui_scrollable_step_size_get"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_scrollable_step_size_get_static_delegate)}); if (efl_ui_scrollable_step_size_set_static_delegate == null) efl_ui_scrollable_step_size_set_static_delegate = new efl_ui_scrollable_step_size_set_delegate(step_size_set); if (methods.FirstOrDefault(m => m.Name == "SetStepSize") != null) descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(_Module.Module, "efl_ui_scrollable_step_size_set"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_scrollable_step_size_set_static_delegate)}); if (efl_ui_scrollable_scroll_static_delegate == null) efl_ui_scrollable_scroll_static_delegate = new efl_ui_scrollable_scroll_delegate(scroll); if (methods.FirstOrDefault(m => m.Name == "Scroll") != null) descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(_Module.Module, "efl_ui_scrollable_scroll"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_scrollable_scroll_static_delegate)}); if (efl_ui_scrollbar_bar_mode_get_static_delegate == null) efl_ui_scrollbar_bar_mode_get_static_delegate = new efl_ui_scrollbar_bar_mode_get_delegate(bar_mode_get); if (methods.FirstOrDefault(m => m.Name == "GetBarMode") != null) descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(_Module.Module, "efl_ui_scrollbar_bar_mode_get"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_scrollbar_bar_mode_get_static_delegate)}); if (efl_ui_scrollbar_bar_mode_set_static_delegate == null) efl_ui_scrollbar_bar_mode_set_static_delegate = new efl_ui_scrollbar_bar_mode_set_delegate(bar_mode_set); if (methods.FirstOrDefault(m => m.Name == "SetBarMode") != null) descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(_Module.Module, "efl_ui_scrollbar_bar_mode_set"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_scrollbar_bar_mode_set_static_delegate)}); if (efl_ui_scrollbar_bar_size_get_static_delegate == null) efl_ui_scrollbar_bar_size_get_static_delegate = new efl_ui_scrollbar_bar_size_get_delegate(bar_size_get); if (methods.FirstOrDefault(m => m.Name == "GetBarSize") != null) descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(_Module.Module, "efl_ui_scrollbar_bar_size_get"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_scrollbar_bar_size_get_static_delegate)}); if (efl_ui_scrollbar_bar_position_get_static_delegate == null) efl_ui_scrollbar_bar_position_get_static_delegate = new efl_ui_scrollbar_bar_position_get_delegate(bar_position_get); if (methods.FirstOrDefault(m => m.Name == "GetBarPosition") != null) descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(_Module.Module, "efl_ui_scrollbar_bar_position_get"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_scrollbar_bar_position_get_static_delegate)}); if (efl_ui_scrollbar_bar_position_set_static_delegate == null) efl_ui_scrollbar_bar_position_set_static_delegate = new efl_ui_scrollbar_bar_position_set_delegate(bar_position_set); if (methods.FirstOrDefault(m => m.Name == "SetBarPosition") != null) descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(_Module.Module, "efl_ui_scrollbar_bar_position_set"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_scrollbar_bar_position_set_static_delegate)}); if (efl_ui_scrollbar_bar_visibility_update_static_delegate == null) efl_ui_scrollbar_bar_visibility_update_static_delegate = new efl_ui_scrollbar_bar_visibility_update_delegate(bar_visibility_update); if (methods.FirstOrDefault(m => m.Name == "UpdateBarVisibility") != null) descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(_Module.Module, "efl_ui_scrollbar_bar_visibility_update"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_scrollbar_bar_visibility_update_static_delegate)}); if (efl_ui_zoom_animation_get_static_delegate == null) efl_ui_zoom_animation_get_static_delegate = new efl_ui_zoom_animation_get_delegate(zoom_animation_get); if (methods.FirstOrDefault(m => m.Name == "GetZoomAnimation") != null) descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(_Module.Module, "efl_ui_zoom_animation_get"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_zoom_animation_get_static_delegate)}); if (efl_ui_zoom_animation_set_static_delegate == null) efl_ui_zoom_animation_set_static_delegate = new efl_ui_zoom_animation_set_delegate(zoom_animation_set); if (methods.FirstOrDefault(m => m.Name == "SetZoomAnimation") != null) descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(_Module.Module, "efl_ui_zoom_animation_set"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_zoom_animation_set_static_delegate)}); if (efl_ui_zoom_level_get_static_delegate == null) efl_ui_zoom_level_get_static_delegate = new efl_ui_zoom_level_get_delegate(zoom_level_get); if (methods.FirstOrDefault(m => m.Name == "GetZoomLevel") != null) descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(_Module.Module, "efl_ui_zoom_level_get"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_zoom_level_get_static_delegate)}); if (efl_ui_zoom_level_set_static_delegate == null) efl_ui_zoom_level_set_static_delegate = new efl_ui_zoom_level_set_delegate(zoom_level_set); if (methods.FirstOrDefault(m => m.Name == "SetZoomLevel") != null) descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(_Module.Module, "efl_ui_zoom_level_set"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_zoom_level_set_static_delegate)}); if (efl_ui_zoom_mode_get_static_delegate == null) efl_ui_zoom_mode_get_static_delegate = new efl_ui_zoom_mode_get_delegate(zoom_mode_get); if (methods.FirstOrDefault(m => m.Name == "GetZoomMode") != null) descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(_Module.Module, "efl_ui_zoom_mode_get"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_zoom_mode_get_static_delegate)}); if (efl_ui_zoom_mode_set_static_delegate == null) efl_ui_zoom_mode_set_static_delegate = new efl_ui_zoom_mode_set_delegate(zoom_mode_set); if (methods.FirstOrDefault(m => m.Name == "SetZoomMode") != null) descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(_Module.Module, "efl_ui_zoom_mode_set"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_zoom_mode_set_static_delegate)}); descs.AddRange(base.GetEoOps(type)); return descs; } public override IntPtr GetEflClass() { return Efl.Ui.ImageZoomable.efl_ui_image_zoomable_class_get(); } public static new IntPtr GetEflClassStatic() { return Efl.Ui.ImageZoomable.efl_ui_image_zoomable_class_get(); } [return: MarshalAs(UnmanagedType.U1)] private delegate bool efl_ui_image_zoomable_gesture_enabled_get_delegate(System.IntPtr obj, System.IntPtr pd); [return: MarshalAs(UnmanagedType.U1)] public delegate bool efl_ui_image_zoomable_gesture_enabled_get_api_delegate(System.IntPtr obj); public static Efl.Eo.FunctionWrapper<efl_ui_image_zoomable_gesture_enabled_get_api_delegate> efl_ui_image_zoomable_gesture_enabled_get_ptr = new Efl.Eo.FunctionWrapper<efl_ui_image_zoomable_gesture_enabled_get_api_delegate>(_Module, "efl_ui_image_zoomable_gesture_enabled_get"); private static bool gesture_enabled_get(System.IntPtr obj, System.IntPtr pd) { Eina.Log.Debug("function efl_ui_image_zoomable_gesture_enabled_get was called"); Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd); if(wrapper != null) { bool _ret_var = default(bool); try { _ret_var = ((ImageZoomable)wrapper).GetGestureEnabled(); } catch (Exception e) { Eina.Log.Warning($"Callback error: {e.ToString()}"); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } return _ret_var; } else { return efl_ui_image_zoomable_gesture_enabled_get_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj))); } } private static efl_ui_image_zoomable_gesture_enabled_get_delegate efl_ui_image_zoomable_gesture_enabled_get_static_delegate; private delegate void efl_ui_image_zoomable_gesture_enabled_set_delegate(System.IntPtr obj, System.IntPtr pd, [MarshalAs(UnmanagedType.U1)] bool gesture); public delegate void efl_ui_image_zoomable_gesture_enabled_set_api_delegate(System.IntPtr obj, [MarshalAs(UnmanagedType.U1)] bool gesture); public static Efl.Eo.FunctionWrapper<efl_ui_image_zoomable_gesture_enabled_set_api_delegate> efl_ui_image_zoomable_gesture_enabled_set_ptr = new Efl.Eo.FunctionWrapper<efl_ui_image_zoomable_gesture_enabled_set_api_delegate>(_Module, "efl_ui_image_zoomable_gesture_enabled_set"); private static void gesture_enabled_set(System.IntPtr obj, System.IntPtr pd, bool gesture) { Eina.Log.Debug("function efl_ui_image_zoomable_gesture_enabled_set was called"); Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd); if(wrapper != null) { try { ((ImageZoomable)wrapper).SetGestureEnabled( gesture); } catch (Exception e) { Eina.Log.Warning($"Callback error: {e.ToString()}"); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } else { efl_ui_image_zoomable_gesture_enabled_set_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)), gesture); } } private static efl_ui_image_zoomable_gesture_enabled_set_delegate efl_ui_image_zoomable_gesture_enabled_set_static_delegate; private delegate Eina.Rect.NativeStruct efl_ui_image_zoomable_image_region_get_delegate(System.IntPtr obj, System.IntPtr pd); public delegate Eina.Rect.NativeStruct efl_ui_image_zoomable_image_region_get_api_delegate(System.IntPtr obj); public static Efl.Eo.FunctionWrapper<efl_ui_image_zoomable_image_region_get_api_delegate> efl_ui_image_zoomable_image_region_get_ptr = new Efl.Eo.FunctionWrapper<efl_ui_image_zoomable_image_region_get_api_delegate>(_Module, "efl_ui_image_zoomable_image_region_get"); private static Eina.Rect.NativeStruct image_region_get(System.IntPtr obj, System.IntPtr pd) { Eina.Log.Debug("function efl_ui_image_zoomable_image_region_get was called"); Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd); if(wrapper != null) { Eina.Rect _ret_var = default(Eina.Rect); try { _ret_var = ((ImageZoomable)wrapper).GetImageRegion(); } catch (Exception e) { Eina.Log.Warning($"Callback error: {e.ToString()}"); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } return _ret_var; } else { return efl_ui_image_zoomable_image_region_get_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj))); } } private static efl_ui_image_zoomable_image_region_get_delegate efl_ui_image_zoomable_image_region_get_static_delegate; private delegate void efl_ui_image_zoomable_image_region_set_delegate(System.IntPtr obj, System.IntPtr pd, Eina.Rect.NativeStruct region); public delegate void efl_ui_image_zoomable_image_region_set_api_delegate(System.IntPtr obj, Eina.Rect.NativeStruct region); public static Efl.Eo.FunctionWrapper<efl_ui_image_zoomable_image_region_set_api_delegate> efl_ui_image_zoomable_image_region_set_ptr = new Efl.Eo.FunctionWrapper<efl_ui_image_zoomable_image_region_set_api_delegate>(_Module, "efl_ui_image_zoomable_image_region_set"); private static void image_region_set(System.IntPtr obj, System.IntPtr pd, Eina.Rect.NativeStruct region) { Eina.Log.Debug("function efl_ui_image_zoomable_image_region_set was called"); Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd); if(wrapper != null) { Eina.Rect _in_region = region; try { ((ImageZoomable)wrapper).SetImageRegion( _in_region); } catch (Exception e) { Eina.Log.Warning($"Callback error: {e.ToString()}"); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } else { efl_ui_image_zoomable_image_region_set_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)), region); } } private static efl_ui_image_zoomable_image_region_set_delegate efl_ui_image_zoomable_image_region_set_static_delegate; private delegate Eina.Position2D.NativeStruct efl_ui_scrollable_content_pos_get_delegate(System.IntPtr obj, System.IntPtr pd); public delegate Eina.Position2D.NativeStruct efl_ui_scrollable_content_pos_get_api_delegate(System.IntPtr obj); public static Efl.Eo.FunctionWrapper<efl_ui_scrollable_content_pos_get_api_delegate> efl_ui_scrollable_content_pos_get_ptr = new Efl.Eo.FunctionWrapper<efl_ui_scrollable_content_pos_get_api_delegate>(_Module, "efl_ui_scrollable_content_pos_get"); private static Eina.Position2D.NativeStruct content_pos_get(System.IntPtr obj, System.IntPtr pd) { Eina.Log.Debug("function efl_ui_scrollable_content_pos_get was called"); Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd); if(wrapper != null) { Eina.Position2D _ret_var = default(Eina.Position2D); try { _ret_var = ((ImageZoomable)wrapper).GetContentPos(); } catch (Exception e) { Eina.Log.Warning($"Callback error: {e.ToString()}"); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } return _ret_var; } else { return efl_ui_scrollable_content_pos_get_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj))); } } private static efl_ui_scrollable_content_pos_get_delegate efl_ui_scrollable_content_pos_get_static_delegate; private delegate void efl_ui_scrollable_content_pos_set_delegate(System.IntPtr obj, System.IntPtr pd, Eina.Position2D.NativeStruct pos); public delegate void efl_ui_scrollable_content_pos_set_api_delegate(System.IntPtr obj, Eina.Position2D.NativeStruct pos); public static Efl.Eo.FunctionWrapper<efl_ui_scrollable_content_pos_set_api_delegate> efl_ui_scrollable_content_pos_set_ptr = new Efl.Eo.FunctionWrapper<efl_ui_scrollable_content_pos_set_api_delegate>(_Module, "efl_ui_scrollable_content_pos_set"); private static void content_pos_set(System.IntPtr obj, System.IntPtr pd, Eina.Position2D.NativeStruct pos) { Eina.Log.Debug("function efl_ui_scrollable_content_pos_set was called"); Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd); if(wrapper != null) { Eina.Position2D _in_pos = pos; try { ((ImageZoomable)wrapper).SetContentPos( _in_pos); } catch (Exception e) { Eina.Log.Warning($"Callback error: {e.ToString()}"); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } else { efl_ui_scrollable_content_pos_set_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)), pos); } } private static efl_ui_scrollable_content_pos_set_delegate efl_ui_scrollable_content_pos_set_static_delegate; private delegate Eina.Size2D.NativeStruct efl_ui_scrollable_content_size_get_delegate(System.IntPtr obj, System.IntPtr pd); public delegate Eina.Size2D.NativeStruct efl_ui_scrollable_content_size_get_api_delegate(System.IntPtr obj); public static Efl.Eo.FunctionWrapper<efl_ui_scrollable_content_size_get_api_delegate> efl_ui_scrollable_content_size_get_ptr = new Efl.Eo.FunctionWrapper<efl_ui_scrollable_content_size_get_api_delegate>(_Module, "efl_ui_scrollable_content_size_get"); private static Eina.Size2D.NativeStruct content_size_get(System.IntPtr obj, System.IntPtr pd) { Eina.Log.Debug("function efl_ui_scrollable_content_size_get was called"); Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd); if(wrapper != null) { Eina.Size2D _ret_var = default(Eina.Size2D); try { _ret_var = ((ImageZoomable)wrapper).GetContentSize(); } catch (Exception e) { Eina.Log.Warning($"Callback error: {e.ToString()}"); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } return _ret_var; } else { return efl_ui_scrollable_content_size_get_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj))); } } private static efl_ui_scrollable_content_size_get_delegate efl_ui_scrollable_content_size_get_static_delegate; private delegate Eina.Rect.NativeStruct efl_ui_scrollable_viewport_geometry_get_delegate(System.IntPtr obj, System.IntPtr pd); public delegate Eina.Rect.NativeStruct efl_ui_scrollable_viewport_geometry_get_api_delegate(System.IntPtr obj); public static Efl.Eo.FunctionWrapper<efl_ui_scrollable_viewport_geometry_get_api_delegate> efl_ui_scrollable_viewport_geometry_get_ptr = new Efl.Eo.FunctionWrapper<efl_ui_scrollable_viewport_geometry_get_api_delegate>(_Module, "efl_ui_scrollable_viewport_geometry_get"); private static Eina.Rect.NativeStruct viewport_geometry_get(System.IntPtr obj, System.IntPtr pd) { Eina.Log.Debug("function efl_ui_scrollable_viewport_geometry_get was called"); Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd); if(wrapper != null) { Eina.Rect _ret_var = default(Eina.Rect); try { _ret_var = ((ImageZoomable)wrapper).GetViewportGeometry(); } catch (Exception e) { Eina.Log.Warning($"Callback error: {e.ToString()}"); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } return _ret_var; } else { return efl_ui_scrollable_viewport_geometry_get_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj))); } } private static efl_ui_scrollable_viewport_geometry_get_delegate efl_ui_scrollable_viewport_geometry_get_static_delegate; private delegate void efl_ui_scrollable_bounce_enabled_get_delegate(System.IntPtr obj, System.IntPtr pd, [MarshalAs(UnmanagedType.U1)] out bool horiz, [MarshalAs(UnmanagedType.U1)] out bool vert); public delegate void efl_ui_scrollable_bounce_enabled_get_api_delegate(System.IntPtr obj, [MarshalAs(UnmanagedType.U1)] out bool horiz, [MarshalAs(UnmanagedType.U1)] out bool vert); public static Efl.Eo.FunctionWrapper<efl_ui_scrollable_bounce_enabled_get_api_delegate> efl_ui_scrollable_bounce_enabled_get_ptr = new Efl.Eo.FunctionWrapper<efl_ui_scrollable_bounce_enabled_get_api_delegate>(_Module, "efl_ui_scrollable_bounce_enabled_get"); private static void bounce_enabled_get(System.IntPtr obj, System.IntPtr pd, out bool horiz, out bool vert) { Eina.Log.Debug("function efl_ui_scrollable_bounce_enabled_get was called"); Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd); if(wrapper != null) { horiz = default(bool); vert = default(bool); try { ((ImageZoomable)wrapper).GetBounceEnabled( out horiz, out vert); } catch (Exception e) { Eina.Log.Warning($"Callback error: {e.ToString()}"); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } else { efl_ui_scrollable_bounce_enabled_get_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)), out horiz, out vert); } } private static efl_ui_scrollable_bounce_enabled_get_delegate efl_ui_scrollable_bounce_enabled_get_static_delegate; private delegate void efl_ui_scrollable_bounce_enabled_set_delegate(System.IntPtr obj, System.IntPtr pd, [MarshalAs(UnmanagedType.U1)] bool horiz, [MarshalAs(UnmanagedType.U1)] bool vert); public delegate void efl_ui_scrollable_bounce_enabled_set_api_delegate(System.IntPtr obj, [MarshalAs(UnmanagedType.U1)] bool horiz, [MarshalAs(UnmanagedType.U1)] bool vert); public static Efl.Eo.FunctionWrapper<efl_ui_scrollable_bounce_enabled_set_api_delegate> efl_ui_scrollable_bounce_enabled_set_ptr = new Efl.Eo.FunctionWrapper<efl_ui_scrollable_bounce_enabled_set_api_delegate>(_Module, "efl_ui_scrollable_bounce_enabled_set"); private static void bounce_enabled_set(System.IntPtr obj, System.IntPtr pd, bool horiz, bool vert) { Eina.Log.Debug("function efl_ui_scrollable_bounce_enabled_set was called"); Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd); if(wrapper != null) { try { ((ImageZoomable)wrapper).SetBounceEnabled( horiz, vert); } catch (Exception e) { Eina.Log.Warning($"Callback error: {e.ToString()}"); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } else { efl_ui_scrollable_bounce_enabled_set_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)), horiz, vert); } } private static efl_ui_scrollable_bounce_enabled_set_delegate efl_ui_scrollable_bounce_enabled_set_static_delegate; [return: MarshalAs(UnmanagedType.U1)] private delegate bool efl_ui_scrollable_scroll_freeze_get_delegate(System.IntPtr obj, System.IntPtr pd); [return: MarshalAs(UnmanagedType.U1)] public delegate bool efl_ui_scrollable_scroll_freeze_get_api_delegate(System.IntPtr obj); public static Efl.Eo.FunctionWrapper<efl_ui_scrollable_scroll_freeze_get_api_delegate> efl_ui_scrollable_scroll_freeze_get_ptr = new Efl.Eo.FunctionWrapper<efl_ui_scrollable_scroll_freeze_get_api_delegate>(_Module, "efl_ui_scrollable_scroll_freeze_get"); private static bool scroll_freeze_get(System.IntPtr obj, System.IntPtr pd) { Eina.Log.Debug("function efl_ui_scrollable_scroll_freeze_get was called"); Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd); if(wrapper != null) { bool _ret_var = default(bool); try { _ret_var = ((ImageZoomable)wrapper).GetScrollFreeze(); } catch (Exception e) { Eina.Log.Warning($"Callback error: {e.ToString()}"); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } return _ret_var; } else { return efl_ui_scrollable_scroll_freeze_get_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj))); } } private static efl_ui_scrollable_scroll_freeze_get_delegate efl_ui_scrollable_scroll_freeze_get_static_delegate; private delegate void efl_ui_scrollable_scroll_freeze_set_delegate(System.IntPtr obj, System.IntPtr pd, [MarshalAs(UnmanagedType.U1)] bool freeze); public delegate void efl_ui_scrollable_scroll_freeze_set_api_delegate(System.IntPtr obj, [MarshalAs(UnmanagedType.U1)] bool freeze); public static Efl.Eo.FunctionWrapper<efl_ui_scrollable_scroll_freeze_set_api_delegate> efl_ui_scrollable_scroll_freeze_set_ptr = new Efl.Eo.FunctionWrapper<efl_ui_scrollable_scroll_freeze_set_api_delegate>(_Module, "efl_ui_scrollable_scroll_freeze_set"); private static void scroll_freeze_set(System.IntPtr obj, System.IntPtr pd, bool freeze) { Eina.Log.Debug("function efl_ui_scrollable_scroll_freeze_set was called"); Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd); if(wrapper != null) { try { ((ImageZoomable)wrapper).SetScrollFreeze( freeze); } catch (Exception e) { Eina.Log.Warning($"Callback error: {e.ToString()}"); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } else { efl_ui_scrollable_scroll_freeze_set_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)), freeze); } } private static efl_ui_scrollable_scroll_freeze_set_delegate efl_ui_scrollable_scroll_freeze_set_static_delegate; [return: MarshalAs(UnmanagedType.U1)] private delegate bool efl_ui_scrollable_scroll_hold_get_delegate(System.IntPtr obj, System.IntPtr pd); [return: MarshalAs(UnmanagedType.U1)] public delegate bool efl_ui_scrollable_scroll_hold_get_api_delegate(System.IntPtr obj); public static Efl.Eo.FunctionWrapper<efl_ui_scrollable_scroll_hold_get_api_delegate> efl_ui_scrollable_scroll_hold_get_ptr = new Efl.Eo.FunctionWrapper<efl_ui_scrollable_scroll_hold_get_api_delegate>(_Module, "efl_ui_scrollable_scroll_hold_get"); private static bool scroll_hold_get(System.IntPtr obj, System.IntPtr pd) { Eina.Log.Debug("function efl_ui_scrollable_scroll_hold_get was called"); Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd); if(wrapper != null) { bool _ret_var = default(bool); try { _ret_var = ((ImageZoomable)wrapper).GetScrollHold(); } catch (Exception e) { Eina.Log.Warning($"Callback error: {e.ToString()}"); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } return _ret_var; } else { return efl_ui_scrollable_scroll_hold_get_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj))); } } private static efl_ui_scrollable_scroll_hold_get_delegate efl_ui_scrollable_scroll_hold_get_static_delegate; private delegate void efl_ui_scrollable_scroll_hold_set_delegate(System.IntPtr obj, System.IntPtr pd, [MarshalAs(UnmanagedType.U1)] bool hold); public delegate void efl_ui_scrollable_scroll_hold_set_api_delegate(System.IntPtr obj, [MarshalAs(UnmanagedType.U1)] bool hold); public static Efl.Eo.FunctionWrapper<efl_ui_scrollable_scroll_hold_set_api_delegate> efl_ui_scrollable_scroll_hold_set_ptr = new Efl.Eo.FunctionWrapper<efl_ui_scrollable_scroll_hold_set_api_delegate>(_Module, "efl_ui_scrollable_scroll_hold_set"); private static void scroll_hold_set(System.IntPtr obj, System.IntPtr pd, bool hold) { Eina.Log.Debug("function efl_ui_scrollable_scroll_hold_set was called"); Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd); if(wrapper != null) { try { ((ImageZoomable)wrapper).SetScrollHold( hold); } catch (Exception e) { Eina.Log.Warning($"Callback error: {e.ToString()}"); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } else { efl_ui_scrollable_scroll_hold_set_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)), hold); } } private static efl_ui_scrollable_scroll_hold_set_delegate efl_ui_scrollable_scroll_hold_set_static_delegate; private delegate void efl_ui_scrollable_looping_get_delegate(System.IntPtr obj, System.IntPtr pd, [MarshalAs(UnmanagedType.U1)] out bool loop_h, [MarshalAs(UnmanagedType.U1)] out bool loop_v); public delegate void efl_ui_scrollable_looping_get_api_delegate(System.IntPtr obj, [MarshalAs(UnmanagedType.U1)] out bool loop_h, [MarshalAs(UnmanagedType.U1)] out bool loop_v); public static Efl.Eo.FunctionWrapper<efl_ui_scrollable_looping_get_api_delegate> efl_ui_scrollable_looping_get_ptr = new Efl.Eo.FunctionWrapper<efl_ui_scrollable_looping_get_api_delegate>(_Module, "efl_ui_scrollable_looping_get"); private static void looping_get(System.IntPtr obj, System.IntPtr pd, out bool loop_h, out bool loop_v) { Eina.Log.Debug("function efl_ui_scrollable_looping_get was called"); Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd); if(wrapper != null) { loop_h = default(bool); loop_v = default(bool); try { ((ImageZoomable)wrapper).GetLooping( out loop_h, out loop_v); } catch (Exception e) { Eina.Log.Warning($"Callback error: {e.ToString()}"); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } else { efl_ui_scrollable_looping_get_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)), out loop_h, out loop_v); } } private static efl_ui_scrollable_looping_get_delegate efl_ui_scrollable_looping_get_static_delegate; private delegate void efl_ui_scrollable_looping_set_delegate(System.IntPtr obj, System.IntPtr pd, [MarshalAs(UnmanagedType.U1)] bool loop_h, [MarshalAs(UnmanagedType.U1)] bool loop_v); public delegate void efl_ui_scrollable_looping_set_api_delegate(System.IntPtr obj, [MarshalAs(UnmanagedType.U1)] bool loop_h, [MarshalAs(UnmanagedType.U1)] bool loop_v); public static Efl.Eo.FunctionWrapper<efl_ui_scrollable_looping_set_api_delegate> efl_ui_scrollable_looping_set_ptr = new Efl.Eo.FunctionWrapper<efl_ui_scrollable_looping_set_api_delegate>(_Module, "efl_ui_scrollable_looping_set"); private static void looping_set(System.IntPtr obj, System.IntPtr pd, bool loop_h, bool loop_v) { Eina.Log.Debug("function efl_ui_scrollable_looping_set was called"); Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd); if(wrapper != null) { try { ((ImageZoomable)wrapper).SetLooping( loop_h, loop_v); } catch (Exception e) { Eina.Log.Warning($"Callback error: {e.ToString()}"); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } else { efl_ui_scrollable_looping_set_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)), loop_h, loop_v); } } private static efl_ui_scrollable_looping_set_delegate efl_ui_scrollable_looping_set_static_delegate; private delegate Efl.Ui.ScrollBlock efl_ui_scrollable_movement_block_get_delegate(System.IntPtr obj, System.IntPtr pd); public delegate Efl.Ui.ScrollBlock efl_ui_scrollable_movement_block_get_api_delegate(System.IntPtr obj); public static Efl.Eo.FunctionWrapper<efl_ui_scrollable_movement_block_get_api_delegate> efl_ui_scrollable_movement_block_get_ptr = new Efl.Eo.FunctionWrapper<efl_ui_scrollable_movement_block_get_api_delegate>(_Module, "efl_ui_scrollable_movement_block_get"); private static Efl.Ui.ScrollBlock movement_block_get(System.IntPtr obj, System.IntPtr pd) { Eina.Log.Debug("function efl_ui_scrollable_movement_block_get was called"); Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd); if(wrapper != null) { Efl.Ui.ScrollBlock _ret_var = default(Efl.Ui.ScrollBlock); try { _ret_var = ((ImageZoomable)wrapper).GetMovementBlock(); } catch (Exception e) { Eina.Log.Warning($"Callback error: {e.ToString()}"); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } return _ret_var; } else { return efl_ui_scrollable_movement_block_get_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj))); } } private static efl_ui_scrollable_movement_block_get_delegate efl_ui_scrollable_movement_block_get_static_delegate; private delegate void efl_ui_scrollable_movement_block_set_delegate(System.IntPtr obj, System.IntPtr pd, Efl.Ui.ScrollBlock block); public delegate void efl_ui_scrollable_movement_block_set_api_delegate(System.IntPtr obj, Efl.Ui.ScrollBlock block); public static Efl.Eo.FunctionWrapper<efl_ui_scrollable_movement_block_set_api_delegate> efl_ui_scrollable_movement_block_set_ptr = new Efl.Eo.FunctionWrapper<efl_ui_scrollable_movement_block_set_api_delegate>(_Module, "efl_ui_scrollable_movement_block_set"); private static void movement_block_set(System.IntPtr obj, System.IntPtr pd, Efl.Ui.ScrollBlock block) { Eina.Log.Debug("function efl_ui_scrollable_movement_block_set was called"); Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd); if(wrapper != null) { try { ((ImageZoomable)wrapper).SetMovementBlock( block); } catch (Exception e) { Eina.Log.Warning($"Callback error: {e.ToString()}"); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } else { efl_ui_scrollable_movement_block_set_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)), block); } } private static efl_ui_scrollable_movement_block_set_delegate efl_ui_scrollable_movement_block_set_static_delegate; private delegate void efl_ui_scrollable_gravity_get_delegate(System.IntPtr obj, System.IntPtr pd, out double x, out double y); public delegate void efl_ui_scrollable_gravity_get_api_delegate(System.IntPtr obj, out double x, out double y); public static Efl.Eo.FunctionWrapper<efl_ui_scrollable_gravity_get_api_delegate> efl_ui_scrollable_gravity_get_ptr = new Efl.Eo.FunctionWrapper<efl_ui_scrollable_gravity_get_api_delegate>(_Module, "efl_ui_scrollable_gravity_get"); private static void gravity_get(System.IntPtr obj, System.IntPtr pd, out double x, out double y) { Eina.Log.Debug("function efl_ui_scrollable_gravity_get was called"); Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd); if(wrapper != null) { x = default(double); y = default(double); try { ((ImageZoomable)wrapper).GetGravity( out x, out y); } catch (Exception e) { Eina.Log.Warning($"Callback error: {e.ToString()}"); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } else { efl_ui_scrollable_gravity_get_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)), out x, out y); } } private static efl_ui_scrollable_gravity_get_delegate efl_ui_scrollable_gravity_get_static_delegate; private delegate void efl_ui_scrollable_gravity_set_delegate(System.IntPtr obj, System.IntPtr pd, double x, double y); public delegate void efl_ui_scrollable_gravity_set_api_delegate(System.IntPtr obj, double x, double y); public static Efl.Eo.FunctionWrapper<efl_ui_scrollable_gravity_set_api_delegate> efl_ui_scrollable_gravity_set_ptr = new Efl.Eo.FunctionWrapper<efl_ui_scrollable_gravity_set_api_delegate>(_Module, "efl_ui_scrollable_gravity_set"); private static void gravity_set(System.IntPtr obj, System.IntPtr pd, double x, double y) { Eina.Log.Debug("function efl_ui_scrollable_gravity_set was called"); Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd); if(wrapper != null) { try { ((ImageZoomable)wrapper).SetGravity( x, y); } catch (Exception e) { Eina.Log.Warning($"Callback error: {e.ToString()}"); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } else { efl_ui_scrollable_gravity_set_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)), x, y); } } private static efl_ui_scrollable_gravity_set_delegate efl_ui_scrollable_gravity_set_static_delegate; private delegate void efl_ui_scrollable_match_content_set_delegate(System.IntPtr obj, System.IntPtr pd, [MarshalAs(UnmanagedType.U1)] bool w, [MarshalAs(UnmanagedType.U1)] bool h); public delegate void efl_ui_scrollable_match_content_set_api_delegate(System.IntPtr obj, [MarshalAs(UnmanagedType.U1)] bool w, [MarshalAs(UnmanagedType.U1)] bool h); public static Efl.Eo.FunctionWrapper<efl_ui_scrollable_match_content_set_api_delegate> efl_ui_scrollable_match_content_set_ptr = new Efl.Eo.FunctionWrapper<efl_ui_scrollable_match_content_set_api_delegate>(_Module, "efl_ui_scrollable_match_content_set"); private static void match_content_set(System.IntPtr obj, System.IntPtr pd, bool w, bool h) { Eina.Log.Debug("function efl_ui_scrollable_match_content_set was called"); Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd); if(wrapper != null) { try { ((ImageZoomable)wrapper).SetMatchContent( w, h); } catch (Exception e) { Eina.Log.Warning($"Callback error: {e.ToString()}"); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } else { efl_ui_scrollable_match_content_set_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)), w, h); } } private static efl_ui_scrollable_match_content_set_delegate efl_ui_scrollable_match_content_set_static_delegate; private delegate Eina.Position2D.NativeStruct efl_ui_scrollable_step_size_get_delegate(System.IntPtr obj, System.IntPtr pd); public delegate Eina.Position2D.NativeStruct efl_ui_scrollable_step_size_get_api_delegate(System.IntPtr obj); public static Efl.Eo.FunctionWrapper<efl_ui_scrollable_step_size_get_api_delegate> efl_ui_scrollable_step_size_get_ptr = new Efl.Eo.FunctionWrapper<efl_ui_scrollable_step_size_get_api_delegate>(_Module, "efl_ui_scrollable_step_size_get"); private static Eina.Position2D.NativeStruct step_size_get(System.IntPtr obj, System.IntPtr pd) { Eina.Log.Debug("function efl_ui_scrollable_step_size_get was called"); Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd); if(wrapper != null) { Eina.Position2D _ret_var = default(Eina.Position2D); try { _ret_var = ((ImageZoomable)wrapper).GetStepSize(); } catch (Exception e) { Eina.Log.Warning($"Callback error: {e.ToString()}"); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } return _ret_var; } else { return efl_ui_scrollable_step_size_get_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj))); } } private static efl_ui_scrollable_step_size_get_delegate efl_ui_scrollable_step_size_get_static_delegate; private delegate void efl_ui_scrollable_step_size_set_delegate(System.IntPtr obj, System.IntPtr pd, Eina.Position2D.NativeStruct step); public delegate void efl_ui_scrollable_step_size_set_api_delegate(System.IntPtr obj, Eina.Position2D.NativeStruct step); public static Efl.Eo.FunctionWrapper<efl_ui_scrollable_step_size_set_api_delegate> efl_ui_scrollable_step_size_set_ptr = new Efl.Eo.FunctionWrapper<efl_ui_scrollable_step_size_set_api_delegate>(_Module, "efl_ui_scrollable_step_size_set"); private static void step_size_set(System.IntPtr obj, System.IntPtr pd, Eina.Position2D.NativeStruct step) { Eina.Log.Debug("function efl_ui_scrollable_step_size_set was called"); Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd); if(wrapper != null) { Eina.Position2D _in_step = step; try { ((ImageZoomable)wrapper).SetStepSize( _in_step); } catch (Exception e) { Eina.Log.Warning($"Callback error: {e.ToString()}"); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } else { efl_ui_scrollable_step_size_set_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)), step); } } private static efl_ui_scrollable_step_size_set_delegate efl_ui_scrollable_step_size_set_static_delegate; private delegate void efl_ui_scrollable_scroll_delegate(System.IntPtr obj, System.IntPtr pd, Eina.Rect.NativeStruct rect, [MarshalAs(UnmanagedType.U1)] bool animation); public delegate void efl_ui_scrollable_scroll_api_delegate(System.IntPtr obj, Eina.Rect.NativeStruct rect, [MarshalAs(UnmanagedType.U1)] bool animation); public static Efl.Eo.FunctionWrapper<efl_ui_scrollable_scroll_api_delegate> efl_ui_scrollable_scroll_ptr = new Efl.Eo.FunctionWrapper<efl_ui_scrollable_scroll_api_delegate>(_Module, "efl_ui_scrollable_scroll"); private static void scroll(System.IntPtr obj, System.IntPtr pd, Eina.Rect.NativeStruct rect, bool animation) { Eina.Log.Debug("function efl_ui_scrollable_scroll was called"); Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd); if(wrapper != null) { Eina.Rect _in_rect = rect; try { ((ImageZoomable)wrapper).Scroll( _in_rect, animation); } catch (Exception e) { Eina.Log.Warning($"Callback error: {e.ToString()}"); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } else { efl_ui_scrollable_scroll_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)), rect, animation); } } private static efl_ui_scrollable_scroll_delegate efl_ui_scrollable_scroll_static_delegate; private delegate void efl_ui_scrollbar_bar_mode_get_delegate(System.IntPtr obj, System.IntPtr pd, out Efl.Ui.ScrollbarMode hbar, out Efl.Ui.ScrollbarMode vbar); public delegate void efl_ui_scrollbar_bar_mode_get_api_delegate(System.IntPtr obj, out Efl.Ui.ScrollbarMode hbar, out Efl.Ui.ScrollbarMode vbar); public static Efl.Eo.FunctionWrapper<efl_ui_scrollbar_bar_mode_get_api_delegate> efl_ui_scrollbar_bar_mode_get_ptr = new Efl.Eo.FunctionWrapper<efl_ui_scrollbar_bar_mode_get_api_delegate>(_Module, "efl_ui_scrollbar_bar_mode_get"); private static void bar_mode_get(System.IntPtr obj, System.IntPtr pd, out Efl.Ui.ScrollbarMode hbar, out Efl.Ui.ScrollbarMode vbar) { Eina.Log.Debug("function efl_ui_scrollbar_bar_mode_get was called"); Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd); if(wrapper != null) { hbar = default(Efl.Ui.ScrollbarMode); vbar = default(Efl.Ui.ScrollbarMode); try { ((ImageZoomable)wrapper).GetBarMode( out hbar, out vbar); } catch (Exception e) { Eina.Log.Warning($"Callback error: {e.ToString()}"); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } else { efl_ui_scrollbar_bar_mode_get_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)), out hbar, out vbar); } } private static efl_ui_scrollbar_bar_mode_get_delegate efl_ui_scrollbar_bar_mode_get_static_delegate; private delegate void efl_ui_scrollbar_bar_mode_set_delegate(System.IntPtr obj, System.IntPtr pd, Efl.Ui.ScrollbarMode hbar, Efl.Ui.ScrollbarMode vbar); public delegate void efl_ui_scrollbar_bar_mode_set_api_delegate(System.IntPtr obj, Efl.Ui.ScrollbarMode hbar, Efl.Ui.ScrollbarMode vbar); public static Efl.Eo.FunctionWrapper<efl_ui_scrollbar_bar_mode_set_api_delegate> efl_ui_scrollbar_bar_mode_set_ptr = new Efl.Eo.FunctionWrapper<efl_ui_scrollbar_bar_mode_set_api_delegate>(_Module, "efl_ui_scrollbar_bar_mode_set"); private static void bar_mode_set(System.IntPtr obj, System.IntPtr pd, Efl.Ui.ScrollbarMode hbar, Efl.Ui.ScrollbarMode vbar) { Eina.Log.Debug("function efl_ui_scrollbar_bar_mode_set was called"); Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd); if(wrapper != null) { try { ((ImageZoomable)wrapper).SetBarMode( hbar, vbar); } catch (Exception e) { Eina.Log.Warning($"Callback error: {e.ToString()}"); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } else { efl_ui_scrollbar_bar_mode_set_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)), hbar, vbar); } } private static efl_ui_scrollbar_bar_mode_set_delegate efl_ui_scrollbar_bar_mode_set_static_delegate; private delegate void efl_ui_scrollbar_bar_size_get_delegate(System.IntPtr obj, System.IntPtr pd, out double width, out double height); public delegate void efl_ui_scrollbar_bar_size_get_api_delegate(System.IntPtr obj, out double width, out double height); public static Efl.Eo.FunctionWrapper<efl_ui_scrollbar_bar_size_get_api_delegate> efl_ui_scrollbar_bar_size_get_ptr = new Efl.Eo.FunctionWrapper<efl_ui_scrollbar_bar_size_get_api_delegate>(_Module, "efl_ui_scrollbar_bar_size_get"); private static void bar_size_get(System.IntPtr obj, System.IntPtr pd, out double width, out double height) { Eina.Log.Debug("function efl_ui_scrollbar_bar_size_get was called"); Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd); if(wrapper != null) { width = default(double); height = default(double); try { ((ImageZoomable)wrapper).GetBarSize( out width, out height); } catch (Exception e) { Eina.Log.Warning($"Callback error: {e.ToString()}"); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } else { efl_ui_scrollbar_bar_size_get_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)), out width, out height); } } private static efl_ui_scrollbar_bar_size_get_delegate efl_ui_scrollbar_bar_size_get_static_delegate; private delegate void efl_ui_scrollbar_bar_position_get_delegate(System.IntPtr obj, System.IntPtr pd, out double posx, out double posy); public delegate void efl_ui_scrollbar_bar_position_get_api_delegate(System.IntPtr obj, out double posx, out double posy); public static Efl.Eo.FunctionWrapper<efl_ui_scrollbar_bar_position_get_api_delegate> efl_ui_scrollbar_bar_position_get_ptr = new Efl.Eo.FunctionWrapper<efl_ui_scrollbar_bar_position_get_api_delegate>(_Module, "efl_ui_scrollbar_bar_position_get"); private static void bar_position_get(System.IntPtr obj, System.IntPtr pd, out double posx, out double posy) { Eina.Log.Debug("function efl_ui_scrollbar_bar_position_get was called"); Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd); if(wrapper != null) { posx = default(double); posy = default(double); try { ((ImageZoomable)wrapper).GetBarPosition( out posx, out posy); } catch (Exception e) { Eina.Log.Warning($"Callback error: {e.ToString()}"); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } else { efl_ui_scrollbar_bar_position_get_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)), out posx, out posy); } } private static efl_ui_scrollbar_bar_position_get_delegate efl_ui_scrollbar_bar_position_get_static_delegate; private delegate void efl_ui_scrollbar_bar_position_set_delegate(System.IntPtr obj, System.IntPtr pd, double posx, double posy); public delegate void efl_ui_scrollbar_bar_position_set_api_delegate(System.IntPtr obj, double posx, double posy); public static Efl.Eo.FunctionWrapper<efl_ui_scrollbar_bar_position_set_api_delegate> efl_ui_scrollbar_bar_position_set_ptr = new Efl.Eo.FunctionWrapper<efl_ui_scrollbar_bar_position_set_api_delegate>(_Module, "efl_ui_scrollbar_bar_position_set"); private static void bar_position_set(System.IntPtr obj, System.IntPtr pd, double posx, double posy) { Eina.Log.Debug("function efl_ui_scrollbar_bar_position_set was called"); Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd); if(wrapper != null) { try { ((ImageZoomable)wrapper).SetBarPosition( posx, posy); } catch (Exception e) { Eina.Log.Warning($"Callback error: {e.ToString()}"); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } else { efl_ui_scrollbar_bar_position_set_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)), posx, posy); } } private static efl_ui_scrollbar_bar_position_set_delegate efl_ui_scrollbar_bar_position_set_static_delegate; private delegate void efl_ui_scrollbar_bar_visibility_update_delegate(System.IntPtr obj, System.IntPtr pd); public delegate void efl_ui_scrollbar_bar_visibility_update_api_delegate(System.IntPtr obj); public static Efl.Eo.FunctionWrapper<efl_ui_scrollbar_bar_visibility_update_api_delegate> efl_ui_scrollbar_bar_visibility_update_ptr = new Efl.Eo.FunctionWrapper<efl_ui_scrollbar_bar_visibility_update_api_delegate>(_Module, "efl_ui_scrollbar_bar_visibility_update"); private static void bar_visibility_update(System.IntPtr obj, System.IntPtr pd) { Eina.Log.Debug("function efl_ui_scrollbar_bar_visibility_update was called"); Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd); if(wrapper != null) { try { ((ImageZoomable)wrapper).UpdateBarVisibility(); } catch (Exception e) { Eina.Log.Warning($"Callback error: {e.ToString()}"); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } else { efl_ui_scrollbar_bar_visibility_update_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj))); } } private static efl_ui_scrollbar_bar_visibility_update_delegate efl_ui_scrollbar_bar_visibility_update_static_delegate; [return: MarshalAs(UnmanagedType.U1)] private delegate bool efl_ui_zoom_animation_get_delegate(System.IntPtr obj, System.IntPtr pd); [return: MarshalAs(UnmanagedType.U1)] public delegate bool efl_ui_zoom_animation_get_api_delegate(System.IntPtr obj); public static Efl.Eo.FunctionWrapper<efl_ui_zoom_animation_get_api_delegate> efl_ui_zoom_animation_get_ptr = new Efl.Eo.FunctionWrapper<efl_ui_zoom_animation_get_api_delegate>(_Module, "efl_ui_zoom_animation_get"); private static bool zoom_animation_get(System.IntPtr obj, System.IntPtr pd) { Eina.Log.Debug("function efl_ui_zoom_animation_get was called"); Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd); if(wrapper != null) { bool _ret_var = default(bool); try { _ret_var = ((ImageZoomable)wrapper).GetZoomAnimation(); } catch (Exception e) { Eina.Log.Warning($"Callback error: {e.ToString()}"); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } return _ret_var; } else { return efl_ui_zoom_animation_get_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj))); } } private static efl_ui_zoom_animation_get_delegate efl_ui_zoom_animation_get_static_delegate; private delegate void efl_ui_zoom_animation_set_delegate(System.IntPtr obj, System.IntPtr pd, [MarshalAs(UnmanagedType.U1)] bool paused); public delegate void efl_ui_zoom_animation_set_api_delegate(System.IntPtr obj, [MarshalAs(UnmanagedType.U1)] bool paused); public static Efl.Eo.FunctionWrapper<efl_ui_zoom_animation_set_api_delegate> efl_ui_zoom_animation_set_ptr = new Efl.Eo.FunctionWrapper<efl_ui_zoom_animation_set_api_delegate>(_Module, "efl_ui_zoom_animation_set"); private static void zoom_animation_set(System.IntPtr obj, System.IntPtr pd, bool paused) { Eina.Log.Debug("function efl_ui_zoom_animation_set was called"); Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd); if(wrapper != null) { try { ((ImageZoomable)wrapper).SetZoomAnimation( paused); } catch (Exception e) { Eina.Log.Warning($"Callback error: {e.ToString()}"); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } else { efl_ui_zoom_animation_set_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)), paused); } } private static efl_ui_zoom_animation_set_delegate efl_ui_zoom_animation_set_static_delegate; private delegate double efl_ui_zoom_level_get_delegate(System.IntPtr obj, System.IntPtr pd); public delegate double efl_ui_zoom_level_get_api_delegate(System.IntPtr obj); public static Efl.Eo.FunctionWrapper<efl_ui_zoom_level_get_api_delegate> efl_ui_zoom_level_get_ptr = new Efl.Eo.FunctionWrapper<efl_ui_zoom_level_get_api_delegate>(_Module, "efl_ui_zoom_level_get"); private static double zoom_level_get(System.IntPtr obj, System.IntPtr pd) { Eina.Log.Debug("function efl_ui_zoom_level_get was called"); Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd); if(wrapper != null) { double _ret_var = default(double); try { _ret_var = ((ImageZoomable)wrapper).GetZoomLevel(); } catch (Exception e) { Eina.Log.Warning($"Callback error: {e.ToString()}"); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } return _ret_var; } else { return efl_ui_zoom_level_get_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj))); } } private static efl_ui_zoom_level_get_delegate efl_ui_zoom_level_get_static_delegate; private delegate void efl_ui_zoom_level_set_delegate(System.IntPtr obj, System.IntPtr pd, double zoom); public delegate void efl_ui_zoom_level_set_api_delegate(System.IntPtr obj, double zoom); public static Efl.Eo.FunctionWrapper<efl_ui_zoom_level_set_api_delegate> efl_ui_zoom_level_set_ptr = new Efl.Eo.FunctionWrapper<efl_ui_zoom_level_set_api_delegate>(_Module, "efl_ui_zoom_level_set"); private static void zoom_level_set(System.IntPtr obj, System.IntPtr pd, double zoom) { Eina.Log.Debug("function efl_ui_zoom_level_set was called"); Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd); if(wrapper != null) { try { ((ImageZoomable)wrapper).SetZoomLevel( zoom); } catch (Exception e) { Eina.Log.Warning($"Callback error: {e.ToString()}"); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } else { efl_ui_zoom_level_set_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)), zoom); } } private static efl_ui_zoom_level_set_delegate efl_ui_zoom_level_set_static_delegate; private delegate Efl.Ui.ZoomMode efl_ui_zoom_mode_get_delegate(System.IntPtr obj, System.IntPtr pd); public delegate Efl.Ui.ZoomMode efl_ui_zoom_mode_get_api_delegate(System.IntPtr obj); public static Efl.Eo.FunctionWrapper<efl_ui_zoom_mode_get_api_delegate> efl_ui_zoom_mode_get_ptr = new Efl.Eo.FunctionWrapper<efl_ui_zoom_mode_get_api_delegate>(_Module, "efl_ui_zoom_mode_get"); private static Efl.Ui.ZoomMode zoom_mode_get(System.IntPtr obj, System.IntPtr pd) { Eina.Log.Debug("function efl_ui_zoom_mode_get was called"); Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd); if(wrapper != null) { Efl.Ui.ZoomMode _ret_var = default(Efl.Ui.ZoomMode); try { _ret_var = ((ImageZoomable)wrapper).GetZoomMode(); } catch (Exception e) { Eina.Log.Warning($"Callback error: {e.ToString()}"); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } return _ret_var; } else { return efl_ui_zoom_mode_get_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj))); } } private static efl_ui_zoom_mode_get_delegate efl_ui_zoom_mode_get_static_delegate; private delegate void efl_ui_zoom_mode_set_delegate(System.IntPtr obj, System.IntPtr pd, Efl.Ui.ZoomMode mode); public delegate void efl_ui_zoom_mode_set_api_delegate(System.IntPtr obj, Efl.Ui.ZoomMode mode); public static Efl.Eo.FunctionWrapper<efl_ui_zoom_mode_set_api_delegate> efl_ui_zoom_mode_set_ptr = new Efl.Eo.FunctionWrapper<efl_ui_zoom_mode_set_api_delegate>(_Module, "efl_ui_zoom_mode_set"); private static void zoom_mode_set(System.IntPtr obj, System.IntPtr pd, Efl.Ui.ZoomMode mode) { Eina.Log.Debug("function efl_ui_zoom_mode_set was called"); Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd); if(wrapper != null) { try { ((ImageZoomable)wrapper).SetZoomMode( mode); } catch (Exception e) { Eina.Log.Warning($"Callback error: {e.ToString()}"); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } else { efl_ui_zoom_mode_set_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)), mode); } } private static efl_ui_zoom_mode_set_delegate efl_ui_zoom_mode_set_static_delegate; } } } namespace Elm { namespace Photocam { /// <summary></summary> [StructLayout(LayoutKind.Sequential)] public struct Error { ///<summary>Placeholder field</summary> public IntPtr field; public static implicit operator Error(IntPtr ptr) { var tmp = (Error.NativeStruct)Marshal.PtrToStructure(ptr, typeof(Error.NativeStruct)); return tmp; } ///<summary>Internal wrapper for struct Error.</summary> [StructLayout(LayoutKind.Sequential)] public struct NativeStruct { internal IntPtr field; ///<summary>Implicit conversion to the internal/marshalling representation.</summary> public static implicit operator Error.NativeStruct(Error _external_struct) { var _internal_struct = new Error.NativeStruct(); return _internal_struct; } ///<summary>Implicit conversion to the managed representation.</summary> public static implicit operator Error(Error.NativeStruct _internal_struct) { var _external_struct = new Error(); return _external_struct; } } } } } namespace Elm { namespace Photocam { /// <summary></summary> [StructLayout(LayoutKind.Sequential)] public struct Progress { ///<summary>Placeholder field</summary> public IntPtr field; public static implicit operator Progress(IntPtr ptr) { var tmp = (Progress.NativeStruct)Marshal.PtrToStructure(ptr, typeof(Progress.NativeStruct)); return tmp; } ///<summary>Internal wrapper for struct Progress.</summary> [StructLayout(LayoutKind.Sequential)] public struct NativeStruct { internal IntPtr field; ///<summary>Implicit conversion to the internal/marshalling representation.</summary> public static implicit operator Progress.NativeStruct(Progress _external_struct) { var _internal_struct = new Progress.NativeStruct(); return _internal_struct; } ///<summary>Implicit conversion to the managed representation.</summary> public static implicit operator Progress(Progress.NativeStruct _internal_struct) { var _external_struct = new Progress(); return _external_struct; } } } } }
54.23119
519
0.669125
[ "Apache-2.0" ]
wantfire/TizenFX
internals/src/EflSharp/EflSharp/efl/efl_ui_image_zoomable.eo.cs
168,659
C#
using UnityEngine; public class RepeatBackground : MonoBehaviour { private Vector3 backgroundStartPosition; private float backgroundWidth; private void Start() { backgroundStartPosition = transform.position; backgroundWidth = GetComponent<BoxCollider>().size.x; } private void Update() { // If the background has moved left such that half of it // has moved past the start position, reset the camera's // transform to the initial position. if (transform.position.x < backgroundStartPosition.x - (backgroundWidth / 2f)) transform.position = backgroundStartPosition; } }
29.782609
86
0.659854
[ "MIT" ]
azimmomin/CreateWithCodeWeek3
Prototype3/Assets/Scripts/RepeatBackground.cs
687
C#
using System.Collections.Generic; using System.Linq; namespace WebApi.Models { public class DictionaryCommentRepository : ICommentRepository { private int nextID = 0; private Dictionary<int, Comment> comments = new Dictionary<int, Comment>(); public IEnumerable<Comment> Get() { return comments.Values.OrderBy(comment => comment.ID); } public bool TryGet(int id, out Comment comment) { return comments.TryGetValue(id, out comment); } public Comment Add(Comment comment) { comment.ID = nextID++; comments[comment.ID] = comment; return comment; } public bool Delete(int id) { return comments.Remove(id); } public bool Update(Comment comment) { bool update = comments.ContainsKey(comment.ID); comments[comment.ID] = comment; return update; } } }
25.125
83
0.567164
[ "MIT" ]
huruiyi/CSharpExample
CSharpExample/WebApiDemo/WebApi/Models/DictionaryCommentRepository.cs
1,007
C#
using UnityEngine; public class StartWith : MonoBehaviour { [SerializeField] private Item item; [SerializeField] private CurrentGameState gameState; public void Start() => Message.Publish(new GainItem(item)); }
25
63
0.746667
[ "MIT" ]
EnigmaDragons/LDJam46
src/LDJam46/Assets/Scripts/Inventory/StartWith.cs
227
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace ProductCodeValidator { public static class IsbnValidator { public static bool IsValidIsbn(String isbn) { return IsValidIsbnFormat(isbn) && (IsValidIsnb10Checksum(isbn) || IsValidIsbn13Checksum(isbn)); } public static bool IsValidIsbnFormat(String isbn) { var isbnRegex = new Regex(@"ISBN(-1(?:(0)|3))?:?\x20+(?(1)(?(2)(?:(?=.{13}$)\d{1,5}([ -])\d{1,7}\3\d{1,6}\3(?:\d|x)$)|(?:(?=.{17}$)97(?:8|9)([ -])\d{1,5}\4\d{1,7}\4\d{1,6}\4\d$))|(?(.{13}$)(?:\d{1,5}([ -])\d{1,7}\5\d{1,6}\5(?:\d|x)$)|(?:(?=.{17}$)97(?:8|9)([ -])\d{1,5}\6\d{1,7}\6\d{1,6}\6\d$)))"); return isbnRegex.IsMatch(isbn); } public static bool IsValidIsnb10Checksum(String isbn) { if (isbn == null) { return false; } // Remove leading 'ISBN' String isbn = RemoveIsbn10(isbn); // Check, if ISBN is digits only and of length 10 if (!ValidatorHelpers.IsDigitsOnly(isbn) || isbn.Length != 10) { return false; } // Calculate checksum int sum = 0; for (int i = 0; i < 9; i++) { sum += (i + 1) * int.Parse(isbn[i].ToString()); } int remainder = sum % 11; if (remainder == 10) { return isbn[9] == 'X'; } else { return isbn[9] == (char)('0' + remainder); } } public static bool IsValidIsbn13Checksum(String isbn) { isbn = RemoveIsbn13(isbn); if (!ValidatorHelpers.IsDigitsOnly(isbn) || isbn.Length != 13) { return false; } var weight = 1; var sum = 0; for (int i = 0; i < isbn.Length -1; i++) { sum += int.Parse(isbn[i].ToString()) * weight; weight = (weight + 2) % 4; } var remainder = (10 - (sum % 10)) % 10; return isbn[isbn.Length - 1] == (char)('0' + remainder); } private static String RemoveIsbn13(String isbn) { var removeIsbn = new Regex(@"ISBN(?:-13)?:?\x20*"); isbn = removeIsbn.Replace(isbn, ""); return isbn.Replace("-", "").Replace(" ", ""); } private static String RemoveIsbn10(String isbn) { var removeIsbn = new Regex(@"ISBN(?:-10)?:?\x20*"); isbn = removeIsbn.Replace(isbn, ""); return isbn.Replace("-", "").Replace(" ", ""); } public static bool EanIsIsbn(String ean) { var isbnRegex = new Regex(@"^(97(8|9))?\d{9}(\d|X)$"); return isbnRegex.IsMatch(ean); } } }
28.980952
310
0.457443
[ "MIT" ]
ThomasPe/ProductCodeValidator
ProductCodeValidator/IsbnValidator.cs
3,045
C#
using System; using System.Collections.Generic; static class RC4 { static void Main(string[] args) { // Operating on a 3-bit key as an example. var k = new int[] { 2, 6, 1, 5 }; var text = new int[] { 1, 3, 1, 2 }; var s = new List<int>() { 0, 1, 2, 3, 4, 5, 6, 7 }; var t = new List<int>() { 2, 6, 1, 5, 2, 6, 1, 5 }; KSA(s, t); var temp = PRGA(s, text); Console.Write("Cipher = ["); foreach (var element in temp) { Console.Write(element + " "); } Console.WriteLine("]"); } public static List<int> PRGA(List<int> s_list, int[] text) { int i = 0, j = 0; var cipher = new List<int>(); for(int index = 0; index < text.Length; index++) { i = (i + 1) % 8; j = (j + s_list[i]) % 8; s_list.Swap(i, j); var t = (s_list[i] + s_list[j]) % 8; var k = s_list[t]; cipher.Add(k ^ text[index]); } return cipher; } public static void KSA(List<int> s_list, List<int> t_list) { var j = 0; for (int i = 0; i < 8; i++) { j = (j + s_list[i] + t_list[i]) % 8; s_list.Swap(i, j); } } public static void Swap(this List<int> list, int i, int j) { var temp = list[i]; list[i] = list[j]; list[j] = temp; } }
24.1
62
0.437068
[ "MIT" ]
taylorflatt/rc4-cipher
rc4.cs
1,446
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Purview.V20210701 { public static class GetPrivateEndpointConnection { /// <summary> /// A private endpoint connection class. /// </summary> public static Task<GetPrivateEndpointConnectionResult> InvokeAsync(GetPrivateEndpointConnectionArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetPrivateEndpointConnectionResult>("azure-native:purview/v20210701:getPrivateEndpointConnection", args ?? new GetPrivateEndpointConnectionArgs(), options.WithVersion()); } public sealed class GetPrivateEndpointConnectionArgs : Pulumi.InvokeArgs { /// <summary> /// The name of the account. /// </summary> [Input("accountName", required: true)] public string AccountName { get; set; } = null!; /// <summary> /// Name of the private endpoint connection. /// </summary> [Input("privateEndpointConnectionName", required: true)] public string PrivateEndpointConnectionName { get; set; } = null!; /// <summary> /// The resource group name. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; public GetPrivateEndpointConnectionArgs() { } } [OutputType] public sealed class GetPrivateEndpointConnectionResult { /// <summary> /// Gets or sets the identifier. /// </summary> public readonly string Id; /// <summary> /// Gets or sets the name. /// </summary> public readonly string Name; /// <summary> /// The private endpoint information. /// </summary> public readonly Outputs.PrivateEndpointResponse? PrivateEndpoint; /// <summary> /// The private link service connection state. /// </summary> public readonly Outputs.PrivateLinkServiceConnectionStateResponse? PrivateLinkServiceConnectionState; /// <summary> /// The provisioning state. /// </summary> public readonly string ProvisioningState; /// <summary> /// Gets or sets the type. /// </summary> public readonly string Type; [OutputConstructor] private GetPrivateEndpointConnectionResult( string id, string name, Outputs.PrivateEndpointResponse? privateEndpoint, Outputs.PrivateLinkServiceConnectionStateResponse? privateLinkServiceConnectionState, string provisioningState, string type) { Id = id; Name = name; PrivateEndpoint = privateEndpoint; PrivateLinkServiceConnectionState = privateLinkServiceConnectionState; ProvisioningState = provisioningState; Type = type; } } }
32.777778
224
0.628968
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Purview/V20210701/GetPrivateEndpointConnection.cs
3,245
C#
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Universal charset detector code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 2001 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Shy Shalom <shooshX@gmail.com> * Rudi Pettazzi <rudi.pettazzi@gmail.com> (C# port) * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ using System; namespace Ude.Core { public class SingleByteCharSetProber : CharsetProber { const int SAMPLE_SIZE = 64; const int SB_ENOUGH_REL_THRESHOLD = 1024; const float POSITIVE_SHORTCUT_THRESHOLD = 0.95f; const float NEGATIVE_SHORTCUT_THRESHOLD = 0.05f; const int SYMBOL_CAT_ORDER = 250; const int NUMBER_OF_SEQ_CAT = 4; const int POSITIVE_CAT = NUMBER_OF_SEQ_CAT-1; const int NEGATIVE_CAT = 0; protected SequenceModel model; // true if we need to reverse every pair in the model lookup readonly bool reversed; // char order of last character byte lastOrder; int totalSeqs; int totalChar; readonly int[] seqCounters = new int[NUMBER_OF_SEQ_CAT]; // characters that fall in our sampling range int freqChar; // Optional auxiliary prober for name decision. created and destroyed by the GroupProber readonly CharsetProber nameProber; public SingleByteCharSetProber(SequenceModel model) : this(model, false, null) { } public SingleByteCharSetProber(SequenceModel model, bool reversed, CharsetProber nameProber) { this.model = model; this.reversed = reversed; this.nameProber = nameProber; Reset(); } public override ProbingState HandleData(byte[] buf, int offset, int len) { int max = offset + len; for (int i = offset; i < max; i++) { byte order = model.GetOrder(buf[i]); if (order < SYMBOL_CAT_ORDER) totalChar++; if (order < SAMPLE_SIZE) { freqChar++; if (lastOrder < SAMPLE_SIZE) { totalSeqs++; if (!reversed) ++(seqCounters[model.GetPrecedence(lastOrder*SAMPLE_SIZE+order)]); else // reverse the order of the letters in the lookup ++(seqCounters[model.GetPrecedence(order*SAMPLE_SIZE+lastOrder)]); } } lastOrder = order; } if (state == ProbingState.Detecting) { if (totalSeqs > SB_ENOUGH_REL_THRESHOLD) { float cf = GetConfidence(); if (cf > POSITIVE_SHORTCUT_THRESHOLD) state = ProbingState.FoundIt; else if (cf < NEGATIVE_SHORTCUT_THRESHOLD) state = ProbingState.NotMe; } } return state; } public override void DumpStatus() { Console.WriteLine(" SBCS: {0} [{1}]", GetConfidence(), GetCharsetName()); } public override float GetConfidence() { /* NEGATIVE_APPROACH if (totalSeqs > 0) { if (totalSeqs > seqCounters[NEGATIVE_CAT] * 10) return (totalSeqs - seqCounters[NEGATIVE_CAT] * 10)/totalSeqs * freqChar / mTotalChar; } return 0.01f; */ // POSITIVE_APPROACH float r = 0.0f; if (totalSeqs > 0) { r = 1.0f * seqCounters[POSITIVE_CAT] / totalSeqs / model.TypicalPositiveRatio; r = r * freqChar / totalChar; if (r >= 1.0f) r = 0.99f; return r; } return 0.01f; } public override void Reset() { state = ProbingState.Detecting; lastOrder = 255; for (int i = 0; i < NUMBER_OF_SEQ_CAT; i++) seqCounters[i] = 0; totalSeqs = 0; totalChar = 0; freqChar = 0; } public override string GetCharsetName() { return (nameProber is null) ? model.CharsetName : nameProber.GetCharsetName(); } } }
36.843023
107
0.539214
[ "MIT" ]
Klug76/flashdevelop
PluginCore/UdeLibrary/Ude.Core/SBCharsetProber.cs
6,166
C#
/* * 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.Collections.Generic; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.Smartag.Transform; using Aliyun.Acs.Smartag.Transform.V20180313; namespace Aliyun.Acs.Smartag.Model.V20180313 { public class DetachNetworkOptimizationSagsRequest : RpcAcsRequest<DetachNetworkOptimizationSagsResponse> { public DetachNetworkOptimizationSagsRequest() : base("Smartag", "2018-03-13", "DetachNetworkOptimizationSags", "smartag", "openAPI") { if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null) { this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Endpoint.endpointMap, null); this.GetType().GetProperty("ProductEndpointType").SetValue(this, Endpoint.endpointRegionalType, null); } } private long? resourceOwnerId; private string networkOptId; private List<string> smartAGIdss = new List<string>(){ }; private string resourceOwnerAccount; private string ownerAccount; private long? ownerId; public long? ResourceOwnerId { get { return resourceOwnerId; } set { resourceOwnerId = value; DictionaryUtil.Add(QueryParameters, "ResourceOwnerId", value.ToString()); } } public string NetworkOptId { get { return networkOptId; } set { networkOptId = value; DictionaryUtil.Add(QueryParameters, "NetworkOptId", value); } } public List<string> SmartAGIdss { get { return smartAGIdss; } set { smartAGIdss = value; for (int i = 0; i < smartAGIdss.Count; i++) { DictionaryUtil.Add(QueryParameters,"SmartAGIds." + (i + 1) , smartAGIdss[i]); } } } public string ResourceOwnerAccount { get { return resourceOwnerAccount; } set { resourceOwnerAccount = value; DictionaryUtil.Add(QueryParameters, "ResourceOwnerAccount", value); } } public string OwnerAccount { get { return ownerAccount; } set { ownerAccount = value; DictionaryUtil.Add(QueryParameters, "OwnerAccount", value); } } public long? OwnerId { get { return ownerId; } set { ownerId = value; DictionaryUtil.Add(QueryParameters, "OwnerId", value.ToString()); } } public override DetachNetworkOptimizationSagsResponse GetResponse(UnmarshallerContext unmarshallerContext) { return DetachNetworkOptimizationSagsResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
25.253521
134
0.667038
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-smartag/Smartag/Model/V20180313/DetachNetworkOptimizationSagsRequest.cs
3,586
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace LiftOff.Models.ManageViewModels { public class TwoFactorAuthenticationViewModel { public bool HasAuthenticator { get; set; } public int RecoveryCodesLeft { get; set; } public bool Is2faEnabled { get; set; } } }
22.388889
50
0.727047
[ "MIT" ]
phucodes/LiftOff
LiftOff/Models/ManageViewModels/TwoFactorAuthenticationViewModel.cs
405
C#
using Bittrex.Net.Objects; using System; using System.Collections.Generic; using System.Linq; namespace BotTraderCore { /// <summary> /// Stores a range summary (between two flat segments) that includes /// the high and low in that range. Used to render more accurate graphs /// with fewer data points. /// </summary> public class ChangeSummary { public DataPoint Start { get; set; } public DataPoint End { get; set; } public DataPoint High { get; set; } public DataPoint Low { get; set; } /// <summary> /// The number of points this summary represents. /// </summary> public int PointCount { get; set; } public ChangeSummary() { } } }
22.333333
72
0.683582
[ "MIT" ]
KidzCode1/StockAnalysis
BotTraderCore/ChangeSummary.cs
672
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using FlatRedBall.Glue.SaveClasses; using FlatRedBall.Glue.Controls; using FlatRedBall.Glue.Elements; namespace FlatRedBall.Glue.Plugins.Interfaces { public interface INewFile : IPlugin { void AddNewFileOptions(NewFileWindow newFileWindow); bool CreateNewFile(AssetTypeInfo assetTypeInfo, object extraData, string directory, string name, out string resultingName); void ReactToNewFile(ReferencedFileSave newFile); } }
30.111111
131
0.780443
[ "MIT" ]
coldacid/FlatRedBall
FRBDK/Glue/Glue/Plugins/Interfaces/INewFile.cs
544
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace DotNetKit.Wpf.Sample { /// <summary> /// DecorationSampleControl.xaml の相互作用ロジック /// </summary> public partial class DecorationSampleControl : UserControl { public class Person { public string Name { get; set; } public int Age { get; set; } public string Gender { get; set; } public string Birthday { get; set; } public string Masterpiece { get; set; } } public class Singers { public Person Miku { get; set; } } public DecorationSampleControl() { InitializeComponent(); DataContext = new Person() { Name = "Miku", Age = 16, Gender = "Female", Birthday = "08/31", Masterpiece = "Ghost Rule", }; } } }
25.226415
62
0.557966
[ "MIT" ]
vain0/playground
2016-10-27-wpf-record-grid/DotNetKit.Wpf.RecordGrid.Sample/Control/DecorationSampleControl.xaml.cs
1,357
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the connect-2017-08-08.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Connect.Model { /// <summary> /// Contains information about a quick connect. /// </summary> public partial class QuickConnect { private string _description; private string _name; private string _quickConnectARN; private QuickConnectConfig _quickConnectConfig; private string _quickConnectId; private Dictionary<string, string> _tags = new Dictionary<string, string>(); /// <summary> /// Gets and sets the property Description. /// <para> /// The description. /// </para> /// </summary> [AWSProperty(Min=1, Max=250)] public string Description { get { return this._description; } set { this._description = value; } } // Check to see if Description property is set internal bool IsSetDescription() { return this._description != null; } /// <summary> /// Gets and sets the property Name. /// <para> /// The name of the quick connect. /// </para> /// </summary> [AWSProperty(Min=1, Max=127)] public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } /// <summary> /// Gets and sets the property QuickConnectARN. /// <para> /// The Amazon Resource Name (ARN) of the quick connect. /// </para> /// </summary> public string QuickConnectARN { get { return this._quickConnectARN; } set { this._quickConnectARN = value; } } // Check to see if QuickConnectARN property is set internal bool IsSetQuickConnectARN() { return this._quickConnectARN != null; } /// <summary> /// Gets and sets the property QuickConnectConfig. /// <para> /// Contains information about the quick connect. /// </para> /// </summary> public QuickConnectConfig QuickConnectConfig { get { return this._quickConnectConfig; } set { this._quickConnectConfig = value; } } // Check to see if QuickConnectConfig property is set internal bool IsSetQuickConnectConfig() { return this._quickConnectConfig != null; } /// <summary> /// Gets and sets the property QuickConnectId. /// <para> /// The identifier for the quick connect. /// </para> /// </summary> public string QuickConnectId { get { return this._quickConnectId; } set { this._quickConnectId = value; } } // Check to see if QuickConnectId property is set internal bool IsSetQuickConnectId() { return this._quickConnectId != null; } /// <summary> /// Gets and sets the property Tags. /// <para> /// One or more tags. /// </para> /// </summary> [AWSProperty(Min=1, Max=50)] public Dictionary<string, string> Tags { get { return this._tags; } set { this._tags = value; } } // Check to see if Tags property is set internal bool IsSetTags() { return this._tags != null && this._tags.Count > 0; } } }
28.883871
105
0.566451
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/Connect/Generated/Model/QuickConnect.cs
4,477
C#
using System; using System.Collections.Concurrent; using System.Linq; using System.Threading; using System.Threading.Tasks; using ITVComponents.Helpers; using ITVComponents.InterProcessCommunication.InMemory.Hub.Communication; using ITVComponents.InterProcessCommunication.InMemory.Hub.ProtoExtensions; using ITVComponents.InterProcessCommunication.MessagingShared.Extensions; using ITVComponents.InterProcessCommunication.MessagingShared.Hub.Exceptions; using ITVComponents.InterProcessCommunication.MessagingShared.Hub.Protocol; using ITVComponents.InterProcessCommunication.MessagingShared.Security; using ITVComponents.Logging; namespace ITVComponents.InterProcessCommunication.InMemory.Hub.Channels { public class MemoryServiceChannel:IMemoryChannel { private readonly MscMode mode; private readonly int ttl; private readonly IIdentityProvider userProvider; private const string serverChannel = "{0}_srv"; private const string clientChannel = "{0}_cli"; private FilePipe incoming; private FilePipe outgoing; private CancellationTokenSource src; private CancellationToken endTok; private DateTime connectionLossTime; private bool connected; private ConcurrentDictionary<string, OperationWaitHandle> waitingOperations = new ConcurrentDictionary<string, OperationWaitHandle>(); private Random reqRnd = new Random(); private bool disposed = false; public MemoryServiceChannel(string name, bool biDirectional, MscMode mode, int ttl, IIdentityProvider userProvider) { Name = name; this.mode = mode; this.ttl = ttl; this.userProvider = userProvider; src = new CancellationTokenSource(); endTok = src.Token; string incomingName = string.Empty, outgoingName = string .Empty; if (mode == MscMode.Client) { if (biDirectional) { incomingName = string.Format(clientChannel, name); } outgoingName = string.Format(serverChannel, name); } else { if (biDirectional) { outgoingName = string.Format(clientChannel, name); } incomingName = string.Format(serverChannel, name); } if (!string.IsNullOrEmpty(incomingName)) { incoming = new FilePipe(incomingName); incoming.DataReceived += IncomingData; incoming.Listen(); } if (!string.IsNullOrEmpty(outgoingName)) { outgoing = new FilePipe(outgoingName); } connected = true; Connected = true; } public string Name { get; } public bool Connected { get; private set; } public int Ttl => ttl; public bool IsGlobal => incoming?.IsGlobal ?? outgoing?.IsGlobal ?? false; public void Dispose() { if (!disposed) { try { var t = waitingOperations.Keys.ToArray(); foreach (var key in t) { var ok = waitingOperations.TryRemove(key, out var op); if (!op.ServerResponse.Task.IsCompleted) { op.ServerResponse.SetException(new Exception("Service is shutting down.")); } } src?.Cancel(); src?.Dispose(); if (incoming != null) { incoming.DataReceived -= IncomingData; incoming.Dispose(); } outgoing?.Dispose(); src = null; incoming = null; outgoing = null; } catch (Exception ex) { LogEnvironment.LogEvent($"Error disconnecting: {ex.OutlineException()}", LogSeverity.Error); } finally { disposed = true; } } } public CancellationToken CancellationToken => endTok; public async Task WriteAsync(object message) { if (outgoing != null) { try { await outgoing.WriteAsync(JsonHelper.ToJsonStrongTyped(message), endTok); connected = true; if (!Connected) { Connected = true; OnConnectionStatusChanged(); } } catch { if (connected) { connected = false; connectionLossTime = DateTime.Now; } else { var secs = DateTime.Now.Subtract(connectionLossTime).TotalSeconds; if (secs > ttl && Connected) { Connected = false; OnConnectionStatusChanged(); } } throw; } } else { throw new CommunicationException("This is a unidirectional channel!"); } } public void Write(object message) { var awaiter = WriteAsync(message).ConfigureAwait(false).GetAwaiter(); awaiter.GetResult(); } public Task<object> Request(object requestMessage) { Hub.ProtoExtensions.Request r; lock (reqRnd) { r = new Request { Payload = requestMessage, RequestId = $"{mode}_{reqRnd.Next(25000)}_{DateTime.Now.Ticks}", Identity = (userProvider?.CurrentIdentity != null) ? JsonHelper.ToJsonStrongTyped(userProvider.CurrentIdentity) : null }; } return AsyncExtensions.CancelAfterAsync((c) => { OperationWaitHandle wh = new OperationWaitHandle(); waitingOperations.TryAdd(r.RequestId, wh); try { Write(r); } catch (Exception ex) { waitingOperations.TryRemove(r.RequestId, out _); if (!wh.ServerResponse.Task.IsCompleted) { wh.ServerResponse.SetException(ex); } } return wh.ServerResponse.Task; }, TimeSpan.FromSeconds(10), t => { waitingOperations.TryRemove(r.RequestId, out _); }); } protected virtual void OnConnectionStatusChanged() { ConnectionStatusChanged?.Invoke(this, EventArgs.Empty); } protected virtual void OnObjectReceived(ObjectReceivedEventArgs e) { ObjectReceived?.Invoke(this, e); } private void IncomingData(object? sender, IncomingDataEventArgs e) { Task.Run(async () => { var context = new DataTransferContext(); string requestId = null; var obj = JsonHelper.FromJsonStringStrongTyped<object>(e.Data); LogEnvironment.LogDebugEvent($"Message-Type: {obj.GetType()}", LogSeverity.Report); if (obj is Request req) { obj = req.Payload; requestId = req.RequestId; if (!string.IsNullOrEmpty(req.Identity)) { context.Identity = JsonHelper.FromJsonStringStrongTyped<TransferIdentity>(req.Identity).ToIdentity(); } } else if (obj is Response rep) { obj = null; var ok = waitingOperations.TryRemove(rep.RequestId, out var wait); if (ok) { wait.ServerResponse.SetResult(rep.Payload); } else { throw new CommunicationException("The given operation is not open."); } } if (obj != null) { var evData = new ObjectReceivedEventArgs { Value = obj, Context = context }; OnObjectReceived(evData); if (!string.IsNullOrEmpty(requestId) && outgoing != null) { await WriteAsync(new Response { RequestId = requestId, Payload = evData.Result }); } else if (evData.Result != null) { await WriteAsync(evData.Result); } } }); } public event EventHandler ConnectionStatusChanged; public event EventHandler<ObjectReceivedEventArgs> ObjectReceived; } public enum MscMode { Server, Client } }
34.411348
142
0.484955
[ "MIT" ]
ITVenture/ITVComponents
ITVComponents.InterProcessCommunication.InMemory/Hub/Channels/MemoryServiceChannel.cs
9,706
C#
using Elastic.Xunit.XunitPlumbing; using Nest; namespace Examples.Ml.AnomalyDetection.Apis { public class PutCalendarPage : ExampleBase { [U(Skip = "Example not implemented")] public void Line45() { // tag::e61b5abe85000cc954a42e2cd74f3a26[] var response0 = new SearchResponse<object>(); // end::e61b5abe85000cc954a42e2cd74f3a26[] response0.MatchesExample(@"PUT _ml/calendars/planned-outages"); } } }
23.611111
66
0.738824
[ "Apache-2.0" ]
AnthAbou/elasticsearch-net
src/Examples/Examples/Ml/AnomalyDetection/Apis/PutCalendarPage.cs
425
C#
/* _BEGIN_TEMPLATE_ { "id": "LOOTA_802", "name": [ "裁决者之戒", "Justicar's Ring" ], "text": [ "<b>被动</b>\n你的英雄技能变得更强,且法力值消耗变为(1)点。", "<b>Passive</b>\nYour Hero Power is upgraded and costs (1)." ], "cardClass": "NEUTRAL", "type": "SPELL", "cost": 0, "rarity": null, "set": "LOOTAPALOOZA", "collectible": null, "dbfId": 46408 } _END_TEMPLATE_ */ namespace HREngine.Bots { class Sim_LOOTA_802 : SimTemplate //* 裁决者之戒 Justicar's Ring { //<b>Passive</b>Your Hero Power is upgraded and costs (1). //<b>被动</b>你的英雄技能变得更强,且法力值消耗变为(1)。 } }
20.517241
66
0.581513
[ "MIT" ]
chi-rei-den/Silverfish
cards/LOOTAPALOOZA/LOOTA/Sim_LOOTA_802.cs
713
C#
namespace Gerrit.Api.Domain.Changes { public enum ChangeInfoStatus { New, Submitted, Merged, Abandoned, Draft } }
15.090909
36
0.536145
[ "Apache-2.0" ]
GerritApiDotNet/Gerrit.Api.Net
src/Gerrit.Api.Domain/Changes/ChangeInfoStatus.cs
168
C#
using System; using Calamari.Common.Plumbing.Deployment; namespace Calamari.Common.Features.Packages { public interface IExtractPackage { void ExtractToStagingDirectory(PathToPackage? pathToPackage, IPackageExtractor? customPackageExtractor = null); void ExtractToStagingDirectory(PathToPackage? pathToPackage, string extractedToPathOutputVariableName); void ExtractToEnvironmentCurrentDirectory(PathToPackage pathToPackage); void ExtractToApplicationDirectory(PathToPackage pathToPackage, IPackageExtractor? customPackageExtractor = null); } }
45.307692
122
0.809847
[ "Apache-2.0" ]
OctopusDeploy/Calamari
source/Calamari.Common/Features/Packages/IExtractPackage.cs
589
C#
using System.Threading.Tasks; #pragma warning disable 1591 namespace Ianitor.Osp.Backend.CoreServices.Services { public interface IUserSchemaService { Task SetupAsync(); } }
19.4
51
0.731959
[ "MIT" ]
ianitor/ObjectServicePlatform
Osp/Backend/Ianitor.Osp.Backend.CoreServices/Services/IUserSchemaService.cs
194
C#
// // The Open Toolkit Library License // // Copyright (c) 2006 - 2010 the Open Toolkit library. // // 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.Diagnostics; using System.Runtime.InteropServices; using Microsoft.Win32; using osuTK.Input; using osuTK.Platform.Common; namespace osuTK.Platform.Windows { /// \internal /// <summary> /// Contains methods to register for and process mouse WM_INPUT messages. /// </summary> internal sealed class WinRawMouse : IMouseDriver2 { private readonly List<MouseState> mice = new List<MouseState>(); private readonly List<string> names = new List<string>(); private readonly Dictionary<ContextHandle, int> rawids = new Dictionary<ContextHandle, int>(); private readonly IntPtr Window; private readonly object UpdateLock = new object(); public WinRawMouse(IntPtr window) { Debug.WriteLine("Using WinRawMouse."); Debug.Indent(); if (window == IntPtr.Zero) { throw new ArgumentNullException("window"); } Window = window; RefreshDevices(); Debug.Unindent(); } public void RefreshDevices() { lock (UpdateLock) { // Mark all devices as disconnected. We will check which of those // are connected later on. for (int i = 0; i < mice.Count; i++) { MouseState state = mice[i]; state.IsConnected = false; mice[i] = state; } // Discover mouse devices foreach (RawInputDeviceList dev in WinRawInput.GetDeviceList()) { ContextHandle id = new ContextHandle(dev.Device); if (rawids.ContainsKey(id)) { // Device already registered, mark as connected MouseState state = mice[rawids[id]]; state.IsConnected = true; mice[rawids[id]] = state; continue; } // Unregistered device, find what it is string name = GetDeviceName(dev); if (name.ToLower().Contains("root")) { // This is a terminal services device, skip it. continue; } else if (dev.Type == RawInputDeviceType.MOUSE || dev.Type == RawInputDeviceType.HID) { // This is a mouse or a USB mouse device. In the latter case, discover if it really is a // mouse device by qeurying the registry. RegistryKey regkey = FindRegistryKey(name); if (regkey == null) { continue; } string deviceDesc = (string)regkey.GetValue("DeviceDesc"); string deviceClass = (string)regkey.GetValue("Class") as string; if (deviceClass == null) { // Added to address osuTK issue 3198 with mouse on Windows 8 string deviceClassGUID = (string)regkey.GetValue("ClassGUID"); RegistryKey classGUIDKey = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Class\" + deviceClassGUID); deviceClass = classGUIDKey != null ? (string)classGUIDKey.GetValue("Class") : string.Empty; } // deviceDesc remained null on a new Win7 system - not sure why. // Since the description is not vital information, use a dummy description // when that happens. if (String.IsNullOrEmpty(deviceDesc)) { deviceDesc = "Windows Mouse " + mice.Count; } else { deviceDesc = deviceDesc.Substring(deviceDesc.LastIndexOf(';') + 1); } if (!String.IsNullOrEmpty(deviceClass) && deviceClass.ToLower().Equals("mouse")) { if (!rawids.ContainsKey(new ContextHandle(dev.Device))) { // Register the device: RawInputDeviceInfo info = new RawInputDeviceInfo(); int devInfoSize = API.RawInputDeviceInfoSize; Functions.GetRawInputDeviceInfo(dev.Device, RawInputDeviceInfoEnum.DEVICEINFO, info, ref devInfoSize); RegisterRawDevice(Window, deviceDesc); MouseState state = new MouseState(); state.IsConnected = true; mice.Add(state); names.Add(deviceDesc); rawids.Add(new ContextHandle(dev.Device), mice.Count - 1); } } } } } } public bool ProcessMouseEvent(IntPtr raw_buffer) { bool processed = false; RawInput rin; if (Functions.GetRawInputData(raw_buffer, out rin) > 0) { RawMouse raw = rin.Data.Mouse; ContextHandle handle = new ContextHandle(rin.Header.Device); MouseState mouse; if (!rawids.ContainsKey(handle)) { RefreshDevices(); } if (mice.Count == 0) { return false; } // Note:For some reason, my Microsoft Digital 3000 keyboard reports 0 // as rin.Header.Device for the "zoom-in/zoom-out" buttons. // That's problematic, because no device has a "0" id. // As a workaround, we'll add those buttons to the first device (if any). int mouse_handle = rawids.ContainsKey(handle) ? rawids[handle] : 0; mouse = mice[mouse_handle]; // Set and release capture of the mouse to fix http://www.opentk.com/node/2133, Patch by Artfunkel if ((raw.ButtonFlags & RawInputMouseState.LEFT_BUTTON_DOWN) != 0) { mouse.EnableBit((int)MouseButton.Left); Functions.SetCapture(Window); } if ((raw.ButtonFlags & RawInputMouseState.LEFT_BUTTON_UP) != 0) { mouse.DisableBit((int)MouseButton.Left); Functions.ReleaseCapture(); } if ((raw.ButtonFlags & RawInputMouseState.RIGHT_BUTTON_DOWN) != 0) { mouse.EnableBit((int)MouseButton.Right); Functions.SetCapture(Window); } if ((raw.ButtonFlags & RawInputMouseState.RIGHT_BUTTON_UP) != 0) { mouse.DisableBit((int)MouseButton.Right); Functions.ReleaseCapture(); } if ((raw.ButtonFlags & RawInputMouseState.MIDDLE_BUTTON_DOWN) != 0) { mouse.EnableBit((int)MouseButton.Middle); Functions.SetCapture(Window); } if ((raw.ButtonFlags & RawInputMouseState.MIDDLE_BUTTON_UP) != 0) { mouse.DisableBit((int)MouseButton.Middle); Functions.ReleaseCapture(); } if ((raw.ButtonFlags & RawInputMouseState.BUTTON_4_DOWN) != 0) { mouse.EnableBit((int)MouseButton.Button1); Functions.SetCapture(Window); } if ((raw.ButtonFlags & RawInputMouseState.BUTTON_4_UP) != 0) { mouse.DisableBit((int)MouseButton.Button1); Functions.ReleaseCapture(); } if ((raw.ButtonFlags & RawInputMouseState.BUTTON_5_DOWN) != 0) { mouse.EnableBit((int)MouseButton.Button2); Functions.SetCapture(Window); } if ((raw.ButtonFlags & RawInputMouseState.BUTTON_5_UP) != 0) { mouse.DisableBit((int)MouseButton.Button2); Functions.ReleaseCapture(); } if ((raw.ButtonFlags & RawInputMouseState.WHEEL) != 0) { mouse.SetScrollRelative(0, (short)raw.ButtonData / 120.0f); } if ((raw.ButtonFlags & RawInputMouseState.HWHEEL) != 0) { mouse.SetScrollRelative((short)raw.ButtonData / 120.0f, 0); } mouse.Flags = (MouseStateFlags)raw.Flags; if ((raw.Flags & RawMouseFlags.MOUSE_MOVE_ABSOLUTE) != 0) { mouse.X = raw.LastX; mouse.Y = raw.LastY; } else { // Seems like MOUSE_MOVE_RELATIVE is the default, unless otherwise noted. mouse.X += raw.LastX; mouse.Y += raw.LastY; } lock (UpdateLock) { mice[mouse_handle] = mouse; processed = true; } } return processed; } private static string GetDeviceName(RawInputDeviceList dev) { // get name size int size = 0; Functions.GetRawInputDeviceInfo(dev.Device, RawInputDeviceInfoEnum.DEVICENAME, IntPtr.Zero, ref size); // get actual name IntPtr name_ptr = Marshal.AllocHGlobal((IntPtr)size); Functions.GetRawInputDeviceInfo(dev.Device, RawInputDeviceInfoEnum.DEVICENAME, name_ptr, ref size); string name = Marshal.PtrToStringAnsi(name_ptr); Marshal.FreeHGlobal(name_ptr); return name; } private static RegistryKey FindRegistryKey(string name) { if (name.Length < 4) { return null; } // remove the \??\ name = name.Substring(4); string[] split = name.Split('#'); if (split.Length < 3) { return null; } string id_01 = split[0]; // ACPI (Class code) string id_02 = split[1]; // PNP0303 (SubClass code) string id_03 = split[2]; // 3&13c0b0c5&0 (Protocol code) // The final part is the class GUID and is not needed here string findme = string.Format( @"System\CurrentControlSet\Enum\{0}\{1}\{2}", id_01, id_02, id_03); RegistryKey regkey = Registry.LocalMachine.OpenSubKey(findme); return regkey; } private static void RegisterRawDevice(IntPtr window, string device) { RawInputDevice[] rid = new RawInputDevice[] { new RawInputDevice(HIDUsageGD.Mouse, RawInputDeviceFlags.INPUTSINK, window) }; if (!Functions.RegisterRawInputDevices(rid, 1, API.RawInputDeviceSize)) { Debug.Print("[Warning] Raw input registration failed with error: {0}. Device: {1}", Marshal.GetLastWin32Error(), rid[0].ToString()); } else { Debug.Print("Registered mouse {0}", device); } } public MouseState GetState() { lock (UpdateLock) { MouseState master = new MouseState(); foreach (MouseState ms in mice) { master.MergeBits(ms); } return master; } } public MouseState GetState(int index) { lock (UpdateLock) { if (mice.Count > index) { return mice[index]; } else { return new MouseState(); } } } public void GetStates(List<MouseState> result) { lock (UpdateLock) { result.Clear(); for (int i = 0; i < mice.Count; i++) { result.Add(GetState(i)); } } } public void SetPosition(double x, double y) { Functions.SetCursorPos((int)x, (int)y); } public MouseState GetCursorState() { // For simplicity, get hardware state // and simply overwrite its x and y location POINT p = new POINT(); Functions.GetCursorPos(ref p); var state = GetState(); state.X = p.X; state.Y = p.Y; return state; } } }
38.199482
150
0.492031
[ "BSD-3-Clause" ]
MiraiSubject/osuTK
src/osuTK/Platform/Windows/WinRawMouse.cs
14,747
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MS-PL license. // See the LICENSE file in the project root for more information. using MvvmCross.Base; using Xunit; namespace MvvmCross.UnitTest.Base { public class MvxPropertyNameFromExpressionTests { public class TestClass { public string Foo { get; set; } public string GetFooExpression() { return this.GetPropertyNameFromExpression(() => Foo); } } [Fact] public void TestPropertyExpression() { var t = new TestClass(); var result = t.GetFooExpression(); Assert.Equal("Foo", result); } [Fact] public void TestUnaryPropertyExpression() { var t = new TestClass(); var result = t.GetPropertyNameFromExpression(() => t.Foo); Assert.Equal("Foo", result); } } }
25.65
73
0.574074
[ "MIT" ]
Nivaes/Nivaes.App.Cross
Nivaes.App.Cross.UnitTest/Base/MvxPropertyParsingExpressionTest.cs
1,028
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the apigateway-2015-07-09.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.APIGateway.Model { /// <summary> /// The requested service is not available. For details see the accompanying error message. /// Retry after the specified time period. /// </summary> #if !NETSTANDARD [Serializable] #endif public partial class ServiceUnavailableException : AmazonAPIGatewayException { private string _retryAfterSeconds; /// <summary> /// Constructs a new ServiceUnavailableException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public ServiceUnavailableException(string message) : base(message) {} /// <summary> /// Construct instance of ServiceUnavailableException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public ServiceUnavailableException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of ServiceUnavailableException /// </summary> /// <param name="innerException"></param> public ServiceUnavailableException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of ServiceUnavailableException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public ServiceUnavailableException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of ServiceUnavailableException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public ServiceUnavailableException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, requestId, statusCode) {} #if !NETSTANDARD /// <summary> /// Constructs a new instance of the ServiceUnavailableException class with serialized data. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception> protected ServiceUnavailableException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { this.RetryAfterSeconds = (string)info.GetValue("RetryAfterSeconds", typeof(string)); } /// <summary> /// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception> #if BCL35 [System.Security.Permissions.SecurityPermission( System.Security.Permissions.SecurityAction.LinkDemand, Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] #endif [System.Security.SecurityCritical] // These FxCop rules are giving false-positives for this method [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")] public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { base.GetObjectData(info, context); info.AddValue("RetryAfterSeconds", this.RetryAfterSeconds); } #endif /// <summary> /// Gets and sets the property RetryAfterSeconds. /// </summary> public string RetryAfterSeconds { get { return this._retryAfterSeconds; } set { this._retryAfterSeconds = value; } } // Check to see if RetryAfterSeconds property is set internal bool IsSetRetryAfterSeconds() { return this._retryAfterSeconds != null; } } }
46.27972
178
0.67528
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/APIGateway/Generated/Model/ServiceUnavailableException.cs
6,618
C#
using DevelopmentInProgress.TradeView.Core.Enums; using System.Collections.Generic; namespace DevelopmentInProgress.TradeView.Core.Model { public class Symbol { public string Name { get; set; } public Exchange Exchange { get; set; } public string NameDelimiter { get; set; } public string ExchangeSymbol { get; set; } public decimal NotionalMinimumValue { get; set; } public Asset BaseAsset { get; set; } public InclusiveRange Price { get; set; } public InclusiveRange Quantity { get; set; } public Asset QuoteAsset { get; set; } public SymbolStatus Status { get; set; } public bool IsIcebergAllowed { get; set; } public IEnumerable<OrderType> OrderTypes { get; set; } public SymbolStats SymbolStatistics { get; set; } } }
36.565217
62
0.655172
[ "Apache-2.0" ]
CasparsTools/tradeview
src/DevelopmentInProgress.TradeView.Core/Model/Symbol.cs
843
C#
using System.Collections.Generic; using System.Drawing; using System.IO; using System.Threading; using de.fearvel.io.DataTypes; using PdfSharp.Pdf; using PdfSharp.Pdf.Advanced; using PdfSharp.Pdf.IO; using Tesseract; namespace de.fearvel.io.File { /// <summary> /// EXPERIMENTAL /// Ocr Class /// <copyright>Andreas Schreiner 2019</copyright> /// </summary> public static class Ocr { /// <summary> /// function to receive Text from a pdf /// </summary> /// <param name="pdf">PDF File</param> /// <returns></returns> public static OcrDocument ScanPicturesOfAPdf(string pdf) { return ImageToText(Path.GetFileName(pdf), PdfPictureExtractor(pdf)); } /// <summary> /// Extracts all pictures of an Pdf /// </summary> /// <param name="pdf">FileLocation of the PDF</param> /// <returns>List of Bitmaps of the PDF</returns> public static List<Bitmap> PdfPictureExtractor(string pdf) { List<Bitmap> pagePictures = new List<Bitmap>(); PdfDocument document = PdfReader.Open(pdf); foreach (PdfPage page in document.Pages) { var resources = page.Elements.GetDictionary("/Resources"); if (resources == null) continue; var xObjects = resources.Elements.GetDictionary("/XObject"); if (xObjects == null) continue; var items = xObjects.Elements.Values; foreach (var item in items) { PdfReference reference = item as PdfReference; PdfDictionary xObject = reference?.Value as PdfDictionary; if (xObject == null || xObject.Elements.GetString("/Subtype") != "/Image") continue; byte[] stream = xObject.Stream.Value; using (var ms = new MemoryStream(stream)) { var a = new Bitmap(ms); pagePictures.Add(a); } } } return pagePictures; } /// <summary> /// Reads Text from images /// </summary> /// <param name="name">Name of the OCR Document</param> /// <param name="images">List of bitmaps to be read</param> /// <param name="lang">language of the Text within the pictures</param> /// <returns></returns> public static OcrDocument ImageToText(string name, List<Bitmap> images, string lang = "deu") { var ocrDocument = new OcrDocument(name); var threads = new List<Thread>(); for (int i = 0; i < images.Count -1; i++) { var thread = new Thread( () => { using (var engine = new TesseractEngine(@"./tessdata", lang, EngineMode.Default)) { using (var img = PixConverter.ToPix(images[i])) { using (var page = engine.Process(img)) { ocrDocument.Pages.Add(new OcrDocument.Page(){Number = i+1, Content = page.GetText()}); } } } }); thread.Start(); threads.Add(thread); } var running = true; while (running) { running = false; foreach (var thread in threads) { if (thread.ThreadState == ThreadState.Running) { running = true; } } } return ocrDocument; } } }
36.766355
122
0.477123
[ "MIT" ]
Fearvel/FileTools
de.fearvel.io/File/Ocr.cs
3,936
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("10.RadiansToDegrees")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("10.RadiansToDegrees")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("854de240-b4d0-416c-b8cd-71899fa87e5a")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38
84
0.748933
[ "MIT" ]
gmanolov/Programming-Basics
02.SimpleCalculations/10.RadiansToDegrees/Properties/AssemblyInfo.cs
1,409
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TextEditor.Document { internal class Table { #region subclass internal class TTitle { } internal class TGroup { } internal class THeader { } internal class TBody { } internal class TFoot { } internal class Row { List<Entry> _lstEntry = new List<Entry>(); } internal class Entry { } #endregion #region fields List<TGroup> _lstGroup = new List<TGroup>(); #endregion #region properties public TGroup[] TableGroups { get { return _lstGroup.ToArray(); } } public TTitle Title { get; set; } public string tabstyle { get;set; } public string tocentry { get;set; } public string frame { get;set; } public string colsep { get;set; } public string rowsep { get;set; } public string orient { get;set; } public string pgwide { get;set; } public string applicRefId { get;set; } public string id { get; set; } #region changeAttGroup public string changeType { get;set; } public string changeMark { get;set; } public string reasonForUpdateRefIds { get; set; } #endregion #region authorityAttGroup public string authorityName { get; set; } public string authorityDocument { get; set; } #endregion #region securityAttGroup /// <summary> /// 取值范围“00”-“99” /// </summary> string securityClassification { get; set; } #region commercialSecurityAttGroup public string commercialClassification { get;set;} public string caveat { get;set;} #endregion #endregion #endregion public Table() { //Title = new TTitle(); _lstGroup.Add(new TGroup()); } } }
16.707547
53
0.636364
[ "Apache-2.0" ]
hobosoft/TextEditor
TextEditor/Document/SDTable.cs
1,789
C#
using System.IO; using System.Threading; using FirebirdSql.Data.FirebirdClient; namespace FluentMigrator.Tests.Integration.Processors.Firebird { public class FbDatabase { public static void CreateDatabase(string connectionString) { var connectionStringBuilder = new FbConnectionStringBuilder(connectionString); if (File.Exists(connectionStringBuilder.Database)) DropDatabase(connectionString); FbConnection.CreateDatabase(connectionString); } public static void DropDatabase(string connectionString) { FbConnection.ClearAllPools(); // Avoid "lock time-out on wait transaction" exception var retries = 5; while (true) { try { FbConnection.DropDatabase(connectionString); break; } catch { if (--retries == 0) throw; else Thread.Sleep(100); } } } } }
27.642857
90
0.51938
[ "Apache-2.0" ]
BartDM/fluentmigrator
src/FluentMigrator.Tests/Integration/Processors/Firebird/FbDatabase.cs
1,163
C#
// 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. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301 { using static Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Extensions; /// <summary>PrivateLinkServiceConnection resource.</summary> public partial class PrivateLinkServiceConnection { /// <summary> /// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="json">The JsonNode that should be deserialized into this object.</param> partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonObject json); /// <summary> /// <c>AfterToJson</c> will be called after the json erialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonObject" /// /> before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="container">The JSON container that the serialization result will be placed in.</param> partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonObject container); /// <summary> /// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of /// the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="json">The JsonNode that should be deserialized into this object.</param> /// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return /// instantly.</param> partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonObject json, ref bool returnNow); /// <summary> /// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the /// object before it is serialized. /// If you wish to disable the default serialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="container">The JSON container that the serialization result will be placed in.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonObject container, ref bool returnNow); /// <summary> /// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.IPrivateLinkServiceConnection. /// </summary> /// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonNode" /> to deserialize from.</param> /// <returns> /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.IPrivateLinkServiceConnection. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.IPrivateLinkServiceConnection FromJson(Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonNode node) { return node is Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonObject json ? new PrivateLinkServiceConnection(json) : null; } /// <summary> /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonObject into a new instance of <see cref="PrivateLinkServiceConnection" />. /// </summary> /// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonObject instance to deserialize from.</param> internal PrivateLinkServiceConnection(Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonObject json) { bool returnNow = false; BeforeFromJson(json, ref returnNow); if (returnNow) { return; } __subResourceAutoGenerated = new Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.SubResourceAutoGenerated(json); {_property = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonObject>("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.CloudService.Models.Api20210301.PrivateLinkServiceConnectionProperties.FromJson(__jsonProperties) : Property;} {_name = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonString>("name"), out var __jsonName) ? (string)__jsonName : (string)Name;} {_type = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonString>("type"), out var __jsonType) ? (string)__jsonType : (string)Type;} {_etag = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonString>("etag"), out var __jsonEtag) ? (string)__jsonEtag : (string)Etag;} AfterFromJson(json); } /// <summary> /// Serializes this instance of <see cref="PrivateLinkServiceConnection" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonNode" />. /// </summary> /// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller /// passes in <c>null</c>, a new instance will be created and returned to the caller.</param> /// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.SerializationMode"/>.</param> /// <returns> /// a serialized instance of <see cref="PrivateLinkServiceConnection" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonNode" />. /// </returns> public Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.SerializationMode serializationMode) { container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonObject(); bool returnNow = false; BeforeToJson(ref container, ref returnNow); if (returnNow) { return container; } __subResourceAutoGenerated?.ToJson(container, serializationMode); AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.SerializationMode.IncludeReadOnly)) { AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); } if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.SerializationMode.IncludeReadOnly)) { AddIf( null != (((object)this._etag)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json.JsonString(this._etag.ToString()) : null, "etag" ,container.Add ); } AfterToJson(ref container); return container; } } }
76.216667
307
0.701618
[ "MIT" ]
Agazoth/azure-powershell
src/CloudService/generated/api/Models/Api20210301/PrivateLinkServiceConnection.json.cs
9,027
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Bleak.Tests.x64")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Bleak.Tests.x64")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("E89238B4-A876-4797-B664-CFC99618F6AA")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.942857
84
0.740279
[ "MIT" ]
danielkrupinski/Bleak
Bleak.Tests.x64/Properties/AssemblyInfo.cs
1,366
C#
using System.Runtime.InteropServices; namespace THNETII.WinApi.Native.WinNT { // C:\Program Files (x86)\Windows Kits\10\Include\10.0.17134.0\um\winnt.h, line 18430 [StructLayout(LayoutKind.Sequential)] public struct IMAGE_ARCHITECTURE_ENTRY { /// <summary> /// RVA of instruction to fixup /// </summary> public int FixupInstRVA; /// <summary> /// fixup instruction (see alphaops.h) /// </summary> public int NewInst; } }
26.631579
89
0.616601
[ "MIT" ]
couven92/thnetii-windows-api
src-native/THNETII.WinApi.Headers.WinNT/IMAGE_ARCHITECTURE_ENTRY.cs
506
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Extensions { public static class Extensions { public static void Print(this IEnumerable collection) { Console.WriteLine("-".Repeat(50)); foreach (var item in collection) { Console.WriteLine(item); } Console.WriteLine("-".Repeat(50)); } public static void Print<T>(this IEnumerable<T> collection) { ((IEnumerable)collection).Print(); } public static void ForEach<T>(this IEnumerable<T> collection, Action<T> action) { foreach (var item in collection) { action(item); } } public static void Print(this string str) { Console.WriteLine(str); } public static string Repeat(this string str, int count) { var builder = new StringBuilder(str.Length * count); for (int i = 0; i < count; i++) { builder.Append(str); } return builder.ToString(); } } }
22.571429
87
0.526899
[ "MIT" ]
DimitarDKirov/Data-Bases
19. Redis-and-Redis-with-.NET/Demo/RedisAndRedisWithDotNet/Extensions/Extensions (Minkov-pc's conflicted copy 2014-09-02).cs
1,266
C#
#region License /* Copyright © 2014-2018 European Support Limited 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 using Amdocs.Ginger.Common; using GingerCore.Environments; using GingerCore.DataSource; namespace GingerCore.Actions { public abstract class ActWithoutDriver : Act { public BusinessFlow RunOnBusinessFlow; public ProjEnvironment RunOnEnvironment; public ObservableList<DataSourceBase> DSList; public abstract void Execute(); } }
28.852941
73
0.767584
[ "Apache-2.0" ]
DebasmitaGhosh/Ginger
Ginger/GingerCore/Actions/ActWithoutDriver.cs
982
C#
using ShopsRUs.Application.Repository; using ShopsRUs.Domain.Entities; using ShopsRUs.Persistence.Contexts; namespace ShopsRUs.Persistence.Repository { public class InvoiceRepository : Repository<Invoice>, IInvoiceRepository { public InvoiceRepository(ApplicationDbContext context) : base(context) { } } }
23
78
0.73913
[ "MIT" ]
multecipenguen/ShopsRUs
ShopsRUs.Persistence/Repository/InvoiceRepository.cs
347
C#
using Microsoft.AspNetCore.Authorization; using System.Text; using System.Threading.Tasks; using BeeTex.Data.Entity; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.WebUtilities; namespace BeeTex.Web.Areas.Identity.Pages.Account { [AllowAnonymous] public class RegisterConfirmationModel : PageModel { private readonly UserManager<UserEntity> _userManager; private readonly IEmailSender _sender; public RegisterConfirmationModel(UserManager<UserEntity> userManager, IEmailSender sender) { _userManager = userManager; _sender = sender; } public string Email { get; set; } public bool DisplayConfirmAccountLink { get; set; } public string EmailConfirmationUrl { get; set; } public async Task<IActionResult> OnGetAsync(string email, string returnUrl = null) { if (email == null) { return RedirectToPage("/Index"); } var user = await _userManager.FindByEmailAsync(email); if (user == null) { return NotFound($"Unable to load user with email '{email}'."); } Email = email; // Once you add a real email sender, you should remove this code that lets you confirm the account DisplayConfirmAccountLink = true; if (DisplayConfirmAccountLink) { var userId = await _userManager.GetUserIdAsync(user); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); EmailConfirmationUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { area = "Identity", userId = userId, code = code, returnUrl = returnUrl }, protocol: Request.Scheme); } return Page(); } } }
34.333333
110
0.616274
[ "MIT" ]
kalinailieva/BeeTex
BeeTex.Web/BeeTex.Web/Areas/Identity/Pages/Account/RegisterConfirmation.cshtml.cs
2,165
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/MsHTML.h in the Windows SDK for Windows 10.0.22000.0 // Original source is Copyright © Microsoft. All rights reserved. using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace TerraFX.Interop.Windows; /// <include file='IHTMLOpsProfile.xml' path='doc/member[@name="IHTMLOpsProfile"]/*' /> [Guid("3050F401-98B5-11CF-BB82-00AA00BDCE0B")] [NativeTypeName("struct IHTMLOpsProfile : IDispatch")] [NativeInheritance("IDispatch")] public unsafe partial struct IHTMLOpsProfile : IHTMLOpsProfile.Interface { public void** lpVtbl; /// <inheritdoc cref="IUnknown.QueryInterface" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(0)] public HRESULT QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject) { return ((delegate* unmanaged<IHTMLOpsProfile*, Guid*, void**, int>)(lpVtbl[0]))((IHTMLOpsProfile*)Unsafe.AsPointer(ref this), riid, ppvObject); } /// <inheritdoc cref="IUnknown.AddRef" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(1)] [return: NativeTypeName("ULONG")] public uint AddRef() { return ((delegate* unmanaged<IHTMLOpsProfile*, uint>)(lpVtbl[1]))((IHTMLOpsProfile*)Unsafe.AsPointer(ref this)); } /// <inheritdoc cref="IUnknown.Release" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(2)] [return: NativeTypeName("ULONG")] public uint Release() { return ((delegate* unmanaged<IHTMLOpsProfile*, uint>)(lpVtbl[2]))((IHTMLOpsProfile*)Unsafe.AsPointer(ref this)); } /// <inheritdoc cref="IDispatch.GetTypeInfoCount" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(3)] public HRESULT GetTypeInfoCount(uint* pctinfo) { return ((delegate* unmanaged<IHTMLOpsProfile*, uint*, int>)(lpVtbl[3]))((IHTMLOpsProfile*)Unsafe.AsPointer(ref this), pctinfo); } /// <inheritdoc cref="IDispatch.GetTypeInfo" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(4)] public HRESULT GetTypeInfo(uint iTInfo, [NativeTypeName("LCID")] uint lcid, ITypeInfo** ppTInfo) { return ((delegate* unmanaged<IHTMLOpsProfile*, uint, uint, ITypeInfo**, int>)(lpVtbl[4]))((IHTMLOpsProfile*)Unsafe.AsPointer(ref this), iTInfo, lcid, ppTInfo); } /// <inheritdoc cref="IDispatch.GetIDsOfNames" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(5)] public HRESULT GetIDsOfNames([NativeTypeName("const IID &")] Guid* riid, [NativeTypeName("LPOLESTR *")] ushort** rgszNames, uint cNames, [NativeTypeName("LCID")] uint lcid, [NativeTypeName("DISPID *")] int* rgDispId) { return ((delegate* unmanaged<IHTMLOpsProfile*, Guid*, ushort**, uint, uint, int*, int>)(lpVtbl[5]))((IHTMLOpsProfile*)Unsafe.AsPointer(ref this), riid, rgszNames, cNames, lcid, rgDispId); } /// <inheritdoc cref="IDispatch.Invoke" /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(6)] public HRESULT Invoke([NativeTypeName("DISPID")] int dispIdMember, [NativeTypeName("const IID &")] Guid* riid, [NativeTypeName("LCID")] uint lcid, [NativeTypeName("WORD")] ushort wFlags, DISPPARAMS* pDispParams, VARIANT* pVarResult, EXCEPINFO* pExcepInfo, uint* puArgErr) { return ((delegate* unmanaged<IHTMLOpsProfile*, int, Guid*, uint, ushort, DISPPARAMS*, VARIANT*, EXCEPINFO*, uint*, int>)(lpVtbl[6]))((IHTMLOpsProfile*)Unsafe.AsPointer(ref this), dispIdMember, riid, lcid, wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr); } /// <include file='IHTMLOpsProfile.xml' path='doc/member[@name="IHTMLOpsProfile.addRequest"]/*' /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(7)] public HRESULT addRequest([NativeTypeName("BSTR")] ushort* name, VARIANT reserved, [NativeTypeName("VARIANT_BOOL *")] short* success) { return ((delegate* unmanaged<IHTMLOpsProfile*, ushort*, VARIANT, short*, int>)(lpVtbl[7]))((IHTMLOpsProfile*)Unsafe.AsPointer(ref this), name, reserved, success); } /// <include file='IHTMLOpsProfile.xml' path='doc/member[@name="IHTMLOpsProfile.clearRequest"]/*' /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(8)] public HRESULT clearRequest() { return ((delegate* unmanaged<IHTMLOpsProfile*, int>)(lpVtbl[8]))((IHTMLOpsProfile*)Unsafe.AsPointer(ref this)); } /// <include file='IHTMLOpsProfile.xml' path='doc/member[@name="IHTMLOpsProfile.doRequest"]/*' /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(9)] public HRESULT doRequest(VARIANT usage, VARIANT fname, VARIANT domain, VARIANT path, VARIANT expire, VARIANT reserved) { return ((delegate* unmanaged<IHTMLOpsProfile*, VARIANT, VARIANT, VARIANT, VARIANT, VARIANT, VARIANT, int>)(lpVtbl[9]))((IHTMLOpsProfile*)Unsafe.AsPointer(ref this), usage, fname, domain, path, expire, reserved); } /// <include file='IHTMLOpsProfile.xml' path='doc/member[@name="IHTMLOpsProfile.getAttribute"]/*' /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(10)] public HRESULT getAttribute([NativeTypeName("BSTR")] ushort* name, [NativeTypeName("BSTR *")] ushort** value) { return ((delegate* unmanaged<IHTMLOpsProfile*, ushort*, ushort**, int>)(lpVtbl[10]))((IHTMLOpsProfile*)Unsafe.AsPointer(ref this), name, value); } /// <include file='IHTMLOpsProfile.xml' path='doc/member[@name="IHTMLOpsProfile.setAttribute"]/*' /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(11)] public HRESULT setAttribute([NativeTypeName("BSTR")] ushort* name, [NativeTypeName("BSTR")] ushort* value, VARIANT prefs, [NativeTypeName("VARIANT_BOOL *")] short* success) { return ((delegate* unmanaged<IHTMLOpsProfile*, ushort*, ushort*, VARIANT, short*, int>)(lpVtbl[11]))((IHTMLOpsProfile*)Unsafe.AsPointer(ref this), name, value, prefs, success); } /// <include file='IHTMLOpsProfile.xml' path='doc/member[@name="IHTMLOpsProfile.commitChanges"]/*' /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(12)] public HRESULT commitChanges([NativeTypeName("VARIANT_BOOL *")] short* success) { return ((delegate* unmanaged<IHTMLOpsProfile*, short*, int>)(lpVtbl[12]))((IHTMLOpsProfile*)Unsafe.AsPointer(ref this), success); } /// <include file='IHTMLOpsProfile.xml' path='doc/member[@name="IHTMLOpsProfile.addReadRequest"]/*' /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(13)] public HRESULT addReadRequest([NativeTypeName("BSTR")] ushort* name, VARIANT reserved, [NativeTypeName("VARIANT_BOOL *")] short* success) { return ((delegate* unmanaged<IHTMLOpsProfile*, ushort*, VARIANT, short*, int>)(lpVtbl[13]))((IHTMLOpsProfile*)Unsafe.AsPointer(ref this), name, reserved, success); } /// <include file='IHTMLOpsProfile.xml' path='doc/member[@name="IHTMLOpsProfile.doReadRequest"]/*' /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(14)] public HRESULT doReadRequest(VARIANT usage, VARIANT fname, VARIANT domain, VARIANT path, VARIANT expire, VARIANT reserved) { return ((delegate* unmanaged<IHTMLOpsProfile*, VARIANT, VARIANT, VARIANT, VARIANT, VARIANT, VARIANT, int>)(lpVtbl[14]))((IHTMLOpsProfile*)Unsafe.AsPointer(ref this), usage, fname, domain, path, expire, reserved); } /// <include file='IHTMLOpsProfile.xml' path='doc/member[@name="IHTMLOpsProfile.doWriteRequest"]/*' /> [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(15)] public HRESULT doWriteRequest([NativeTypeName("VARIANT_BOOL *")] short* success) { return ((delegate* unmanaged<IHTMLOpsProfile*, short*, int>)(lpVtbl[15]))((IHTMLOpsProfile*)Unsafe.AsPointer(ref this), success); } public interface Interface : IDispatch.Interface { [VtblIndex(7)] HRESULT addRequest([NativeTypeName("BSTR")] ushort* name, VARIANT reserved, [NativeTypeName("VARIANT_BOOL *")] short* success); [VtblIndex(8)] HRESULT clearRequest(); [VtblIndex(9)] HRESULT doRequest(VARIANT usage, VARIANT fname, VARIANT domain, VARIANT path, VARIANT expire, VARIANT reserved); [VtblIndex(10)] HRESULT getAttribute([NativeTypeName("BSTR")] ushort* name, [NativeTypeName("BSTR *")] ushort** value); [VtblIndex(11)] HRESULT setAttribute([NativeTypeName("BSTR")] ushort* name, [NativeTypeName("BSTR")] ushort* value, VARIANT prefs, [NativeTypeName("VARIANT_BOOL *")] short* success); [VtblIndex(12)] HRESULT commitChanges([NativeTypeName("VARIANT_BOOL *")] short* success); [VtblIndex(13)] HRESULT addReadRequest([NativeTypeName("BSTR")] ushort* name, VARIANT reserved, [NativeTypeName("VARIANT_BOOL *")] short* success); [VtblIndex(14)] HRESULT doReadRequest(VARIANT usage, VARIANT fname, VARIANT domain, VARIANT path, VARIANT expire, VARIANT reserved); [VtblIndex(15)] HRESULT doWriteRequest([NativeTypeName("VARIANT_BOOL *")] short* success); } public partial struct Vtbl<TSelf> where TSelf : unmanaged, Interface { [NativeTypeName("HRESULT (const IID &, void **) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, Guid*, void**, int> QueryInterface; [NativeTypeName("ULONG () __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, uint> AddRef; [NativeTypeName("ULONG () __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, uint> Release; [NativeTypeName("HRESULT (UINT *) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, uint*, int> GetTypeInfoCount; [NativeTypeName("HRESULT (UINT, LCID, ITypeInfo **) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, uint, uint, ITypeInfo**, int> GetTypeInfo; [NativeTypeName("HRESULT (const IID &, LPOLESTR *, UINT, LCID, DISPID *) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, Guid*, ushort**, uint, uint, int*, int> GetIDsOfNames; [NativeTypeName("HRESULT (DISPID, const IID &, LCID, WORD, DISPPARAMS *, VARIANT *, EXCEPINFO *, UINT *) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, int, Guid*, uint, ushort, DISPPARAMS*, VARIANT*, EXCEPINFO*, uint*, int> Invoke; [NativeTypeName("HRESULT (BSTR, VARIANT, VARIANT_BOOL *) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, ushort*, VARIANT, short*, int> addRequest; [NativeTypeName("HRESULT () __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, int> clearRequest; [NativeTypeName("HRESULT (VARIANT, VARIANT, VARIANT, VARIANT, VARIANT, VARIANT) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, VARIANT, VARIANT, VARIANT, VARIANT, VARIANT, VARIANT, int> doRequest; [NativeTypeName("HRESULT (BSTR, BSTR *) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, ushort*, ushort**, int> getAttribute; [NativeTypeName("HRESULT (BSTR, BSTR, VARIANT, VARIANT_BOOL *) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, ushort*, ushort*, VARIANT, short*, int> setAttribute; [NativeTypeName("HRESULT (VARIANT_BOOL *) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, short*, int> commitChanges; [NativeTypeName("HRESULT (BSTR, VARIANT, VARIANT_BOOL *) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, ushort*, VARIANT, short*, int> addReadRequest; [NativeTypeName("HRESULT (VARIANT, VARIANT, VARIANT, VARIANT, VARIANT, VARIANT) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, VARIANT, VARIANT, VARIANT, VARIANT, VARIANT, VARIANT, int> doReadRequest; [NativeTypeName("HRESULT (VARIANT_BOOL *) __attribute__((stdcall))")] public delegate* unmanaged<TSelf*, short*, int> doWriteRequest; } }
52.637931
275
0.696037
[ "MIT" ]
reflectronic/terrafx.interop.windows
sources/Interop/Windows/Windows/um/MsHTML/IHTMLOpsProfile.cs
12,214
C#
using System; using System.Collections; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; partial class dbg { public static bool publicOnly = true; public static bool propsOnly = false; public static int max_items = 25; public static int depth = 1; public static void printf(string format, params object[] args) { try { print(string.Format(format, args)); } catch { } } public static void print(object @object, params object[] args) { try { if (args.Length == 0) { new dbg().WriteObject(@object); } else { var sb = new StringBuilder(); foreach (var o in new[] { @object }.Concat(args)) { if (sb.Length > 0) sb.Append(" "); sb.Append((o ?? "{null}").ToString()); } new dbg().writeLine(sb.ToString()); } } catch { } } //=============================== int level = 0; string indent = " "; void write(object @object = null) { if (@object != null) Console.Out.Write(@object.ToString().ReplaceClrAliaces()); } void writeLine(object @object = null) { write(@object); Console.Out.WriteLine(); } string Indent { get { return new string('0', level).Replace("0", indent); } } string DisplayName(IEnumerable obj) { if (obj is Array) { var arr = obj as Array; return "{" + obj + "} - Length: " + arr.Length + " item" + (arr.Length == 1 ? "" : "s"); } else if (obj is IList) { var arr = obj as IList; return "{IList} - Count: " + arr.Count; } else { var count = obj.Cast<object>().Count(); return "{IEnumerable} - " + count + " item" + (count == 1 ? "" : "s"); } } static bool isPrimitive(object obj) { return (obj == null || obj.GetType().IsPrimitive || obj is decimal || obj is string); } void WriteObject(object obj) { var enumerableElement = obj as IEnumerable; level++; if (isPrimitive(obj)) { writeLine(obj); } else if (enumerableElement != null) { writeLine(DisplayName(enumerableElement)); int index = 0; foreach (object item in enumerableElement) { write(Indent); if (index > max_items) //need to have some limit { writeLine("... truncated ..."); break; } write("[" + (index++) + "]: "); if (level < (depth + 1)) { level++; WriteValue(item); // WriteObject(item); level--; } writeLine(""); } } else { writeLine("{" + obj + "}"); foreach (MemberInfo m in GetMembers(obj)) { write(Indent); write("." + m.Name); write(" = "); object value = GetMemberValue(obj, m); if (isPrimitive(value) || (level >= depth)) { WriteValue(value); writeLine(""); } else WriteObject(value); } } level--; } object GetMemberValue(object element, MemberInfo m) { FieldInfo f = m as FieldInfo; PropertyInfo p = m as PropertyInfo; if (f != null || p != null) { try { Type t = f != null ? f.FieldType : p.PropertyType; return f != null ? f.GetValue(element) : p.GetValue(element, null); } catch { return "{???}"; } } return null; } void WriteValue(object o) { if (o == null) write("{null}"); else if (o is DateTime) write("{" + o + "}"); else if (o is ValueType) write(o); else if (o is string) write("\"" + o + "\""); else write("{" + o.ToString().TrimStart('{').TrimEnd('}') + "}"); } MemberInfo[] GetMembers(object obj) { Func<MemberInfo, bool> relevant_types = x => x.MemberType == MemberTypes.Field || x.MemberType == MemberTypes.Property; if (propsOnly) relevant_types = x => x.MemberType == MemberTypes.Property; MemberInfo[] members = obj.GetType() .GetMembers(BindingFlags.Public | BindingFlags.Instance) .Where(relevant_types) .OrderBy(x => x.Name) .ToArray(); var private_members = new MemberInfo[0]; if (!publicOnly) private_members = obj.GetType() .GetMembers(BindingFlags.NonPublic | BindingFlags.Instance) .Where(relevant_types) .OrderBy(x => x.Name) .OrderBy(x => char.IsLower(x.Name[0])) .OrderBy(x => x.Name.StartsWith("_")) .ToArray(); var items = members.Concat(private_members); return items.ToArray(); } } static class Extension { static public string ReplaceWholeWord(this string text, string pattern, string replacement) { return Regex.Replace(text, @"\b(" + pattern + @")\b", replacement); } static public string ReplaceClrAliaces(this string text, bool hideSystemNamespace = false) { if (string.IsNullOrEmpty(text)) return text; else { var retval = text.ReplaceWholeWord("System.Object", "object") .ReplaceWholeWord("System.Boolean", "bool") .ReplaceWholeWord("System.Byte", "byte") .ReplaceWholeWord("System.SByte", "sbyte") .ReplaceWholeWord("System.Char", "char") .ReplaceWholeWord("System.Decimal", "decimal") .ReplaceWholeWord("System.Double", "double") .ReplaceWholeWord("System.Single", "float") .ReplaceWholeWord("System.Int32", "int") .ReplaceWholeWord("System.UInt32", "uint") .ReplaceWholeWord("System.Int64", "long") .ReplaceWholeWord("System.UInt64", "ulong") .ReplaceWholeWord("System.Object", "object") .ReplaceWholeWord("System.Int16", "short") .ReplaceWholeWord("System.UInt16", "ushort") .ReplaceWholeWord("System.String", "string") .ReplaceWholeWord("System.Void", "void") .ReplaceWholeWord("Void", "void"); if (hideSystemNamespace && retval.StartsWith("System.")) { string typeName = retval.Substring("System.".Length); if (!typeName.Contains('.')) // it is not a complex namespace retval = typeName; } return retval.Replace("`1", "<T>") .Replace("`2", "<T, T1>") .Replace("`3", "<T, T1, T2>") .Replace("`4", "<T, T1, T2, T3>"); } } }
31.90873
129
0.439871
[ "MIT" ]
cnark/cs-script
Source/dbg.cs
8,041
C#
using System.Collections.Generic; using System.Xml.Serialization; using Essensoft.AspNetCore.Payment.Alipay.Domain; using Newtonsoft.Json; namespace Essensoft.AspNetCore.Payment.Alipay.Response { /// <summary> /// KoubeiItemCategoryChildrenBatchqueryResponse. /// </summary> public class KoubeiItemCategoryChildrenBatchqueryResponse : AlipayResponse { /// <summary> /// 口碑标准后台类目信息列表 /// </summary> [JsonProperty("category_list")] [XmlArray("category_list")] [XmlArrayItem("standard_category_info")] public List<StandardCategoryInfo> CategoryList { get; set; } } }
29.318182
78
0.694574
[ "MIT" ]
AkonCoder/Payment
src/Essensoft.AspNetCore.Payment.Alipay/Response/KoubeiItemCategoryChildrenBatchqueryResponse.cs
669
C#
/* * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 20220523 * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IGrowthRateApiSync : IApiAccessor { #region Synchronous Operations /// <summary> /// /// </summary> /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="limit"> (optional)</param> /// <param name="offset"> (optional)</param> /// <returns>string</returns> string GrowthRateList(int? limit = default(int?), int? offset = default(int?)); /// <summary> /// /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="limit"> (optional)</param> /// <param name="offset"> (optional)</param> /// <returns>ApiResponse of string</returns> ApiResponse<string> GrowthRateListWithHttpInfo(int? limit = default(int?), int? offset = default(int?)); /// <summary> /// /// </summary> /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id"></param> /// <returns>string</returns> string GrowthRateRead(int id); /// <summary> /// /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id"></param> /// <returns>ApiResponse of string</returns> ApiResponse<string> GrowthRateReadWithHttpInfo(int id); #endregion Synchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IGrowthRateApiAsync : IApiAccessor { #region Asynchronous Operations /// <summary> /// /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="limit"> (optional)</param> /// <param name="offset"> (optional)</param> /// <param name="cancellationToken">Cancellation Token to cancel the request.</param> /// <returns>Task of string</returns> System.Threading.Tasks.Task<string> GrowthRateListAsync(int? limit = default(int?), int? offset = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="limit"> (optional)</param> /// <param name="offset"> (optional)</param> /// <param name="cancellationToken">Cancellation Token to cancel the request.</param> /// <returns>Task of ApiResponse (string)</returns> System.Threading.Tasks.Task<ApiResponse<string>> GrowthRateListWithHttpInfoAsync(int? limit = default(int?), int? offset = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id"></param> /// <param name="cancellationToken">Cancellation Token to cancel the request.</param> /// <returns>Task of string</returns> System.Threading.Tasks.Task<string> GrowthRateReadAsync(int id, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id"></param> /// <param name="cancellationToken">Cancellation Token to cancel the request.</param> /// <returns>Task of ApiResponse (string)</returns> System.Threading.Tasks.Task<ApiResponse<string>> GrowthRateReadWithHttpInfoAsync(int id, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IGrowthRateApi : IGrowthRateApiSync, IGrowthRateApiAsync { } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public partial class GrowthRateApi : IGrowthRateApi { private Org.OpenAPITools.Client.ExceptionFactory _exceptionFactory = (name, response) => null; /// <summary> /// Initializes a new instance of the <see cref="GrowthRateApi"/> class. /// </summary> /// <returns></returns> public GrowthRateApi() : this((string)null) { } /// <summary> /// Initializes a new instance of the <see cref="GrowthRateApi"/> class. /// </summary> /// <returns></returns> public GrowthRateApi(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, new Org.OpenAPITools.Client.Configuration { BasePath = basePath } ); this.Client = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); this.AsynchronousClient = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); this.ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; } /// <summary> /// Initializes a new instance of the <see cref="GrowthRateApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public GrowthRateApi(Org.OpenAPITools.Client.Configuration configuration) { if (configuration == null) throw new ArgumentNullException("configuration"); this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, configuration ); this.Client = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); this.AsynchronousClient = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; } /// <summary> /// Initializes a new instance of the <see cref="GrowthRateApi"/> class /// using a Configuration object and client instance. /// </summary> /// <param name="client">The client interface for synchronous API access.</param> /// <param name="asyncClient">The client interface for asynchronous API access.</param> /// <param name="configuration">The configuration object.</param> public GrowthRateApi(Org.OpenAPITools.Client.ISynchronousClient client, Org.OpenAPITools.Client.IAsynchronousClient asyncClient, Org.OpenAPITools.Client.IReadableConfiguration configuration) { if (client == null) throw new ArgumentNullException("client"); if (asyncClient == null) throw new ArgumentNullException("asyncClient"); if (configuration == null) throw new ArgumentNullException("configuration"); this.Client = client; this.AsynchronousClient = asyncClient; this.Configuration = configuration; this.ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; } /// <summary> /// The client for accessing this underlying API asynchronously. /// </summary> public Org.OpenAPITools.Client.IAsynchronousClient AsynchronousClient { get; set; } /// <summary> /// The client for accessing this underlying API synchronously. /// </summary> public Org.OpenAPITools.Client.ISynchronousClient Client { get; set; } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public string GetBasePath() { return this.Configuration.BasePath; } /// <summary> /// Gets or sets the configuration object /// </summary> /// <value>An instance of the Configuration</value> public Org.OpenAPITools.Client.IReadableConfiguration Configuration { get; set; } /// <summary> /// Provides a factory method hook for the creation of exceptions. /// </summary> public Org.OpenAPITools.Client.ExceptionFactory ExceptionFactory { get { if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) { throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); } return _exceptionFactory; } set { _exceptionFactory = value; } } /// <summary> /// /// </summary> /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="limit"> (optional)</param> /// <param name="offset"> (optional)</param> /// <returns>string</returns> public string GrowthRateList(int? limit = default(int?), int? offset = default(int?)) { Org.OpenAPITools.Client.ApiResponse<string> localVarResponse = GrowthRateListWithHttpInfo(limit, offset); return localVarResponse.Data; } /// <summary> /// /// </summary> /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="limit"> (optional)</param> /// <param name="offset"> (optional)</param> /// <returns>ApiResponse of string</returns> public Org.OpenAPITools.Client.ApiResponse<string> GrowthRateListWithHttpInfo(int? limit = default(int?), int? offset = default(int?)) { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); string[] _contentTypes = new string[] { }; // to determine the Accept header string[] _accepts = new string[] { "text/plain" }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); if (localVarContentType != null) { localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); if (localVarAccept != null) { localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); } if (limit != null) { localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "limit", limit)); } if (offset != null) { localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "offset", offset)); } // make the HTTP request var localVarResponse = this.Client.Get<string>("/api/v2/growth-rate/", localVarRequestOptions, this.Configuration); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GrowthRateList", localVarResponse); if (_exception != null) { throw _exception; } } return localVarResponse; } /// <summary> /// /// </summary> /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="limit"> (optional)</param> /// <param name="offset"> (optional)</param> /// <param name="cancellationToken">Cancellation Token to cancel the request.</param> /// <returns>Task of string</returns> public async System.Threading.Tasks.Task<string> GrowthRateListAsync(int? limit = default(int?), int? offset = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { Org.OpenAPITools.Client.ApiResponse<string> localVarResponse = await GrowthRateListWithHttpInfoAsync(limit, offset, cancellationToken).ConfigureAwait(false); return localVarResponse.Data; } /// <summary> /// /// </summary> /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="limit"> (optional)</param> /// <param name="offset"> (optional)</param> /// <param name="cancellationToken">Cancellation Token to cancel the request.</param> /// <returns>Task of ApiResponse (string)</returns> public async System.Threading.Tasks.Task<Org.OpenAPITools.Client.ApiResponse<string>> GrowthRateListWithHttpInfoAsync(int? limit = default(int?), int? offset = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); string[] _contentTypes = new string[] { }; // to determine the Accept header string[] _accepts = new string[] { "text/plain" }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); if (localVarContentType != null) { localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); if (localVarAccept != null) { localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); } if (limit != null) { localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "limit", limit)); } if (offset != null) { localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "offset", offset)); } // make the HTTP request var localVarResponse = await this.AsynchronousClient.GetAsync<string>("/api/v2/growth-rate/", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GrowthRateList", localVarResponse); if (_exception != null) { throw _exception; } } return localVarResponse; } /// <summary> /// /// </summary> /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id"></param> /// <returns>string</returns> public string GrowthRateRead(int id) { Org.OpenAPITools.Client.ApiResponse<string> localVarResponse = GrowthRateReadWithHttpInfo(id); return localVarResponse.Data; } /// <summary> /// /// </summary> /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id"></param> /// <returns>ApiResponse of string</returns> public Org.OpenAPITools.Client.ApiResponse<string> GrowthRateReadWithHttpInfo(int id) { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); string[] _contentTypes = new string[] { }; // to determine the Accept header string[] _accepts = new string[] { "text/plain" }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); if (localVarContentType != null) { localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); if (localVarAccept != null) { localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); } localVarRequestOptions.PathParameters.Add("id", Org.OpenAPITools.Client.ClientUtils.ParameterToString(id)); // path parameter // make the HTTP request var localVarResponse = this.Client.Get<string>("/api/v2/growth-rate/{id}/", localVarRequestOptions, this.Configuration); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GrowthRateRead", localVarResponse); if (_exception != null) { throw _exception; } } return localVarResponse; } /// <summary> /// /// </summary> /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id"></param> /// <param name="cancellationToken">Cancellation Token to cancel the request.</param> /// <returns>Task of string</returns> public async System.Threading.Tasks.Task<string> GrowthRateReadAsync(int id, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { Org.OpenAPITools.Client.ApiResponse<string> localVarResponse = await GrowthRateReadWithHttpInfoAsync(id, cancellationToken).ConfigureAwait(false); return localVarResponse.Data; } /// <summary> /// /// </summary> /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id"></param> /// <param name="cancellationToken">Cancellation Token to cancel the request.</param> /// <returns>Task of ApiResponse (string)</returns> public async System.Threading.Tasks.Task<Org.OpenAPITools.Client.ApiResponse<string>> GrowthRateReadWithHttpInfoAsync(int id, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); string[] _contentTypes = new string[] { }; // to determine the Accept header string[] _accepts = new string[] { "text/plain" }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); if (localVarContentType != null) { localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); if (localVarAccept != null) { localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); } localVarRequestOptions.PathParameters.Add("id", Org.OpenAPITools.Client.ClientUtils.ParameterToString(id)); // path parameter // make the HTTP request var localVarResponse = await this.AsynchronousClient.GetAsync<string>("/api/v2/growth-rate/{id}/", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GrowthRateRead", localVarResponse); if (_exception != null) { throw _exception; } } return localVarResponse; } } }
43.386139
282
0.616796
[ "MIT" ]
cliffano/pokeapi-clients
clients/csharp-netcore/generated/src/Org.OpenAPITools/Api/GrowthRateApi.cs
21,910
C#
// Copyright (c) Brett Lyle Mahon. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Microsoft.AspNetCore.Razor.TagHelpers; using System.Collections; using System.Collections.Generic; using System.Linq; namespace BladeRazor.TagHelpers { [HtmlTargetElement("form-index", TagStructure = TagStructure.NormalOrSelfClosing)] public class FormIndexTagHelper : FormBaseTagHelper { protected IHtmlHelper htmlHelper; /// <summary> /// Set empty to hide buttons /// </summary> [HtmlAttributeName("asp-edit-page")] public string EditPage { get; set; } = "Edit"; [HtmlAttributeName("asp-view-page")] public string ViewPage { get; set; } = "Details"; [HtmlAttributeName("asp-delete-page")] public string DeletePage { get; set; } = "Delete"; [HtmlAttributeName("asp-commands-enabled")] public bool CommandsEnabled { get; set; } = false; protected string editCommand = "edit"; protected string viewCommand = "view"; protected string deleteCommand = "delete"; [HtmlAttributeName("asp-render-value-html")] public bool RenderValueHtml { get; set; } = true; /// <summary> /// Comma seperated /// </summary> [HtmlAttributeName("asp-hide-properties")] public string HideProperties { get; set; } public FormIndexTagHelper(IHtmlGenerator generator, IHtmlHelper htmlHelper, IStyles styles = null) : base(generator, styles) { this.htmlHelper = htmlHelper; } //TODO: Implement Display(Order) built in attribute public override void Process(TagHelperContext context, TagHelperOutput output) { // setup tag output.TagName = "table"; output.TagMode = TagMode.StartTagAndEndTag; output.Attributes.Add("class", styles.Table); // check that we have a list if (!For.Metadata.IsCollectionType) return; // setup properties to hide var hideProperties = HideProperties?.Split(',').Select(p => p.Trim()).ToList(); // get the key property string keyProperty = GetKeyProperty(); // create the headers CreateHeaders(output, hideProperties); // can we conextualise the htmlhelper - if not do not render html values if (htmlHelper is IViewContextAware ht) ht.Contextualize(ViewContext); else RenderValueHtml = false; // now loop through items var collection = (ICollection)For.Model; foreach (var item in collection) { // create the row var row = new TagBuilder("tr") { TagRenderMode = TagRenderMode.Normal }; // get the explorer var explorer = For.ModelExplorer.GetExplorerForModel(item); // get the key value string keyValue = Utility.GetKeyValue(keyProperty, explorer); // loop through the element properties foreach (var p in explorer.Properties) { if (hideProperties != null && hideProperties.Contains(p.Metadata.PropertyName)) continue; if (!Utility.DisplayForView(p.Metadata)) continue; // create a model expression from the explorer //var f = new ModelExpression($"{p.Container.Metadata.Name }.{ p.Metadata.Name}", explorer); var value = Utility.GetFormattedHtml(p, ViewContext, htmlHelper, RenderValueHtml); // check for complex object and set value value = Utility.GetComplexValue(p, value, ViewContext, htmlHelper, RenderValueHtml); // render the cell var cell = new TagBuilder("td"); //TODO: Uncomment in order to hide this on mobile when this works (FormIndex) //cell.Attributes.Add("class", styles.TableCellHideMobile); cell.InnerHtml.AppendHtml(value); row.InnerHtml.AppendHtml(cell); } // render the buttons cell if (keyValue != null) { var buttons = new TagBuilder("td"); var routes = new Dictionary<string, string>() { { keyProperty.ToLower(), keyValue } }; if (!string.IsNullOrEmpty(EditPage)) buttons.InnerHtml.AppendHtml(GenerateEditButton(explorer, keyProperty, keyValue)); if (!string.IsNullOrEmpty(ViewPage)) buttons.InnerHtml.AppendHtml(GenerateViewButton(explorer, keyProperty, keyValue)); if (!string.IsNullOrEmpty(DeletePage)) buttons.InnerHtml.AppendHtml(GenerateDeleteButton(explorer, keyProperty, keyValue)); row.InnerHtml.AppendHtml(buttons); } output.Content.AppendHtml(row); } } protected virtual string GetKeyProperty() { return Utility.GetKeyProperty(For.Metadata.ElementMetadata.Properties); } protected virtual void CreateHeaders(TagHelperOutput output, List<string> hideProperties) { CreateHeadersCore(output, hideProperties, For.Metadata.ElementMetadata.Properties); } protected void CreateHeadersCore(TagHelperOutput output, List<string> hideProperties, Microsoft.AspNetCore.Mvc.ModelBinding.ModelPropertyCollection properties) { // create headers var headerRow = new TagBuilder("tr") { TagRenderMode = TagRenderMode.Normal }; foreach (var p in properties) { // test against hide list if (hideProperties != null && hideProperties.Contains(p.PropertyName)) continue; if (!Utility.DisplayForView(p)) continue; // render the cell var headerCell = new TagBuilder("th"); //TODO: Uncomment in order to hide this on mobile when this works (FormIndex) //cell.Attributes.Add("class", styles.TableCellHideMobile); if (p.DisplayName != null) headerCell.InnerHtml.AppendHtml(p.DisplayName); else headerCell.InnerHtml.Append(p.Name); headerRow.InnerHtml.AppendHtml(headerCell); } // render one last cell for the buttons var lastHeader = new TagBuilder("th"); headerRow.InnerHtml.AppendHtml(lastHeader); output.Content.AppendHtml(headerRow); } protected virtual IHtmlContent GenerateViewButton(ModelExplorer itemExplorer, string keyProperty, string keyValue) { var routes = new Dictionary<string, string>() { { keyProperty.ToLower(), keyValue } }; if (CommandsEnabled) routes.Add("command", viewCommand); return tg.GenerateAnchorTagHelper(ViewPage, ViewPage, styles.ButtonView, routes); } protected virtual IHtmlContent GenerateEditButton(ModelExplorer itemExplorer, string keyProperty, string keyValue) { var routes = new Dictionary<string, string>() { { keyProperty.ToLower(), keyValue } }; if (CommandsEnabled) routes.Add("command", editCommand); return tg.GenerateAnchorTagHelper(EditPage, EditPage, styles.ButtonEdit, routes); } protected virtual IHtmlContent GenerateDeleteButton(ModelExplorer itemExplorer, string keyProperty, string keyValue) { var routes = new Dictionary<string, string>() { { keyProperty.ToLower(), keyValue } }; if (CommandsEnabled) routes.Add("command", deleteCommand); return tg.GenerateAnchorTagHelper(DeletePage, DeletePage, styles.ButtonDelete, routes); } } }
40.306604
167
0.584201
[ "Apache-2.0" ]
BrettMahon/BladeRazor
BladeRazor/TagHelpers/FormIndexTagHelper.cs
8,547
C#
/* * This file is part of AceQL C# Client SDK. * AceQL C# Client SDK: Remote SQL access over HTTP with AceQL HTTP. * Copyright (C) 2020, KawanSoft SAS * (http://www.kawansoft.com). 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. */ using AceQL.Client.Api.Metadata; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AceQL.Client.Api.Metadata { /// <summary> /// Class ForeignKey. A SQL Foreign Key. /// Implements the <see cref="AceQL.Client.Api.Metadata.CatalogAndSchema" /> /// </summary> /// <seealso cref="AceQL.Client.Api.Metadata.CatalogAndSchema" /> public class ForeignKey : CatalogAndSchema { /// <summary> /// The imported key cascade /// </summary> public static readonly string importedKeyCascade = "importedKeyCascade"; /// <summary> /// The imported key restrict /// </summary> public static readonly string importedKeyRestrict = "importedKeyRestrict"; /// <summary> /// The imported key set null /// </summary> public static readonly string importedKeySetNull = "importedKeySetNull"; /// <summary> /// The imported key no action /// </summary> public static readonly string importedKeyNoAction = "importedKeyNoAction"; /// <summary> /// The imported key set default /// </summary> public static readonly string importedKeySetDefault = "importedKeySetDefault"; /// <summary> /// The imported key initially deferred /// </summary> public static readonly string importedKeyInitiallyDeferred = "importedKeyInitiallyDeferred"; /// <summary> /// The imported key initially immediate /// </summary> public static readonly string importedKeyInitiallyImmediate = "importedKeyInitiallyImmediate"; /// <summary> /// The imported key not deferrable /// </summary> public static readonly string importedKeyNotDeferrable = "importedKeyNotDeferrable"; /// <summary> /// The primary key table /// </summary> private String primaryKeyTable; /// <summary> /// The primary key column /// </summary> private String primaryKeyColumn; /// <summary> /// The foreign key catalog /// </summary> private String foreignKeyCatalog; /// <summary> /// The foreign key schema /// </summary> private String foreignKeySchema; /// <summary> /// The foreign key table /// </summary> private String foreignKeyTable; /// <summary> /// The foreign key column /// </summary> private String foreignKeyColumn; /// <summary> /// The key sequence /// </summary> private int keySequence; /// <summary> /// The update rule /// </summary> private String updateRule; /// <summary> /// The delete rule /// </summary> private String deleteRule; /// <summary> /// The foreign key name /// </summary> private String foreignKeyName; /// <summary> /// The primary key name /// </summary> private String primaryKeyName; /// <summary> /// The deferrability /// </summary> private int deferrability; /// <summary> /// Gets or sets the primary key table. /// </summary> /// <value>The primary key table.</value> public string PrimaryKeyTable { get => primaryKeyTable; set => primaryKeyTable = value; } /// <summary> /// Gets or sets the primary key column. /// </summary> /// <value>The primary key column.</value> public string PrimaryKeyColumn { get => primaryKeyColumn; set => primaryKeyColumn = value; } /// <summary> /// Gets or sets the foreign key catalog. /// </summary> /// <value>The foreign key catalog.</value> public string ForeignKeyCatalog { get => foreignKeyCatalog; set => foreignKeyCatalog = value; } /// <summary> /// Gets or sets the foreign key schema. /// </summary> /// <value>The foreign key schema.</value> public string ForeignKeySchema { get => foreignKeySchema; set => foreignKeySchema = value; } /// <summary> /// Gets or sets the foreign key table. /// </summary> /// <value>The foreign key table.</value> public string ForeignKeyTable { get => foreignKeyTable; set => foreignKeyTable = value; } /// <summary> /// Gets or sets the foreign key column. /// </summary> /// <value>The foreign key column.</value> public string ForeignKeyColumn { get => foreignKeyColumn; set => foreignKeyColumn = value; } /// <summary> /// Gets or sets the key sequence. /// </summary> /// <value>The key sequence.</value> public int KeySequence { get => keySequence; set => keySequence = value; } /// <summary> /// Gets or sets the update rule. /// </summary> /// <value>The update rule.</value> public string UpdateRule { get => updateRule; set => updateRule = value; } /// <summary> /// Gets or sets the delete rule. /// </summary> /// <value>The delete rule.</value> public string DeleteRule { get => deleteRule; set => deleteRule = value; } /// <summary> /// Gets or sets the name of the foreign key. /// </summary> /// <value>The name of the foreign key.</value> public string ForeignKeyName { get => foreignKeyName; set => foreignKeyName = value; } /// <summary> /// Gets or sets the name of the primary key. /// </summary> /// <value>The name of the primary key.</value> public string PrimaryKeyName { get => primaryKeyName; set => primaryKeyName = value; } /// <summary> /// Gets or sets the deferrability. /// </summary> /// <value>The deferrability.</value> public int Deferrability { get => deferrability; set => deferrability = value; } /// <summary> /// Determines whether the specified <see cref="System.Object" /> is equal to this instance. /// </summary> /// <param name="obj">Objet à comparer avec l'objet actif.</param> /// <returns><c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>.</returns> public override bool Equals(object obj) { var key = obj as ForeignKey; return key != null && foreignKeyTable == key.foreignKeyTable && foreignKeyName == key.foreignKeyName; } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns> public override int GetHashCode() { var hashCode = 2080242271; hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(foreignKeyTable); hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(foreignKeyName); return hashCode; } /// <summary> /// Retourne une chaîne qui représente l'objet actif. /// </summary> /// <returns>Chaîne qui représente l'objet actif.</returns> public override String ToString() { return "ForeignKey [primaryKeyTable=" + primaryKeyTable + ", primaryKeyColumn=" + primaryKeyColumn + ", foreignKeyCatalog=" + foreignKeyCatalog + ", foreignKeySchema=" + foreignKeySchema + ", foreignKeyTable=" + foreignKeyTable + ", foreignKeyColumn=" + foreignKeyColumn + ", keySequence=" + keySequence + ", updateRule=" + updateRule + ", deleteRule=" + deleteRule + ", foreignKeyName=" + foreignKeyName + ", primaryKeyName=" + primaryKeyName + ", deferrability=" + deferrability + ", getCatalog()=" + Catalog + ", getSchema()=" + Schema + "]"; } } }
41.486364
140
0.580147
[ "Apache-2.0" ]
kawansoft/AceQL.Client
AceQL.Client/Src/Api.Metadata/ForeignKey.cs
9,134
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; //using CG.Web.MegaApiClient; // MEGA Api ! namespace DalvicUWPCSharp.Model { public class DataItem { //public int Id { get; set; } public string Content { get; set; } //public string Category { get; set; } //public string Headline { get; set; } //public string Subhead { get; set; } //public string DateLine { get; set; } //public string Image { get; set; } } }
27.772727
46
0.648118
[ "Apache-2.0" ]
mediaexplorer74/AstoriaUWP
AstoriaUWP/Model/DataItem.cs
611
C#
using System; using System.ComponentModel.DataAnnotations; using FutureState.Specifications; namespace FutureState.Domain { public interface IFSEntity { Guid Id { get; } string DisplayName { get; } string Description { get; } } /// <summary> /// Base entity definition for an enterprise asset or model. /// </summary> public abstract class FSEntity : IFSEntity { /// <summary> /// Gets the software model id. /// </summary> [Key] public Guid Id { get; set; } /// <summary> /// Gets the display name of the interface. /// </summary> [StringLength(100)] [NotEmpty("DisplayName", ErrorMessage = "Display Name is required.")] public string DisplayName { get; set; } /// <summary> /// Gets the description of the port. /// </summary> [StringLength(500)] public string Description { get; set; } } }
25.075
77
0.559322
[ "Apache-2.0" ]
arisanikolaou/futurestate
src/FutureState.Domain/IFSEntity.cs
1,005
C#
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace Persistence.Migrations.ConfigurationDb { public partial class InitialIdentityServerConfigDbMigration : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "ApiResources", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Enabled = table.Column<bool>(nullable: false), Name = table.Column<string>(maxLength: 200, nullable: false), DisplayName = table.Column<string>(maxLength: 200, nullable: true), Description = table.Column<string>(maxLength: 1000, nullable: true), Created = table.Column<DateTime>(nullable: false), Updated = table.Column<DateTime>(nullable: true), LastAccessed = table.Column<DateTime>(nullable: true), NonEditable = table.Column<bool>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_ApiResources", x => x.Id); }); migrationBuilder.CreateTable( name: "Clients", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Enabled = table.Column<bool>(nullable: false), ClientId = table.Column<string>(maxLength: 200, nullable: false), ProtocolType = table.Column<string>(maxLength: 200, nullable: false), RequireClientSecret = table.Column<bool>(nullable: false), ClientName = table.Column<string>(maxLength: 200, nullable: true), Description = table.Column<string>(maxLength: 1000, nullable: true), ClientUri = table.Column<string>(maxLength: 2000, nullable: true), LogoUri = table.Column<string>(maxLength: 2000, nullable: true), RequireConsent = table.Column<bool>(nullable: false), AllowRememberConsent = table.Column<bool>(nullable: false), AlwaysIncludeUserClaimsInIdToken = table.Column<bool>(nullable: false), RequirePkce = table.Column<bool>(nullable: false), AllowPlainTextPkce = table.Column<bool>(nullable: false), AllowAccessTokensViaBrowser = table.Column<bool>(nullable: false), FrontChannelLogoutUri = table.Column<string>(maxLength: 2000, nullable: true), FrontChannelLogoutSessionRequired = table.Column<bool>(nullable: false), BackChannelLogoutUri = table.Column<string>(maxLength: 2000, nullable: true), BackChannelLogoutSessionRequired = table.Column<bool>(nullable: false), AllowOfflineAccess = table.Column<bool>(nullable: false), IdentityTokenLifetime = table.Column<int>(nullable: false), AccessTokenLifetime = table.Column<int>(nullable: false), AuthorizationCodeLifetime = table.Column<int>(nullable: false), ConsentLifetime = table.Column<int>(nullable: true), AbsoluteRefreshTokenLifetime = table.Column<int>(nullable: false), SlidingRefreshTokenLifetime = table.Column<int>(nullable: false), RefreshTokenUsage = table.Column<int>(nullable: false), UpdateAccessTokenClaimsOnRefresh = table.Column<bool>(nullable: false), RefreshTokenExpiration = table.Column<int>(nullable: false), AccessTokenType = table.Column<int>(nullable: false), EnableLocalLogin = table.Column<bool>(nullable: false), IncludeJwtId = table.Column<bool>(nullable: false), AlwaysSendClientClaims = table.Column<bool>(nullable: false), ClientClaimsPrefix = table.Column<string>(maxLength: 200, nullable: true), PairWiseSubjectSalt = table.Column<string>(maxLength: 200, nullable: true), Created = table.Column<DateTime>(nullable: false), Updated = table.Column<DateTime>(nullable: true), LastAccessed = table.Column<DateTime>(nullable: true), UserSsoLifetime = table.Column<int>(nullable: true), UserCodeType = table.Column<string>(maxLength: 100, nullable: true), DeviceCodeLifetime = table.Column<int>(nullable: false), NonEditable = table.Column<bool>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Clients", x => x.Id); }); migrationBuilder.CreateTable( name: "IdentityResources", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Enabled = table.Column<bool>(nullable: false), Name = table.Column<string>(maxLength: 200, nullable: false), DisplayName = table.Column<string>(maxLength: 200, nullable: true), Description = table.Column<string>(maxLength: 1000, nullable: true), Required = table.Column<bool>(nullable: false), Emphasize = table.Column<bool>(nullable: false), ShowInDiscoveryDocument = table.Column<bool>(nullable: false), Created = table.Column<DateTime>(nullable: false), Updated = table.Column<DateTime>(nullable: true), NonEditable = table.Column<bool>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_IdentityResources", x => x.Id); }); migrationBuilder.CreateTable( name: "ApiClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Type = table.Column<string>(maxLength: 200, nullable: false), ApiResourceId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_ApiClaims", x => x.Id); table.ForeignKey( name: "FK_ApiClaims_ApiResources_ApiResourceId", column: x => x.ApiResourceId, principalTable: "ApiResources", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "ApiProperties", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Key = table.Column<string>(maxLength: 250, nullable: false), Value = table.Column<string>(maxLength: 2000, nullable: false), ApiResourceId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_ApiProperties", x => x.Id); table.ForeignKey( name: "FK_ApiProperties_ApiResources_ApiResourceId", column: x => x.ApiResourceId, principalTable: "ApiResources", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "ApiScopes", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Name = table.Column<string>(maxLength: 200, nullable: false), DisplayName = table.Column<string>(maxLength: 200, nullable: true), Description = table.Column<string>(maxLength: 1000, nullable: true), Required = table.Column<bool>(nullable: false), Emphasize = table.Column<bool>(nullable: false), ShowInDiscoveryDocument = table.Column<bool>(nullable: false), ApiResourceId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_ApiScopes", x => x.Id); table.ForeignKey( name: "FK_ApiScopes_ApiResources_ApiResourceId", column: x => x.ApiResourceId, principalTable: "ApiResources", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "ApiSecrets", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Description = table.Column<string>(maxLength: 1000, nullable: true), Value = table.Column<string>(maxLength: 4000, nullable: false), Expiration = table.Column<DateTime>(nullable: true), Type = table.Column<string>(maxLength: 250, nullable: false), Created = table.Column<DateTime>(nullable: false), ApiResourceId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_ApiSecrets", x => x.Id); table.ForeignKey( name: "FK_ApiSecrets_ApiResources_ApiResourceId", column: x => x.ApiResourceId, principalTable: "ApiResources", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "ClientClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Type = table.Column<string>(maxLength: 250, nullable: false), Value = table.Column<string>(maxLength: 250, nullable: false), ClientId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_ClientClaims", x => x.Id); table.ForeignKey( name: "FK_ClientClaims_Clients_ClientId", column: x => x.ClientId, principalTable: "Clients", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "ClientCorsOrigins", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Origin = table.Column<string>(maxLength: 150, nullable: false), ClientId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_ClientCorsOrigins", x => x.Id); table.ForeignKey( name: "FK_ClientCorsOrigins_Clients_ClientId", column: x => x.ClientId, principalTable: "Clients", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "ClientGrantTypes", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), GrantType = table.Column<string>(maxLength: 250, nullable: false), ClientId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_ClientGrantTypes", x => x.Id); table.ForeignKey( name: "FK_ClientGrantTypes_Clients_ClientId", column: x => x.ClientId, principalTable: "Clients", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "ClientIdPRestrictions", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Provider = table.Column<string>(maxLength: 200, nullable: false), ClientId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_ClientIdPRestrictions", x => x.Id); table.ForeignKey( name: "FK_ClientIdPRestrictions_Clients_ClientId", column: x => x.ClientId, principalTable: "Clients", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "ClientPostLogoutRedirectUris", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), PostLogoutRedirectUri = table.Column<string>(maxLength: 2000, nullable: false), ClientId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_ClientPostLogoutRedirectUris", x => x.Id); table.ForeignKey( name: "FK_ClientPostLogoutRedirectUris_Clients_ClientId", column: x => x.ClientId, principalTable: "Clients", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "ClientProperties", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Key = table.Column<string>(maxLength: 250, nullable: false), Value = table.Column<string>(maxLength: 2000, nullable: false), ClientId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_ClientProperties", x => x.Id); table.ForeignKey( name: "FK_ClientProperties_Clients_ClientId", column: x => x.ClientId, principalTable: "Clients", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "ClientRedirectUris", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), RedirectUri = table.Column<string>(maxLength: 2000, nullable: false), ClientId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_ClientRedirectUris", x => x.Id); table.ForeignKey( name: "FK_ClientRedirectUris_Clients_ClientId", column: x => x.ClientId, principalTable: "Clients", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "ClientScopes", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Scope = table.Column<string>(maxLength: 200, nullable: false), ClientId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_ClientScopes", x => x.Id); table.ForeignKey( name: "FK_ClientScopes_Clients_ClientId", column: x => x.ClientId, principalTable: "Clients", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "ClientSecrets", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Description = table.Column<string>(maxLength: 2000, nullable: true), Value = table.Column<string>(maxLength: 4000, nullable: false), Expiration = table.Column<DateTime>(nullable: true), Type = table.Column<string>(maxLength: 250, nullable: false), Created = table.Column<DateTime>(nullable: false), ClientId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_ClientSecrets", x => x.Id); table.ForeignKey( name: "FK_ClientSecrets_Clients_ClientId", column: x => x.ClientId, principalTable: "Clients", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "IdentityClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Type = table.Column<string>(maxLength: 200, nullable: false), IdentityResourceId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_IdentityClaims", x => x.Id); table.ForeignKey( name: "FK_IdentityClaims_IdentityResources_IdentityResourceId", column: x => x.IdentityResourceId, principalTable: "IdentityResources", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "IdentityProperties", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Key = table.Column<string>(maxLength: 250, nullable: false), Value = table.Column<string>(maxLength: 2000, nullable: false), IdentityResourceId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_IdentityProperties", x => x.Id); table.ForeignKey( name: "FK_IdentityProperties_IdentityResources_IdentityResourceId", column: x => x.IdentityResourceId, principalTable: "IdentityResources", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "ApiScopeClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Type = table.Column<string>(maxLength: 200, nullable: false), ApiScopeId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_ApiScopeClaims", x => x.Id); table.ForeignKey( name: "FK_ApiScopeClaims_ApiScopes_ApiScopeId", column: x => x.ApiScopeId, principalTable: "ApiScopes", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_ApiClaims_ApiResourceId", table: "ApiClaims", column: "ApiResourceId"); migrationBuilder.CreateIndex( name: "IX_ApiProperties_ApiResourceId", table: "ApiProperties", column: "ApiResourceId"); migrationBuilder.CreateIndex( name: "IX_ApiResources_Name", table: "ApiResources", column: "Name", unique: true); migrationBuilder.CreateIndex( name: "IX_ApiScopeClaims_ApiScopeId", table: "ApiScopeClaims", column: "ApiScopeId"); migrationBuilder.CreateIndex( name: "IX_ApiScopes_ApiResourceId", table: "ApiScopes", column: "ApiResourceId"); migrationBuilder.CreateIndex( name: "IX_ApiScopes_Name", table: "ApiScopes", column: "Name", unique: true); migrationBuilder.CreateIndex( name: "IX_ApiSecrets_ApiResourceId", table: "ApiSecrets", column: "ApiResourceId"); migrationBuilder.CreateIndex( name: "IX_ClientClaims_ClientId", table: "ClientClaims", column: "ClientId"); migrationBuilder.CreateIndex( name: "IX_ClientCorsOrigins_ClientId", table: "ClientCorsOrigins", column: "ClientId"); migrationBuilder.CreateIndex( name: "IX_ClientGrantTypes_ClientId", table: "ClientGrantTypes", column: "ClientId"); migrationBuilder.CreateIndex( name: "IX_ClientIdPRestrictions_ClientId", table: "ClientIdPRestrictions", column: "ClientId"); migrationBuilder.CreateIndex( name: "IX_ClientPostLogoutRedirectUris_ClientId", table: "ClientPostLogoutRedirectUris", column: "ClientId"); migrationBuilder.CreateIndex( name: "IX_ClientProperties_ClientId", table: "ClientProperties", column: "ClientId"); migrationBuilder.CreateIndex( name: "IX_ClientRedirectUris_ClientId", table: "ClientRedirectUris", column: "ClientId"); migrationBuilder.CreateIndex( name: "IX_Clients_ClientId", table: "Clients", column: "ClientId", unique: true); migrationBuilder.CreateIndex( name: "IX_ClientScopes_ClientId", table: "ClientScopes", column: "ClientId"); migrationBuilder.CreateIndex( name: "IX_ClientSecrets_ClientId", table: "ClientSecrets", column: "ClientId"); migrationBuilder.CreateIndex( name: "IX_IdentityClaims_IdentityResourceId", table: "IdentityClaims", column: "IdentityResourceId"); migrationBuilder.CreateIndex( name: "IX_IdentityProperties_IdentityResourceId", table: "IdentityProperties", column: "IdentityResourceId"); migrationBuilder.CreateIndex( name: "IX_IdentityResources_Name", table: "IdentityResources", column: "Name", unique: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "ApiClaims"); migrationBuilder.DropTable( name: "ApiProperties"); migrationBuilder.DropTable( name: "ApiScopeClaims"); migrationBuilder.DropTable( name: "ApiSecrets"); migrationBuilder.DropTable( name: "ClientClaims"); migrationBuilder.DropTable( name: "ClientCorsOrigins"); migrationBuilder.DropTable( name: "ClientGrantTypes"); migrationBuilder.DropTable( name: "ClientIdPRestrictions"); migrationBuilder.DropTable( name: "ClientPostLogoutRedirectUris"); migrationBuilder.DropTable( name: "ClientProperties"); migrationBuilder.DropTable( name: "ClientRedirectUris"); migrationBuilder.DropTable( name: "ClientScopes"); migrationBuilder.DropTable( name: "ClientSecrets"); migrationBuilder.DropTable( name: "IdentityClaims"); migrationBuilder.DropTable( name: "IdentityProperties"); migrationBuilder.DropTable( name: "ApiScopes"); migrationBuilder.DropTable( name: "Clients"); migrationBuilder.DropTable( name: "IdentityResources"); migrationBuilder.DropTable( name: "ApiResources"); } } }
45.371711
99
0.493402
[ "MIT" ]
kheneahm-ares/travelog-identityserver
Persistence/Migrations/ConfigurationDb/20210216042446_InitialIdentityServerConfigDbMigration.cs
27,588
C#
namespace PCSC.Reactive.Events { /// <summary>Information about a smart card reader status change.</summary> public class CardStatusChanged : MonitorEvent { /// <summary>The new status of this reader.</summary> /// <remarks> /// <para>Is a bit mask containing one or more of the following values:</para> /// <list type="table"> /// <listheader><term>State</term><description>Description</description></listheader> /// <item><term><see cref="F:PCSC.SCRState.Unaware" /></term><description>The application is unaware of the current state, and would like to know. The use of this value results in an immediate return from state transition monitoring services. This is represented by all bits set to zero.</description></item> /// <item><term><see cref="F:PCSC.SCRState.Ignore" /></term><description>This reader should be ignored</description></item> /// <item><term><see cref="F:PCSC.SCRState.Changed" /></term><description>There is a difference between the state believed by the application, and the state known by the resource manager. When this bit is set, the application may assume a significant state change has occurred on this reader.</description></item> /// <item><term><see cref="F:PCSC.SCRState.Unknown" /></term><description>The given reader name is not recognized by the resource manager. If this bit is set, then <see cref="F:PCSC.SCRState.Changed" /> and <see cref="F:PCSC.SCRState.Ignore" /> will also be set</description></item> /// <item><term><see cref="F:PCSC.SCRState.Unavailable" /></term><description>The actual state of this reader is not available. If this bit is set, then all the following bits are clear.</description></item> /// <item><term><see cref="F:PCSC.SCRState.Empty" /></term><description>There is no card in the reader. If this bit is set, all the following bits will be clear</description></item> /// <item><term><see cref="F:PCSC.SCRState.Present" /></term><description>There is a card in the reader</description></item> /// <item><term><see cref="F:PCSC.SCRState.Exclusive" /></term><description>The card in the reader is allocated for exclusive use by another application. If this bit is set, <see cref="F:PCSC.SCRState.Present" /> will also be set.</description></item> /// <item><term><see cref="F:PCSC.SCRState.InUse" /></term><description>The card in the reader is in use by one or more other applications, but may be connected to in shared mode. If this bit is set, <see cref="F:PCSC.SCRState.Present" /> will also be set.</description></item> /// <item><term><see cref="F:PCSC.SCRState.Mute" /></term><description>There is an unresponsive card in the reader.</description></item> /// </list> /// </remarks> public SCRState NewState { get; } /// <summary>The reader's status before this event.</summary> /// <remarks> /// <para>Is a bit mask containing one or more of the following values:</para> /// <list type="table"> /// <listheader><term>State</term><description>Description</description></listheader> /// <item><term><see cref="F:PCSC.SCRState.Unaware" /></term><description>The application is unaware of the current state, and would like to know. The use of this value results in an immediate return from state transition monitoring services. This is represented by all bits set to zero.</description></item> /// <item><term><see cref="F:PCSC.SCRState.Ignore" /></term><description>This reader should be ignored</description></item> /// <item><term><see cref="F:PCSC.SCRState.Changed" /></term><description>There is a difference between the state believed by the application, and the state known by the resource manager. When this bit is set, the application may assume a significant state change has occurred on this reader.</description></item> /// <item><term><see cref="F:PCSC.SCRState.Unknown" /></term><description>The given reader name is not recognized by the resource manager. If this bit is set, then <see cref="F:PCSC.SCRState.Changed" /> and <see cref="F:PCSC.SCRState.Ignore" /> will also be set</description></item> /// <item><term><see cref="F:PCSC.SCRState.Unavailable" /></term><description>The actual state of this reader is not available. If this bit is set, then all the following bits are clear.</description></item> /// <item><term><see cref="F:PCSC.SCRState.Empty" /></term><description>There is no card in the reader. If this bit is set, all the following bits will be clear</description></item> /// <item><term><see cref="F:PCSC.SCRState.Present" /></term><description>There is a card in the reader</description></item> /// <item><term><see cref="F:PCSC.SCRState.Exclusive" /></term><description>The card in the reader is allocated for exclusive use by another application. If this bit is set, <see cref="F:PCSC.SCRState.Present" /> will also be set.</description></item> /// <item><term><see cref="F:PCSC.SCRState.InUse" /></term><description>The card in the reader is in use by one or more other applications, but may be connected to in shared mode. If this bit is set, <see cref="F:PCSC.SCRState.Present" /> will also be set.</description></item> /// <item><term><see cref="F:PCSC.SCRState.Mute" /></term><description>There is an unresponsive card in the reader.</description></item> /// </list> /// </remarks> public SCRState PreviousState { get; } /// <summary> /// Creates a new CardStatusChanged instance /// </summary> /// <param name="readerName">Name of the reader</param> /// <param name="atr">The card's ATR</param> /// <param name="previousState">The previous state</param> /// <param name="newState">The new state</param> public CardStatusChanged(string readerName, byte[] atr, SCRState previousState, SCRState newState) : base(readerName, atr) { PreviousState = previousState; NewState = newState; } } }
109.931034
330
0.654015
[ "BSD-2-Clause" ]
JeremyOrionDev/ReadID
pcsc-sharp-rx/Events/CardStatusChanged.cs
6,378
C#
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Yna.Engine; using Yna.Engine.Graphics; using SpaceGame.Data.Description; namespace SpaceGame.Player.Weapon { public class WeaponManager : YnGroup { private SpacePlayer _player; private YnTimer _shootTimer; private Stack<int> _recycled; private bool _canShoot; private WeaponDescription _primaryWeaponDescription; private WeaponDescription _secondaryWeaponDescription; public WeaponManager(SpacePlayer player) { _player = player; _recycled = new Stack<int>(); _canShoot = true; _shootTimer = new YnTimer(100, 0); } public override void Initialize() { base.Initialize(); _primaryWeaponDescription = Registry.WeaponDescriptions[(int)_player.PrimaryWeaponType]; _secondaryWeaponDescription = Registry.WeaponDescriptions[(int)_player.SecondaryWeaponType]; _shootTimer.Completed += () => _canShoot = true; } public override void Update(GameTime gameTime) { base.Update(gameTime); _shootTimer.Update(gameTime); } public override void Kill() { base.Kill(); } public override void Revive() { base.Revive(); } void weapon_Killed(object sender, EventArgs e) { int index = Members.IndexOf(sender as BaseWeapon); } public void Shoot(int type) { if (_canShoot) { if (type == 1) { PrimaryWeapon weapon; int[] minMax = GetStartEndValues(); for (int i = minMax[0]; i <= minMax[1]; i++) { if (_recycled.Count > 0) { weapon = Members.ElementAt(_recycled.Pop()) as PrimaryWeapon; weapon.Reset(_player.Rectangle, i); } else { weapon = new PrimaryWeapon(_primaryWeaponDescription, _player.Rectangle, i); weapon.SetOrigin(SpriteOrigin.Center); weapon.Viewport = _player.Viewport; weapon.Killed += weapon_Killed; Add(weapon); } weapon.Rotation = MathHelper.ToRadians(_primaryWeaponDescription.Rotations[i]); _shootTimer.Interval = weapon.Interval; } } else AddSecondaryWeapon(); _canShoot = false; _shootTimer.Start(); } } private void AddSecondaryWeapon() { SecondaryWeapon missile = new SecondaryWeapon(_player.Rectangle); missile.Killed += weapon_Killed; _shootTimer.Interval = missile.Interval; Add(missile); } private int[] GetStartEndValues() { int[] values = new int[2]; switch (_player.BonusLevel) { case BonusLevel.None: values[0] = values[1] = 3; break; case BonusLevel.Level1: values[0] = 2; values[1] = 4; break; case BonusLevel.Level2: values[0] = 1; values[1] = 5; break; case BonusLevel.Level3: case BonusLevel.Level4: values[0] = 0; values[1] = 6; break; } return values; } } }
29.447761
104
0.482007
[ "MIT" ]
demonixis/SpaceGame-XNA
SpaceGame/Player/Weapon/WeaponManager.cs
3,948
C#
// Copyright (c) .NET Foundation. 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.Linq; using System.Linq.Expressions; using System.Reflection; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Cosmos.Internal; using Microsoft.EntityFrameworkCore.Cosmos.Metadata.Internal; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Metadata.Internal; using Microsoft.EntityFrameworkCore.Query; using Microsoft.EntityFrameworkCore.Storage; using Newtonsoft.Json.Linq; namespace Microsoft.EntityFrameworkCore.Cosmos.Query.Internal { public class EntityShaper : IShaper { private readonly IEntityType _entityType; private readonly bool _trackingQuery; private readonly bool _useQueryBuffer; private readonly IEntityMaterializerSource _entityMaterializerSource; public EntityShaper( IEntityType entityType, bool trackingQuery, bool useQueryBuffer, IEntityMaterializerSource entityMaterializerSource) { _entityType = entityType; _entityMaterializerSource = entityMaterializerSource; _trackingQuery = trackingQuery; _useQueryBuffer = useQueryBuffer; } public virtual Type Type => _entityType.ClrType; public virtual LambdaExpression CreateShaperLambda() { var jObjectParameter = Expression.Parameter(typeof(JObject), "jObject"); var entityInfo = CreateEntityInfoExpression(_entityType, null); return Expression.Lambda( Expression.Convert( Expression.Call( _shapeMethodInfo, jObjectParameter, EntityQueryModelVisitor.QueryContextParameter, Expression.Constant(_trackingQuery), Expression.Constant(_useQueryBuffer), entityInfo), _entityType.ClrType), jObjectParameter); } private NewExpression CreateEntityInfoExpression(IEntityType entityType, INavigation navigation) { var usedProperties = new List<IProperty>(); var materializer = CreateMaterializerExpression(entityType, usedProperties, out var indexMap); var valueBufferFactory = ValueBufferFactoryFactory.Create(usedProperties); var nestedEntities = new List<Expression>(); foreach (var ownedNavigation in entityType.GetNavigations().Concat(entityType.GetDerivedNavigations())) { var fk = ownedNavigation.ForeignKey; if (!fk.IsOwnership || ownedNavigation.IsDependentToPrincipal() || fk.DeclaringEntityType.IsDocumentRoot()) { continue; } nestedEntities.Add(CreateEntityInfoExpression(fk.DeclaringEntityType, ownedNavigation)); } var nestedEntitiesExpression = nestedEntities.Count == 0 ? (Expression)Expression.Constant(null, typeof(IList<EntityInfo>)) : Expression.ListInit( Expression.New(typeof(List<EntityInfo>)), nestedEntities.Select(n => Expression.ElementInit(_listAddMethodInfo, n))); return Expression.New( EntityInfo.ConstructorInfo, Expression.Constant(navigation, typeof(INavigation)), Expression.Constant(entityType.FindPrimaryKey(), typeof(IKey)), valueBufferFactory, materializer, Expression.Constant(indexMap, typeof(Dictionary<Type, int[]>)), nestedEntitiesExpression); } private LambdaExpression CreateMaterializerExpression( IEntityType entityType, List<IProperty> usedProperties, out Dictionary<Type, int[]> typeIndexMap) { typeIndexMap = null; var materializationContextParameter = Expression.Parameter(typeof(MaterializationContext), "materializationContext"); var concreteEntityTypes = entityType.GetConcreteTypesInHierarchy().ToList(); var firstEntityType = concreteEntityTypes[0]; var indexMap = new int[firstEntityType.PropertyCount()]; foreach (var property in firstEntityType.GetProperties()) { usedProperties.Add(property); indexMap[property.GetIndex()] = usedProperties.Count - 1; } var materializer = _entityMaterializerSource .CreateMaterializeExpression( firstEntityType, materializationContextParameter); if (concreteEntityTypes.Count == 1) { return Expression.Lambda(materializer, materializationContextParameter); } var discriminatorProperty = firstEntityType.Cosmos().DiscriminatorProperty; var firstDiscriminatorValue = Expression.Constant( firstEntityType.Cosmos().DiscriminatorValue, discriminatorProperty.ClrType); var discriminatorValueVariable = Expression.Variable(discriminatorProperty.ClrType); var returnLabelTarget = Expression.Label(entityType.ClrType); var blockExpressions = new Expression[] { Expression.Assign( discriminatorValueVariable, _entityMaterializerSource .CreateReadValueExpression( Expression.Call(materializationContextParameter, MaterializationContext.GetValueBufferMethod), discriminatorProperty.ClrType, indexMap[discriminatorProperty.GetIndex()])), Expression.IfThenElse( Expression.Equal(discriminatorValueVariable, firstDiscriminatorValue), Expression.Return(returnLabelTarget, materializer), Expression.Throw( Expression.Call( _createUnableToDiscriminateException, Expression.Constant(firstEntityType)))), Expression.Label( returnLabelTarget, Expression.Default(returnLabelTarget.Type)) }; foreach (var concreteEntityType in concreteEntityTypes.Skip(1)) { indexMap = new int[concreteEntityType.PropertyCount()]; var shadowPropertyExists = false; foreach (var property in concreteEntityType.GetProperties()) { var propertyIndex = usedProperties.IndexOf(property); if (propertyIndex == -1) { usedProperties.Add(property); propertyIndex = usedProperties.Count - 1; } indexMap[property.GetIndex()] = propertyIndex; shadowPropertyExists = shadowPropertyExists || property.IsShadowProperty(); } if (shadowPropertyExists) { if (typeIndexMap == null) { typeIndexMap = new Dictionary<Type, int[]>(); } typeIndexMap[concreteEntityType.ClrType] = indexMap; } var discriminatorValue = Expression.Constant( concreteEntityType.Cosmos().DiscriminatorValue, discriminatorProperty.ClrType); materializer = _entityMaterializerSource .CreateMaterializeExpression( concreteEntityType, materializationContextParameter); blockExpressions[1] = Expression.IfThenElse( Expression.Equal(discriminatorValueVariable, discriminatorValue), Expression.Return(returnLabelTarget, materializer), blockExpressions[1]); } return Expression.Lambda( Expression.Block(new[] { discriminatorValueVariable }, blockExpressions), materializationContextParameter); } private static readonly MethodInfo _listAddMethodInfo = typeof(List<EntityInfo>).GetTypeInfo().GetDeclaredMethod(nameof(List<EntityInfo>.Add)); private static readonly MethodInfo _shapeMethodInfo = typeof(EntityShaper).GetTypeInfo().GetDeclaredMethod(nameof(Shape)); [UsedImplicitly] private static object Shape( JObject jObject, QueryContext queryContext, bool trackingQuery, bool bufferedQuery, EntityInfo entityInfo) { var valueBuffer = new ValueBuffer(entityInfo.ValueBufferFactory(jObject)); if (!bufferedQuery) { if (trackingQuery) { var entry = queryContext.StateManager.TryGetEntry(entityInfo.Key, valueBuffer, throwOnNullKey: true); if (entry != null) { return ShapeNestedEntities( jObject, queryContext, trackingQuery, bufferedQuery, entityInfo, entry.Entity); } } var entity = entityInfo.Materializer(new MaterializationContext(valueBuffer, queryContext.Context)); return ShapeNestedEntities( jObject, queryContext, trackingQuery, bufferedQuery, entityInfo, entity); } else { var entity = queryContext.QueryBuffer .GetEntity( entityInfo.Key, new EntityLoadInfo( new MaterializationContext(valueBuffer, queryContext.Context), entityInfo.Materializer, entityInfo.TypeIndexMap), queryStateManager: trackingQuery, throwOnNullKey: true); return ShapeNestedEntities( jObject, queryContext, trackingQuery, bufferedQuery, entityInfo, entity); } } private static object ShapeNestedEntities( JObject jObject, QueryContext queryContext, bool trackingQuery, bool bufferedQuery, EntityInfo entityInfo, object parentEntity) { if (entityInfo.NestedEntities == null) { return parentEntity; } foreach (var nestedEntityInfo in entityInfo.NestedEntities) { var nestedNavigation = nestedEntityInfo.Navigation; var nestedFk = nestedNavigation.ForeignKey; if (nestedFk.IsUnique) { if (!(jObject[nestedFk.DeclaringEntityType.Cosmos().ContainingPropertyName] is JObject nestedJObject)) { continue; } var nestedEntity = Shape( nestedJObject, queryContext, trackingQuery, bufferedQuery, nestedEntityInfo); nestedNavigation.GetSetter().SetClrValue(parentEntity, nestedEntity); } else { var nestedEntities = new List<object>(); if (jObject[nestedFk.DeclaringEntityType.Cosmos().ContainingPropertyName] is JArray jArray && jArray.Count != 0) { foreach (JObject nestedJObject in jArray) { nestedEntities.Add( Shape( nestedJObject, queryContext, trackingQuery, bufferedQuery, nestedEntityInfo)); } } nestedNavigation.GetCollectionAccessor().AddRange(parentEntity, nestedEntities); } } return parentEntity; } private static readonly MethodInfo _createUnableToDiscriminateException = typeof(EntityShaper).GetTypeInfo() .GetDeclaredMethod(nameof(CreateUnableToDiscriminateException)); [UsedImplicitly] private static Exception CreateUnableToDiscriminateException(IEntityType entityType) => new InvalidOperationException(CosmosStrings.UnableToDiscriminate(entityType.DisplayName())); private class EntityInfo { public static readonly ConstructorInfo ConstructorInfo = typeof(EntityInfo).GetTypeInfo().DeclaredConstructors.Single(c => c.GetParameters().Length > 0); public EntityInfo( INavigation navigation, IKey key, Func<JObject, object[]> valueBufferFactory, Func<MaterializationContext, object> materializer, Dictionary<Type, int[]> typeIndexMap, IList<EntityInfo> nestedEntities) { Navigation = navigation; Key = key; ValueBufferFactory = valueBufferFactory; Materializer = materializer; TypeIndexMap = typeIndexMap; NestedEntities = nestedEntities; } public INavigation Navigation { get; } public IKey Key { get; } public Func<JObject, object[]> ValueBufferFactory { get; } public Func<MaterializationContext, object> Materializer { get; } public Dictionary<Type, int[]> TypeIndexMap { get; } public IList<EntityInfo> NestedEntities { get; } } } }
40.284946
126
0.54691
[ "Apache-2.0" ]
BionStt/EntityFrameworkCore
src/EFCore.Cosmos/Query/Internal/EntityShaper.cs
14,988
C#
// Copyright 2016-2040 Nino Crudele // // 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. #region Usings using System; using System.Runtime.Serialization; #endregion namespace SnapGate.Framework.Contracts.Bubbling { /// <summary> /// Action parameter /// </summary> [DataContract] [Serializable] public class Parameter : IParameter { /// <summary> /// Initializes a new instance of the <see cref="Parameter" /> class. /// </summary> /// <param name="name"> /// The name. /// </param> /// <param name="type"> /// The type. /// </param> /// <param name="value"> /// The value. /// </param> public Parameter(string name, Type type, object value) { Name = name; Type = type; Value = value; } /// <summary> /// Property name /// </summary> [DataMember] public string Name { get; set; } /// <summary> /// Property Type /// </summary> [DataMember] public Type Type { get; set; } /// <summary> /// Property Value /// </summary> [DataMember] public object Value { get; set; } } }
26.838235
81
0.55726
[ "Apache-2.0" ]
ninocrudele/SnapGate
Framework.Contracts/Bubbling/Parameter.cs
1,827
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Threading.Tasks; namespace System.Collections.Extensions { internal static class ObjectExtensions { public static byte[] Serialize(this object item) { using (var ms = new MemoryStream()) { var bf = new BinaryFormatter(); bf.Serialize(ms, item); return ms.ToArray(); } } } }
22.68
56
0.608466
[ "MIT" ]
brandondahler/Collections.BloomFilter
Collections.BloomFilter/Extensions/ObjectExtensions.cs
569
C#
namespace Stryker.Core.ProjectComponents { public interface IFileLeaf<T> : IProjectComponent { T SyntaxTree { get; set; } T MutatedSyntaxTree { get; set; } } }
19
53
0.631579
[ "Apache-2.0" ]
Bforslund/stryker-net
src/Stryker.Core/Stryker.Core/ProjectComponents/IFileLeaf.cs
192
C#
// // http://code.google.com/p/servicestack/wiki/TypeSerializer // ServiceStack.Text: .NET C# POCO Type Text Serializer. // // Authors: // Demis Bellot (demis.bellot@gmail.com) // // Copyright 2011 Liquidbit Ltd. // // Licensed under the same terms of ServiceStack: new BSD license. // using System; using System.Reflection; #if !XBOX using System.Linq.Expressions ; #endif namespace ServiceStack.Text.Reflection { public static class StaticAccessors { public static Func<object, object> GetValueGetter(this PropertyInfo propertyInfo, Type type) { #if SILVERLIGHT || MONOTOUCH || XBOX var getMethodInfo = propertyInfo.GetGetMethod(); if (getMethodInfo == null) return null; return x => getMethodInfo.Invoke(x, new object[0]); #else var instance = Expression.Parameter(typeof(object), "i"); var convertInstance = Expression.TypeAs(instance, propertyInfo.DeclaringType); var property = Expression.Property(convertInstance, propertyInfo); var convertProperty = Expression.TypeAs(property, typeof(object)); return Expression.Lambda<Func<object, object>>(convertProperty, instance).Compile(); #endif } public static Func<T, object> GetValueGetter<T>(this PropertyInfo propertyInfo) { #if SILVERLIGHT || MONOTOUCH || XBOX var getMethodInfo = propertyInfo.GetGetMethod(); if (getMethodInfo == null) return null; return x => getMethodInfo.Invoke(x, new object[0]); #else var instance = Expression.Parameter(propertyInfo.DeclaringType, "i"); var property = Expression.Property(instance, propertyInfo); var convert = Expression.TypeAs(property, typeof(object)); return Expression.Lambda<Func<T, object>>(convert, instance).Compile(); #endif } #if !XBOX public static Action<T, object> GetValueSetter<T>(this PropertyInfo propertyInfo) { if (typeof(T) != propertyInfo.DeclaringType) { throw new ArgumentException(); } var instance = Expression.Parameter(propertyInfo.DeclaringType, "i"); var argument = Expression.Parameter(typeof(object), "a"); var setterCall = Expression.Call( instance, propertyInfo.GetSetMethod(), Expression.Convert(argument, propertyInfo.PropertyType)); return Expression.Lambda<Action<T, object>> ( setterCall, instance, argument ).Compile(); } #endif } }
30.753247
95
0.706503
[ "BSD-3-Clause" ]
scopely/ServiceStack.Text
src/ServiceStack.Text/Reflection/StaticAccessors.cs
2,368
C#
#if USE_UNI_LUA using LuaAPI = UniLua.Lua; using RealStatePtr = UniLua.ILuaState; using LuaCSFunction = UniLua.CSharpFunctionDelegate; #else using LuaAPI = XLua.LuaDLL.Lua; using RealStatePtr = System.IntPtr; using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; #endif using XLua; using System.Collections.Generic; namespace CSObjectWrap { public class UnityEngineVector3Wrap { public static void __Register(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Utils.BeginObjectRegister(typeof(UnityEngine.Vector3), L, translator, 6, 6, 6, 3); Utils.RegisterFunc(L, Utils.OBJ_META_IDX, "__add", __AddMeta); Utils.RegisterFunc(L, Utils.OBJ_META_IDX, "__sub", __SubMeta); Utils.RegisterFunc(L, Utils.OBJ_META_IDX, "__unm", __UnmMeta); Utils.RegisterFunc(L, Utils.OBJ_META_IDX, "__mul", __MulMeta); Utils.RegisterFunc(L, Utils.OBJ_META_IDX, "__div", __DivMeta); Utils.RegisterFunc(L, Utils.OBJ_META_IDX, "__eq", __EqMeta); Utils.RegisterFunc(L, Utils.METHOD_IDX, "Set", Set); Utils.RegisterFunc(L, Utils.METHOD_IDX, "Scale", Scale); Utils.RegisterFunc(L, Utils.METHOD_IDX, "GetHashCode", GetHashCode); Utils.RegisterFunc(L, Utils.METHOD_IDX, "Equals", Equals); Utils.RegisterFunc(L, Utils.METHOD_IDX, "Normalize", Normalize); Utils.RegisterFunc(L, Utils.METHOD_IDX, "ToString", ToString); Utils.RegisterFunc(L, Utils.GETTER_IDX, "normalized", get_normalized); Utils.RegisterFunc(L, Utils.GETTER_IDX, "magnitude", get_magnitude); Utils.RegisterFunc(L, Utils.GETTER_IDX, "sqrMagnitude", get_sqrMagnitude); Utils.RegisterFunc(L, Utils.GETTER_IDX, "x", get_x); Utils.RegisterFunc(L, Utils.GETTER_IDX, "y", get_y); Utils.RegisterFunc(L, Utils.GETTER_IDX, "z", get_z); Utils.RegisterFunc(L, Utils.SETTER_IDX, "x", set_x); Utils.RegisterFunc(L, Utils.SETTER_IDX, "y", set_y); Utils.RegisterFunc(L, Utils.SETTER_IDX, "z", set_z); Utils.EndObjectRegister(typeof(UnityEngine.Vector3), L, translator, __CSIndexer, __NewIndexer, null, null, null); Utils.BeginClassRegister(typeof(UnityEngine.Vector3), L, __CreateInstance, 24, 8, 0); Utils.RegisterFunc(L, Utils.CLS_IDX, "Slerp", Slerp_xlua_st_); Utils.RegisterFunc(L, Utils.CLS_IDX, "SlerpUnclamped", SlerpUnclamped_xlua_st_); Utils.RegisterFunc(L, Utils.CLS_IDX, "OrthoNormalize", OrthoNormalize_xlua_st_); Utils.RegisterFunc(L, Utils.CLS_IDX, "RotateTowards", RotateTowards_xlua_st_); Utils.RegisterFunc(L, Utils.CLS_IDX, "Lerp", Lerp_xlua_st_); Utils.RegisterFunc(L, Utils.CLS_IDX, "LerpUnclamped", LerpUnclamped_xlua_st_); Utils.RegisterFunc(L, Utils.CLS_IDX, "MoveTowards", MoveTowards_xlua_st_); Utils.RegisterFunc(L, Utils.CLS_IDX, "SmoothDamp", SmoothDamp_xlua_st_); Utils.RegisterFunc(L, Utils.CLS_IDX, "Scale", Scale_xlua_st_); Utils.RegisterFunc(L, Utils.CLS_IDX, "Cross", Cross_xlua_st_); Utils.RegisterFunc(L, Utils.CLS_IDX, "Reflect", Reflect_xlua_st_); Utils.RegisterFunc(L, Utils.CLS_IDX, "Normalize", Normalize_xlua_st_); Utils.RegisterFunc(L, Utils.CLS_IDX, "Dot", Dot_xlua_st_); Utils.RegisterFunc(L, Utils.CLS_IDX, "Project", Project_xlua_st_); Utils.RegisterFunc(L, Utils.CLS_IDX, "ProjectOnPlane", ProjectOnPlane_xlua_st_); Utils.RegisterFunc(L, Utils.CLS_IDX, "Angle", Angle_xlua_st_); Utils.RegisterFunc(L, Utils.CLS_IDX, "Distance", Distance_xlua_st_); Utils.RegisterFunc(L, Utils.CLS_IDX, "ClampMagnitude", ClampMagnitude_xlua_st_); Utils.RegisterFunc(L, Utils.CLS_IDX, "Magnitude", Magnitude_xlua_st_); Utils.RegisterFunc(L, Utils.CLS_IDX, "SqrMagnitude", SqrMagnitude_xlua_st_); Utils.RegisterFunc(L, Utils.CLS_IDX, "Min", Min_xlua_st_); Utils.RegisterFunc(L, Utils.CLS_IDX, "Max", Max_xlua_st_); Utils.RegisterObject(L, translator, Utils.CLS_IDX, "kEpsilon", UnityEngine.Vector3.kEpsilon); Utils.RegisterObject(L, translator, Utils.CLS_IDX, "UnderlyingSystemType", typeof(UnityEngine.Vector3)); Utils.RegisterFunc(L, Utils.CLS_GETTER_IDX, "zero", get_zero); Utils.RegisterFunc(L, Utils.CLS_GETTER_IDX, "one", get_one); Utils.RegisterFunc(L, Utils.CLS_GETTER_IDX, "forward", get_forward); Utils.RegisterFunc(L, Utils.CLS_GETTER_IDX, "back", get_back); Utils.RegisterFunc(L, Utils.CLS_GETTER_IDX, "up", get_up); Utils.RegisterFunc(L, Utils.CLS_GETTER_IDX, "down", get_down); Utils.RegisterFunc(L, Utils.CLS_GETTER_IDX, "left", get_left); Utils.RegisterFunc(L, Utils.CLS_GETTER_IDX, "right", get_right); Utils.EndClassRegister(typeof(UnityEngine.Vector3), L, translator); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int __CreateInstance(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { if(LuaAPI.lua_gettop(L) == 4 && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 2) && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 3) && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 4)) { float x = (float)LuaAPI.lua_tonumber(L, 2); float y = (float)LuaAPI.lua_tonumber(L, 3); float z = (float)LuaAPI.lua_tonumber(L, 4); UnityEngine.Vector3 __cl_gen_ret = new UnityEngine.Vector3(x, y, z); translator.PushUnityEngineVector3(L, __cl_gen_ret); return 1; } if(LuaAPI.lua_gettop(L) == 3 && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 2) && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 3)) { float x = (float)LuaAPI.lua_tonumber(L, 2); float y = (float)LuaAPI.lua_tonumber(L, 3); UnityEngine.Vector3 __cl_gen_ret = new UnityEngine.Vector3(x, y); translator.PushUnityEngineVector3(L, __cl_gen_ret); return 1; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } return LuaAPI.luaL_error(L, "invalid arguments to UnityEngine.Vector3 constructor!"); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] public static int __CSIndexer(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { if (translator.Assignable<UnityEngine.Vector3>(L, 1) && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 2)) { UnityEngine.Vector3 __cl_gen_to_be_invoked;translator.Get(L, 1, out __cl_gen_to_be_invoked); int index = LuaAPI.xlua_tointeger(L, 2); LuaAPI.lua_pushboolean(L, true); LuaAPI.lua_pushnumber(L, __cl_gen_to_be_invoked[index]); return 2; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } LuaAPI.lua_pushboolean(L, false); return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] public static int __NewIndexer(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { if (translator.Assignable<UnityEngine.Vector3>(L, 1) && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 2) && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 3)) { UnityEngine.Vector3 __cl_gen_to_be_invoked;translator.Get(L, 1, out __cl_gen_to_be_invoked); int key = LuaAPI.xlua_tointeger(L, 2); __cl_gen_to_be_invoked[key] = (float)LuaAPI.lua_tonumber(L, 3); LuaAPI.lua_pushboolean(L, true); return 1; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } LuaAPI.lua_pushboolean(L, false); return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int __AddMeta(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { if (translator.Assignable<UnityEngine.Vector3>(L, 1) && translator.Assignable<UnityEngine.Vector3>(L, 2)) { UnityEngine.Vector3 leftside;translator.Get(L, 1, out leftside); UnityEngine.Vector3 rightside;translator.Get(L, 2, out rightside); translator.PushUnityEngineVector3(L, leftside + rightside); return 1; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } return LuaAPI.luaL_error(L, "invalid arguments to right hand of + operator, need UnityEngine.Vector3!"); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int __SubMeta(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { if (translator.Assignable<UnityEngine.Vector3>(L, 1) && translator.Assignable<UnityEngine.Vector3>(L, 2)) { UnityEngine.Vector3 leftside;translator.Get(L, 1, out leftside); UnityEngine.Vector3 rightside;translator.Get(L, 2, out rightside); translator.PushUnityEngineVector3(L, leftside - rightside); return 1; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } return LuaAPI.luaL_error(L, "invalid arguments to right hand of - operator, need UnityEngine.Vector3!"); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int __UnmMeta(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); UnityEngine.Vector3 rightside;translator.Get(L, 1, out rightside); try { translator.PushUnityEngineVector3(L, - rightside); } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int __MulMeta(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { if (translator.Assignable<UnityEngine.Vector3>(L, 1) && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 2)) { UnityEngine.Vector3 leftside;translator.Get(L, 1, out leftside); float rightside = (float)LuaAPI.lua_tonumber(L, 2); translator.PushUnityEngineVector3(L, leftside * rightside); return 1; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } try { if (LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 1) && translator.Assignable<UnityEngine.Vector3>(L, 2)) { float leftside = (float)LuaAPI.lua_tonumber(L, 1); UnityEngine.Vector3 rightside;translator.Get(L, 2, out rightside); translator.PushUnityEngineVector3(L, leftside * rightside); return 1; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } return LuaAPI.luaL_error(L, "invalid arguments to right hand of * operator, need UnityEngine.Vector3!"); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int __DivMeta(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { if (translator.Assignable<UnityEngine.Vector3>(L, 1) && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 2)) { UnityEngine.Vector3 leftside;translator.Get(L, 1, out leftside); float rightside = (float)LuaAPI.lua_tonumber(L, 2); translator.PushUnityEngineVector3(L, leftside / rightside); return 1; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } return LuaAPI.luaL_error(L, "invalid arguments to right hand of / operator, need UnityEngine.Vector3!"); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int __EqMeta(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { if (translator.Assignable<UnityEngine.Vector3>(L, 1) && translator.Assignable<UnityEngine.Vector3>(L, 2)) { UnityEngine.Vector3 leftside;translator.Get(L, 1, out leftside); UnityEngine.Vector3 rightside;translator.Get(L, 2, out rightside); LuaAPI.lua_pushboolean(L, leftside == rightside); return 1; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } return LuaAPI.luaL_error(L, "invalid arguments to right hand of == operator, need UnityEngine.Vector3!"); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int Slerp_xlua_st_(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { { UnityEngine.Vector3 a;translator.Get(L, 1, out a); UnityEngine.Vector3 b;translator.Get(L, 2, out b); float t = (float)LuaAPI.lua_tonumber(L, 3); UnityEngine.Vector3 __cl_gen_ret = UnityEngine.Vector3.Slerp( a, b, t ); translator.PushUnityEngineVector3(L, __cl_gen_ret); return 1; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int SlerpUnclamped_xlua_st_(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { { UnityEngine.Vector3 a;translator.Get(L, 1, out a); UnityEngine.Vector3 b;translator.Get(L, 2, out b); float t = (float)LuaAPI.lua_tonumber(L, 3); UnityEngine.Vector3 __cl_gen_ret = UnityEngine.Vector3.SlerpUnclamped( a, b, t ); translator.PushUnityEngineVector3(L, __cl_gen_ret); return 1; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int OrthoNormalize_xlua_st_(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); int __gen_param_count = LuaAPI.lua_gettop(L); try { if(__gen_param_count == 2&& translator.Assignable<UnityEngine.Vector3>(L, 1)&& translator.Assignable<UnityEngine.Vector3>(L, 2)) { UnityEngine.Vector3 normal;translator.Get(L, 1, out normal); UnityEngine.Vector3 tangent;translator.Get(L, 2, out tangent); UnityEngine.Vector3.OrthoNormalize( ref normal, ref tangent ); translator.PushUnityEngineVector3(L, normal); translator.UpdateUnityEngineVector3(L, 1, normal); translator.PushUnityEngineVector3(L, tangent); translator.UpdateUnityEngineVector3(L, 2, tangent); return 2; } if(__gen_param_count == 3&& translator.Assignable<UnityEngine.Vector3>(L, 1)&& translator.Assignable<UnityEngine.Vector3>(L, 2)&& translator.Assignable<UnityEngine.Vector3>(L, 3)) { UnityEngine.Vector3 normal;translator.Get(L, 1, out normal); UnityEngine.Vector3 tangent;translator.Get(L, 2, out tangent); UnityEngine.Vector3 binormal;translator.Get(L, 3, out binormal); UnityEngine.Vector3.OrthoNormalize( ref normal, ref tangent, ref binormal ); translator.PushUnityEngineVector3(L, normal); translator.UpdateUnityEngineVector3(L, 1, normal); translator.PushUnityEngineVector3(L, tangent); translator.UpdateUnityEngineVector3(L, 2, tangent); translator.PushUnityEngineVector3(L, binormal); translator.UpdateUnityEngineVector3(L, 3, binormal); return 3; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } return LuaAPI.luaL_error(L, "invalid arguments to UnityEngine.Vector3.OrthoNormalize!"); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int RotateTowards_xlua_st_(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { { UnityEngine.Vector3 current;translator.Get(L, 1, out current); UnityEngine.Vector3 target;translator.Get(L, 2, out target); float maxRadiansDelta = (float)LuaAPI.lua_tonumber(L, 3); float maxMagnitudeDelta = (float)LuaAPI.lua_tonumber(L, 4); UnityEngine.Vector3 __cl_gen_ret = UnityEngine.Vector3.RotateTowards( current, target, maxRadiansDelta, maxMagnitudeDelta ); translator.PushUnityEngineVector3(L, __cl_gen_ret); return 1; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int Lerp_xlua_st_(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { { UnityEngine.Vector3 a;translator.Get(L, 1, out a); UnityEngine.Vector3 b;translator.Get(L, 2, out b); float t = (float)LuaAPI.lua_tonumber(L, 3); UnityEngine.Vector3 __cl_gen_ret = UnityEngine.Vector3.Lerp( a, b, t ); translator.PushUnityEngineVector3(L, __cl_gen_ret); return 1; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int LerpUnclamped_xlua_st_(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { { UnityEngine.Vector3 a;translator.Get(L, 1, out a); UnityEngine.Vector3 b;translator.Get(L, 2, out b); float t = (float)LuaAPI.lua_tonumber(L, 3); UnityEngine.Vector3 __cl_gen_ret = UnityEngine.Vector3.LerpUnclamped( a, b, t ); translator.PushUnityEngineVector3(L, __cl_gen_ret); return 1; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int MoveTowards_xlua_st_(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { { UnityEngine.Vector3 current;translator.Get(L, 1, out current); UnityEngine.Vector3 target;translator.Get(L, 2, out target); float maxDistanceDelta = (float)LuaAPI.lua_tonumber(L, 3); UnityEngine.Vector3 __cl_gen_ret = UnityEngine.Vector3.MoveTowards( current, target, maxDistanceDelta ); translator.PushUnityEngineVector3(L, __cl_gen_ret); return 1; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int SmoothDamp_xlua_st_(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); int __gen_param_count = LuaAPI.lua_gettop(L); try { if(__gen_param_count == 4&& translator.Assignable<UnityEngine.Vector3>(L, 1)&& translator.Assignable<UnityEngine.Vector3>(L, 2)&& translator.Assignable<UnityEngine.Vector3>(L, 3)&& LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 4)) { UnityEngine.Vector3 current;translator.Get(L, 1, out current); UnityEngine.Vector3 target;translator.Get(L, 2, out target); UnityEngine.Vector3 currentVelocity;translator.Get(L, 3, out currentVelocity); float smoothTime = (float)LuaAPI.lua_tonumber(L, 4); UnityEngine.Vector3 __cl_gen_ret = UnityEngine.Vector3.SmoothDamp( current, target, ref currentVelocity, smoothTime ); translator.PushUnityEngineVector3(L, __cl_gen_ret); translator.PushUnityEngineVector3(L, currentVelocity); translator.UpdateUnityEngineVector3(L, 3, currentVelocity); return 2; } if(__gen_param_count == 5&& translator.Assignable<UnityEngine.Vector3>(L, 1)&& translator.Assignable<UnityEngine.Vector3>(L, 2)&& translator.Assignable<UnityEngine.Vector3>(L, 3)&& LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 4)&& LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 5)) { UnityEngine.Vector3 current;translator.Get(L, 1, out current); UnityEngine.Vector3 target;translator.Get(L, 2, out target); UnityEngine.Vector3 currentVelocity;translator.Get(L, 3, out currentVelocity); float smoothTime = (float)LuaAPI.lua_tonumber(L, 4); float maxSpeed = (float)LuaAPI.lua_tonumber(L, 5); UnityEngine.Vector3 __cl_gen_ret = UnityEngine.Vector3.SmoothDamp( current, target, ref currentVelocity, smoothTime, maxSpeed ); translator.PushUnityEngineVector3(L, __cl_gen_ret); translator.PushUnityEngineVector3(L, currentVelocity); translator.UpdateUnityEngineVector3(L, 3, currentVelocity); return 2; } if(__gen_param_count == 6&& translator.Assignable<UnityEngine.Vector3>(L, 1)&& translator.Assignable<UnityEngine.Vector3>(L, 2)&& translator.Assignable<UnityEngine.Vector3>(L, 3)&& LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 4)&& LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 5)&& LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 6)) { UnityEngine.Vector3 current;translator.Get(L, 1, out current); UnityEngine.Vector3 target;translator.Get(L, 2, out target); UnityEngine.Vector3 currentVelocity;translator.Get(L, 3, out currentVelocity); float smoothTime = (float)LuaAPI.lua_tonumber(L, 4); float maxSpeed = (float)LuaAPI.lua_tonumber(L, 5); float deltaTime = (float)LuaAPI.lua_tonumber(L, 6); UnityEngine.Vector3 __cl_gen_ret = UnityEngine.Vector3.SmoothDamp( current, target, ref currentVelocity, smoothTime, maxSpeed, deltaTime ); translator.PushUnityEngineVector3(L, __cl_gen_ret); translator.PushUnityEngineVector3(L, currentVelocity); translator.UpdateUnityEngineVector3(L, 3, currentVelocity); return 2; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } return LuaAPI.luaL_error(L, "invalid arguments to UnityEngine.Vector3.SmoothDamp!"); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int Set(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); UnityEngine.Vector3 __cl_gen_to_be_invoked;translator.Get(L, 1, out __cl_gen_to_be_invoked); try { { float new_x = (float)LuaAPI.lua_tonumber(L, 2); float new_y = (float)LuaAPI.lua_tonumber(L, 3); float new_z = (float)LuaAPI.lua_tonumber(L, 4); __cl_gen_to_be_invoked.Set( new_x, new_y, new_z ); translator.UpdateUnityEngineVector3(L, 1, __cl_gen_to_be_invoked); return 0; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int Scale_xlua_st_(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { { UnityEngine.Vector3 a;translator.Get(L, 1, out a); UnityEngine.Vector3 b;translator.Get(L, 2, out b); UnityEngine.Vector3 __cl_gen_ret = UnityEngine.Vector3.Scale( a, b ); translator.PushUnityEngineVector3(L, __cl_gen_ret); return 1; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int Scale(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); UnityEngine.Vector3 __cl_gen_to_be_invoked;translator.Get(L, 1, out __cl_gen_to_be_invoked); try { { UnityEngine.Vector3 scale;translator.Get(L, 2, out scale); __cl_gen_to_be_invoked.Scale( scale ); translator.UpdateUnityEngineVector3(L, 1, __cl_gen_to_be_invoked); return 0; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int Cross_xlua_st_(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { { UnityEngine.Vector3 lhs;translator.Get(L, 1, out lhs); UnityEngine.Vector3 rhs;translator.Get(L, 2, out rhs); UnityEngine.Vector3 __cl_gen_ret = UnityEngine.Vector3.Cross( lhs, rhs ); translator.PushUnityEngineVector3(L, __cl_gen_ret); return 1; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int GetHashCode(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); UnityEngine.Vector3 __cl_gen_to_be_invoked;translator.Get(L, 1, out __cl_gen_to_be_invoked); try { { int __cl_gen_ret = __cl_gen_to_be_invoked.GetHashCode( ); LuaAPI.xlua_pushinteger(L, __cl_gen_ret); translator.UpdateUnityEngineVector3(L, 1, __cl_gen_to_be_invoked); return 1; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int Equals(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); UnityEngine.Vector3 __cl_gen_to_be_invoked;translator.Get(L, 1, out __cl_gen_to_be_invoked); try { { object other = translator.GetObject(L, 2, typeof(object)); bool __cl_gen_ret = __cl_gen_to_be_invoked.Equals( other ); LuaAPI.lua_pushboolean(L, __cl_gen_ret); translator.UpdateUnityEngineVector3(L, 1, __cl_gen_to_be_invoked); return 1; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int Reflect_xlua_st_(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { { UnityEngine.Vector3 inDirection;translator.Get(L, 1, out inDirection); UnityEngine.Vector3 inNormal;translator.Get(L, 2, out inNormal); UnityEngine.Vector3 __cl_gen_ret = UnityEngine.Vector3.Reflect( inDirection, inNormal ); translator.PushUnityEngineVector3(L, __cl_gen_ret); return 1; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int Normalize_xlua_st_(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { { UnityEngine.Vector3 value;translator.Get(L, 1, out value); UnityEngine.Vector3 __cl_gen_ret = UnityEngine.Vector3.Normalize( value ); translator.PushUnityEngineVector3(L, __cl_gen_ret); return 1; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int Normalize(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); UnityEngine.Vector3 __cl_gen_to_be_invoked;translator.Get(L, 1, out __cl_gen_to_be_invoked); try { { __cl_gen_to_be_invoked.Normalize( ); translator.UpdateUnityEngineVector3(L, 1, __cl_gen_to_be_invoked); return 0; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int Dot_xlua_st_(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { { UnityEngine.Vector3 lhs;translator.Get(L, 1, out lhs); UnityEngine.Vector3 rhs;translator.Get(L, 2, out rhs); float __cl_gen_ret = UnityEngine.Vector3.Dot( lhs, rhs ); LuaAPI.lua_pushnumber(L, __cl_gen_ret); return 1; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int Project_xlua_st_(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { { UnityEngine.Vector3 vector;translator.Get(L, 1, out vector); UnityEngine.Vector3 onNormal;translator.Get(L, 2, out onNormal); UnityEngine.Vector3 __cl_gen_ret = UnityEngine.Vector3.Project( vector, onNormal ); translator.PushUnityEngineVector3(L, __cl_gen_ret); return 1; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int ProjectOnPlane_xlua_st_(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { { UnityEngine.Vector3 vector;translator.Get(L, 1, out vector); UnityEngine.Vector3 planeNormal;translator.Get(L, 2, out planeNormal); UnityEngine.Vector3 __cl_gen_ret = UnityEngine.Vector3.ProjectOnPlane( vector, planeNormal ); translator.PushUnityEngineVector3(L, __cl_gen_ret); return 1; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int Angle_xlua_st_(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { { UnityEngine.Vector3 from;translator.Get(L, 1, out from); UnityEngine.Vector3 to;translator.Get(L, 2, out to); float __cl_gen_ret = UnityEngine.Vector3.Angle( from, to ); LuaAPI.lua_pushnumber(L, __cl_gen_ret); return 1; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int Distance_xlua_st_(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { { UnityEngine.Vector3 a;translator.Get(L, 1, out a); UnityEngine.Vector3 b;translator.Get(L, 2, out b); float __cl_gen_ret = UnityEngine.Vector3.Distance( a, b ); LuaAPI.lua_pushnumber(L, __cl_gen_ret); return 1; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int ClampMagnitude_xlua_st_(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { { UnityEngine.Vector3 vector;translator.Get(L, 1, out vector); float maxLength = (float)LuaAPI.lua_tonumber(L, 2); UnityEngine.Vector3 __cl_gen_ret = UnityEngine.Vector3.ClampMagnitude( vector, maxLength ); translator.PushUnityEngineVector3(L, __cl_gen_ret); return 1; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int Magnitude_xlua_st_(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { { UnityEngine.Vector3 a;translator.Get(L, 1, out a); float __cl_gen_ret = UnityEngine.Vector3.Magnitude( a ); LuaAPI.lua_pushnumber(L, __cl_gen_ret); return 1; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int SqrMagnitude_xlua_st_(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { { UnityEngine.Vector3 a;translator.Get(L, 1, out a); float __cl_gen_ret = UnityEngine.Vector3.SqrMagnitude( a ); LuaAPI.lua_pushnumber(L, __cl_gen_ret); return 1; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int Min_xlua_st_(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { { UnityEngine.Vector3 lhs;translator.Get(L, 1, out lhs); UnityEngine.Vector3 rhs;translator.Get(L, 2, out rhs); UnityEngine.Vector3 __cl_gen_ret = UnityEngine.Vector3.Min( lhs, rhs ); translator.PushUnityEngineVector3(L, __cl_gen_ret); return 1; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int Max_xlua_st_(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { { UnityEngine.Vector3 lhs;translator.Get(L, 1, out lhs); UnityEngine.Vector3 rhs;translator.Get(L, 2, out rhs); UnityEngine.Vector3 __cl_gen_ret = UnityEngine.Vector3.Max( lhs, rhs ); translator.PushUnityEngineVector3(L, __cl_gen_ret); return 1; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int ToString(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); UnityEngine.Vector3 __cl_gen_to_be_invoked;translator.Get(L, 1, out __cl_gen_to_be_invoked); int __gen_param_count = LuaAPI.lua_gettop(L); try { if(__gen_param_count == 1) { string __cl_gen_ret = __cl_gen_to_be_invoked.ToString( ); LuaAPI.lua_pushstring(L, __cl_gen_ret); translator.UpdateUnityEngineVector3(L, 1, __cl_gen_to_be_invoked); return 1; } if(__gen_param_count == 2&& (LuaAPI.lua_isnil(L, 2) || LuaAPI.lua_type(L, 2) == LuaTypes.LUA_TSTRING)) { string format = LuaAPI.lua_tostring(L, 2); string __cl_gen_ret = __cl_gen_to_be_invoked.ToString( format ); LuaAPI.lua_pushstring(L, __cl_gen_ret); translator.UpdateUnityEngineVector3(L, 1, __cl_gen_to_be_invoked); return 1; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } return LuaAPI.luaL_error(L, "invalid arguments to UnityEngine.Vector3.ToString!"); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int get_normalized(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { UnityEngine.Vector3 __cl_gen_to_be_invoked;translator.Get(L, 1, out __cl_gen_to_be_invoked); translator.PushUnityEngineVector3(L, __cl_gen_to_be_invoked.normalized); } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int get_magnitude(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { UnityEngine.Vector3 __cl_gen_to_be_invoked;translator.Get(L, 1, out __cl_gen_to_be_invoked); LuaAPI.lua_pushnumber(L, __cl_gen_to_be_invoked.magnitude); } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int get_sqrMagnitude(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { UnityEngine.Vector3 __cl_gen_to_be_invoked;translator.Get(L, 1, out __cl_gen_to_be_invoked); LuaAPI.lua_pushnumber(L, __cl_gen_to_be_invoked.sqrMagnitude); } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int get_zero(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { translator.PushUnityEngineVector3(L, UnityEngine.Vector3.zero); } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int get_one(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { translator.PushUnityEngineVector3(L, UnityEngine.Vector3.one); } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int get_forward(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { translator.PushUnityEngineVector3(L, UnityEngine.Vector3.forward); } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int get_back(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { translator.PushUnityEngineVector3(L, UnityEngine.Vector3.back); } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int get_up(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { translator.PushUnityEngineVector3(L, UnityEngine.Vector3.up); } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int get_down(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { translator.PushUnityEngineVector3(L, UnityEngine.Vector3.down); } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int get_left(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { translator.PushUnityEngineVector3(L, UnityEngine.Vector3.left); } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int get_right(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { translator.PushUnityEngineVector3(L, UnityEngine.Vector3.right); } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int get_x(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { UnityEngine.Vector3 __cl_gen_to_be_invoked;translator.Get(L, 1, out __cl_gen_to_be_invoked); LuaAPI.lua_pushnumber(L, __cl_gen_to_be_invoked.x); } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int get_y(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { UnityEngine.Vector3 __cl_gen_to_be_invoked;translator.Get(L, 1, out __cl_gen_to_be_invoked); LuaAPI.lua_pushnumber(L, __cl_gen_to_be_invoked.y); } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int get_z(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { UnityEngine.Vector3 __cl_gen_to_be_invoked;translator.Get(L, 1, out __cl_gen_to_be_invoked); LuaAPI.lua_pushnumber(L, __cl_gen_to_be_invoked.z); } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int set_x(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { UnityEngine.Vector3 __cl_gen_to_be_invoked;translator.Get(L, 1, out __cl_gen_to_be_invoked); __cl_gen_to_be_invoked.x = (float)LuaAPI.lua_tonumber(L, 2); translator.UpdateUnityEngineVector3(L, 1, __cl_gen_to_be_invoked); } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } return 0; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int set_y(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { UnityEngine.Vector3 __cl_gen_to_be_invoked;translator.Get(L, 1, out __cl_gen_to_be_invoked); __cl_gen_to_be_invoked.y = (float)LuaAPI.lua_tonumber(L, 2); translator.UpdateUnityEngineVector3(L, 1, __cl_gen_to_be_invoked); } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } return 0; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int set_z(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { UnityEngine.Vector3 __cl_gen_to_be_invoked;translator.Get(L, 1, out __cl_gen_to_be_invoked); __cl_gen_to_be_invoked.z = (float)LuaAPI.lua_tonumber(L, 2); translator.UpdateUnityEngineVector3(L, 1, __cl_gen_to_be_invoked); } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } return 0; } } }
38.996603
341
0.509608
[ "MIT" ]
gdgeek/GGJ2017
Assets/XLua/Gen/UnityEngineVector3Wrap.cs
57,405
C#
namespace DomainDispatcher { using System; using System.Collections.Generic; using System.Linq; using Abstractions; using Abstractions.Events; public partial class InMemoryEventBusSubscriptionsManager : IEventBusSubscriptionsManager { private readonly Dictionary<string, List<SubscriptionInfo>> _handlers; private readonly List<Type> _eventTypes; public event EventHandler<string> OnEventRemoved; public InMemoryEventBusSubscriptionsManager() { _handlers = new Dictionary<string, List<SubscriptionInfo>>(); _eventTypes = new List<Type>(); } public bool IsEmpty => !_handlers.Keys.Any(); public void Clear() => _handlers.Clear(); public void AddSubscription<T, TH>() where T : DomainEvent where TH : IIntegrationEventHandler<T> { var eventName = GetEventKey<T>(); DoAddSubscription(typeof(TH), eventName); _eventTypes.Add(typeof(T)); } private void DoAddSubscription(Type handlerType, string eventName) { if (!HasSubscriptionsForEvent(eventName)) { _handlers.Add(eventName, new List<SubscriptionInfo>()); } if (_handlers[eventName].Any(s => s.HandlerType == handlerType)) { throw new ArgumentException( $"Handler Type {handlerType.Name} already registered for '{eventName}'", nameof(handlerType)); } _handlers[eventName].Add(SubscriptionInfo.New(handlerType)); } public void RemoveSubscription<T, TH>() where TH : IIntegrationEventHandler<T> where T : DomainEvent { var handlerToRemove = FindSubscriptionToRemove<T, TH>(); var eventName = GetEventKey<T>(); DoRemoveHandler(eventName, handlerToRemove); } private void DoRemoveHandler(string eventName, SubscriptionInfo subsToRemove) { if (subsToRemove != null) { _handlers[eventName].Remove(subsToRemove); if (!_handlers[eventName].Any()) { _handlers.Remove(eventName); var eventType = _eventTypes.SingleOrDefault(e => e.Name == eventName); if (eventType != null) { _eventTypes.Remove(eventType); } RaiseOnEventRemoved(eventName); } } } public IEnumerable<SubscriptionInfo> GetHandlersForEvent<T>() where T : DomainEvent { var key = GetEventKey<T>(); return GetHandlersForEvent(key); } public IEnumerable<SubscriptionInfo> GetHandlersForEvent(string eventName) => _handlers[eventName]; private void RaiseOnEventRemoved(string eventName) { var handler = OnEventRemoved; if (handler != null) { //OnEventRemoved(this, eventName); } } private SubscriptionInfo FindSubscriptionToRemove<T, TH>() where T : DomainEvent where TH : IIntegrationEventHandler<T> { var eventName = GetEventKey<T>(); return DoFindSubscriptionToRemove(eventName, typeof(TH)); } private SubscriptionInfo DoFindSubscriptionToRemove(string eventName, Type handlerType) { if (!HasSubscriptionsForEvent(eventName)) { return null; } return _handlers[eventName].SingleOrDefault(s => s.HandlerType == handlerType); } public bool HasSubscriptionsForEvent<T>() where T : DomainEvent { var key = GetEventKey<T>(); return HasSubscriptionsForEvent(key); } public bool HasSubscriptionsForEvent(string eventName) => _handlers.ContainsKey(eventName); public Type GetEventTypeByName(string eventName) => _eventTypes.SingleOrDefault(t => t.Name == eventName); public string GetEventKey<T>() { return typeof(T).Name; } } }
33.062016
114
0.576084
[ "MIT" ]
blocshop/domain-dispatcher
DomainDispatcher/InMemoryEventBusSubscriptionsManager.cs
4,267
C#
#region License /* * Ktos.AspNetCore.Authentication.ApiKeyHeader * * Copyright (C) Marcin Badurowicz <m at badurowicz dot net> 2018 * * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files * (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #endregion License using System; using System.Net; using System.Text.Json; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Xunit; namespace Ktos.AspNetCore.Authentication.ApiKeyHeader.Tests { public class ApiKeyHeaderAuthenticationHandlerTests { public const string TestApiKey = "testapi"; [Fact] public async Task EmptyApiKeyReturns401() { var client = TestBed.GetClientWithOptions(options => options.ApiKey = TestApiKey); var response = await client.GetAsync("/"); Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); Assert.Equal(string.Empty, await response.Content.ReadAsStringAsync()); } [Fact] public async Task InvalidCredentialsReturns401() { var client = TestBed.GetClientWithOptions(options => options.ApiKey = TestApiKey); client.UseApiKey("wrongkey"); var response = await client.GetAsync("/"); Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); Assert.Equal(string.Empty, await response.Content.ReadAsStringAsync()); } [Fact] public async Task ValidCredentialsAuthorize() { var client = TestBed.GetClientWithOptions(options => options.ApiKey = TestApiKey); client.UseApiKey(TestApiKey); var response = await client.GetAsync("/"); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(ApiKeyHeaderAuthenticationDefaults.AuthenticationClaimName, await response.Content.ReadAsStringAsync()); } [Fact] public async Task ValidCredentialsAndCustomHeaderAuthorize() { const string key = "testapi"; const string header = "X-API-KEY"; var client = TestBed.GetClientWithOptions(options => { options.ApiKey = key; options.Header = header; }); client.UseApiKey(key, header); var response = await client.GetAsync("/"); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(ApiKeyHeaderAuthenticationDefaults.AuthenticationClaimName, await response.Content.ReadAsStringAsync()); } [Fact] public async Task InvalidCredentialsAndCustomHeaderReturns401() { const string key = "testapi"; const string wrongkey = "wrongkey"; const string header = "X-API-KEY"; var client = TestBed.GetClientWithOptions(options => { options.ApiKey = key; options.Header = header; }); client.UseApiKey(wrongkey, header); var response = await client.GetAsync("/"); Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); Assert.Equal(string.Empty, await response.Content.ReadAsStringAsync()); } [Fact] public async Task ValidCredentialsAndCustomAuthenticationLogicAuthorize() { const string key = "goodkey"; const string key2 = "goodkey2"; var client = TestBed.GetClientWithOptions(options => { options.CustomAuthenticationHandler = SimpleCustomAuthenticationLogic; }); client.UseApiKey(key); var response = await client.GetAsync("/"); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(key, await response.Content.ReadAsStringAsync()); client.UseApiKey(key2); response = await client.GetAsync("/"); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(key2, await response.Content.ReadAsStringAsync()); } [Fact] public async Task ValidCredentialsAndCustomAuthenticationLogicProperlySetClaims() { const string key = "goodkey"; const string claimName = "John"; var client = TestBed.GetClientWithOptions(options => { options.CustomAuthenticationHandler = _ => (true, claimName); }); client.UseApiKey(key); var response = await client.GetAsync("/"); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(claimName, await response.Content.ReadAsStringAsync()); } [Fact] public async Task ValidCredentialsAndCustomAuthenticationLogicProperlySetClaimsInContext() { const string key = "goodkey"; const string claimName = "John"; var client = TestBed.GetClientWithOptions(options => { options.CustomAuthenticationHandler = _ => (true, claimName); }); client.UseApiKey(key); var response = await client.GetAsync(TestBed.FullUserPath); var content = await response.Content.ReadAsStringAsync(); var user = JsonDocument.Parse(content); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(claimName, user.RootElement.GetProperty("Name").GetString()); } [Fact] public async Task ValidCredentialsAndCustomAuthenticationFullTicketProperlySetOtherClaimsInTicket() { const string key = "goodkey"; var client = TestBed.GetClientWithBuilder(builder => { builder.AddApiKeyHeaderAuthentication(options => options.UseRegisteredAuthenticationHandler = true); builder.Services.AddSingleton<IApiKeyCustomAuthenticationTicketHandler, CustomFullTicketHandler>(); }); client.UseApiKey(key); var response = await client.GetAsync(TestBed.FullTicketPrincipalClaimsPath); var content = await response.Content.ReadAsStringAsync(); var claims = JsonDocument.Parse(content); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", claims.RootElement[0].GetProperty("Type").GetString()); Assert.Equal(CustomFullTicketHandler.TestUserName, claims.RootElement[0].GetProperty("Value").GetString()); Assert.Equal("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", claims.RootElement[1].GetProperty("Type").GetString()); Assert.Equal(CustomFullTicketHandler.TestRole, claims.RootElement[1].GetProperty("Value").GetString()); } [Fact] public async Task ValidCredentialsAndCustomAuthenticationFullTicketProperlySetTicketProperties() { const string key = "goodkey"; var client = TestBed.GetClientWithBuilder(builder => { builder.AddApiKeyHeaderAuthentication(options => options.UseRegisteredAuthenticationHandler = true); builder.Services.AddSingleton<IApiKeyCustomAuthenticationTicketHandler, CustomFullTicketHandler>(); }); client.UseApiKey(key); var response = await client.GetAsync(TestBed.FullTicketPropertiesPath); var content = await response.Content.ReadAsStringAsync(); var claims = JsonDocument.Parse(content); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(CustomFullTicketHandler.Redirect, claims.RootElement.GetProperty("Items").GetProperty(".redirect").GetString()); } [Fact] public async Task ValidCredentialsAndCustomAuthenticationFullTicketProperlySetClaimsInContext() { const string key = "goodkey"; const string claimName = "John"; var client = TestBed.GetClientWithBuilder(builder => { builder.AddApiKeyHeaderAuthentication(options => options.UseRegisteredAuthenticationHandler = true); builder.Services.AddSingleton<IApiKeyCustomAuthenticationTicketHandler, CustomFullTicketHandler>(); }); client.UseApiKey(key); var response = await client.GetAsync(TestBed.FullUserPath); var content = await response.Content.ReadAsStringAsync(); var user = JsonDocument.Parse(content); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(claimName, user.RootElement.GetProperty("Name").GetString()); } [Fact] public async Task ValidCredentialsAndCustomAuthenticationLogicReturningNullNameThrows() { const string key = "goodkey"; var client = TestBed.GetClientWithOptions(options => options.CustomAuthenticationHandler = (_) => (true, null)); client.UseApiKey(key); await Assert.ThrowsAsync<ArgumentNullException>(async () => await client.GetAsync("/")); } [Fact] public async Task ValidCredentialsAndCustomAuthenticationServiceAuthorize() { const string key = "testapi"; var client = TestBed.GetClientWithBuilder(builder => { builder.AddApiKeyHeaderAuthentication(options => options.UseRegisteredAuthenticationHandler = true); builder.Services.AddSingleton<IApiKeyCustomAuthenticator, TestApiKeyService>(); }); client.UseApiKey(key); var response = await client.GetAsync("/"); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(key.ToUpper(), await response.Content.ReadAsStringAsync()); } [Fact] public async Task ValidCredentialsAndNoRegisteredAuthenticationServiceReturns401() { var client = TestBed.GetClientWithBuilder(builder => { builder.AddApiKeyHeaderAuthentication(options => options.UseRegisteredAuthenticationHandler = true); }); client.UseApiKey("testapi"); var response = await client.GetAsync("/"); Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); Assert.Equal(string.Empty, await response.Content.ReadAsStringAsync()); } [Fact] public async Task InvalidCredentialsAndCustomAuthenticationServiceReturns401() { const string key = "badapi"; var client = TestBed.GetClientWithBuilder(builder => { builder.AddApiKeyHeaderAuthentication(options => options.UseRegisteredAuthenticationHandler = true); builder.Services.AddSingleton<IApiKeyCustomAuthenticator, TestApiKeyService>(); }); client.UseApiKey(key); var response = await client.GetAsync("/"); Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); Assert.Equal(string.Empty, await response.Content.ReadAsStringAsync()); } [Fact] public async Task ValidCredentialsAndCustomAuthenticationLogicAndCustomHeaderAuthorize() { const string key = "goodkey"; const string key2 = "goodkey2"; const string customHeader = "X-CUSTOM-HEADER"; var client = TestBed.GetClientWithOptions(options => { options.Header = customHeader; options.CustomAuthenticationHandler = SimpleCustomAuthenticationLogic; }); client.UseApiKey(key, customHeader); var response = await client.GetAsync("/"); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(key, await response.Content.ReadAsStringAsync()); client.UseApiKey(key2, customHeader); response = await client.GetAsync("/"); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(key2, await response.Content.ReadAsStringAsync()); } [Fact] public async Task InvalidCredentialsAndCustomAuthenticationLogicReturns401() { const string key = "goodkey"; const string key2 = "badkey"; var client = TestBed.GetClientWithOptions(options => { options.CustomAuthenticationHandler = SimpleCustomAuthenticationLogic; }); client.UseApiKey(key); var response = await client.GetAsync("/"); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(key, await response.Content.ReadAsStringAsync()); client.UseApiKey(key2); response = await client.GetAsync("/"); Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); Assert.Equal(string.Empty, await response.Content.ReadAsStringAsync()); } [Fact] public async Task InvalidCredentialsAndCustomAuthenticationLogicAndCustomHeaderReturns401() { const string key = "goodkey"; const string key2 = "badkey"; const string customHeader = "X-CUSTOM-HEADER"; var client = TestBed.GetClientWithOptions(options => { options.Header = customHeader; options.CustomAuthenticationHandler = SimpleCustomAuthenticationLogic; }); client.UseApiKey(key, customHeader); var response = await client.GetAsync("/"); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(key, await response.Content.ReadAsStringAsync()); client.UseApiKey(key2, customHeader); response = await client.GetAsync("/"); Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); Assert.Equal(string.Empty, await response.Content.ReadAsStringAsync()); } private (bool, string) SimpleCustomAuthenticationLogic(string apiKey) { return (apiKey.StartsWith("good"), apiKey); } } }
41.527778
172
0.653645
[ "MIT" ]
ktos/Ktos.AspNetCore.Authentication.ApiKeyHeader
test/ApiKeyHeaderAuthenticationHandlerTests.cs
14,952
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; [System.Serializable] public class Virtue { public string m_Name; public int m_Rating; public Virtue(string p_Name, int p_Rating) { m_Name = p_Name; m_Rating = p_Rating; } }
19.2
48
0.694444
[ "MIT" ]
SonKatarina23/HellYea
Assets/Script/Virtue.cs
290
C#
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. namespace StyleCop.Analyzers.Test.CSharp7.DocumentationRules { using StyleCop.Analyzers.Test.DocumentationRules; public class SA1625CSharp7UnitTests : SA1625UnitTests { } }
30.916667
107
0.770889
[ "Apache-2.0" ]
Andreyul/StyleCopAnalyzers
StyleCop.Analyzers/StyleCop.Analyzers.Test.CSharp7/DocumentationRules/SA1625CSharp7UnitTests.cs
373
C#
// 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. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.Functions.Support { /// <summary>TypeConverter implementation for ResourceScopeType.</summary> public partial class ResourceScopeTypeTypeConverter : global::System.Management.Automation.PSTypeConverter { /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c>. /// </returns> public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => true; /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c>. /// </returns> public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns> /// an instance of <see cref="ResourceScopeType" />, or <c>null</c> if there is no suitable conversion. /// </returns> public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ResourceScopeType.CreateFrom(sourceValue); /// <summary>NotImplemented -- this will return <c>null</c></summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns>will always return <c>null</c>.</returns> public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; } }
63.542373
210
0.649773
[ "MIT" ]
Arsasana/azure-powershell
src/Functions/generated/api/Support/ResourceScopeType.TypeConverter.cs
3,691
C#
using System.Collections.Generic; using System.Linq; using Domain.Common; using Domain.Exceptions; namespace Domain.ValueObjects { public class Colour : ValueObject { static Colour() { } private Colour() { } private Colour(string code) { Code = code; } public static Colour From(string code) { var colour = new Colour { Code = code }; if (!SupportedColours.Contains(colour)) { throw new UnsupportedColourException(code); } return colour; } public static Colour White => new Colour("#FFFFFF"); public static Colour Red => new Colour("#FF5733"); public static Colour Orange => new Colour("#FFC300"); public static Colour Yellow => new Colour("#FFFF66"); public static Colour Green => new Colour("#CCFF99 "); public static Colour Blue => new Colour("#6666FF"); public static Colour Purple => new Colour("#9966CC"); public static Colour Grey => new Colour("#999999"); public string Code { get; private set; } public static implicit operator string(Colour colour) { return colour.ToString(); } public static explicit operator Colour(string code) { return From(code); } public override string ToString() { return Code; } protected static IEnumerable<Colour> SupportedColours { get { yield return White; yield return Red; yield return Orange; yield return Yellow; yield return Green; yield return Blue; yield return Purple; yield return Grey; } } protected override IEnumerable<object> GetEqualityComponents() { yield return Code; } } }
23.284091
70
0.524646
[ "MIT" ]
petrubocsanean/CleanGraphQL
src/Domain/ValueObjects/Colour.cs
2,049
C#
namespace TrainsOnline.Desktop.ViewModels.Station { using System.Threading.Tasks; using Caliburn.Micro; using TrainsOnline.Desktop.Application.Interfaces.RemoteDataProvider; using TrainsOnline.Desktop.Common.GeoHelpers; using TrainsOnline.Desktop.Domain.DTO.Station; using TrainsOnline.Desktop.Domain.Models.General; using TrainsOnline.Desktop.ViewModels.General; using TrainsOnline.Desktop.ViewModels.User; using TrainsOnline.Desktop.Views.Route; using static TrainsOnline.Desktop.Domain.DTO.Station.GetStationDetailsResponse; using static TrainsOnline.Desktop.Domain.DTO.Station.GetStationsListResponse; public class StationMasterDetailDetailViewModel : Screen, IStationMasterDetailDetailView { private INavigationService NavService { get; } private IRemoteDataProviderService RemoteDataProvider { get; } public StationMasterDetailDetailViewModel(INavigationService navigationService, IRemoteDataProviderService remoteDataProvider, StationLookupModel item) { NavService = navigationService; RemoteDataProvider = remoteDataProvider; Item = item; } private StationLookupModel _item; public StationLookupModel Item { get => _item; set => Set(ref _item, value); } private GetStationDetailsResponse _details; public GetStationDetailsResponse Details { get => _details; set => Set(ref _details, value); } public async Task LoadDetails() { GetStationDetailsResponse data = await RemoteDataProvider.GetStation(Item.Id); Details = data; //Refresh(); } public void ShowStationOnMap() { GeoCoordinate[] coords = new GeoCoordinate[] { new GeoCoordinate(Details.Latitude, Details.Longitude) }; NavService.NavigateToViewModel<GeneralMapViewModel>(new GeneralMapViewParameters(coords)); } public void ShowDestinationOnMap(RouteDeparturesLookupModel route) { GeoCoordinate[] coords = new GeoCoordinate[] { new GeoCoordinate(route.To.Latitude, route.To.Longitude), }; NavService.NavigateToViewModel<GeneralMapViewModel>(new GeneralMapViewParameters(coords)); } public void ShowRouteOnMap(RouteDeparturesLookupModel route) { GeoCoordinate[] coords = new GeoCoordinate[] { new GeoCoordinate(Details.Latitude, Details.Longitude), new GeoCoordinate(route.To.Latitude, route.To.Longitude) }; NavService.NavigateToViewModel<GeneralMapViewModel>(new GeneralMapViewParameters(coords)); } public async void BuyTicket(RouteDeparturesLookupModel route) { if (!RemoteDataProvider.IsAuthenticated) { NavService.NavigateToViewModel<LoginRegisterViewModel>(); return; } await RemoteDataProvider.CreateTicketForCurrentUser(route.Id); } } }
36.388889
102
0.641527
[ "MIT" ]
adambajguz/TrainsOnline
frontend/TrainsOnline.Desktop/ViewModels/Station/StationMasterDetailDetailViewModel.cs
3,277
C#
using System; using UnityEngine; using UnityStandardAssets.Vehicles.Car; internal enum CarDriveType { FrontWheelDrive, RearWheelDrive, FourWheelDrive } internal enum SpeedType { MPH, KPH } public class CarController : Photon.MonoBehaviour { [SerializeField] private CarDriveType m_CarDriveType = CarDriveType.FourWheelDrive; [SerializeField] private WheelCollider[] m_WheelColliders = new WheelCollider[4]; [SerializeField] private GameObject[] m_WheelMeshes = new GameObject[4]; [SerializeField] private WheelEffects[] m_WheelEffects = new WheelEffects[4]; [SerializeField] private Vector3 m_CentreOfMassOffset; [SerializeField] private float m_MaximumSteerAngle; [Range(0, 1)] [SerializeField] private float m_SteerHelper; // 0 is raw physics , 1 the car will grip in the direction it is facing [Range(0, 1)] [SerializeField] private float m_TractionControl; // 0 is no traction control, 1 is full interference [SerializeField] private float m_FullTorqueOverAllWheels; [SerializeField] private float m_ReverseTorque; [SerializeField] private float m_MaxHandbrakeTorque; [SerializeField] private float m_Downforce = 100f; [SerializeField] private SpeedType m_SpeedType; [SerializeField] private float m_Topspeed = 200; [SerializeField] private static int NoOfGears = 5; [SerializeField] private float m_RevRangeBoundary = 1f; [SerializeField] private float m_SlipLimit; [SerializeField] private float m_BrakeTorque; private Quaternion[] m_WheelMeshLocalRotations; private Vector3 m_Prevpos, m_Pos; private float m_SteerAngle; private int m_GearNum; private float m_GearFactor; private float m_OldRotation; private float m_CurrentTorque; private Rigidbody m_Rigidbody; private const float k_ReversingThreshold = 0.01f; private float speed; private float steerAngle; private float accel; public bool Skidding { get; private set; } public float BrakeInput { get; private set; } public float CurrentSteerAngle{ get { return m_SteerAngle; } set { steerAngle = value; } } public float CurrentSpeed{ get { return m_Rigidbody.velocity.magnitude*2.23693629f; } set { speed = value; } } public float MaxSpeed{get { return m_Topspeed; }} public float Revs { get; private set; } public float AccelInput { get; private set; } // Use this for initialization private void Start() { m_WheelMeshLocalRotations = new Quaternion[4]; for (int i = 0; i < 4; i++) { m_WheelMeshLocalRotations[i] = m_WheelMeshes[i].transform.localRotation; } m_WheelColliders[0].attachedRigidbody.centerOfMass = m_CentreOfMassOffset; m_MaxHandbrakeTorque = float.MaxValue; m_Rigidbody = GetComponent<Rigidbody>(); m_CurrentTorque = m_FullTorqueOverAllWheels - (m_TractionControl*m_FullTorqueOverAllWheels); } private void GearChanging() { float f = Mathf.Abs(CurrentSpeed/MaxSpeed); float upgearlimit = (1/(float) NoOfGears)*(m_GearNum + 1); float downgearlimit = (1/(float) NoOfGears)*m_GearNum; if (m_GearNum > 0 && f < downgearlimit) { m_GearNum--; } if (f > upgearlimit && (m_GearNum < (NoOfGears - 1))) { m_GearNum++; } } // simple function to add a curved bias towards 1 for a value in the 0-1 range private static float CurveFactor(float factor) { return 1 - (1 - factor)*(1 - factor); } // unclamped version of Lerp, to allow value to exceed the from-to range private static float ULerp(float from, float to, float value) { return (1.0f - value)*from + value*to; } private void CalculateGearFactor() { float f = (1/(float) NoOfGears); // gear factor is a normalised representation of the current speed within the current gear's range of speeds. // We smooth towards the 'target' gear factor, so that revs don't instantly snap up or down when changing gear. var targetGearFactor = Mathf.InverseLerp(f*m_GearNum, f*(m_GearNum + 1), Mathf.Abs(CurrentSpeed/MaxSpeed)); m_GearFactor = Mathf.Lerp(m_GearFactor, targetGearFactor, Time.deltaTime*5f); } private void CalculateRevs() { // calculate engine revs (for display / sound) // (this is done in retrospect - revs are not used in force/power calculations) CalculateGearFactor(); var gearNumFactor = m_GearNum/(float) NoOfGears; var revsRangeMin = ULerp(0f, m_RevRangeBoundary, CurveFactor(gearNumFactor)); var revsRangeMax = ULerp(m_RevRangeBoundary, 1f, gearNumFactor); Revs = ULerp(revsRangeMin, revsRangeMax, m_GearFactor); } public void Move(float steering, float accel, float footbrake, float handbrake) { for (int i = 0; i < 4; i++) { Quaternion quat; Vector3 position; m_WheelColliders[i].GetWorldPose(out position, out quat); m_WheelMeshes[i].transform.position = position; m_WheelMeshes[i].transform.rotation = quat; } //clamp input values steering = Mathf.Clamp(steering, -1, 1); AccelInput = accel = Mathf.Clamp(accel, 0, 1); BrakeInput = footbrake = -1*Mathf.Clamp(footbrake, -1, 0); handbrake = Mathf.Clamp(handbrake, 0, 1); //Set the steer on the front wheels. //Assuming that wheels 0 and 1 are the front wheels. m_SteerAngle = steering*m_MaximumSteerAngle; m_WheelColliders[0].steerAngle = m_SteerAngle; m_WheelColliders[1].steerAngle = m_SteerAngle; SteerHelper(); ApplyDrive(accel, footbrake); CapSpeed(); //Set the handbrake. //Assuming that wheels 2 and 3 are the rear wheels. if (handbrake > 0f) { var hbTorque = handbrake*m_MaxHandbrakeTorque; m_WheelColliders[2].brakeTorque = hbTorque; m_WheelColliders[3].brakeTorque = hbTorque; } CalculateRevs(); GearChanging(); AddDownForce(); CheckForWheelSpin(); TractionControl(); } private void CapSpeed() { float speed = m_Rigidbody.velocity.magnitude; switch (m_SpeedType) { case SpeedType.MPH: speed *= 2.23693629f; if (speed > m_Topspeed) m_Rigidbody.velocity = (m_Topspeed/2.23693629f) * m_Rigidbody.velocity.normalized; break; case SpeedType.KPH: speed *= 3.6f; if (speed > m_Topspeed) m_Rigidbody.velocity = (m_Topspeed/3.6f) * m_Rigidbody.velocity.normalized; break; } } private void ApplyDrive(float accel, float footbrake) { float thrustTorque; switch (m_CarDriveType) { case CarDriveType.FourWheelDrive: thrustTorque = accel * (m_CurrentTorque / 4f); for (int i = 0; i < 4; i++) { m_WheelColliders[i].motorTorque = thrustTorque; } break; case CarDriveType.FrontWheelDrive: thrustTorque = accel * (m_CurrentTorque / 2f); m_WheelColliders[0].motorTorque = m_WheelColliders[1].motorTorque = thrustTorque; break; case CarDriveType.RearWheelDrive: thrustTorque = accel * (m_CurrentTorque / 2f); m_WheelColliders[2].motorTorque = m_WheelColliders[3].motorTorque = thrustTorque; break; } for (int i = 0; i < 4; i++) { if (CurrentSpeed > 5 && Vector3.Angle(transform.forward, m_Rigidbody.velocity) < 50f) { m_WheelColliders[i].brakeTorque = m_BrakeTorque*footbrake; } else if (footbrake > 0) { m_WheelColliders[i].brakeTorque = 0f; m_WheelColliders[i].motorTorque = -m_ReverseTorque*footbrake; } } } private void SteerHelper() { for (int i = 0; i < 4; i++) { WheelHit wheelhit; m_WheelColliders[i].GetGroundHit(out wheelhit); if (wheelhit.normal == Vector3.zero) return; // wheels arent on the ground so dont realign the rigidbody velocity } // this if is needed to avoid gimbal lock problems that will make the car suddenly shift direction if (Mathf.Abs(m_OldRotation - transform.eulerAngles.y) < 10f) { var turnadjust = (transform.eulerAngles.y - m_OldRotation) * m_SteerHelper; Quaternion velRotation = Quaternion.AngleAxis(turnadjust, Vector3.up); m_Rigidbody.velocity = velRotation * m_Rigidbody.velocity; } m_OldRotation = transform.eulerAngles.y; } // this is used to add more grip in relation to speed private void AddDownForce() { m_WheelColliders[0].attachedRigidbody.AddForce(-transform.up*m_Downforce* m_WheelColliders[0].attachedRigidbody.velocity.magnitude); } // checks if the wheels are spinning and is so does three things // 1) emits particles // 2) plays tiure skidding sounds // 3) leaves skidmarks on the ground // these effects are controlled through the WheelEffects class private void CheckForWheelSpin() { // loop through all wheels for (int i = 0; i < 4; i++) { WheelHit wheelHit; m_WheelColliders[i].GetGroundHit(out wheelHit); // is the tire slipping above the given threshhold if (Mathf.Abs(wheelHit.forwardSlip) >= m_SlipLimit || Mathf.Abs(wheelHit.sidewaysSlip) >= m_SlipLimit) { m_WheelEffects[i].EmitTyreSmoke(); // avoiding all four tires screeching at the same time // if they do it can lead to some strange audio artefacts if (!AnySkidSoundPlaying()) { m_WheelEffects[i].PlayAudio(); } continue; } // if it wasnt slipping stop all the audio if (m_WheelEffects[i].PlayingAudio) { m_WheelEffects[i].StopAudio(); } // end the trail generation m_WheelEffects[i].EndSkidTrail(); } } // crude traction control that reduces the power to wheel if the car is wheel spinning too much private void TractionControl() { WheelHit wheelHit; switch (m_CarDriveType) { case CarDriveType.FourWheelDrive: // loop through all wheels for (int i = 0; i < 4; i++) { m_WheelColliders[i].GetGroundHit(out wheelHit); AdjustTorque(wheelHit.forwardSlip); } break; case CarDriveType.RearWheelDrive: m_WheelColliders[2].GetGroundHit(out wheelHit); AdjustTorque(wheelHit.forwardSlip); m_WheelColliders[3].GetGroundHit(out wheelHit); AdjustTorque(wheelHit.forwardSlip); break; case CarDriveType.FrontWheelDrive: m_WheelColliders[0].GetGroundHit(out wheelHit); AdjustTorque(wheelHit.forwardSlip); m_WheelColliders[1].GetGroundHit(out wheelHit); AdjustTorque(wheelHit.forwardSlip); break; } } private void AdjustTorque(float forwardSlip) { if (forwardSlip >= m_SlipLimit && m_CurrentTorque >= 0) { m_CurrentTorque -= 10 * m_TractionControl; } else { m_CurrentTorque += 10 * m_TractionControl; if (m_CurrentTorque > m_FullTorqueOverAllWheels) { m_CurrentTorque = m_FullTorqueOverAllWheels; } } } private bool AnySkidSoundPlaying() { for (int i = 0; i < 4; i++) { if (m_WheelEffects[i].PlayingAudio) { return true; } } return false; } void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info) { if (stream.isWriting) { stream.SendNext(transform.position); stream.SendNext(transform.rotation); stream.SendNext(CurrentSpeed); stream.SendNext(CurrentSteerAngle); stream.SendNext(AccelInput); } else { transform.position = (Vector3)stream.ReceiveNext(); transform.rotation = (Quaternion)stream.ReceiveNext(); CurrentSpeed = (float)stream.ReceiveNext(); CurrentSteerAngle = (float)stream.ReceiveNext(); AccelInput = (float)stream.ReceiveNext(); } } }
36.547074
139
0.552879
[ "Apache-2.0" ]
spuller7/Truck-Project
Assets/Standard Assets/Vehicles/Car/Scripts/CarController.cs
14,363
C#
namespace SOSOWJB.Framework.Editions.Dto { //Mapped in CustomDtoMapper public class LocalizableComboboxItemDto { public string Value { get; set; } public string DisplayText { get; set; } } }
19.9
41
0.743719
[ "Apache-2.0" ]
sosowjb/framework
src/main/SOSOWJB.Framework.Application.Shared/Editions/Dto/LocalizableComboboxItemDto.cs
199
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace IoTConnect.Model { /// <summary> /// Update OTA Status Model /// </summary> public class UpdateOTAStatusModel { /// <summary> /// Device Guid. Call Device.All() method to get list of device. Pass either deviceguid or uniqueid. /// </summary> public string deviceGuid { get; set; } /// <summary> /// unique Id. Call Device.All() method to get list of device. Pass either deviceguid or uniqueid. /// </summary> public string uniqueId { get; set; } [Required(ErrorMessage = "Ota Update Item Guid is Required.")] /// <summary> /// OTA Update Item Guid. Call Firmware.AllOTAupgrade() method to get list of entity. /// </summary> public string otaUpdateItemGuid { get; set; } [Required(ErrorMessage = "Status is Required.")] /// <summary> /// Status. should be Pending/Sent/success/failed/skipped. /// </summary> public string status { get; set; } } }
30.078947
108
0.608924
[ "MIT" ]
iotconnect-apps/AppConnect-AirQualityMonitoring
iot.solution.iotconnect/Model/Firmware/Request/UpdateOTAStatusModel.cs
1,145
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // This RegexNode class is internal to the Regex package. // It is built into a parsed tree for a regular expression. // Implementation notes: // // Since the node tree is a temporary data structure only used // during compilation of the regexp to integer codes, it's // designed for clarity and convenience rather than // space efficiency. // // RegexNodes are built into a tree, linked by the _children list. // Each node also has a _parent and _ichild member indicating // its parent and which child # it is in its parent's list. // // RegexNodes come in as many types as there are constructs in // a regular expression, for example, "concatenate", "alternate", // "one", "rept", "group". There are also node types for basic // peephole optimizations, e.g., "onerep", "notsetrep", etc. // // Because perl 5 allows "lookback" groups that scan backwards, // each node also gets a "direction". Normally the value of // boolean _backward = false. // // During parsing, top-level nodes are also stacked onto a parse // stack (a stack of trees). For this purpose we have a _next // pointer. [Note that to save a few bytes, we could overload the // _parent pointer instead.] // // On the parse stack, each tree has a "role" - basically, the // nonterminal in the grammar that the parser has currently // assigned to the tree. That code is stored in _role. // // Finally, some of the different kinds of nodes have data. // Two integers (for the looping constructs) are stored in // _operands, an object (either a string or a set) // is stored in _data using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Threading; namespace System.Text.RegularExpressions { internal sealed class RegexNode { // RegexNode types // The following are leaves, and correspond to primitive operations public const int Oneloop = RegexCode.Oneloop; // c,n a* public const int Notoneloop = RegexCode.Notoneloop; // c,n .* public const int Setloop = RegexCode.Setloop; // set,n \d* public const int Onelazy = RegexCode.Onelazy; // c,n a*? public const int Notonelazy = RegexCode.Notonelazy; // c,n .*? public const int Setlazy = RegexCode.Setlazy; // set,n \d*? public const int One = RegexCode.One; // char a public const int Notone = RegexCode.Notone; // char . [^a] public const int Set = RegexCode.Set; // set [a-z] \w \s \d public const int Multi = RegexCode.Multi; // string abcdef public const int Ref = RegexCode.Ref; // index \1 public const int Bol = RegexCode.Bol; // ^ public const int Eol = RegexCode.Eol; // $ public const int Boundary = RegexCode.Boundary; // \b public const int NonBoundary = RegexCode.NonBoundary; // \B public const int ECMABoundary = RegexCode.ECMABoundary; // \b public const int NonECMABoundary = RegexCode.NonECMABoundary; // \B public const int Beginning = RegexCode.Beginning; // \A public const int Start = RegexCode.Start; // \G public const int EndZ = RegexCode.EndZ; // \Z public const int End = RegexCode.End; // \z public const int Oneloopatomic = RegexCode.Oneloopatomic; // c,n (?> a*) public const int Notoneloopatomic = RegexCode.Notoneloopatomic; // c,n (?> .*) public const int Setloopatomic = RegexCode.Setloopatomic; // set,n (?> \d*) public const int UpdateBumpalong = RegexCode.UpdateBumpalong; // Interior nodes do not correspond to primitive operations, but // control structures compositing other operations // Concat and alternate take n children, and can run forward or backwards public const int Nothing = 22; // [] public const int Empty = 23; // () public const int Alternate = 24; // a|b public const int Concatenate = 25; // ab public const int Loop = 26; // m,x * + ? {,} public const int Lazyloop = 27; // m,x *? +? ?? {,}? public const int Capture = 28; // n () - capturing group public const int Group = 29; // (?:) - noncapturing group public const int Require = 30; // (?=) (?<=) - lookahead and lookbehind assertions public const int Prevent = 31; // (?!) (?<!) - negative lookahead and lookbehind assertions public const int Atomic = 32; // (?>) - atomic subexpression public const int Testref = 33; // (?(n) | ) - alternation, reference public const int Testgroup = 34; // (?(...) | )- alternation, expression /// <summary>empty bit from the node's options to store data on whether a node contains captures</summary> internal const RegexOptions HasCapturesFlag = (RegexOptions)(1 << 31); private object? Children; public int Type { get; private set; } public string? Str { get; private set; } public char Ch { get; private set; } public int M { get; private set; } public int N { get; private set; } public RegexOptions Options; public RegexNode? Next; public RegexNode(int type, RegexOptions options) { Type = type; Options = options; } public RegexNode(int type, RegexOptions options, char ch) { Type = type; Options = options; Ch = ch; } public RegexNode(int type, RegexOptions options, string str) { Type = type; Options = options; Str = str; } public RegexNode(int type, RegexOptions options, int m) { Type = type; Options = options; M = m; } public RegexNode(int type, RegexOptions options, int m, int n) { Type = type; Options = options; M = m; N = n; } /// <summary>Creates a RegexNode representing a single character.</summary> /// <param name="ch">The character.</param> /// <param name="options">The node's options.</param> /// <param name="culture">The culture to use to perform any required transformations.</param> /// <returns>The created RegexNode. This might be a RegexNode.One or a RegexNode.Set.</returns> public static RegexNode CreateOneWithCaseConversion(char ch, RegexOptions options, CultureInfo? culture) { // If the options specify case-insensitivity, we try to create a node that fully encapsulates that. if ((options & RegexOptions.IgnoreCase) != 0) { Debug.Assert(culture is not null); // If the character is part of a Unicode category that doesn't participate in case conversion, // we can simply strip out the IgnoreCase option and make the node case-sensitive. if (!RegexCharClass.ParticipatesInCaseConversion(ch)) { return new RegexNode(One, options & ~RegexOptions.IgnoreCase, ch); } // Create a set for the character, trying to include all case-insensitive equivalent characters. // If it's successful in doing so, resultIsCaseInsensitive will be false and we can strip // out RegexOptions.IgnoreCase as part of creating the set. string stringSet = RegexCharClass.OneToStringClass(ch, culture, out bool resultIsCaseInsensitive); if (!resultIsCaseInsensitive) { return new RegexNode(Set, options & ~RegexOptions.IgnoreCase, stringSet); } // Otherwise, until we can get rid of ToLower usage at match time entirely (https://github.com/dotnet/runtime/issues/61048), // lowercase the character and proceed to create an IgnoreCase One node. ch = culture.TextInfo.ToLower(ch); } // Create a One node for the character. return new RegexNode(One, options, ch); } /// <summary>Reverses all children of a concatenation when in RightToLeft mode.</summary> public RegexNode ReverseConcatenationIfRightToLeft() { if ((Options & RegexOptions.RightToLeft) != 0 && Type == Concatenate && ChildCount() > 1) { ((List<RegexNode>)Children!).Reverse(); } return this; } /// <summary> /// Pass type as OneLazy or OneLoop /// </summary> private void MakeRep(int type, int min, int max) { Type += type - One; M = min; N = max; } private void MakeLoopAtomic() { switch (Type) { case Oneloop or Notoneloop or Setloop: // For loops, we simply change the Type to the atomic variant. // Atomic greedy loops should consume as many values as they can. Type += Oneloopatomic - Oneloop; break; case Onelazy or Notonelazy or Setlazy: // For lazy, we not only change the Type, we also lower the max number of iterations // to the minimum number of iterations, as they should end up matching as little as possible. Type += Oneloopatomic - Onelazy; N = M; break; default: Debug.Fail($"Unexpected type: {Type}"); break; } } #if DEBUG /// <summary>Validate invariants the rest of the implementation relies on for processing fully-built trees.</summary> [Conditional("DEBUG")] private void ValidateFinalTreeInvariants() { Debug.Assert(Type == Capture, "Every generated tree should begin with a capture node"); var toExamine = new Stack<RegexNode>(); toExamine.Push(this); while (toExamine.Count > 0) { RegexNode node = toExamine.Pop(); // Add all children to be examined int childCount = node.ChildCount(); for (int i = 0; i < childCount; i++) { RegexNode child = node.Child(i); Debug.Assert(child.Next == node, $"{child.Description()} missing reference to parent {node.Description()}"); toExamine.Push(child); } // Validate that we never see certain node types. Debug.Assert(Type != Group, "All Group nodes should have been removed."); // Validate node types and expected child counts. switch (node.Type) { case Group: Debug.Fail("All Group nodes should have been removed."); break; case Beginning: case Bol: case Boundary: case ECMABoundary: case Empty: case End: case EndZ: case Eol: case Multi: case NonBoundary: case NonECMABoundary: case Nothing: case Notone: case Notonelazy: case Notoneloop: case Notoneloopatomic: case One: case Onelazy: case Oneloop: case Oneloopatomic: case Ref: case Set: case Setlazy: case Setloop: case Setloopatomic: case Start: case UpdateBumpalong: Debug.Assert(childCount == 0, $"Expected zero children for {node.TypeName}, got {childCount}."); break; case Atomic: case Capture: case Lazyloop: case Loop: case Prevent: case Require: Debug.Assert(childCount == 1, $"Expected one and only one child for {node.TypeName}, got {childCount}."); break; case Testref: Debug.Assert(childCount is 1 or 2, $"Expected one or two children for {node.TypeName}, got {childCount}"); break; case Testgroup: Debug.Assert(childCount is 2 or 3, $"Expected two or three children for {node.TypeName}, got {childCount}"); break; case Concatenate: case Alternate: Debug.Assert(childCount >= 2, $"Expected at least two children for {node.TypeName}, got {childCount}."); break; default: Debug.Fail($"Unexpected node type: {node.Type}"); break; } // Validate node configuration. switch (node.Type) { case Multi: Debug.Assert(node.Str is not null, "Expect non-null multi string"); Debug.Assert(node.Str.Length >= 2, $"Expected {node.Str} to be at least two characters"); break; case Set: case Setloop: case Setloopatomic: case Setlazy: Debug.Assert(!string.IsNullOrEmpty(node.Str), $"Expected non-null, non-empty string for {node.TypeName}."); break; default: Debug.Assert(node.Str is null, $"Expected null string for {node.TypeName}, got \"{node.Str}\"."); break; } } } #endif /// <summary>Performs additional optimizations on an entire tree prior to being used.</summary> /// <remarks> /// Some optimizations are performed by the parser while parsing, and others are performed /// as nodes are being added to the tree. The optimizations here expect the tree to be fully /// formed, as they inspect relationships between nodes that may not have been in place as /// individual nodes were being processed/added to the tree. /// </remarks> internal RegexNode FinalOptimize() { RegexNode rootNode = this; Debug.Assert(rootNode.Type == Capture); Debug.Assert(rootNode.Next is null); Debug.Assert(rootNode.ChildCount() == 1); if ((Options & RegexOptions.RightToLeft) == 0) // only apply optimization when LTR to avoid needing additional code for the rarer RTL case { // Optimization: backtracking removal at expression end. // If we find backtracking construct at the end of the regex, we can instead make it non-backtracking, // since nothing would ever backtrack into it anyway. Doing this then makes the construct available // to implementations that don't support backtracking. rootNode.EliminateEndingBacktracking(); // Optimization: unnecessary re-processing of starting loops. // If an expression is guaranteed to begin with a single-character unbounded loop that isn't part of an alternation (in which case it // wouldn't be guaranteed to be at the beginning) or a capture (in which case a back reference could be influenced by its length), then we // can update the tree with a temporary node to indicate that the implementation should use that node's ending position in the input text // as the next starting position at which to start the next match. This avoids redoing matches we've already performed, e.g. matching // "\w+@dot.net" against "is this a valid address@dot.net", the \w+ will initially match the "is" and then will fail to match the "@". // Rather than bumping the scan loop by 1 and trying again to match at the "s", we can instead start at the " ". For functional correctness // we can only consider unbounded loops, as to be able to start at the end of the loop we need the loop to have consumed all possible matches; // otherwise, you could end up with a pattern like "a{1,3}b" matching against "aaaabc", which should match, but if we pre-emptively stop consuming // after the first three a's and re-start from that position, we'll end up failing the match even though it should have succeeded. We can also // apply this optimization to non-atomic loops. Even though backtracking could be necessary, such backtracking would be handled within the processing // of a single starting position. { RegexNode node = rootNode.Child(0); // skip implicit root capture node while (true) { switch (node.Type) { case Atomic: case Concatenate: node = node.Child(0); continue; case Oneloop when node.N == int.MaxValue: case Oneloopatomic when node.N == int.MaxValue: case Notoneloop when node.N == int.MaxValue: case Notoneloopatomic when node.N == int.MaxValue: case Setloop when node.N == int.MaxValue: case Setloopatomic when node.N == int.MaxValue: RegexNode? parent = node.Next; if (parent != null && parent.Type == Concatenate) { parent.InsertChild(1, new RegexNode(UpdateBumpalong, node.Options)); } break; } break; } } } // Done optimizing. Return the final tree. #if DEBUG rootNode.ValidateFinalTreeInvariants(); #endif return rootNode; } /// <summary>Converts nodes at the end of the node tree to be atomic.</summary> /// <remarks> /// The correctness of this optimization depends on nothing being able to backtrack into /// the provided node. That means it must be at the root of the overall expression, or /// it must be an Atomic node that nothing will backtrack into by the very nature of Atomic. /// </remarks> private void EliminateEndingBacktracking() { if (!StackHelper.TryEnsureSufficientExecutionStack()) { // If we can't recur further, just stop optimizing. return; } // RegexOptions.NonBacktracking doesn't support atomic groups, so when that option // is set we don't want to create atomic groups where they weren't explicitly authored. if ((Options & RegexOptions.NonBacktracking) != 0) { return; } // Walk the tree starting from the current node. RegexNode node = this; while (true) { switch (node.Type) { // {One/Notone/Set}loops can be upgraded to {One/Notone/Set}loopatomic nodes, e.g. [abc]* => (?>[abc]*). // And {One/Notone/Set}lazys can similarly be upgraded to be atomic, which really makes them into repeaters // or even empty nodes. case Oneloop: case Notoneloop: case Setloop: case Onelazy: case Notonelazy: case Setlazy: node.MakeLoopAtomic(); break; // Just because a particular node is atomic doesn't mean all its descendants are. // Process them as well. case Atomic: node = node.Child(0); continue; // For Capture and Concatenate, we just recur into their last child (only child in the case // of Capture). However, if the child is Alternate, Loop, and Lazyloop, we can also make the // node itself atomic by wrapping it in an Atomic node. Since we later check to see whether a // node is atomic based on its parent or grandparent, we don't bother wrapping such a node in // an Atomic one if its grandparent is already Atomic. // e.g. [xyz](?:abc|def) => [xyz](?>abc|def) case Capture: case Concatenate: RegexNode existingChild = node.Child(node.ChildCount() - 1); if ((existingChild.Type == Alternate || existingChild.Type == Loop || existingChild.Type == Lazyloop) && (node.Next is null || node.Next.Type != Atomic)) // validate grandparent isn't atomic { var atomic = new RegexNode(Atomic, existingChild.Options); atomic.AddChild(existingChild); node.ReplaceChild(node.ChildCount() - 1, atomic); } node = existingChild; continue; // For alternate, we can recur into each branch separately. We use this iteration for the first branch. // e.g. abc*|def* => ab(?>c*)|de(?>f*) case Alternate: { int branches = node.ChildCount(); for (int i = 1; i < branches; i++) { node.Child(i).EliminateEndingBacktracking(); } } node = node.Child(0); continue; // For Loop, we search to see if there's a viable last expression, and iff there // is we recur into processing it. // e.g. (?:abc*)* => (?:ab(?>c*))* case Loop: { RegexNode? loopDescendent = node.FindLastExpressionInLoopForAutoAtomic(); if (loopDescendent != null) { node = loopDescendent; continue; // loop around to process node } } break; } break; } } /// <summary>Whether this node may be considered to be atomic based on its parent.</summary> /// <remarks> /// This may have false negatives, meaning the node may actually be atomic even if this returns false. /// But any true result may be relied on to mean the node will actually be considered to be atomic. /// </remarks> public bool IsAtomicByParent() { // Walk up the parent hierarchy. RegexNode child = this; for (RegexNode? parent = child.Next; parent is not null; child = parent, parent = child.Next) { switch (parent.Type) { case Atomic: case Prevent: case Require: // If the parent is atomic, so is the child. That's the whole purpose // of the Atomic node, and lookarounds are also implicitly atomic. return true; case Alternate: case Testref: // Skip alternations. Each branch is considered independently, // so any atomicity applied to the alternation also applies to // each individual branch. This is true as well for conditional // backreferences, where each of the yes/no branches are independent. case Testgroup when parent.Child(0) != child: // As with alternations, each yes/no branch of an expression conditional // are independent from each other, but the conditional expression itself // can be backtracked into from each of the branches, so we can't make // it atomic just because the whole conditional is. case Capture: // Skip captures. They don't affect atomicity. case Concatenate when parent.Child(parent.ChildCount() - 1) == child: // If the parent is a concatenation and this is the last node, // any atomicity applying to the concatenation applies to this // node, too. continue; default: // For any other parent type, give up on trying to prove atomicity. return false; } } // The parent was null, so nothing can backtrack in. return true; } /// <summary> /// Removes redundant nodes from the subtree, and returns an optimized subtree. /// </summary> internal RegexNode Reduce() { switch (Type) { case Alternate: return ReduceAlternation(); case Concatenate: return ReduceConcatenation(); case Loop: case Lazyloop: return ReduceLoops(); case Atomic: return ReduceAtomic(); case Group: return ReduceGroup(); case Set: case Setloop: case Setloopatomic: case Setlazy: return ReduceSet(); case Prevent: return ReducePrevent(); default: return this; } } /// <summary>Remove an unnecessary Concatenation or Alternation node</summary> /// <remarks> /// Simple optimization for a concatenation or alternation: /// - if the node has only one child, use it instead /// - if the node has zero children, turn it into an empty with the specified empty type /// </remarks> private RegexNode ReplaceNodeIfUnnecessary(int emptyTypeIfNoChildren) { Debug.Assert( (Type == Alternate && emptyTypeIfNoChildren == Nothing) || (Type == Concatenate && emptyTypeIfNoChildren == Empty)); return ChildCount() switch { 0 => new RegexNode(emptyTypeIfNoChildren, Options), 1 => Child(0), _ => this, }; } /// <summary>Remove all non-capturing groups.</summary> /// <remark> /// Simple optimization: once parsed into a tree, non-capturing groups /// serve no function, so strip them out. /// e.g. (?:(?:(?:abc))) => abc /// </remark> private RegexNode ReduceGroup() { Debug.Assert(Type == Group); RegexNode u = this; while (u.Type == Group) { Debug.Assert(u.ChildCount() == 1); u = u.Child(0); } return u; } /// <summary> /// Remove unnecessary atomic nodes, and make appropriate descendents of the atomic node themselves atomic. /// </summary> /// <remarks> /// e.g. (?>(?>(?>a*))) => (?>a*) /// e.g. (?>(abc*)*) => (?>(abc(?>c*))*) /// </remarks> private RegexNode ReduceAtomic() { // RegexOptions.NonBacktracking doesn't support atomic groups, so when that option // is set we don't want to create atomic groups where they weren't explicitly authored. if ((Options & RegexOptions.NonBacktracking) != 0) { return this; } Debug.Assert(Type == Atomic); Debug.Assert(ChildCount() == 1); RegexNode atomic = this; RegexNode child = Child(0); while (child.Type == Atomic) { atomic = child; child = atomic.Child(0); } switch (child.Type) { // If the child is already atomic, we can just remove the atomic node. case Oneloopatomic: case Notoneloopatomic: case Setloopatomic: return child; // If an atomic subexpression contains only a {one/notone/set}{loop/lazy}, // change it to be an {one/notone/set}loopatomic and remove the atomic node. case Oneloop: case Notoneloop: case Setloop: case Onelazy: case Notonelazy: case Setlazy: child.MakeLoopAtomic(); return child; // Alternations have a variety of possible optimizations that can be applied // iff they're atomic. case Alternate: if ((Options & RegexOptions.RightToLeft) == 0) { List<RegexNode>? branches = child.Children as List<RegexNode>; Debug.Assert(branches is not null && branches.Count != 0); // If an alternation is atomic and its first branch is Empty, the whole thing // is a nop, as Empty will match everything trivially, and no backtracking // into the node will be performed, making the remaining branches irrelevant. if (branches[0].Type == Empty) { return new RegexNode(Empty, child.Options); } // Similarly, we can trim off any branches after an Empty, as they'll never be used. // An Empty will match anything, and thus branches after that would only be used // if we backtracked into it and advanced passed the Empty after trying the Empty... // but if the alternation is atomic, such backtracking won't happen. for (int i = 1; i < branches.Count - 1; i++) { if (branches[i].Type == Empty) { branches.RemoveRange(i + 1, branches.Count - (i + 1)); break; } } // If an alternation is atomic, we won't ever backtrack back into it, which // means order matters but not repetition. With backtracking, it would be incorrect // to convert an expression like "hi|there|hello" into "hi|hello|there", as doing // so could then change the order of results if we matched "hi" and then failed // based on what came after it, and both "hello" and "there" could be successful // with what came later. But without backtracking, we can reorder "hi|there|hello" // to instead be "hi|hello|there", as "hello" and "there" can't match the same text, // and once this atomic alternation has matched, we won't try another branch. This // reordering is valuable as it then enables further optimizations, e.g. // "hi|there|hello" => "hi|hello|there" => "h(?:i|ello)|there", which means we only // need to check the 'h' once in case it's not an 'h', and it's easier to employ different // code gen that, for example, switches on first character of the branches, enabling faster // choice of branch without always having to walk through each. bool reordered = false; for (int start = 0; start < branches.Count; start++) { // Get the node that may start our range. If it's a one, multi, or concat of those, proceed. RegexNode startNode = branches[start]; if (startNode.FindBranchOneOrMultiStart() is null) { continue; } // Find the contiguous range of nodes from this point that are similarly one, multi, or concat of those. int endExclusive = start + 1; while (endExclusive < branches.Count && branches[endExclusive].FindBranchOneOrMultiStart() is not null) { endExclusive++; } // If there's at least 3, there may be something to reorder (we won't reorder anything // before the starting position, and so only 2 items is considered ordered). if (endExclusive - start >= 3) { int compare = start; while (compare < endExclusive) { // Get the starting character char c = branches[compare].FindBranchOneOrMultiStart()!.FirstCharOfOneOrMulti(); // Move compare to point to the last branch that has the same starting value. while (compare < endExclusive && branches[compare].FindBranchOneOrMultiStart()!.FirstCharOfOneOrMulti() == c) { compare++; } // Compare now points to the first node that doesn't match the starting node. // If we've walked off our range, there's nothing left to reorder. if (compare < endExclusive) { // There may be something to reorder. See if there are any other nodes that begin with the same character. for (int next = compare + 1; next < endExclusive; next++) { RegexNode nextChild = branches[next]; if (nextChild.FindBranchOneOrMultiStart()!.FirstCharOfOneOrMulti() == c) { branches.RemoveAt(next); branches.Insert(compare++, nextChild); reordered = true; } } } } } // Move to the end of the range we've now explored. endExclusive is not a viable // starting position either, and the start++ for the loop will thus take us to // the next potential place to start a range. start = endExclusive; } // If anything we reordered, there may be new optimization opportunities inside // of the alternation, so reduce it again. if (reordered) { atomic.ReplaceChild(0, child); child = atomic.Child(0); } } goto default; // For everything else, try to reduce ending backtracking of the last contained expression. default: child.EliminateEndingBacktracking(); return atomic; } } /// <summary>Combine nested loops where applicable.</summary> /// <remarks> /// Nested repeaters just get multiplied with each other if they're not too lumpy. /// Other optimizations may have also resulted in {Lazy}loops directly containing /// sets, ones, and notones, in which case they can be transformed into the corresponding /// individual looping constructs. /// </remarks> private RegexNode ReduceLoops() { Debug.Assert(Type == Loop || Type == Lazyloop); RegexNode u = this; int type = Type; int min = M; int max = N; while (u.ChildCount() > 0) { RegexNode child = u.Child(0); // multiply reps of the same type only if (child.Type != type) { bool valid = false; if (type == Loop) { switch (child.Type) { case Oneloop: case Oneloopatomic: case Notoneloop: case Notoneloopatomic: case Setloop: case Setloopatomic: valid = true; break; } } else // type == Lazyloop { switch (child.Type) { case Onelazy: case Notonelazy: case Setlazy: valid = true; break; } } if (!valid) { break; } } // child can be too lumpy to blur, e.g., (a {100,105}) {3} or (a {2,})? // [but things like (a {2,})+ are not too lumpy...] if (u.M == 0 && child.M > 1 || child.N < child.M * 2) { break; } u = child; if (u.M > 0) { u.M = min = ((int.MaxValue - 1) / u.M < min) ? int.MaxValue : u.M * min; } if (u.N > 0) { u.N = max = ((int.MaxValue - 1) / u.N < max) ? int.MaxValue : u.N * max; } } if (min == int.MaxValue) { return new RegexNode(Nothing, Options); } // If the Loop or Lazyloop now only has one child node and its a Set, One, or Notone, // reduce to just Setloop/lazy, Oneloop/lazy, or Notoneloop/lazy. The parser will // generally have only produced the latter, but other reductions could have exposed // this. if (u.ChildCount() == 1) { RegexNode child = u.Child(0); switch (child.Type) { case One: case Notone: case Set: child.MakeRep(u.Type == Lazyloop ? Onelazy : Oneloop, u.M, u.N); u = child; break; } } return u; } /// <summary> /// Reduces set-related nodes to simpler one-related and notone-related nodes, where applicable. /// </summary> /// <remarks> /// e.g. /// [a] => a /// [a]* => a* /// [a]*? => a*? /// (?>[a]*) => (?>a*) /// [^a] => ^a /// []* => Nothing /// </remarks> private RegexNode ReduceSet() { // Extract empty-set, one, and not-one case as special Debug.Assert(Type == Set || Type == Setloop || Type == Setloopatomic || Type == Setlazy); Debug.Assert(!string.IsNullOrEmpty(Str)); if (RegexCharClass.IsEmpty(Str)) { Type = Nothing; Str = null; } else if (RegexCharClass.IsSingleton(Str)) { Ch = RegexCharClass.SingletonChar(Str); Str = null; Type = Type == Set ? One : Type == Setloop ? Oneloop : Type == Setloopatomic ? Oneloopatomic : Onelazy; } else if (RegexCharClass.IsSingletonInverse(Str)) { Ch = RegexCharClass.SingletonChar(Str); Str = null; Type = Type == Set ? Notone : Type == Setloop ? Notoneloop : Type == Setloopatomic ? Notoneloopatomic : Notonelazy; } return this; } /// <summary>Optimize an alternation.</summary> private RegexNode ReduceAlternation() { Debug.Assert(Type == Alternate); switch (ChildCount()) { case 0: return new RegexNode(Nothing, Options); case 1: return Child(0); default: ReduceSingleLetterAndNestedAlternations(); RegexNode node = ReplaceNodeIfUnnecessary(Nothing); node = ExtractCommonPrefixText(node); node = ExtractCommonPrefixOneNotoneSet(node); return node; } // This function performs two optimizations: // - Single-letter alternations can be replaced by faster set specifications // e.g. "a|b|c|def|g|h" -> "[a-c]|def|[gh]" // - Nested alternations with no intervening operators can be flattened: // e.g. "apple|(?:orange|pear)|grape" -> "apple|orange|pear|grape" void ReduceSingleLetterAndNestedAlternations() { bool wasLastSet = false; bool lastNodeCannotMerge = false; RegexOptions optionsLast = 0; RegexOptions optionsAt; int i; int j; RegexNode at; RegexNode prev; List<RegexNode> children = (List<RegexNode>)Children!; for (i = 0, j = 0; i < children.Count; i++, j++) { at = children[i]; if (j < i) children[j] = at; while (true) { if (at.Type == Alternate) { if (at.Children is List<RegexNode> atChildren) { for (int k = 0; k < atChildren.Count; k++) { atChildren[k].Next = this; } children.InsertRange(i + 1, atChildren); } else { RegexNode atChild = (RegexNode)at.Children!; atChild.Next = this; children.Insert(i + 1, atChild); } j--; } else if (at.Type == Set || at.Type == One) { // Cannot merge sets if L or I options differ, or if either are negated. optionsAt = at.Options & (RegexOptions.RightToLeft | RegexOptions.IgnoreCase); if (at.Type == Set) { if (!wasLastSet || optionsLast != optionsAt || lastNodeCannotMerge || !RegexCharClass.IsMergeable(at.Str!)) { wasLastSet = true; lastNodeCannotMerge = !RegexCharClass.IsMergeable(at.Str!); optionsLast = optionsAt; break; } } else if (!wasLastSet || optionsLast != optionsAt || lastNodeCannotMerge) { wasLastSet = true; lastNodeCannotMerge = false; optionsLast = optionsAt; break; } // The last node was a Set or a One, we're a Set or One and our options are the same. // Merge the two nodes. j--; prev = children[j]; RegexCharClass prevCharClass; if (prev.Type == One) { prevCharClass = new RegexCharClass(); prevCharClass.AddChar(prev.Ch); } else { prevCharClass = RegexCharClass.Parse(prev.Str!); } if (at.Type == One) { prevCharClass.AddChar(at.Ch); } else { RegexCharClass atCharClass = RegexCharClass.Parse(at.Str!); prevCharClass.AddCharClass(atCharClass); } prev.Type = Set; prev.Str = prevCharClass.ToStringClass(Options); if ((prev.Options & RegexOptions.IgnoreCase) != 0 && RegexCharClass.MakeCaseSensitiveIfPossible(prev.Str, RegexParser.GetTargetCulture(prev.Options)) is string newSetString) { prev.Str = newSetString; prev.Options &= ~RegexOptions.IgnoreCase; } } else if (at.Type == Nothing) { j--; } else { wasLastSet = false; lastNodeCannotMerge = false; } break; } } if (j < i) { children.RemoveRange(j, i - j); } } // This function optimizes out prefix nodes from alternation branches that are // the same across multiple contiguous branches. // e.g. \w12|\d34|\d56|\w78|\w90 => \w12|\d(?:34|56)|\w(?:78|90) static RegexNode ExtractCommonPrefixOneNotoneSet(RegexNode alternation) { if (alternation.Type != Alternate) { return alternation; } Debug.Assert(alternation.Children is List<RegexNode> { Count: >= 2 }); var children = (List<RegexNode>)alternation.Children; // Only process left-to-right prefixes. if ((alternation.Options & RegexOptions.RightToLeft) != 0) { return alternation; } // Only handle the case where each branch is a concatenation foreach (RegexNode child in children) { if (child.Type != Concatenate || child.ChildCount() < 2) { return alternation; } } for (int startingIndex = 0; startingIndex < children.Count - 1; startingIndex++) { Debug.Assert(children[startingIndex].Children is List<RegexNode> { Count: >= 2 }); // Only handle the case where each branch begins with the same One, Notone, or Set (individual or loop). // Note that while we can do this for individual characters, fixed length loops, and atomic loops, doing // it for non-atomic variable length loops could change behavior as each branch could otherwise have a // different number of characters consumed by the loop based on what's after it. RegexNode required = children[startingIndex].Child(0); switch (required.Type) { case One or Notone or Set: case Oneloopatomic or Notoneloopatomic or Setloopatomic: case Oneloop or Notoneloop or Setloop or Onelazy or Notonelazy or Setlazy when required.M == required.N: break; default: continue; } // Only handle the case where each branch begins with the exact same node value int endingIndex = startingIndex + 1; for (; endingIndex < children.Count; endingIndex++) { RegexNode other = children[endingIndex].Child(0); if (required.Type != other.Type || required.Options != other.Options || required.M != other.M || required.N != other.N || required.Ch != other.Ch || required.Str != other.Str) { break; } } if (endingIndex - startingIndex <= 1) { // Nothing to extract from this starting index. continue; } // Remove the prefix node from every branch, adding it to a new alternation var newAlternate = new RegexNode(Alternate, alternation.Options); for (int i = startingIndex; i < endingIndex; i++) { ((List<RegexNode>)children[i].Children!).RemoveAt(0); newAlternate.AddChild(children[i]); } // If this alternation is wrapped as atomic, we need to do the same for the new alternation. if (alternation.Next is RegexNode parent && parent.Type == Atomic) { var atomic = new RegexNode(Atomic, alternation.Options); atomic.AddChild(newAlternate); newAlternate = atomic; } // Now create a concatenation of the prefix node with the new alternation for the combined // branches, and replace all of the branches in this alternation with that new concatenation. var newConcat = new RegexNode(Concatenate, alternation.Options); newConcat.AddChild(required); newConcat.AddChild(newAlternate); alternation.ReplaceChild(startingIndex, newConcat); children.RemoveRange(startingIndex + 1, endingIndex - startingIndex - 1); } // If we've reduced this alternation to just a single branch, return it. // Otherwise, return the alternation. return alternation.ChildCount() == 1 ? alternation.Child(0) : alternation; } // Analyzes all the branches of the alternation for text that's identical at the beginning // of every branch. That text is then pulled out into its own one or multi node in a // concatenation with the alternation (whose branches are updated to remove that prefix). // This is valuable for a few reasons. One, it exposes potentially more text to the // expression prefix analyzer used to influence FindFirstChar. Second, it exposes more // potential alternation optimizations, e.g. if the same prefix is followed in two branches // by sets that can be merged. Third, it reduces the amount of duplicated comparisons required // if we end up backtracking into subsequent branches. // e.g. abc|ade => a(?bc|de) static RegexNode ExtractCommonPrefixText(RegexNode alternation) { if (alternation.Type != Alternate) { return alternation; } Debug.Assert(alternation.Children is List<RegexNode> { Count: >= 2 }); var children = (List<RegexNode>)alternation.Children; // To keep things relatively simple, we currently only handle: // - Left to right (e.g. we don't process alternations in lookbehinds) // - Branches that are one or multi nodes, or that are concatenations beginning with one or multi nodes. // - All branches having the same options. // Only extract left-to-right prefixes. if ((alternation.Options & RegexOptions.RightToLeft) != 0) { return alternation; } Span<char> scratchChar = stackalloc char[1]; ReadOnlySpan<char> startingSpan = stackalloc char[0]; for (int startingIndex = 0; startingIndex < children.Count - 1; startingIndex++) { // Process the first branch to get the maximum possible common string. RegexNode? startingNode = children[startingIndex].FindBranchOneOrMultiStart(); if (startingNode is null) { return alternation; } RegexOptions startingNodeOptions = startingNode.Options; startingSpan = startingNode.Str.AsSpan(); if (startingNode.Type == One) { scratchChar[0] = startingNode.Ch; startingSpan = scratchChar; } Debug.Assert(startingSpan.Length > 0); // Now compare the rest of the branches against it. int endingIndex = startingIndex + 1; for ( ; endingIndex < children.Count; endingIndex++) { // Get the starting node of the next branch. startingNode = children[endingIndex].FindBranchOneOrMultiStart(); if (startingNode is null || startingNode.Options != startingNodeOptions) { break; } // See if the new branch's prefix has a shared prefix with the current one. // If it does, shorten to that; if it doesn't, bail. if (startingNode.Type == One) { if (startingSpan[0] != startingNode.Ch) { break; } if (startingSpan.Length != 1) { startingSpan = startingSpan.Slice(0, 1); } } else { Debug.Assert(startingNode.Type == Multi); Debug.Assert(startingNode.Str!.Length > 0); int minLength = Math.Min(startingSpan.Length, startingNode.Str.Length); int c = 0; while (c < minLength && startingSpan[c] == startingNode.Str[c]) c++; if (c == 0) { break; } startingSpan = startingSpan.Slice(0, c); } } // When we get here, we have a starting string prefix shared by all branches // in the range [startingIndex, endingIndex). if (endingIndex - startingIndex <= 1) { // There's nothing to consolidate for this starting node. continue; } // We should be able to consolidate something for the nodes in the range [startingIndex, endingIndex). Debug.Assert(startingSpan.Length > 0); // Create a new node of the form: // Concatenation(prefix, Alternation(each | node | with | prefix | removed)) // that replaces all these branches in this alternation. var prefix = startingSpan.Length == 1 ? new RegexNode(One, startingNodeOptions, startingSpan[0]) : new RegexNode(Multi, startingNodeOptions, startingSpan.ToString()); var newAlternate = new RegexNode(Alternate, startingNodeOptions); bool seenEmpty = false; for (int i = startingIndex; i < endingIndex; i++) { RegexNode branch = children[i]; ProcessOneOrMulti(branch.Type == Concatenate ? branch.Child(0) : branch, startingSpan); branch = branch.Reduce(); if (branch.Type == Empty) { if (seenEmpty) { continue; } seenEmpty = true; } newAlternate.AddChild(branch); // Remove the starting text from the one or multi node. This may end up changing // the type of the node to be Empty if the starting text matches the node's full value. static void ProcessOneOrMulti(RegexNode node, ReadOnlySpan<char> startingSpan) { if (node.Type == One) { Debug.Assert(startingSpan.Length == 1); Debug.Assert(startingSpan[0] == node.Ch); node.Type = Empty; node.Ch = '\0'; } else { Debug.Assert(node.Type == Multi); Debug.Assert(node.Str.AsSpan().StartsWith(startingSpan, StringComparison.Ordinal)); if (node.Str!.Length == startingSpan.Length) { node.Type = Empty; node.Str = null; } else if (node.Str.Length - 1 == startingSpan.Length) { node.Type = One; node.Ch = node.Str[node.Str.Length - 1]; node.Str = null; } else { node.Str = node.Str.Substring(startingSpan.Length); } } } } if (alternation.Next is RegexNode parent && parent.Type == Atomic) { var atomic = new RegexNode(Atomic, startingNodeOptions); atomic.AddChild(newAlternate); newAlternate = atomic; } var newConcat = new RegexNode(Concatenate, startingNodeOptions); newConcat.AddChild(prefix); newConcat.AddChild(newAlternate); alternation.ReplaceChild(startingIndex, newConcat); children.RemoveRange(startingIndex + 1, endingIndex - startingIndex - 1); } return alternation.ChildCount() == 1 ? alternation.Child(0) : alternation; } } /// <summary> /// Finds the starting one or multi of the branch, if it has one; otherwise, returns null. /// For simplicity, this only considers branches that are One or Multi, or a Concatenation /// beginning with a One or Multi. We don't traverse more than one level to avoid the /// complication of then having to later update that hierarchy when removing the prefix, /// but it could be done in the future if proven beneficial enough. /// </summary> public RegexNode? FindBranchOneOrMultiStart() { RegexNode branch = this; if (branch.Type == Concatenate) { branch = branch.Child(0); } return branch.Type == One || branch.Type == Multi ? branch : null; } /// <summary>Gets the character that begins a One or Multi.</summary> public char FirstCharOfOneOrMulti() { Debug.Assert(Type is One or Multi); Debug.Assert((Options & RegexOptions.RightToLeft) == 0); return Type == One ? Ch : Str![0]; } /// <summary>Finds the guaranteed beginning character of the node, or null if none exists.</summary> public char? FindStartingCharacter() { RegexNode? node = this; while (true) { if (node is null || (node.Options & RegexOptions.RightToLeft) != 0) { return null; } char c; switch (node.Type) { case One: case Oneloop or Oneloopatomic or Onelazy when node.M > 0: c = node.Ch; break; case Multi: c = node.Str![0]; break; case Atomic: case Concatenate: case Capture: case Group: case Loop or Lazyloop when node.M > 0: case Require: node = node.Child(0); continue; default: return null; } if ((node.Options & RegexOptions.IgnoreCase) == 0 || !RegexCharClass.ParticipatesInCaseConversion(c)) { return c; } return null; } } /// <summary> /// Optimizes a concatenation by coalescing adjacent characters and strings, /// coalescing adjacent loops, converting loops to be atomic where applicable, /// and removing the concatenation itself if it's unnecessary. /// </summary> private RegexNode ReduceConcatenation() { Debug.Assert(Type == Concatenate); // If the concat node has zero or only one child, get rid of the concat. switch (ChildCount()) { case 0: return new RegexNode(Empty, Options); case 1: return Child(0); } // Coalesce adjacent characters/strings. ReduceConcatenationWithAdjacentStrings(); // Coalesce adjacent loops. This helps to minimize work done by the interpreter, minimize code gen, // and also help to reduce catastrophic backtracking. ReduceConcatenationWithAdjacentLoops(); // Now convert as many loops as possible to be atomic to avoid unnecessary backtracking. if ((Options & RegexOptions.RightToLeft) == 0) { ReduceConcatenationWithAutoAtomic(); } // If the concatenation is now empty, return an empty node, or if it's got a single child, return that child. // Otherwise, return this. return ReplaceNodeIfUnnecessary(Empty); } /// <summary> /// Combine adjacent characters/strings. /// e.g. (?:abc)(?:def) -> abcdef /// </summary> private void ReduceConcatenationWithAdjacentStrings() { Debug.Assert(Type == Concatenate); Debug.Assert(Children is List<RegexNode>); bool wasLastString = false; RegexOptions optionsLast = 0; int i, j; List<RegexNode> children = (List<RegexNode>)Children!; for (i = 0, j = 0; i < children.Count; i++, j++) { RegexNode at = children[i]; if (j < i) { children[j] = at; } if (at.Type == Concatenate && ((at.Options & RegexOptions.RightToLeft) == (Options & RegexOptions.RightToLeft))) { if (at.Children is List<RegexNode> atChildren) { for (int k = 0; k < atChildren.Count; k++) { atChildren[k].Next = this; } children.InsertRange(i + 1, atChildren); } else { RegexNode atChild = (RegexNode)at.Children!; atChild.Next = this; children.Insert(i + 1, atChild); } j--; } else if (at.Type == Multi || at.Type == One) { // Cannot merge strings if L or I options differ RegexOptions optionsAt = at.Options & (RegexOptions.RightToLeft | RegexOptions.IgnoreCase); if (!wasLastString || optionsLast != optionsAt) { wasLastString = true; optionsLast = optionsAt; continue; } RegexNode prev = children[--j]; if (prev.Type == One) { prev.Type = Multi; prev.Str = prev.Ch.ToString(); } if ((optionsAt & RegexOptions.RightToLeft) == 0) { prev.Str = (at.Type == One) ? $"{prev.Str}{at.Ch}" : prev.Str + at.Str; } else { prev.Str = (at.Type == One) ? $"{at.Ch}{prev.Str}" : at.Str + prev.Str; } } else if (at.Type == Empty) { j--; } else { wasLastString = false; } } if (j < i) { children.RemoveRange(j, i - j); } } /// <summary> /// Combine adjacent loops. /// e.g. a*a*a* => a* /// </summary> private void ReduceConcatenationWithAdjacentLoops() { Debug.Assert(Type == Concatenate); Debug.Assert(Children is List<RegexNode>); var children = (List<RegexNode>)Children!; int current = 0, next = 1, nextSave = 1; while (next < children.Count) { RegexNode currentNode = children[current]; RegexNode nextNode = children[next]; if (currentNode.Options == nextNode.Options) { static bool CanCombineCounts(int nodeMin, int nodeMax, int nextMin, int nextMax) { // We shouldn't have an infinite minimum; bail if we find one. Also check for the // degenerate case where we'd make the min overflow or go infinite when it wasn't already. if (nodeMin == int.MaxValue || nextMin == int.MaxValue || (uint)nodeMin + (uint)nextMin >= int.MaxValue) { return false; } // Similar overflow / go infinite check for max (which can be infinite). if (nodeMax != int.MaxValue && nextMax != int.MaxValue && (uint)nodeMax + (uint)nextMax >= int.MaxValue) { return false; } return true; } switch (currentNode.Type) { // Coalescing a loop with its same type case Oneloop when nextNode.Type == Oneloop && currentNode.Ch == nextNode.Ch: case Oneloopatomic when nextNode.Type == Oneloopatomic && currentNode.Ch == nextNode.Ch: case Onelazy when nextNode.Type == Onelazy && currentNode.Ch == nextNode.Ch: case Notoneloop when nextNode.Type == Notoneloop && currentNode.Ch == nextNode.Ch: case Notoneloopatomic when nextNode.Type == Notoneloopatomic && currentNode.Ch == nextNode.Ch: case Notonelazy when nextNode.Type == Notonelazy && currentNode.Ch == nextNode.Ch: case Setloop when nextNode.Type == Setloop && currentNode.Str == nextNode.Str: case Setloopatomic when nextNode.Type == Setloopatomic && currentNode.Str == nextNode.Str: case Setlazy when nextNode.Type == Setlazy && currentNode.Str == nextNode.Str: if (CanCombineCounts(currentNode.M, currentNode.N, nextNode.M, nextNode.N)) { currentNode.M += nextNode.M; if (currentNode.N != int.MaxValue) { currentNode.N = nextNode.N == int.MaxValue ? int.MaxValue : currentNode.N + nextNode.N; } next++; continue; } break; // Coalescing a loop with an additional item of the same type case Oneloop when nextNode.Type == One && currentNode.Ch == nextNode.Ch: case Oneloopatomic when nextNode.Type == One && currentNode.Ch == nextNode.Ch: case Onelazy when nextNode.Type == One && currentNode.Ch == nextNode.Ch: case Notoneloop when nextNode.Type == Notone && currentNode.Ch == nextNode.Ch: case Notoneloopatomic when nextNode.Type == Notone && currentNode.Ch == nextNode.Ch: case Notonelazy when nextNode.Type == Notone && currentNode.Ch == nextNode.Ch: case Setloop when nextNode.Type == Set && currentNode.Str == nextNode.Str: case Setloopatomic when nextNode.Type == Set && currentNode.Str == nextNode.Str: case Setlazy when nextNode.Type == Set && currentNode.Str == nextNode.Str: if (CanCombineCounts(currentNode.M, currentNode.N, 1, 1)) { currentNode.M++; if (currentNode.N != int.MaxValue) { currentNode.N++; } next++; continue; } break; // Coalescing an individual item with a loop. case One when (nextNode.Type == Oneloop || nextNode.Type == Oneloopatomic || nextNode.Type == Onelazy) && currentNode.Ch == nextNode.Ch: case Notone when (nextNode.Type == Notoneloop || nextNode.Type == Notoneloopatomic || nextNode.Type == Notonelazy) && currentNode.Ch == nextNode.Ch: case Set when (nextNode.Type == Setloop || nextNode.Type == Setloopatomic || nextNode.Type == Setlazy) && currentNode.Str == nextNode.Str: if (CanCombineCounts(1, 1, nextNode.M, nextNode.N)) { currentNode.Type = nextNode.Type; currentNode.M = nextNode.M + 1; currentNode.N = nextNode.N == int.MaxValue ? int.MaxValue : nextNode.N + 1; next++; continue; } break; // Coalescing an individual item with another individual item. case One when nextNode.Type == One && currentNode.Ch == nextNode.Ch: case Notone when nextNode.Type == Notone && currentNode.Ch == nextNode.Ch: case Set when nextNode.Type == Set && currentNode.Str == nextNode.Str: currentNode.MakeRep(Oneloop, 2, 2); next++; continue; } } children[nextSave++] = children[next]; current = next; next++; } if (nextSave < children.Count) { children.RemoveRange(nextSave, children.Count - nextSave); } } /// <summary> /// Finds {one/notone/set}loop nodes in the concatenation that can be automatically upgraded /// to {one/notone/set}loopatomic nodes. Such changes avoid potential useless backtracking. /// e.g. A*B (where sets A and B don't overlap) => (?>A*)B. /// </summary> private void ReduceConcatenationWithAutoAtomic() { // RegexOptions.NonBacktracking doesn't support atomic groups, so when that option // is set we don't want to create atomic groups where they weren't explicitly authored. if ((Options & RegexOptions.NonBacktracking) != 0) { return; } Debug.Assert(Type == Concatenate); Debug.Assert((Options & RegexOptions.RightToLeft) == 0); Debug.Assert(Children is List<RegexNode>); var children = (List<RegexNode>)Children; for (int i = 0; i < children.Count - 1; i++) { ProcessNode(children[i], children[i + 1]); static void ProcessNode(RegexNode node, RegexNode subsequent) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { // If we can't recur further, just stop optimizing. return; } // Skip down the node past irrelevant nodes. while (true) { // We can always recur into captures and into the last node of concatenations. if (node.Type == Capture || node.Type == Concatenate) { node = node.Child(node.ChildCount() - 1); continue; } // For loops with at least one guaranteed iteration, we can recur into them, but // we need to be careful not to just always do so; the ending node of a loop can only // be made atomic if what comes after the loop but also the beginning of the loop are // compatible for the optimization. if (node.Type == Loop) { RegexNode? loopDescendent = node.FindLastExpressionInLoopForAutoAtomic(); if (loopDescendent != null) { node = loopDescendent; continue; } } // Can't skip any further. break; } // If the node can be changed to atomic based on what comes after it, do so. switch (node.Type) { case Oneloop when CanBeMadeAtomic(node, subsequent): case Notoneloop when CanBeMadeAtomic(node, subsequent): case Setloop when CanBeMadeAtomic(node, subsequent): node.MakeLoopAtomic(); break; case Alternate: // In the case of alternation, we can't change the alternation node itself // based on what comes after it (at least not with more complicated analysis // that factors in all branches together), but we can look at each individual // branch, and analyze ending loops in each branch individually to see if they // can be made atomic. Then if we do end up backtracking into the alternation, // we at least won't need to backtrack into that loop. { int alternateBranches = node.ChildCount(); for (int b = 0; b < alternateBranches; b++) { ProcessNode(node.Child(b), subsequent); } } break; } } } } /// <summary> /// Recurs into the last expression of a loop node, looking to see if it can find a node /// that could be made atomic _assuming_ the conditions exist for it with the loop's ancestors. /// </summary> /// <returns>The found node that should be explored further for auto-atomicity; null if it doesn't exist.</returns> private RegexNode? FindLastExpressionInLoopForAutoAtomic() { RegexNode node = this; Debug.Assert(node.Type == Loop); // Start by looking at the loop's sole child. node = node.Child(0); // Skip past captures. while (node.Type == Capture) { node = node.Child(0); } // If the loop's body is a concatenate, we can skip to its last child iff that // last child doesn't conflict with the first child, since this whole concatenation // could be repeated, such that the first node ends up following the last. For // example, in the expression (a+[def])*, the last child is [def] and the first is // a+, which can't possibly overlap with [def]. In contrast, if we had (a+[ade])*, // [ade] could potentially match the starting 'a'. if (node.Type == Concatenate) { int concatCount = node.ChildCount(); RegexNode lastConcatChild = node.Child(concatCount - 1); if (CanBeMadeAtomic(lastConcatChild, node.Child(0))) { return lastConcatChild; } } // Otherwise, the loop has nothing that can participate in auto-atomicity. return null; } /// <summary>Optimizations for negative lookaheads/behinds.</summary> private RegexNode ReducePrevent() { Debug.Assert(Type == Prevent); Debug.Assert(ChildCount() == 1); // A negative lookahead/lookbehind wrapped around an empty child, i.e. (?!), is // sometimes used as a way to insert a guaranteed no-match into the expression. // We can reduce it to simply Nothing. if (Child(0).Type == Empty) { Type = Nothing; Children = null; } return this; } /// <summary> /// Determines whether node can be switched to an atomic loop. Subsequent is the node /// immediately after 'node'. /// </summary> private static bool CanBeMadeAtomic(RegexNode node, RegexNode subsequent) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { // If we can't recur further, just stop optimizing. return false; } // Skip the successor down to the closest node that's guaranteed to follow it. while (subsequent.ChildCount() > 0) { Debug.Assert(subsequent.Type != Group); switch (subsequent.Type) { case Concatenate: case Capture: case Atomic: case Require when (subsequent.Options & RegexOptions.RightToLeft) == 0: // only lookaheads, not lookbehinds (represented as RTL Require nodes) case Loop when subsequent.M > 0: case Lazyloop when subsequent.M > 0: subsequent = subsequent.Child(0); continue; } break; } // If the two nodes don't agree on options in any way, don't try to optimize them. if (node.Options != subsequent.Options) { return false; } // If the successor is an alternation, all of its children need to be evaluated, since any of them // could come after this node. If any of them fail the optimization, then the whole node fails. if (subsequent.Type == Alternate) { int childCount = subsequent.ChildCount(); for (int i = 0; i < childCount; i++) { if (!CanBeMadeAtomic(node, subsequent.Child(i))) { return false; } } return true; } // If this node is a {one/notone/set}loop, see if it overlaps with its successor in the concatenation. // If it doesn't, then we can upgrade it to being a {one/notone/set}loopatomic. // Doing so avoids unnecessary backtracking. switch (node.Type) { case Oneloop: switch (subsequent.Type) { case One when node.Ch != subsequent.Ch: case Onelazy when subsequent.M > 0 && node.Ch != subsequent.Ch: case Oneloop when subsequent.M > 0 && node.Ch != subsequent.Ch: case Oneloopatomic when subsequent.M > 0 && node.Ch != subsequent.Ch: case Notone when node.Ch == subsequent.Ch: case Notonelazy when subsequent.M > 0 && node.Ch == subsequent.Ch: case Notoneloop when subsequent.M > 0 && node.Ch == subsequent.Ch: case Notoneloopatomic when subsequent.M > 0 && node.Ch == subsequent.Ch: case Multi when node.Ch != subsequent.Str![0]: case Set when !RegexCharClass.CharInClass(node.Ch, subsequent.Str!): case Setlazy when subsequent.M > 0 && !RegexCharClass.CharInClass(node.Ch, subsequent.Str!): case Setloop when subsequent.M > 0 && !RegexCharClass.CharInClass(node.Ch, subsequent.Str!): case Setloopatomic when subsequent.M > 0 && !RegexCharClass.CharInClass(node.Ch, subsequent.Str!): case End: case EndZ when node.Ch != '\n': case Eol when node.Ch != '\n': case Boundary when RegexCharClass.IsBoundaryWordChar(node.Ch): case NonBoundary when !RegexCharClass.IsBoundaryWordChar(node.Ch): case ECMABoundary when RegexCharClass.IsECMAWordChar(node.Ch): case NonECMABoundary when !RegexCharClass.IsECMAWordChar(node.Ch): return true; } break; case Notoneloop: switch (subsequent.Type) { case One when node.Ch == subsequent.Ch: case Onelazy when subsequent.M > 0 && node.Ch == subsequent.Ch: case Oneloop when subsequent.M > 0 && node.Ch == subsequent.Ch: case Oneloopatomic when subsequent.M > 0 && node.Ch == subsequent.Ch: case Multi when node.Ch == subsequent.Str![0]: case End: return true; } break; case Setloop: switch (subsequent.Type) { case One when !RegexCharClass.CharInClass(subsequent.Ch, node.Str!): case Onelazy when subsequent.M > 0 && !RegexCharClass.CharInClass(subsequent.Ch, node.Str!): case Oneloop when subsequent.M > 0 && !RegexCharClass.CharInClass(subsequent.Ch, node.Str!): case Oneloopatomic when subsequent.M > 0 && !RegexCharClass.CharInClass(subsequent.Ch, node.Str!): case Multi when !RegexCharClass.CharInClass(subsequent.Str![0], node.Str!): case Set when !RegexCharClass.MayOverlap(node.Str!, subsequent.Str!): case Setlazy when subsequent.M > 0 && !RegexCharClass.MayOverlap(node.Str!, subsequent.Str!): case Setloop when subsequent.M > 0 && !RegexCharClass.MayOverlap(node.Str!, subsequent.Str!): case Setloopatomic when subsequent.M > 0 && !RegexCharClass.MayOverlap(node.Str!, subsequent.Str!): case End: case EndZ when !RegexCharClass.CharInClass('\n', node.Str!): case Eol when !RegexCharClass.CharInClass('\n', node.Str!): case Boundary when node.Str == RegexCharClass.WordClass || node.Str == RegexCharClass.DigitClass: case NonBoundary when node.Str == RegexCharClass.NotWordClass || node.Str == RegexCharClass.NotDigitClass: case ECMABoundary when node.Str == RegexCharClass.ECMAWordClass || node.Str == RegexCharClass.ECMADigitClass: case NonECMABoundary when node.Str == RegexCharClass.NotECMAWordClass || node.Str == RegexCharClass.NotDigitClass: return true; } break; } return false; } /// <summary>Computes a min bound on the required length of any string that could possibly match.</summary> /// <returns>The min computed length. If the result is 0, there is no minimum we can enforce.</returns> /// <remarks> /// e.g. abc[def](ghijkl|mn) => 6 /// </remarks> public int ComputeMinLength() { if (!StackHelper.TryEnsureSufficientExecutionStack()) { // If we can't recur further, assume there's no minimum we can enforce. return 0; } switch (Type) { case One: case Notone: case Set: // Single character. return 1; case Multi: // Every character in the string needs to match. return Str!.Length; case Notonelazy: case Notoneloop: case Notoneloopatomic: case Onelazy: case Oneloop: case Oneloopatomic: case Setlazy: case Setloop: case Setloopatomic: // One character repeated at least M times. return M; case Lazyloop: case Loop: // A node graph repeated at least M times. return (int)Math.Min(int.MaxValue, (long)M * Child(0).ComputeMinLength()); case Alternate: // The minimum required length for any of the alternation's branches. { int childCount = ChildCount(); Debug.Assert(childCount >= 2); int min = Child(0).ComputeMinLength(); for (int i = 1; i < childCount && min > 0; i++) { min = Math.Min(min, Child(i).ComputeMinLength()); } return min; } case Concatenate: // The sum of all of the concatenation's children. { long sum = 0; int childCount = ChildCount(); for (int i = 0; i < childCount; i++) { sum += Child(i).ComputeMinLength(); } return (int)Math.Min(int.MaxValue, sum); } case Atomic: case Capture: case Group: // For groups, we just delegate to the sole child. Debug.Assert(ChildCount() == 1); return Child(0).ComputeMinLength(); case Empty: case Nothing: case UpdateBumpalong: // Nothing to match. In the future, we could potentially use Nothing to say that the min length // is infinite, but that would require a different structure, as that would only apply if the // Nothing match is required in all cases (rather than, say, as one branch of an alternation). case Beginning: case Bol: case Boundary: case ECMABoundary: case End: case EndZ: case Eol: case NonBoundary: case NonECMABoundary: case Start: // Difficult to glean anything meaningful from boundaries or results only known at run time. case Prevent: case Require: // Lookaheads/behinds could potentially be included in the future, but that will require // a different structure, as they can't be added as part of a concatenation, since they overlap // with what comes after. case Ref: case Testgroup: case Testref: // Constructs requiring data at runtime from the matching pattern can't influence min length. return 0; default: #if DEBUG Debug.Fail($"Unknown node: {TypeName}"); #endif goto case Empty; } } /// <summary> /// Determine whether the specified child node is the beginning of a sequence that can /// trivially have length checks combined in order to avoid bounds checks. /// </summary> /// <param name="childIndex">The starting index of the child to check.</param> /// <param name="requiredLength">The sum of all the fixed lengths for the nodes in the sequence.</param> /// <param name="exclusiveEnd">The index of the node just after the last one in the sequence.</param> /// <returns>true if more than one node can have their length checks combined; otherwise, false.</returns> /// <remarks> /// There are additional node types for which we can prove a fixed length, e.g. examining all branches /// of an alternation and returning true if all their lengths are equal. However, the primary purpose /// of this method is to avoid bounds checks by consolidating length checks that guard accesses to /// strings/spans for which the JIT can see a fixed index within bounds, and alternations employ /// patterns that defeat that (e.g. reassigning the span in question). As such, the implementation /// remains focused on only a core subset of nodes that are a) likely to be used in concatenations and /// b) employ simple patterns of checks. /// </remarks> public bool TryGetJoinableLengthCheckChildRange(int childIndex, out int requiredLength, out int exclusiveEnd) { static bool CanJoinLengthCheck(RegexNode node) => node.Type switch { One or Notone or Set => true, Multi => true, Oneloop or Onelazy or Oneloopatomic or Notoneloop or Notonelazy or Notoneloopatomic or Setloop or Setlazy or Setloopatomic when node.M == node.N => true, _ => false, }; RegexNode child = Child(childIndex); if (CanJoinLengthCheck(child)) { requiredLength = child.ComputeMinLength(); int childCount = ChildCount(); for (exclusiveEnd = childIndex + 1; exclusiveEnd < childCount; exclusiveEnd++) { child = Child(exclusiveEnd); if (!CanJoinLengthCheck(child)) { break; } requiredLength += child.ComputeMinLength(); } if (exclusiveEnd - childIndex > 1) { return true; } } requiredLength = 0; exclusiveEnd = 0; return false; } public RegexNode MakeQuantifier(bool lazy, int min, int max) { if (min == 0 && max == 0) return new RegexNode(Empty, Options); if (min == 1 && max == 1) return this; switch (Type) { case One: case Notone: case Set: MakeRep(lazy ? Onelazy : Oneloop, min, max); return this; default: var result = new RegexNode(lazy ? Lazyloop : Loop, Options, min, max); result.AddChild(this); return result; } } public void AddChild(RegexNode newChild) { newChild.Next = this; // so that the child can see its parent while being reduced newChild = newChild.Reduce(); newChild.Next = this; // in case Reduce returns a different node that needs to be reparented if (Children is null) { Children = newChild; } else if (Children is RegexNode currentChild) { Children = new List<RegexNode>() { currentChild, newChild }; } else { ((List<RegexNode>)Children).Add(newChild); } } public void InsertChild(int index, RegexNode newChild) { Debug.Assert(Children is List<RegexNode>); newChild.Next = this; // so that the child can see its parent while being reduced newChild = newChild.Reduce(); newChild.Next = this; // in case Reduce returns a different node that needs to be reparented ((List<RegexNode>)Children).Insert(index, newChild); } public void ReplaceChild(int index, RegexNode newChild) { Debug.Assert(Children != null); Debug.Assert(index < ChildCount()); newChild.Next = this; // so that the child can see its parent while being reduced newChild = newChild.Reduce(); newChild.Next = this; // in case Reduce returns a different node that needs to be reparented if (Children is RegexNode) { Children = newChild; } else { ((List<RegexNode>)Children)[index] = newChild; } } public RegexNode Child(int i) { if (Children is RegexNode child) { return child; } return ((List<RegexNode>)Children!)[i]; } public int ChildCount() { if (Children is null) { return 0; } if (Children is List<RegexNode> children) { return children.Count; } Debug.Assert(Children is RegexNode); return 1; } // Determines whether the node supports a compilation / code generation strategy based on walking the node tree. internal bool SupportsCompilation() { if (!StackHelper.TryEnsureSufficientExecutionStack()) { // If we can't recur further, code generation isn't supported as the tree is too deep. return false; } if ((Options & (RegexOptions.RightToLeft | RegexOptions.NonBacktracking)) != 0) { // NonBacktracking isn't supported, nor RightToLeft. The latter applies to both the top-level // options as well as when used to specify positive and negative lookbehinds. return false; } int childCount = ChildCount(); for (int i = 0; i < childCount; i++) { // The node isn't supported if any of its children aren't supported. if (!Child(i).SupportsCompilation()) { return false; } } // TODO: This should be moved somewhere else, to a pass somewhere where we explicitly // annotate the tree, potentially as part of the final optimization pass. It doesn't // belong in this check. if (Type == Capture) { // If we've found a supported capture, mark all of the nodes in its parent hierarchy as containing a capture. for (RegexNode? parent = this; parent != null && (parent.Options & HasCapturesFlag) == 0; parent = parent.Next) { parent.Options |= HasCapturesFlag; } } // Supported. return true; } /// <summary>Gets whether the node is a Set/Setloop/Setloopatomic/Setlazy node.</summary> public bool IsSetFamily => Type is Set or Setloop or Setloopatomic or Setlazy; /// <summary>Gets whether the node is a One/Oneloop/Oneloopatomic/Onelazy node.</summary> public bool IsOneFamily => Type is One or Oneloop or Oneloopatomic or Onelazy; /// <summary>Gets whether the node is a Notone/Notoneloop/Notoneloopatomic/Notonelazy node.</summary> public bool IsNotoneFamily => Type is Notone or Notoneloop or Notoneloopatomic or Notonelazy; /// <summary>Gets whether this node is contained inside of a loop.</summary> public bool IsInLoop() { for (RegexNode? parent = Next; parent is not null; parent = parent.Next) { if (parent.Type is Loop or Lazyloop) { return true; } } return false; } #if DEBUG private string TypeName => Type switch { Oneloop => nameof(Oneloop), Notoneloop => nameof(Notoneloop), Setloop => nameof(Setloop), Onelazy => nameof(Onelazy), Notonelazy => nameof(Notonelazy), Setlazy => nameof(Setlazy), One => nameof(One), Notone => nameof(Notone), Set => nameof(Set), Multi => nameof(Multi), Ref => nameof(Ref), Bol => nameof(Bol), Eol => nameof(Eol), Boundary => nameof(Boundary), NonBoundary => nameof(NonBoundary), ECMABoundary => nameof(ECMABoundary), NonECMABoundary => nameof(NonECMABoundary), Beginning => nameof(Beginning), Start => nameof(Start), EndZ => nameof(EndZ), End => nameof(End), Oneloopatomic => nameof(Oneloopatomic), Notoneloopatomic => nameof(Notoneloopatomic), Setloopatomic => nameof(Setloopatomic), Nothing => nameof(Nothing), Empty => nameof(Empty), Alternate => nameof(Alternate), Concatenate => nameof(Concatenate), Loop => nameof(Loop), Lazyloop => nameof(Lazyloop), Capture => nameof(Capture), Group => nameof(Group), Require => nameof(Require), Prevent => nameof(Prevent), Atomic => nameof(Atomic), Testref => nameof(Testref), Testgroup => nameof(Testgroup), UpdateBumpalong => nameof(UpdateBumpalong), _ => $"(unknown {Type})" }; [ExcludeFromCodeCoverage] public string Description() { var sb = new StringBuilder(TypeName); if ((Options & RegexOptions.ExplicitCapture) != 0) sb.Append("-C"); if ((Options & RegexOptions.IgnoreCase) != 0) sb.Append("-I"); if ((Options & RegexOptions.RightToLeft) != 0) sb.Append("-L"); if ((Options & RegexOptions.Multiline) != 0) sb.Append("-M"); if ((Options & RegexOptions.Singleline) != 0) sb.Append("-S"); if ((Options & RegexOptions.IgnorePatternWhitespace) != 0) sb.Append("-X"); if ((Options & RegexOptions.ECMAScript) != 0) sb.Append("-E"); switch (Type) { case Oneloop: case Oneloopatomic: case Notoneloop: case Notoneloopatomic: case Onelazy: case Notonelazy: case One: case Notone: sb.Append(" '").Append(RegexCharClass.CharDescription(Ch)).Append('\''); break; case Capture: sb.Append(' ').Append($"index = {M}"); if (N != -1) { sb.Append($", unindex = {N}"); } break; case Ref: case Testref: sb.Append(' ').Append($"index = {M}"); break; case Multi: sb.Append(" \"").Append(Str).Append('"'); break; case Set: case Setloop: case Setloopatomic: case Setlazy: sb.Append(' ').Append(RegexCharClass.SetDescription(Str!)); break; } switch (Type) { case Oneloop: case Oneloopatomic: case Notoneloop: case Notoneloopatomic: case Onelazy: case Notonelazy: case Setloop: case Setloopatomic: case Setlazy: case Loop: case Lazyloop: sb.Append( (M == 0 && N == int.MaxValue) ? "*" : (M == 0 && N == 1) ? "?" : (M == 1 && N == int.MaxValue) ? "+" : (N == int.MaxValue) ? $"{{{M}, *}}" : (N == M) ? $"{{{M}}}" : $"{{{M}, {N}}}"); break; } return sb.ToString(); } [ExcludeFromCodeCoverage] public void Dump() => Debug.WriteLine(ToString()); [ExcludeFromCodeCoverage] public override string ToString() { RegexNode? curNode = this; int curChild = 0; var sb = new StringBuilder().AppendLine(curNode.Description()); var stack = new List<int>(); while (true) { if (curChild < curNode!.ChildCount()) { stack.Add(curChild + 1); curNode = curNode.Child(curChild); curChild = 0; sb.Append(new string(' ', stack.Count * 2)).Append(curNode.Description()).AppendLine(); } else { if (stack.Count == 0) { break; } curChild = stack[stack.Count - 1]; stack.RemoveAt(stack.Count - 1); curNode = curNode.Next; } } return sb.ToString(); } #endif } }
44.821851
172
0.47024
[ "MIT" ]
AntonLapounov/runtime
src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexNode.cs
109,948
C#
using System; using System.Net; using System.Security.Cryptography.X509Certificates; using JetBrains.Annotations; namespace Vostok.Clusterclient.Transport { /// <summary> /// A class that represents <see cref="SocketsTransport" /> settings. /// </summary> [PublicAPI] public class SocketsTransportSettings { /// <summary> /// How much time connection will be alive after last usage. Note that if no other connections to endpoint are active, its value will be divided by 4. /// </summary> public TimeSpan ConnectionIdleTimeout { get; set; } = TimeSpan.FromMinutes(2); /// <summary> /// Gets or sets a maximum time to live for TCP connections. Limiting the lifetime of connections helps to notice changes in DNS records. /// </summary> public TimeSpan ConnectionLifetime { get; set; } = TimeSpan.FromMinutes(10); /// <summary> /// How much time client should wait for internal handler to return control after request cancellation. /// </summary> public TimeSpan RequestAbortTimeout { get; set; } = TimeSpan.FromMilliseconds(250); /// <summary> /// Gets or sets an <see cref="IWebProxy" /> instance which will be used to send requests. /// </summary> public IWebProxy Proxy { get; set; } /// <summary> /// Max connections count to a single endpoint. When this limit is reached, requests get placed into a queue and wait for a free connection. /// </summary> public int MaxConnectionsPerEndpoint { get; set; } = 10 * 1000; /// <summary> /// Gets or sets the maximum response body size in bytes. This parameter doesn't affect content streaming. /// </summary> public long? MaxResponseBodySize { get; set; } /// <summary> /// Gets or sets the delegate that decides whether to use response streaming or not. /// </summary> public Predicate<long?> UseResponseStreaming { get; set; } = _ => false; /// <summary> /// Gets or sets a value that indicates whether the transport should follow HTTP redirection responses. /// </summary> public bool AllowAutoRedirect { get; set; } /// <summary> /// Enables/disables TCP keep-alive mechanism. Currently only works in Windows. /// </summary> public bool TcpKeepAliveEnabled { get; set; } /// <summary> /// Enables/disables ARP cache warmup. Currently only works in Windows. /// </summary> public bool ArpCacheWarmupEnabled { get; set; } /// <summary> /// Gets or sets the duration between two keep-alive transmissions in idle condition. /// </summary> public TimeSpan TcpKeepAliveTime { get; set; } = TimeSpan.FromSeconds(3); /// <summary> /// Gets or sets the duration between two successive keep-alive retransmissions than happen when acknowledgement to the previous /// keep-alive transmission is not received. /// </summary> public TimeSpan TcpKeepAliveInterval { get; set; } = TimeSpan.FromSeconds(1); /// <summary> /// Gets or sets a list of client certificats for SSL connections. /// </summary> public X509Certificate2[] ClientCertificates { get; set; } /// <summary> /// Gets or sets a delegate used to create response body buffers for given sizes. /// </summary> public Func<int, byte[]> BufferFactory { get; set; } = size => new byte[size]; } }
41.709302
158
0.630611
[ "MIT" ]
bymse/clusterclient.transport
Vostok.ClusterClient.Transport/SocketsTransportSettings.cs
3,587
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="HalfEdgeMeshVisual3D.cs" company="Helix 3D Toolkit"> // http://helixtoolkit.codeplex.com, license: MIT // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace HelixToolkit.Wpf { using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Windows.Media; using System.Windows.Media.Media3D; /// <summary> /// Represent a manifold mesh by a halfedge data structure. /// </summary> /// <remarks> /// See http://en.wikipedia.org/wiki/Polygon_mesh http://www.dgp.toronto.edu/~alexk/lydos.html http://openmesh.org http://sharp3d.codeplex.com http://www.cs.sunysb.edu/~gu/software/MeshLib/index.html http://www.flipcode.com/archives/The_Half-Edge_Data_Structure.shtml http://www.cgal.org/Manual/latest/doc_html/cgal_manual/HalfedgeDS/Chapter_main.html http://algorithmicbotany.org/papers/smithco.dis2006.pdf http://www.cs.mtu.edu/~shene/COURSES/cs3621/SLIDES/Mesh.pdf http://mrl.nyu.edu/~dzorin/ig04/lecture24/meshes.pdf http://www.hao-li.com/teaching/surfaceRepresentationAndGeometricModeling/OpenMeshTutorial.pdf http://www.cs.rpi.edu/~cutler/classes/advancedgraphics/S09/lectures/02_Adjacency_Data_Structures.pdf /// </remarks> public class HalfEdgeMesh { /// <summary> /// Initializes a new instance of the <see cref="HalfEdgeMesh" /> class. /// </summary> public HalfEdgeMesh() { this.Vertices = new List<Vertex>(); this.Edges = new List<HalfEdge>(); this.Faces = new List<Face>(); } /// <summary> /// Initializes a new instance of the <see cref="HalfEdgeMesh"/> class. /// </summary> /// <param name="vertices"> /// The vertices. /// </param> /// <param name="triangleIndices"> /// The triangle indices. /// </param> public HalfEdgeMesh(IList<Point3D> vertices, IList<int> triangleIndices = null) : this() { // Add each vertex to the Vertices collection for (int i = 0; i < vertices.Count; i++) { this.Vertices.Add(new Vertex { Position = vertices[i], Index = i }); } if (triangleIndices != null) { // Add each triangle face and update the halfedge structures for (int i = 0; i < triangleIndices.Count; i += 3) { this.AddFace(triangleIndices[i], triangleIndices[i + 1], triangleIndices[i + 2]); } } } /// <summary> /// Gets or sets the edges. /// </summary> /// <value> The edges. </value> public IList<HalfEdge> Edges { get; set; } /// <summary> /// Gets or sets the faces. /// </summary> /// <value> The faces. </value> public IList<Face> Faces { get; set; } /// <summary> /// Gets or sets the vertices. /// </summary> /// <value> The vertices. </value> public IList<Vertex> Vertices { get; set; } /// <summary> /// Adds the face. /// </summary> /// <param name="indices"> /// The indices. /// </param> /// <returns> /// The face. /// </returns> public Face AddFace(params int[] indices) { int n = indices.Length; var faceVertices = indices.Select(i => this.Vertices[i]).ToList(); var face = new Face { Index = this.Faces.Count }; var faceEdges = new HalfEdge[n]; // Create the halfedges for the face for (int j = 0; j < n; j++) { faceEdges[j] = new HalfEdge { StartVertex = faceVertices[j], EndVertex = faceVertices[(j + 1) % n], Face = face, Index = this.Edges.Count }; this.Edges.Add(faceEdges[j]); } // Set the NextEdge properties for (int j = 0; j < n; j++) { faceEdges[j].NextEdge = faceEdges[(j + 1) % n]; } for (int j = 0; j < n; j++) { var startVertex = faceVertices[j]; var endVertex = faceVertices[(j + 1) % n]; if (endVertex.FirstIncomingEdge == null) { // This is the first incoming edge to this vertex endVertex.FirstIncomingEdge = faceEdges[j]; } else { // todo: this needs to be fixed - I have just been trying to get the right structure in this first prototype // The vertex has been used by before, check if any of the edges are adjacent foreach (var e in this.Edges) { if (e == faceEdges[j]) { continue; } if (e.StartVertex == startVertex && e.EndVertex == endVertex) { throw new InvalidOperationException("Edge already used."); } if (e.StartVertex == endVertex && e.EndVertex == startVertex) { e.AdjacentEdge = faceEdges[j]; faceEdges[j].AdjacentEdge = e; break; } } // for (int k = 0; k < n; k++) // { // var v0 = faceVertices[(j + k) % n]; // var v1 = faceVertices[(j + k + 1) % n]; // if (startVertex == v0 && endVertex == v1) // { // throw new InvalidOperationException("Edge already defined."); // } // if (endVertex == v0 && startVertex == v1) // { // // Set the AdjacentEdge property // endVertex.FirstIncomingEdge.AdjacentEdge = faceEdges[(j + k) % n]; // faceEdges[(j + k) % n].AdjacentEdge = endVertex.FirstIncomingEdge; // } // } } } // Add the first edge to the face face.Edge = faceEdges[0]; // Add the face to the faces collection this.Faces.Add(face); return face; } /// <summary> /// Gets the faces. /// </summary> /// <returns> /// The faces. /// </returns> public IEnumerable<HalfEdge> GetFaces() { var isEdgeVisited = new bool[this.Edges.Count]; for (int i = 0; i < this.Edges.Count; i++) { if (!isEdgeVisited[i]) { yield return this.Edges[i]; } foreach (var e in this.Edges[i].Face.Edges) { int j = this.Edges.IndexOf(e); isEdgeVisited[j] = true; } } } /// <summary> /// Create a MeshGeometry3D. /// </summary> /// <returns> /// A MeshGeometry3D. /// </returns> public MeshGeometry3D ToMeshGeometry3D() { return new MeshGeometry3D { Positions = new Point3DCollection(this.Vertices.Select(v => v.Position)), TriangleIndices = new Int32Collection(this.Triangulate()) }; } /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> public override string ToString() { this.Vertices.Select((v, i) => v.Index = i).ToList(); this.Edges.Select((e, i) => e.Index = i).ToList(); this.Faces.Select((f, i) => f.Index = i).ToList(); var builder = new StringBuilder(); foreach (var v in this.Vertices) { builder.AppendLine(v.ToString()); } foreach (var v in this.Edges) { builder.AppendLine(v.ToString()); } foreach (var v in this.Faces) { builder.AppendLine(v.ToString()); } return builder.ToString(); } /// <summary> /// Gets the triangle indices. /// </summary> /// <returns> /// The triangle indices. /// </returns> public IEnumerable<int> Triangulate() { return from face in this.Faces from v in face.Triangulate() select v.Index; } /// <summary> /// Represents a face. /// </summary> public class Face { /// <summary> /// Gets the adjacent faces. /// </summary> /// <value> The adjacent faces. </value> public IEnumerable<Face> AdjacentFaces { get { return this.Edges.Select(edge => edge.AdjacentFace).Where(adjacentFace => adjacentFace != null); } } /// <summary> /// Gets or sets the first edge of the face. /// </summary> /// <value> The edge. </value> public HalfEdge Edge { get; set; } /// <summary> /// Gets the edges. /// </summary> /// <value> The edges. </value> public IEnumerable<HalfEdge> Edges { get { var edge = this.Edge; do { yield return edge; edge = edge.NextEdge; } while (edge != this.Edge); } } /// <summary> /// Gets or sets the index. /// </summary> /// <value> The index. </value> public int Index { get; set; } /// <summary> /// Gets or sets the tag. /// </summary> /// <value> The tag. </value> public object Tag { get; set; } /// <summary> /// Gets the vertices. /// </summary> /// <value> The vertices. </value> public IEnumerable<Vertex> Vertices { get { return this.Edges.Select(e => e.EndVertex); } } /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> public override string ToString() { return string.Format( "f{0}: {1} | {2}", this.Index, this.Vertices.Select(v => v.Index).EnumerateToString("v"), this.Edges.Select(e => e.Index).EnumerateToString("e")); } /// <summary> /// Triangulates this face. /// </summary> /// <returns> /// Triangulated vertices. /// </returns> public IEnumerable<Vertex> Triangulate() { var v = this.Vertices.ToList(); for (int i = 1; i + 1 < v.Count; i++) { yield return v[0]; yield return v[i]; yield return v[i + 1]; } } } /// <summary> /// Represents a half edge. /// </summary> public class HalfEdge { /// <summary> /// Gets or sets the adjacent edge. /// </summary> /// <value> The adjacent edge. </value> public HalfEdge AdjacentEdge { get; set; } /// <summary> /// Gets the adjacent face. /// </summary> /// <value> The adjacent face. </value> public Face AdjacentFace { get { return this.AdjacentEdge != null ? this.AdjacentEdge.Face : null; } } /// <summary> /// Gets or sets the end vertex. /// </summary> /// <value> The end vertex. </value> public Vertex EndVertex { get; set; } /// <summary> /// Gets or sets the face. /// </summary> /// <value> The face. </value> public Face Face { get; set; } /// <summary> /// Gets or sets the index. /// </summary> /// <value> The index. </value> public int Index { get; set; } /// <summary> /// Gets or sets the next edge. /// </summary> /// <value> The next edge. </value> public HalfEdge NextEdge { get; set; } /// <summary> /// Gets or sets the start vertex. /// </summary> /// <value> The start vertex. </value> public Vertex StartVertex { get; set; } /// <summary> /// Gets or sets the tag. /// </summary> /// <value> The tag. </value> public object Tag { get; set; } // public Vertex StartVertex // { // get // { // if (AdjacentEdge != null) return AdjacentEdge.EndVertex; // var edge = this; // do // { // if (edge.NextEdge == this) return edge.EndVertex; // edge = edge.NextEdge; // } while (edge != this); // return null; // } // } /// <summary> /// Checks if the halfedge is on the boundary of the mesh. /// </summary> /// <returns> /// <c>true</c> if the halfedge is on the boundary; otherwise, <c>false</c> . /// </returns> public bool IsOnBoundary() { return this.AdjacentEdge == null; } /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> public override string ToString() { return string.Format( "e{0}: v{1}->v{2} ae{3} f{4} af{5}", this.Index, this.StartVertex.Index, this.EndVertex.Index, this.AdjacentEdge != null ? this.AdjacentEdge.Index.ToString(CultureInfo.InvariantCulture) : "-", this.Face.Index, this.AdjacentFace != null ? this.AdjacentFace.Index.ToString(CultureInfo.InvariantCulture) : "-"); } } /// <summary> /// Represents a vertex. /// </summary> public class Vertex { /// <summary> /// Gets the adjacent faces. /// </summary> /// <value> The adjacent faces. </value> public IEnumerable<Face> AdjacentFaces { get { return this.OutgoingEdges.Select(e => e.Face); } } /// <summary> /// Gets or sets the first incoming edge. /// </summary> /// <value> The first incoming edge. </value> public HalfEdge FirstIncomingEdge { get; set; } /// <summary> /// Gets the incoming halfedges. /// </summary> /// <value> The incoming edges. </value> public IEnumerable<HalfEdge> IncomingEdges { get { var edge = this.FirstIncomingEdge; do { yield return edge; edge = edge.NextEdge.AdjacentEdge; } while (edge != this.FirstIncomingEdge && edge != null); } } /// <summary> /// Gets or sets the index. /// </summary> /// <value> The index. </value> public int Index { get; set; } /// <summary> /// Gets the halfedges originating from the vertex. /// </summary> public IEnumerable<HalfEdge> OutgoingEdges { get { return this.IncomingEdges.Where(e => e.AdjacentEdge != null).Select(e => e.AdjacentEdge); } } /// <summary> /// Gets or sets the position. /// </summary> /// <value> The position. </value> public Point3D Position { get; set; } /// <summary> /// Gets or sets the tag. /// </summary> /// <value> The tag. </value> public object Tag { get; set; } /// <summary> /// Gets or sets the value. /// </summary> /// <value> The value. </value> public double Value { get; set; } /// <summary> /// Gets the vertices in the one ring neighborhood. /// </summary> public IEnumerable<Vertex> Vertices { get { return this.OutgoingEdges.Select(h => h.EndVertex); } } /// <summary> /// Determines whether the vertex is on the boundary. /// </summary> /// <returns> /// <c>true</c> if the vertex is on the boundary; otherwise, <c>false</c> . /// </returns> public bool IsOnBoundary() { if (this.FirstIncomingEdge == null) { return true; } return this.OutgoingEdges.Any(edge => edge.IsOnBoundary()); } /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> public override string ToString() { return string.Format( "v{0}: {1} | {2} | {3} | {4}", this.Index, this.FirstIncomingEdge.Face.Edges.Select(e => e.Index).EnumerateToString("e"), this.IncomingEdges.Select(e => e.Index).EnumerateToString("ie"), this.OutgoingEdges.Select(e => e.Index).EnumerateToString("oe"), this.AdjacentFaces.Select(f => f.Index).EnumerateToString("af")); } } } }
35.14726
720
0.419809
[ "MIT" ]
smallholexu/helix-toolkit
Source/Examples/WPF/ExampleBrowser/Examples/HalfEdgeMesh/HalfEdgeMesh.cs
20,528
C#
using System; using System.Collections.Generic; namespace RCi.Tutorials.Gfx.Utils { public static class U { /// <summary> /// Clamp value (ensure it falls into a given range). /// </summary> public static int Clamp(this int value, int min, int max) { if (value < min) { value = min; return value; } if (value > max) { value = max; } return value; } /// <summary> /// <see cref="ICloneable.Clone"/> and cast it to explicit type <typeparam name="T"/>. /// </summary> public static T Cloned<T>(this T cloneable) where T : ICloneable { return (T)cloneable.Clone(); } /// <summary> /// Fill array with the same value. /// </summary> public static void Fill<T>(this T[] array, T value) { var length = array.Length; if (length == 0) return; // seed var seed = Math.Min(32, array.Length); for (var i = 0; i < seed; i++) { array[i] = value; } // copy by doubling int count; for (count = seed; count <= length / 2; count *= 2) { Array.Copy(array, 0, array, count, count); } // copy last part var leftover = length - count; if (leftover > 0) { Array.Copy(array, 0, array, count, leftover); } } /// <summary> /// Does <see cref="List{T}.ForEach"/> on <see cref="IEnumerable{T}"/> collection. /// </summary> public static void ForEach<T>(this IEnumerable<T> collection, Action<T> action) { foreach (var item in collection) { action(item); } } /// <summary> /// Get handle of this window. /// </summary> public static IntPtr Handle(this System.Windows.Forms.Control window) { return window.IsDisposed ? default : Handle((System.Windows.Forms.IWin32Window)window); } /// <summary> /// Get handle of this window. /// </summary> public static IntPtr Handle(this System.Windows.Forms.IWin32Window window) { return window.Handle; } /// <summary> /// Get handle of this window. /// </summary> public static IntPtr Handle(this System.Windows.Media.Visual window) { var handleSource = window.HandleSource(); return handleSource == null || handleSource.IsDisposed ? default : handleSource.Handle; } /// <summary> /// Object Lifetime: /// /// An HwndSource is a regular common language runtime(CLR) object, and its lifetime is managed by the garbage collector. /// Because the HwndSource represents an unmanaged resource, HwndSource implements IDisposable. /// Synchronously calling Dispose immediately destroys the Win32 window if called from the owner thread. /// If called from another thread, the Win32 window is destroyed asynchronously. /// Calling Dispose explicitly from the interoperating code might be necessary for certain interoperation scenarios. /// </summary> public static System.Windows.Interop.HwndSource HandleSource(this System.Windows.Media.Visual window) { return System.Windows.PresentationSource.FromVisual(window) as System.Windows.Interop.HwndSource; } /// <summary> /// Swap two instances. /// </summary> public static void Swap<T>(ref T value0, ref T value1) { var temp = value0; value0 = value1; value1 = temp; } /// <summary> /// Convert color to RGBA integer: 0xRRGGBBAA; /// </summary> public static int ToRgba(this System.Drawing.Color color) { return ((((color.A << 8) + color.B) << 8) + color.G << 8) + color.R; } } }
32.121212
129
0.522877
[ "MIT" ]
rciworks/RCi.Tutorials.Gfx
Tutorial 018 - GDI Rasterize Triangle/Utils/U.cs
4,242
C#
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LiquidTransformationLib { public class Transformer { public readonly string Template; public readonly bool UseRubyNamingConvention; public readonly DotLiquid.Template LiquidTemplate; public static Transformer GetTransformerFromFile(string filename, bool useRubyNamingConvention = false) { string template = File.ReadAllText(filename); return new Transformer(template, useRubyNamingConvention); } public Transformer(string template, bool useRubyNamingConvention = false) { Template = template; UseRubyNamingConvention = useRubyNamingConvention; if(!useRubyNamingConvention) { DotLiquid.Template.NamingConvention = new DotLiquid.NamingConventions.CSharpNamingConvention(); } LiquidTemplate = DotLiquid.Template.Parse(template); } public string RenderFromString(string content, string rootElement = null) { Dictionary<string, object> dicContent; JsonSerializerSettings sets = new JsonSerializerSettings { CheckAdditionalContent = true, MaxDepth = null }; var jo = JObject.Parse(content); var dic = jo.ToDictionary(); if (rootElement is null) { dicContent = (Dictionary<string, object>)dic; } else { dicContent = new Dictionary<string, object> { { rootElement, dic } }; } var obj = DotLiquid.Hash.FromDictionary(dicContent); return LiquidTemplate.Render(obj); } public string RenderFromFile(string filename, string rootElement = null) { string content = System.IO.File.ReadAllText(filename); return RenderFromString(content,rootElement); } } }
31.637681
111
0.607421
[ "MIT" ]
skastberg/LiquidTransformation
Code/LiquidTransformationLib/Transformer.cs
2,185
C#
namespace Exemplo3.Areas.HelpPage.ModelDescriptions { public class EnumValueDescription { public string Documentation { get; set; } public string Name { get; set; } public string Value { get; set; } } }
21.818182
51
0.641667
[ "MIT" ]
siecola/WebAPIBook2
Exemplo3/Areas/HelpPage/ModelDescriptions/EnumValueDescription.cs
240
C#
//----------------------------------------------------------------------- // <copyright file="EmptyTypeFormatter.cs" company="Sirenix IVS"> // Copyright (c) 2018 Sirenix IVS // // 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. // </copyright> //----------------------------------------------------------------------- namespace XamExporter { /// <summary> /// A formatter for empty types. It writes no data, and skips all data that is to be read, deserializing a "default" value. /// </summary> public class EmptyTypeFormatter<T> : EasyBaseFormatter<T> { /// <summary> /// Skips the entry to read. /// </summary> protected override void ReadDataEntry(ref T value, string entryName, EntryType entryType, IDataReader reader) { // Just skip reader.SkipEntry(); } /// <summary> /// Does nothing at all. /// </summary> protected override void WriteDataEntries(ref T value, IDataWriter writer) { // Do nothing } } }
36.55814
127
0.587786
[ "Apache-2.0" ]
johnbrandle/odin-serializer
OdinSerializer/Core/Formatters/EmptyTypeFormatter.cs
1,574
C#
namespace AncientMysteries.AmmoTypes { public class AT_FerociousPredator : AMAmmoType { public AT_FerociousPredator() { accuracy = 1f; penetration = 0.35f; bulletSpeed = 9f; rangeVariation = 0f; speedVariation = 0f; range = 2000f; rebound = true; affectedByGravity = true; deadly = false; weight = 5f; bulletThickness = 2f; bulletColor = Color.White; bulletType = typeof(Bullet_FerociousPredator); immediatelyDeadly = true; sprite = new Sprite("launcherGrenade"); sprite.CenterOrigin(); } public override void PopShell(float x, float y, int dir) { PistolShell shell = new(x, y) { hSpeed = dir * (1.5f + Rando.Float(1f)) }; Level.Add(shell); } } }
28.352941
64
0.498963
[ "MIT" ]
BThree496/AncientMysteriesMod
AncientMysteries/AmmoTypes/AT_FerociousPredator.cs
966
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.MachineLearningServices.V20200101 { /// <summary> /// An object that represents a machine learning workspace. /// </summary> public partial class Workspace : Pulumi.CustomResource { /// <summary> /// ARM id of the application insights associated with this workspace. This cannot be changed once the workspace has been created /// </summary> [Output("applicationInsights")] public Output<string?> ApplicationInsights { get; private set; } = null!; /// <summary> /// ARM id of the container registry associated with this workspace. This cannot be changed once the workspace has been created /// </summary> [Output("containerRegistry")] public Output<string?> ContainerRegistry { get; private set; } = null!; /// <summary> /// The creation time of the machine learning workspace in ISO8601 format. /// </summary> [Output("creationTime")] public Output<string> CreationTime { get; private set; } = null!; /// <summary> /// The description of this workspace. /// </summary> [Output("description")] public Output<string?> Description { get; private set; } = null!; /// <summary> /// Url for the discovery service to identify regional endpoints for machine learning experimentation services /// </summary> [Output("discoveryUrl")] public Output<string?> DiscoveryUrl { get; private set; } = null!; /// <summary> /// The encryption settings of Azure ML workspace. /// </summary> [Output("encryption")] public Output<Outputs.EncryptionPropertyResponse?> Encryption { get; private set; } = null!; /// <summary> /// The friendly name for this workspace. This name in mutable /// </summary> [Output("friendlyName")] public Output<string?> FriendlyName { get; private set; } = null!; /// <summary> /// The flag to signal HBI data in the workspace and reduce diagnostic data collected by the service /// </summary> [Output("hbiWorkspace")] public Output<bool?> HbiWorkspace { get; private set; } = null!; /// <summary> /// The identity of the resource. /// </summary> [Output("identity")] public Output<Outputs.IdentityResponse?> Identity { get; private set; } = null!; /// <summary> /// ARM id of the key vault associated with this workspace. This cannot be changed once the workspace has been created /// </summary> [Output("keyVault")] public Output<string?> KeyVault { get; private set; } = null!; /// <summary> /// Specifies the location of the resource. /// </summary> [Output("location")] public Output<string?> Location { get; private set; } = null!; /// <summary> /// Specifies the name of the resource. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// The current deployment state of workspace resource. The provisioningState is to indicate states for resource provisioning. /// </summary> [Output("provisioningState")] public Output<string> ProvisioningState { get; private set; } = null!; /// <summary> /// The name of the managed resource group created by workspace RP in customer subscription if the workspace is CMK workspace /// </summary> [Output("serviceProvisionedResourceGroup")] public Output<string> ServiceProvisionedResourceGroup { get; private set; } = null!; /// <summary> /// The sku of the workspace. /// </summary> [Output("sku")] public Output<Outputs.SkuResponse?> Sku { get; private set; } = null!; /// <summary> /// ARM id of the storage account associated with this workspace. This cannot be changed once the workspace has been created /// </summary> [Output("storageAccount")] public Output<string?> StorageAccount { get; private set; } = null!; /// <summary> /// Contains resource tags defined as key/value pairs. /// </summary> [Output("tags")] public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!; /// <summary> /// Specifies the type of the resource. /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// The immutable id associated with this workspace. /// </summary> [Output("workspaceId")] public Output<string> WorkspaceId { get; private set; } = null!; /// <summary> /// Create a Workspace resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public Workspace(string name, WorkspaceArgs args, CustomResourceOptions? options = null) : base("azure-nextgen:machinelearningservices/v20200101:Workspace", name, args ?? new WorkspaceArgs(), MakeResourceOptions(options, "")) { } private Workspace(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-nextgen:machinelearningservices/v20200101:Workspace", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:machinelearningservices/latest:Workspace"}, new Pulumi.Alias { Type = "azure-nextgen:machinelearningservices/v20180301preview:Workspace"}, new Pulumi.Alias { Type = "azure-nextgen:machinelearningservices/v20181119:Workspace"}, new Pulumi.Alias { Type = "azure-nextgen:machinelearningservices/v20190501:Workspace"}, new Pulumi.Alias { Type = "azure-nextgen:machinelearningservices/v20190601:Workspace"}, new Pulumi.Alias { Type = "azure-nextgen:machinelearningservices/v20191101:Workspace"}, new Pulumi.Alias { Type = "azure-nextgen:machinelearningservices/v20200218preview:Workspace"}, new Pulumi.Alias { Type = "azure-nextgen:machinelearningservices/v20200301:Workspace"}, new Pulumi.Alias { Type = "azure-nextgen:machinelearningservices/v20200401:Workspace"}, new Pulumi.Alias { Type = "azure-nextgen:machinelearningservices/v20200501preview:Workspace"}, new Pulumi.Alias { Type = "azure-nextgen:machinelearningservices/v20200515preview:Workspace"}, new Pulumi.Alias { Type = "azure-nextgen:machinelearningservices/v20200601:Workspace"}, new Pulumi.Alias { Type = "azure-nextgen:machinelearningservices/v20200801:Workspace"}, new Pulumi.Alias { Type = "azure-nextgen:machinelearningservices/v20200901preview:Workspace"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing Workspace resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static Workspace Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new Workspace(name, id, options); } } public sealed class WorkspaceArgs : Pulumi.ResourceArgs { /// <summary> /// ARM id of the application insights associated with this workspace. This cannot be changed once the workspace has been created /// </summary> [Input("applicationInsights")] public Input<string>? ApplicationInsights { get; set; } /// <summary> /// ARM id of the container registry associated with this workspace. This cannot be changed once the workspace has been created /// </summary> [Input("containerRegistry")] public Input<string>? ContainerRegistry { get; set; } /// <summary> /// The description of this workspace. /// </summary> [Input("description")] public Input<string>? Description { get; set; } /// <summary> /// Url for the discovery service to identify regional endpoints for machine learning experimentation services /// </summary> [Input("discoveryUrl")] public Input<string>? DiscoveryUrl { get; set; } /// <summary> /// The encryption settings of Azure ML workspace. /// </summary> [Input("encryption")] public Input<Inputs.EncryptionPropertyArgs>? Encryption { get; set; } /// <summary> /// The friendly name for this workspace. This name in mutable /// </summary> [Input("friendlyName")] public Input<string>? FriendlyName { get; set; } /// <summary> /// The flag to signal HBI data in the workspace and reduce diagnostic data collected by the service /// </summary> [Input("hbiWorkspace")] public Input<bool>? HbiWorkspace { get; set; } /// <summary> /// The identity of the resource. /// </summary> [Input("identity")] public Input<Inputs.IdentityArgs>? Identity { get; set; } /// <summary> /// ARM id of the key vault associated with this workspace. This cannot be changed once the workspace has been created /// </summary> [Input("keyVault")] public Input<string>? KeyVault { get; set; } /// <summary> /// Specifies the location of the resource. /// </summary> [Input("location")] public Input<string>? Location { get; set; } /// <summary> /// Name of the resource group in which workspace is located. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; /// <summary> /// The sku of the workspace. /// </summary> [Input("sku")] public Input<Inputs.SkuArgs>? Sku { get; set; } /// <summary> /// ARM id of the storage account associated with this workspace. This cannot be changed once the workspace has been created /// </summary> [Input("storageAccount")] public Input<string>? StorageAccount { get; set; } [Input("tags")] private InputMap<string>? _tags; /// <summary> /// Contains resource tags defined as key/value pairs. /// </summary> public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } /// <summary> /// Name of Azure Machine Learning workspace. /// </summary> [Input("workspaceName", required: true)] public Input<string> WorkspaceName { get; set; } = null!; public WorkspaceArgs() { } } }
42.445578
148
0.603494
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/MachineLearningServices/V20200101/Workspace.cs
12,479
C#
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace BlazingPizza.Server { [Route("orders")] [ApiController] [Authorize] public class OrdersController : Controller { private readonly PizzaStoreContext _db; public OrdersController(PizzaStoreContext db) { _db = db; } [HttpGet] public async Task<ActionResult<List<OrderWithStatus>>> GetOrders() { var orders = await _db.Orders // .Where(o => o.UserId == GetUserId()) .Include(o => o.DeliveryLocation) .Include(o => o.Pizzas).ThenInclude(p => p.Special) .Include(o => o.Pizzas).ThenInclude(p => p.Toppings).ThenInclude(t => t.Topping) .OrderByDescending(o => o.CreatedTime) .ToListAsync(); return orders.Select(o => OrderWithStatus.FromOrder(o)).ToList(); } [HttpGet("{orderId}")] public async Task<ActionResult<OrderWithStatus>> GetOrderWithStatus(int orderId) { var order = await _db.Orders .Where(o => o.OrderId == orderId) // .Where(o => o.UserId == GetUserId()) .Include(o => o.DeliveryLocation) .Include(o => o.Pizzas).ThenInclude(p => p.Special) .Include(o => o.Pizzas).ThenInclude(p => p.Toppings).ThenInclude(t => t.Topping) .SingleOrDefaultAsync(); if (order == null) { return NotFound(); } return OrderWithStatus.FromOrder(order); } [HttpPost] public async Task<ActionResult<int>> PlaceOrder(Order order) { order.CreatedTime = DateTime.Now; order.DeliveryLocation = new LatLong(51.5001, -0.1239); // order.UserId = GetUserId(); // Enforce existence of Pizza.SpecialId and Topping.ToppingId // in the database - prevent the submitter from making up // new specials and toppings foreach (var pizza in order.Pizzas) { pizza.SpecialId = pizza.Special.Id; pizza.Special = null; foreach (var topping in pizza.Toppings) { topping.ToppingId = topping.Topping.Id; topping.Topping = null; } } _db.Orders.Attach(order); await _db.SaveChangesAsync(); // In the background, send push notifications if possible var subscription = await _db.NotificationSubscriptions.Where(e => e.UserId == GetUserId()).SingleOrDefaultAsync(); if (subscription != null) { _ = TrackAndSendNotificationsAsync(order, subscription); } return order.OrderId; } private string GetUserId() { return HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier); } private static async Task TrackAndSendNotificationsAsync(Order order, NotificationSubscription subscription) { // In a realistic case, some other backend process would track // order delivery progress and send us notifications when it // changes. Since we don't have any such process here, fake it. await Task.Delay(OrderWithStatus.PreparationDuration); await SendNotificationAsync(order, subscription, "Your order has been dispatched!"); await Task.Delay(OrderWithStatus.DeliveryDuration); await SendNotificationAsync(order, subscription, "Your order is now delivered. Enjoy!"); } private static Task SendNotificationAsync(Order order, NotificationSubscription subscription, string message) { // This will be implemented later return Task.CompletedTask; } } }
35.698276
126
0.585124
[ "MIT" ]
Aletho95/blazor-workshop
save-points/00-get-started/BlazingPizza.Server/OrdersController.cs
4,143
C#
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 CommandLine; using Google.Ads.GoogleAds.Lib; using Google.Ads.GoogleAds.V9.Errors; using Google.Ads.GoogleAds.V9.Resources; using Google.Ads.GoogleAds.V9.Services; using Google.Api.Gax; using System; using System.Collections.Generic; namespace Google.Ads.GoogleAds.Examples.V9 { /// <summary> /// This code example gets all account budget proposals. To add an account budget proposal, run /// AddAccountBudgetProposal.cs. /// </summary> public class GetAccountBudgetProposals : ExampleBase { /// <summary> /// Command line options for running the <see cref="GetAccountBudgetProposals"/> example. /// </summary> public class Options : OptionsBase { /// <summary> /// The Google Ads customer ID for which the call is made. /// </summary> [Option("customerId", Required = true, HelpText = "The Google Ads customer ID for which the call is made.")] public long CustomerId { get; set; } } /// <summary> /// Main method, to run this code example as a standalone application. /// </summary> /// <param name="args">The command line arguments.</param> public static void Main(string[] args) { Options options = new Options(); CommandLine.Parser.Default.ParseArguments<Options>(args).MapResult( delegate (Options o) { options = o; return 0; }, delegate (IEnumerable<Error> errors) { // The Google Ads customer ID for which the call is made. options.CustomerId = long.Parse("INSERT_CUSTOMER_ID_HERE"); return 0; }); GetAccountBudgetProposals codeExample = new GetAccountBudgetProposals(); Console.WriteLine(codeExample.Description); codeExample.Run(new GoogleAdsClient(), options.CustomerId); } /// <summary> /// The page size to be used by default. /// </summary> private const int PAGE_SIZE = 1_000; /// <summary> /// Returns a description about the code example. /// </summary> public override string Description => "This code example gets all account budget proposals. To add an account budget " + "proposal, run AddAccountBudgetProposal.cs."; /// <summary> /// Runs the code example. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The Google Ads customer ID for which the call is made.</param> public void Run(GoogleAdsClient client, long customerId) { // Get the GoogleAdsServiceClient. GoogleAdsServiceClient googleAdsService = client.GetService( Services.V9.GoogleAdsService); // Construct a GAQL query which will retrieve AccountBudgetProposals. String searchQuery = @"SELECT account_budget_proposal.id, account_budget_proposal.account_budget, account_budget_proposal.billing_setup, account_budget_proposal.status, account_budget_proposal.proposed_name, account_budget_proposal.proposed_notes, account_budget_proposal.proposed_purchase_order_number, account_budget_proposal.proposal_type, account_budget_proposal.approval_date_time, account_budget_proposal.creation_date_time FROM account_budget_proposal"; // Creates a request that will retrieve all account budget proposals using pages of the // specified page size. SearchGoogleAdsRequest request = new SearchGoogleAdsRequest() { PageSize = PAGE_SIZE, Query = searchQuery, CustomerId = customerId.ToString() }; try { // Issues the search request. PagedEnumerable<SearchGoogleAdsResponse, GoogleAdsRow> searchPagedResponse = googleAdsService.Search(request); // Iterates over all rows in all pages and prints the requested field values for the // account budget in each row. foreach (GoogleAdsRow googleAdsRow in searchPagedResponse) { AccountBudgetProposal proposal = googleAdsRow.AccountBudgetProposal; Console.WriteLine($"Account budget proposal with ID '{proposal.Id}' " + $"status '{proposal.Status}', account_budget '{proposal.AccountBudget}' " + $"billing_setup '{proposal.BillingSetup}', " + $"proposed_name '{proposal.ProposedName}', " + $"proposed_notes '{proposal.ProposedNotes}', " + $"proposed_po_number '{proposal.ProposedPurchaseOrderNumber}', " + $"proposal_type '{proposal.ProposalType}', " + $"approval_date_time '{proposal.ApprovalDateTime}', " + $"creation_date_time '{proposal.CreationDateTime}'."); } } catch (GoogleAdsException e) { Console.WriteLine("Failure:"); Console.WriteLine($"Message: {e.Message}"); Console.WriteLine($"Failure: {e.Failure}"); Console.WriteLine($"Request ID: {e.RequestId}"); throw; } } } }
42.52
100
0.584039
[ "Apache-2.0" ]
googleads/google-ads-dotnet
examples/Billing/GetAccountBudgetProposals.cs
6,378
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Problem_5.Word_in_Plural { class WordInPlural { static void Main(string[] args) { //Input string word = Console.ReadLine(); //Logic if (word.EndsWith("y")) { word = word.Remove(word.Length - 1); word += "ies"; } else if (word.EndsWith("o") || word.EndsWith("ch") || word.EndsWith("s") || word.EndsWith("sh") || word.EndsWith("x") || word.EndsWith("z")) { word += "es"; } else { word += "s"; } //Output Console.WriteLine(word); } } }
22.707317
52
0.404941
[ "MIT" ]
Badjanak/C-Sharp-Project
Programming Fundamentals/02. Conditional Statements and Loops-Exercise/Problem 5. Word in Plural/WordInPlural.cs
933
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using Mono.Cecil; using ILRuntime.Runtime.Intepreter; using ILRuntime.Runtime.Enviorment; using ILRuntime.CLR.TypeSystem; using ILRuntime.Runtime.Stack; using ILRuntime.CLR.Utils; namespace ILRuntime.CLR.Method { public class CLRMethod : IMethod { MethodInfo def; ConstructorInfo cDef; List<IType> parameters; ParameterInfo[] parametersCLR; ILRuntime.Runtime.Enviorment.AppDomain appdomain; CLRType declaringType; ParameterInfo[] param; bool isConstructor; CLRRedirectionDelegate redirect; IType[] genericArguments; Type[] genericArgumentsCLR; object[] invocationParam; bool isDelegateInvoke; int hashCode = -1; static int instance_id = 0x20000000; public IType DeclearingType { get { return declaringType; } } public string Name { get { return def.Name; } } public bool HasThis { get { return isConstructor ? !cDef.IsStatic : !def.IsStatic; } } public int GenericParameterCount { get { if (def.ContainsGenericParameters && def.IsGenericMethodDefinition) { return def.GetGenericArguments().Length; } return 0; } } public bool IsGenericInstance { get { return genericArguments != null; } } public bool IsDelegateInvoke { get { return isDelegateInvoke; } } public bool IsStatic { get { if (cDef != null) return cDef.IsStatic; else return def.IsStatic; } } public CLRRedirectionDelegate Redirection { get { return redirect; } } public MethodInfo MethodInfo { get { return def; } } public ConstructorInfo ConstructorInfo { get { return cDef; } } public IType[] GenericArguments { get { return genericArguments; } } public Type[] GenericArgumentsCLR { get { if(genericArgumentsCLR == null) { if (cDef != null) genericArgumentsCLR = cDef.GetGenericArguments(); else genericArgumentsCLR = def.GetGenericArguments(); } return genericArgumentsCLR; } } internal CLRMethod(MethodInfo def, CLRType type, ILRuntime.Runtime.Enviorment.AppDomain domain) { this.def = def; declaringType = type; this.appdomain = domain; param = def.GetParameters(); if (!def.ContainsGenericParameters) { ReturnType = domain.GetType(def.ReturnType.FullName); if (ReturnType == null) { ReturnType = domain.GetType(def.ReturnType.AssemblyQualifiedName); } } if (type.IsDelegate && def.Name == "Invoke") isDelegateInvoke = true; isConstructor = false; if (def != null) { if (def.IsGenericMethod && !def.IsGenericMethodDefinition) { //Redirection of Generic method Definition will be prioritized if(!appdomain.RedirectMap.TryGetValue(def.GetGenericMethodDefinition(), out redirect)) appdomain.RedirectMap.TryGetValue(def, out redirect); } else appdomain.RedirectMap.TryGetValue(def, out redirect); } } internal CLRMethod(ConstructorInfo def, CLRType type, ILRuntime.Runtime.Enviorment.AppDomain domain) { this.cDef = def; declaringType = type; this.appdomain = domain; param = def.GetParameters(); if (!def.ContainsGenericParameters) { ReturnType = type; } isConstructor = true; if (def != null) { appdomain.RedirectMap.TryGetValue(cDef, out redirect); } } public int ParameterCount { get { return param != null ? param.Length : 0; } } public List<IType> Parameters { get { if (parameters == null) { InitParameters(); } return parameters; } } public ParameterInfo[] ParametersCLR { get { if(parametersCLR == null) { if (cDef != null) parametersCLR = cDef.GetParameters(); else parametersCLR = def.GetParameters(); } return parametersCLR; } } public IType ReturnType { get; private set; } public bool IsConstructor { get { return cDef != null; } } void InitParameters() { parameters = new List<IType>(); foreach (var i in param) { IType type = appdomain.GetType(i.ParameterType.FullName); if (type == null) type = appdomain.GetType(i.ParameterType.AssemblyQualifiedName); if (i.ParameterType.IsGenericTypeDefinition) { if (type == null) type = appdomain.GetType(i.ParameterType.GetGenericTypeDefinition().FullName); if (type == null) type = appdomain.GetType(i.ParameterType.GetGenericTypeDefinition().AssemblyQualifiedName); } if (i.ParameterType.ContainsGenericParameters) { var t = i.ParameterType; if (t.HasElementType) t = i.ParameterType.GetElementType(); else if (t.GetGenericArguments().Length > 0) { t = t.GetGenericArguments()[0]; } type = new ILGenericParameterType(t.Name); } if (type == null) throw new TypeLoadException(); parameters.Add(type); } } unsafe StackObject* Minus(StackObject* a, int b) { return (StackObject*)((long)a - sizeof(StackObject) * b); } public unsafe object Invoke(Runtime.Intepreter.ILIntepreter intepreter, StackObject* esp, IList<object> mStack, bool isNewObj = false) { if (parameters == null) { InitParameters(); } int paramCount = ParameterCount; if (invocationParam == null) invocationParam = new object[paramCount]; object[] param = invocationParam; for (int i = paramCount; i >= 1; i--) { var p = Minus(esp, i); var pt = this.param[paramCount - i].ParameterType; var obj = pt.CheckCLRTypes(StackObject.ToObject(p, appdomain, mStack)); obj = ILIntepreter.CheckAndCloneValueType(obj, appdomain); param[paramCount - i] = obj; } if (isConstructor) { if (!isNewObj) { if (!cDef.IsStatic) { object instance = declaringType.TypeForCLR.CheckCLRTypes(StackObject.ToObject((Minus(esp, paramCount + 1)), appdomain, mStack)); if (instance == null) throw new NullReferenceException(); if (instance is CrossBindingAdaptorType && paramCount == 0)//It makes no sense to call the Adaptor's default constructor return null; cDef.Invoke(instance, param); return null; } else { throw new NotImplementedException(); } } else { var res = cDef.Invoke(param); FixReference(paramCount, esp, param, mStack, null, false); return res; } } else { object instance = null; if (!def.IsStatic) { instance = StackObject.ToObject((Minus(esp, paramCount + 1)), appdomain, mStack); if (!(instance is Reflection.ILRuntimeWrapperType)) instance = declaringType.TypeForCLR.CheckCLRTypes(instance); if (declaringType.IsValueType) instance = ILIntepreter.CheckAndCloneValueType(instance, appdomain); if (instance == null) throw new NullReferenceException(); } object res = null; /*if (redirect != null) res = redirect(new ILContext(appdomain, intepreter, esp, mStack, this), instance, param, genericArguments); else*/ { res = def.Invoke(instance, param); } FixReference(paramCount, esp, param, mStack, instance, !def.IsStatic); return res; } } unsafe void FixReference(int paramCount, StackObject* esp, object[] param, IList<object> mStack,object instance, bool hasThis) { var cnt = hasThis ? paramCount + 1 : paramCount; for (int i = cnt; i >= 1; i--) { var p = Minus(esp, i); var val = i <= paramCount ? param[paramCount - i] : instance; switch (p->ObjectType) { case ObjectTypes.StackObjectReference: { var addr = *(long*)&p->Value; var dst = (StackObject*)addr; if (dst->ObjectType >= ObjectTypes.Object) { var obj = val; if (obj is CrossBindingAdaptorType) obj = ((CrossBindingAdaptorType)obj).ILInstance; mStack[dst->Value] = obj; } else { ILIntepreter.UnboxObject(dst, val, mStack, appdomain); } } break; case ObjectTypes.FieldReference: { var obj = mStack[p->Value]; if(obj is ILTypeInstance) { ((ILTypeInstance)obj)[p->ValueLow] = val; } else { var t = appdomain.GetType(obj.GetType()) as CLRType; t.GetField(p->ValueLow).SetValue(obj, val); } } break; case ObjectTypes.StaticFieldReference: { var t = appdomain.GetType(p->Value); if(t is ILType) { ((ILType)t).StaticInstance[p->ValueLow] = val; } else { ((CLRType)t).SetStaticFieldValue(p->ValueLow, val); } } break; case ObjectTypes.ArrayReference: { var arr = mStack[p->Value] as Array; arr.SetValue(val, p->ValueLow); } break; } } } public IMethod MakeGenericMethod(IType[] genericArguments) { Type[] p = new Type[genericArguments.Length]; for (int i = 0; i < genericArguments.Length; i++) { p[i] = genericArguments[i].TypeForCLR; } var t = def.MakeGenericMethod(p); var res = new CLRMethod(t, declaringType, appdomain); res.genericArguments = genericArguments; return res; } public override string ToString() { if (def != null) return def.ToString(); else return cDef.ToString(); } public override int GetHashCode() { if (hashCode == -1) hashCode = System.Threading.Interlocked.Add(ref instance_id, 1); return hashCode; } } }
34.432692
153
0.428372
[ "MIT" ]
naivetang/2019MiniGame22
Unity/Assets/ThirdParty/ILRuntime/ILRuntime/CLR/Method/CLRMethod.cs
14,326
C#
using UnityEngine; using System.Collections; /* ---------------------------------------- * class to demonstrate how to control a * character using Character Controller and the Mecanim system */ public class BasicController: MonoBehaviour { // reference to character's Animator component private Animator anim; // reference to character's Character Controller component private CharacterController controller; // dampening speed public float transitionTime = .25f; // speed limit private float speedLimit = 1.0f; // moving diagonally glaf (true then combine x and z speed) public bool moveDiagonally = true; // control character's direction with mouse public bool mouseRotate = true; // control character's direction with keyboard public bool keyboardRotate = false; /* ---------------------------------------- * cache character's Animator and Character Controller components */ void Start () { controller = GetComponent<CharacterController>(); anim = GetComponent<Animator>(); } /* ---------------------------------------- * Whenever Directional controls are used, update variables from the Animator */ void Update () { // IF Character Controller is grounded... if(controller.isGrounded){ if (Input.GetKey (KeyCode.RightShift) ||Input.GetKey (KeyCode.LeftShift)) // IF Shift key is pressed, THEN set speed limit to 0.5, slowing down the character speedLimit = 0.5f; else // ELSE, set speed limit to full speed (1.0) speedLimit = 1.0f; // a float variable to get Horizontal Axis input (left/right) float h = Input.GetAxis("Horizontal"); // a float variable to get Vertical Axis input (forward/backwards) float v = Input.GetAxis("Vertical"); // float variable for horizontal speed and direction, obtained by multiplying Horizontal Axis by the speed limit float xSpeed = h * speedLimit; // float variable for vertical speed and direction, obtained by multiplying Vertical Axis by the speed limit float zSpeed = v * speedLimit; // float variable for absolute speed float speed = Mathf.Sqrt(h*h+v*v); if(v!=0 && !moveDiagonally) // IF Vertical Axis input is different than 0 AND moveDiagonally boolean is set to false, THEN set horizontal speed as 0 xSpeed = 0; if(v!=0 && keyboardRotate) // IF Vertical Axis input is different than 0 AND keyboardRotate boolean is set to true, THEN rotate character according to Horizontal Axis input this.transform.Rotate(Vector3.up * h, Space.World); if(mouseRotate) // IF mouseRotate boolean is set to true, THEN rotate character according to Horizontal mouse movement this.transform.Rotate(Vector3.up * (Input.GetAxis("Mouse X")) * Mathf.Sign(v), Space.World); // Set zSpeed float as 'zSpeed' variable of the Animator, dampening it for the amount of time in 'transitionTime' anim.SetFloat("zSpeed", zSpeed, transitionTime, Time.deltaTime); // Set xSpeed float as 'xSpeed' variable of the Animator, dampening it for the amount of time in 'transitionTime' anim.SetFloat("xSpeed", xSpeed, transitionTime, Time.deltaTime); // Set speed float as 'Speed' variable of the Animator, dampening it for the amount of time in 'transitionTime' anim.SetFloat("Speed", speed, transitionTime, Time.deltaTime); } if(Input.GetKeyDown(KeyCode.F)){ anim.SetBool("Grenade", true); } else { anim.SetBool("Grenade", false); } if(Input.GetButtonDown("Fire1")){ anim.SetBool("Fire", true); } if(Input.GetButtonUp("Fire1")){ anim.SetBool("Fire", false); } } }
33.579439
149
0.690231
[ "MIT" ]
Brian-Holmes/Unity-2018-Cookbook-Third-Edition
Chapter10_3DAnimation/10_03_mix_mask_anims/BasicController.cs
3,595
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 01.05.2021. using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.GreaterThan.Complete.NullableInt16.DECIMAL_6_1{ //////////////////////////////////////////////////////////////////////////////// using T_DATA1 =System.Nullable<System.Int16>; using T_DATA2 =System.Decimal; using T_DATA1_U=System.Int16; using T_DATA2_U=System.Decimal; //////////////////////////////////////////////////////////////////////////////// //class TestSet_001__fields__03__NV public static class TestSet_001__fields__03__NV { private const string c_NameOf__TABLE ="TEST_MODIFY_ROW2"; private const string c_NameOf__COL_DATA1 ="COL_SMALLINT"; private const string c_NameOf__COL_DATA2 ="COL2_DEC_6_1"; private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("TEST_ID")] public System.Int64? TEST_ID { get; set; } [Column(c_NameOf__COL_DATA1)] public T_DATA1 COL_DATA1 { get; set; } [Column(c_NameOf__COL_DATA2,TypeName="DECIMAL(6,1)")] public T_DATA2 COL_DATA2 { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext };//class MyContext //----------------------------------------------------------------------- [Test] public static void Test_001() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { const T_DATA2_U c_value2=4; System.Int64? testID=Helper__InsertRow(db,null,c_value2); var recs=db.testTable.Where(r => (r.COL_DATA1 /*OP{*/ > /*}OP*/ r.COL_DATA2) && r.TEST_ID==testID); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE (").N("t",c_NameOf__COL_DATA1).T(" > ").N("t",c_NameOf__COL_DATA2).T(") AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")); }//using db tr.Rollback(); }//using tr }//using cn }//Test_001 //----------------------------------------------------------------------- [Test] public static void Test_002() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { const T_DATA2_U c_value2=4; System.Int64? testID=Helper__InsertRow(db,null,c_value2); var recs=db.testTable.Where(r => !(r.COL_DATA1 /*OP{*/ > /*}OP*/ r.COL_DATA2) && r.TEST_ID==testID); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE NOT (").N("t",c_NameOf__COL_DATA1).T(" > ").N("t",c_NameOf__COL_DATA2).T(") AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")); }//using db tr.Rollback(); }//using tr }//using cn }//Test_002 //Helper methods -------------------------------------------------------- private static System.Int64 Helper__InsertRow(MyContext db, T_DATA1 valueForColData1, T_DATA2 valueForColData2) { var newRecord=new MyContext.TEST_RECORD(); newRecord.COL_DATA1 =valueForColData1; newRecord.COL_DATA2 =valueForColData2; db.testTable.Add(newRecord); db.SaveChanges(); db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("INSERT INTO ").N(c_NameOf__TABLE).T(" (").N(c_NameOf__COL_DATA1).T(", ").N(c_NameOf__COL_DATA2).T(")").EOL() .T("VALUES (").P("p0").T(", ").P("p1").T(")").EOL() .T("RETURNING ").N("TEST_ID").EOL() .T("INTO ").P("p2").T(";")); Assert.IsTrue (newRecord.TEST_ID.HasValue); Console.WriteLine("TEST_ID: {0}",newRecord.TEST_ID.Value); return newRecord.TEST_ID.Value; }//Helper__InsertRow };//class TestSet_001__fields__03__NV //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.GreaterThan.Complete.NullableInt16.DECIMAL_6_1
32.68323
155
0.570886
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D1/Query/Operators/SET_001/GreaterThan/Complete/NullableInt16/DECIMAL_6_1/TestSet_001__fields__03__NV.cs
5,264
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Wangkanai.Architecture.Shared; namespace Wangkanai.Architecture.Server.Controllers { [Authorize] [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; } [HttpGet] public IEnumerable<WeatherForecast> Get() { var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)] }) .ToArray(); } } }
29.209302
110
0.621019
[ "Apache-2.0" ]
wangkanai/Architecture
src/Server/Controllers/WeatherForecastController.cs
1,258
C#
using System; using Deveroom.VisualStudio.Common; using Deveroom.VisualStudio.Discovery; namespace Deveroom.VisualStudio.ProjectSystem.Actions { public class SourceLocationContextMenuItem : ContextMenuItem { private readonly string _originalLabel; private readonly SourceLocation _sourceLocation; public SourceLocationContextMenuItem( SourceLocation sourceLocation, string baseFolder, string label, Action<ContextMenuItem> command = null, string icon = null) : base(GetMenuItemLabel(sourceLocation, baseFolder, label), command, icon) { _sourceLocation = sourceLocation; _originalLabel = label; } private static string GetMenuItemLabel(SourceLocation sourceLocation, string baseFolder, string label) { var relativeFilePath = FileSystemHelper.GetRelativePathForFolder(sourceLocation.SourceFile, baseFolder); return $"{relativeFilePath}({sourceLocation.SourceFileLine},{sourceLocation.SourceFileColumn}): {label}"; } public string GetSearchResultLabel() { return $"{_sourceLocation.SourceFile}({_sourceLocation.SourceFileLine},{_sourceLocation.SourceFileColumn}): {_originalLabel}"; } } }
40.21875
138
0.705517
[ "MIT" ]
Philip-Gullick/deveroom-visualstudio
Deveroom.VisualStudio/ProjectSystem/Actions/SourceLocationContextMenuItem.cs
1,289
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace VersionDB { class Program { static int LoadConfigurations() { try { ConfigReader.ReadConfig(); } catch (Exception ex) { Display.DisplayMessage(DisplayType.Error, "Error reading configuration file. Exception:\n{0}", ex); Console.ReadLine(); return -1; } Constants.CHANGE_SCRIPT_DIRECTORY = System.IO.Path.Combine(Constants.WORKING_DIR_ROOT, ConfigReader.Config.ChangeScriptDirectory.Path); Constants.CHANGE_LOG_TABLE = ConfigReader.Config.LogTable.SchemaName + "." + ConfigReader.Config.LogTable.TableName; Constants.CHANGE_LOG_TABLE_WITHOUT_SCHEMA = ConfigReader.Config.LogTable.TableName; Logger.Initialize(System.IO.Path.Combine(Constants.WORKING_DIR_ROOT, ConfigReader.Config.LogDirectory.Path)); try { ChangeReader.ReadAllChanges(); } catch (Exception ex) { Display.DisplayMessage(DisplayType.Error, "Error reading change xml scripts. Exception:\n{0}", ex); Console.ReadLine(); return -1; } return 0; } static void Main(string[] args) { Display.InitializeDisplay(); if (LoadConfigurations() == -1) { return; } bool isDefaultDatabaseSpecified = ConfigReader.Config.DatabaseGroups.Count(x => x.Name == "DEFAULT") == 1; if (isDefaultDatabaseSpecified && ChangeReader.AllReleaseChanges.Count > 0) { Display.DisplayMessage(DisplayType.General, "Press ENTER to execute latest changes (up to version \"{0}\") in the latest release script (\"{1}\") to \"DEFAULT\" database group.\nElse enter specific command. To exit type \"Q\". Type \"-help\" for help.", ChangeReader.AllReleaseChanges.FirstOrDefault(x => x.IsLatestRelease).LastChangeVersion, ChangeReader.AllReleaseChanges.FirstOrDefault(x => x.IsLatestRelease).Name); } else { Display.DisplayMessage(DisplayType.General, "Enter command. To exit type \"Q\". Type \"-help\" for help."); } CommandManager commandManager = new CommandManager(); string command = commandManager.GetCommand(); while (command != "Q") { try { if (string.IsNullOrEmpty(command)) { if (isDefaultDatabaseSpecified && ChangeReader.AllReleaseChanges.Count > 0) { ChangeExecutor.ExecuteChanges(ConfigReader.Config.DatabaseGroups.FirstOrDefault(x => x.Name == "DEFAULT")); } else { Display.DisplayMessage(DisplayType.Warning, "Incorrect Command."); } } else if (command.StartsWith("-init")) { string[] options = command.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); if (options.Length != 2) { Display.DisplayMessage(DisplayType.Warning, "Incorrect command. Correct format is -init<space>{database_group}"); } else if (ConfigReader.Config.DatabaseGroups.Count(x => x.Name == options[1]) == 0) { Display.DisplayMessage(DisplayType.Warning, "Specified database group does not exist in the config file."); } else { Initializer.Initialize(ConfigReader.Config.DatabaseGroups.Where(x => x.Name == options[1]).FirstOrDefault()); } } else if (command.StartsWith("-generatescript")) { string[] options = command.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); if (options.Length != 2) { Display.DisplayMessage(DisplayType.Warning, "Incorrect command. Correct format is -generatescript<space>{database_group}"); } else if (ConfigReader.Config.DatabaseGroups.Count(x => x.Name == options[1]) == 0) { Display.DisplayMessage(DisplayType.Warning, "Specified database group does not exist in the config file."); } else { DatabaseScriptGenerator.ScriptGenerator generator = new DatabaseScriptGenerator.ScriptGenerator(ConfigReader.Config.DatabaseGroups.FirstOrDefault(x => x.Name == options[1]).Databases[0].ConnectionString, Constants.CHANGE_SCRIPT_DIRECTORY); generator.GenerateScriptAndWriteXML(); } } else if (command.StartsWith("-status")) { string[] options = command.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); if (options.Length != 2) { Display.DisplayMessage(DisplayType.Warning, "Incorrect command. Correct format is -status<space>{database_group}"); } else if (ConfigReader.Config.DatabaseGroups.Count(x => x.Name == options[1]) == 0) { Display.DisplayMessage(DisplayType.Warning, "Specified database group does not exist in the config file."); } else { ChangeExecutor.ShowLastExecutedChanges(ConfigReader.Config.DatabaseGroups.Where(x => x.Name == options[1]).FirstOrDefault()); } } else if (command.StartsWith("-log")) { string[] options = command.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); int changeVersion = -1; if (options.Length != 4 || !Int32.TryParse(options[3], out changeVersion)) { Display.DisplayMessage(DisplayType.Warning, "Incorrect command. Correct format is -log<space>{database_group}<space>{release_version}<space>{change_version}"); } else if (ConfigReader.Config.DatabaseGroups.Count(x => x.Name == options[1]) == 0) { Display.DisplayMessage(DisplayType.Warning, "Specified database group does not exist in the config file."); } else { Initializer.LogChanges(ConfigReader.Config.DatabaseGroups.Where(x => x.Name == options[1]).FirstOrDefault(), options[2], changeVersion); } } else if (command.StartsWith("-clear")) { Console.Clear(); } else if (command.StartsWith("-reload")) { if (LoadConfigurations() == -1) { return; } isDefaultDatabaseSpecified = ConfigReader.Config.DatabaseGroups.Count(x => x.Name == "DEFAULT") == 1; commandManager = new CommandManager(); Display.DisplayMessage(DisplayType.Info, "All Configurations have been reloaded."); } else if (command.StartsWith("-help")) { Display.DisplayMessage(DisplayType.Info, @" >> {database_group}<space>{release_version}<space>{change_version} Executes the changes up to {change_version} in {release_version} in the databases in {database_group}. >> {database_group}<space>{release_version} Executes all the latest changes in {release_version} in the databases in {database_group}. >> {database_group} Executes all the latest changes in the latest release version in the databases in {database_group}. >> ENTER (Key press) Executes all the latest changes in the latest release version in the databases in ""DEFAULT"" database_group. >> {database_group}<space>{release_version}<space>{change_version}<space>-force Forcibly executes (even if version chain is not maintained) the changes in {change_version} in the {release_version} in the databases in {database_group} without inserting the log. >> -status<space>{database_group} Shows the current status of the databases in the specified {database_group}. >> -init<space>{database_group} Creates the log table in the databases in {database_group}. >> -generatescript<space>{database_group} Creates the exisitng table/SP/function scripts from the first database in the specified {database_group}. Should be used if the tool is intended to use from an existing database and to automatically generate the scripts for the first time. >> -log<space>{database_group}<space>{release_version}<space>{change_version} Inserts all the logs up to given {change_version} and {release_version} in the databases in {database_group}. It's helpful to insert logs in the existing databases for the first time without actually executing the changes. >> -reload Reloads all the configurations (Config XML and Change XMLs). >> -clear Clears the screen "); } else { string[] parameters = command.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); DatabaseGroup databaseGroup = ConfigReader.Config.DatabaseGroups.FirstOrDefault(x => x.Name == parameters[0]); int changeVersion = -1; if (databaseGroup == null) { Display.DisplayMessage(DisplayType.Warning, "Database Group - {0} does not exist.", parameters[0]); } else if (parameters.Length == 1) { ChangeExecutor.ExecuteChanges(databaseGroup); } else if (parameters.Length == 2) { ChangeExecutor.ExecuteChanges(databaseGroup, parameters[1]); } else if ((parameters.Length == 3 || (parameters.Length == 4 && parameters[3] == "-force")) && Int32.TryParse(parameters[2], out changeVersion)) { ChangeExecutor.ExecuteChanges(databaseGroup, parameters[1], changeVersion, (parameters.Length == 4 && parameters[3] == "-force")); } else { Display.DisplayMessage(DisplayType.Warning, "Incorrect Command."); } } } catch (Exception ex) { if (ex is VersioningException) { Display.DisplayMessage(DisplayType.Warning, ex.Message); } else { Display.DisplayMessage(DisplayType.Error, "The command was aborted due to exception - {0}", ex); } } Display.DisplayMessage(DisplayType.General, "\n\nEnter command. To exit type \"Q\". Type \"-help\" for help."); command = commandManager.GetCommand(); } } } public static class Constants { public static string WORKING_DIR_ROOT = Environment.CurrentDirectory; public static string CHANGE_LOG_TABLE = "dbo._DB_VERSIONING_CHANGE_LOG"; public static string CHANGE_LOG_TABLE_WITHOUT_SCHEMA = "_DB_VERSIONING_CHANGE_LOG"; public static string CHANGE_SCRIPT_DIRECTORY; } }
51.064257
269
0.530161
[ "MIT" ]
m-nasif/VersionDB
Source/Program.cs
12,717
C#
using System; namespace SKIT.FlurlHttpClient.Wechat.Api.Models { /// <summary> /// <para>表示 [POST] /componenttcb/getbucket 接口的响应。</para> /// </summary> public class ComponentTcbGetBucketResponse : WechatApiResponse { public static class Types { public class File { /// <summary> /// 获取或设置文件名称。 /// </summary> [Newtonsoft.Json.JsonProperty("key")] [System.Text.Json.Serialization.JsonPropertyName("key")] public string FileKey { get; set; } = default!; /// <summary> /// 获取或设置文件的 MD5 值。 /// </summary> [Newtonsoft.Json.JsonProperty("md5")] [System.Text.Json.Serialization.JsonPropertyName("md5")] public string FileMd5 { get; set; } = default!; /// <summary> /// 获取或设置文件大小(单位:字节)。 /// </summary> [Newtonsoft.Json.JsonProperty("size")] [System.Text.Json.Serialization.JsonPropertyName("size")] [System.Text.Json.Serialization.JsonNumberHandling(System.Text.Json.Serialization.JsonNumberHandling.AllowReadingFromString)] public int FileSize { get; set; } /// <summary> /// 获取或设置最近修改时间。 /// </summary> [Newtonsoft.Json.JsonProperty("last_modified")] [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.RFC3339DateTimeOffsetConverter))] [System.Text.Json.Serialization.JsonPropertyName("last_modified")] [System.Text.Json.Serialization.JsonConverter(typeof(System.Text.Json.Converters.RFC3339DateTimeOffsetConverter))] public DateTimeOffset LastModifiedTime { get; set; } } } /// <summary> /// 获取或设置文件列表。 /// </summary> [Newtonsoft.Json.JsonProperty("contents")] [System.Text.Json.Serialization.JsonPropertyName("contents")] public Types.File[] FileList { get; set; } = default!; /// <summary> /// 获取或设置内容是否被截断。 /// </summary> [Newtonsoft.Json.JsonProperty("is_truncated")] [System.Text.Json.Serialization.JsonPropertyName("is_truncated")] public bool IsTruncated { get; set; } } }
38.854839
141
0.557493
[ "MIT" ]
OrchesAdam/DotNetCore.SKIT.FlurlHttpClient.Wechat
src/SKIT.FlurlHttpClient.Wechat.Api/Models/ComponentTcb/COS/ComponentTcbGetBucketResponse.cs
2,571
C#
using System; using System.Text.RegularExpressions; namespace _06.SentenceExtractor { public class SentenceExtractor { public static void Main() { var word = Console.ReadLine(); var text = Console.ReadLine(); var pattern = string.Format(@"[^.?!]+\b{0}\b.*?[!.?]", word); var regexKey = new Regex(pattern); var sentences = regexKey.Matches(text); foreach (Match sentence in sentences) { Console.WriteLine(sentence); } } } }
26.045455
73
0.534031
[ "MIT" ]
mdamyanova/C-Sharp-Web-Development
08.C# Fundamentals/08.01.C# Advanced/11.Regular Expressions - Exercise/06.SentenceExtractor/SentenceExtractor.cs
575
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Microsoft.Owin; using Owin; using Microsoft.Owin.Security.Cookies; using System.Security.Claims; using System.Threading.Tasks; using Kentor.OwinCookieSaver; [assembly: OwinStartup(typeof(SampleWebApp.App_Start.Startup))] namespace SampleWebApp.App_Start { public class Startup { class ConditionalMiddlewareInvoker : OwinMiddleware { public ConditionalMiddlewareInvoker(OwinMiddleware next) : base(next) { } public async override Task Invoke(IOwinContext context) { if (context.Request.Path.StartsWithSegments(new PathString("/Fixed")) || context.Request.Path.StartsWithSegments(new PathString("/DuplicateSetCookieHeader"))) { await (new KentorOwinCookieSaverMiddleware(Next)).Invoke(context); } else { await Next.Invoke(context); } } } public void Configuration(IAppBuilder app) { // In normal applications, the cookie saver middleware would be // registered here. In this proof of concept application however // we want to be able to show the behaviour both with and without // the cookie saver middleware enabled. Because of this a hack is // used that only enables the cookie saver middleware when invoked // on certain paths. app.Use(typeof(ConditionalMiddlewareInvoker)); app.UseCookieAuthentication(new CookieAuthenticationOptions()); // Simulate an external login middleware for any Url ending with SetAuthCookie app.Use(async (context, next) => { var lastPart = context.Request.Path.Value.Split('/').Last(); if (lastPart == "SetAuthCookie") { var identity = new ClaimsIdentity("Cookies"); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "NameId")); context.Authentication.SignIn(identity); context.Response.Redirect("Results"); } else { await next.Invoke(); } }); } } }
36.397059
105
0.566869
[ "MIT" ]
AndreiZe/owin-cookie-saver
SampleWebApp/App_Start/Startup.Auth.cs
2,477
C#
using WhoPK.GameLogic.Character; using WhoPK.GameLogic.World.Room; using System; using System.Collections.Generic; using System.Text; namespace WhoPK.GameLogic.Commands { public interface ICommands { void CommandList(string key, string options, Player player, Room room); void ProcessCommand(string command, Player player, Room room); } }
24.6
79
0.742547
[ "MIT" ]
mbevier/ArchaicQuest-II
WhoPK.GameLogic/Commands/ICommands.cs
371
C#
using Relo; using System.Runtime.InteropServices; namespace SageBinaryData { [StructLayout(LayoutKind.Sequential)] public struct TemporalSineWave { public Time WaveLength; public float Amplitude; } [StructLayout(LayoutKind.Sequential)] public struct CameraShift { public ClientRandomVariable Randomness; public List<TemporalSineWave> SineWave; } [StructLayout(LayoutKind.Sequential)] public struct PhaseEffect { public BaseInheritableAsset Base; public AssetReference<BaseRenderAssetType> PhaseMaskModel; public FXShaderMaterial PhaseStateShader; public CameraShift CameraShift; } }
24.103448
66
0.706724
[ "MIT" ]
Qibbi/BinaryAssetBuilder
source/SageBinaryData/SageBinaryData/PhaseEffect.cs
701
C#
namespace WebWarehouse.Services.Messaging { using System.Collections.Generic; using System.Threading.Tasks; public class NullMessageSender : IEmailSender { public Task SendEmailAsync( string from, string fromName, string to, string subject, string htmlContent, IEnumerable<EmailAttachment> attachments = null) { return Task.CompletedTask; } } }
23.75
60
0.593684
[ "MIT" ]
iltodbul/WebWarehouse
Services/WebWarehouse.Services.Messaging/NullMessageSender.cs
477
C#
#region Usings using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Stomp.Net.Messaging; using Stomp.Net.Stomp.Commands; using Stomp.Net.Util; using Stomp.Net.Utilities; #endregion namespace Stomp.Net.Stomp { /// <summary> /// An object capable of receiving messages from some destination /// </summary> public class MessageConsumer : Disposable, IMessageConsumer, IDispatcher { #region Properties public Exception FailureError { get; set; } #endregion #region Ctor // Constructor internal to prevent clients from creating an instance. internal MessageConsumer( Session session, ConsumerId id, IDestination destination, String name, String selector, Int32 prefetch, Boolean noLocal ) { if ( destination == null ) throw new InvalidDestinationException( "Consumer cannot receive on null Destinations." ); _session = session; RedeliveryPolicy = _session.Connection.RedeliveryPolicy; ConsumerInfo = new() { ConsumerId = id, Destination = Destination.Transform( destination ), SubscriptionName = name, Selector = selector, PrefetchSize = prefetch, MaximumPendingMessageLimit = session.Connection.PrefetchPolicy.MaximumPendingMessageLimit, NoLocal = noLocal, DispatchAsync = session.DispatchAsync, Retroactive = session.Retroactive, Exclusive = session.Exclusive, Priority = session.Priority, AckMode = session.AcknowledgementMode }; // Removed unused consumer. options (ConsumerInfo => "consumer.") // TODO: Implement settings? // Removed unused message consumer. options (this => "consumer.nms.") // TODO: Implement settings? } #endregion public void Dispatch( MessageDispatch dispatch ) { var listener = _listener; try { lock ( _syncRoot ) { if ( _clearDispatchList ) { // we are reconnecting so lets flush the in progress messages _clearDispatchList = false; _unconsumedMessages.Clear(); // on resumption a pending delivered ACK will be out of sync with // re-deliveries. _pendingAck = null; } if ( !_unconsumedMessages.Stopped ) if ( listener != null && _unconsumedMessages.Started ) { var message = CreateStompMessage( dispatch ); BeforeMessageIsConsumed( dispatch ); try { var expired = !IgnoreExpiration && message.IsExpired(); if ( !expired ) listener( message ); AfterMessageIsConsumed( dispatch, expired ); } catch ( Exception e ) { if ( _session.IsAutoAcknowledge || _session.IsIndividualAcknowledge ) { // Redeliver the message } else // Transacted or Client ACK: Deliver the next message. AfterMessageIsConsumed( dispatch, false ); if ( Tracer.IsErrorEnabled ) Tracer.Error( ConsumerInfo.ConsumerId + " Exception while processing message: " + e ); } } else _unconsumedMessages.Enqueue( dispatch ); } if ( ++_dispatchedCount % 1000 != 0 ) return; _dispatchedCount = 0; Thread.Sleep( 1 ); } catch ( Exception e ) { _session.Connection.OnSessionException( _session, e ); } } public Boolean Iterate() { if ( _listener == null ) return false; var dispatch = _unconsumedMessages.DequeueNoWait(); if ( dispatch == null ) return false; try { var message = CreateStompMessage( dispatch ); BeforeMessageIsConsumed( dispatch ); // ReSharper disable once PossibleNullReferenceException _listener( message ); AfterMessageIsConsumed( dispatch, false ); } catch ( StompException ex ) { _session.Connection.OnSessionException( _session, ex ); } return true; } public void Start() { if ( _unconsumedMessages.Stopped ) return; _started.Value = true; _unconsumedMessages.Start(); _session.Executor.Wakeup(); } #region Override of Disposable /// <summary> /// Method invoked when the instance gets disposed. /// </summary> protected override void Disposed() { try { Close(); } catch { // Ignore network errors. } } #endregion internal void Acknowledge() { lock ( _dispatchedMessages ) { // Acknowledge all messages so far. var ack = MakeAckForAllDeliveredMessages(); if ( ack == null ) return; // no msgs if ( _session.IsTransacted ) { _session.DoStartTransaction(); ack.TransactionId = _session.TransactionContext.TransactionId; } _session.SendAck( ack ); _pendingAck = null; // Adjust the counters _deliveredCounter = Math.Max( 0, _deliveredCounter - _dispatchedMessages.Count ); _additionalWindowSize = Math.Max( 0, _additionalWindowSize - _dispatchedMessages.Count ); if ( !_session.IsTransacted ) _dispatchedMessages.Clear(); } } internal void ClearMessagesInProgress() { if ( !_inProgressClearRequiredFlag ) return; lock ( _unconsumedMessages ) if ( _inProgressClearRequiredFlag ) { _unconsumedMessages.Clear(); _synchronizationRegistered = false; // allow dispatch on this connection to resume _inProgressClearRequiredFlag = false; } } internal void InProgressClearRequired() { _inProgressClearRequiredFlag = true; // deal with delivered messages async to avoid lock contention with in progress acks _clearDispatchList = true; } internal void Rollback() { lock ( _syncRoot ) lock ( _dispatchedMessages ) { if ( _dispatchedMessages.Count == 0 ) return; // Only increase the redelivery delay after the first redelivery.. var lastMd = _dispatchedMessages.First(); var currentRedeliveryCount = lastMd.Message.RedeliveryCounter; _redeliveryDelay = RedeliveryPolicy.RedeliveryDelay( currentRedeliveryCount ); foreach ( var dispatch in _dispatchedMessages ) dispatch.Message.OnMessageRollback(); if ( RedeliveryPolicy.MaximumRedeliveries >= 0 && lastMd.Message.RedeliveryCounter > RedeliveryPolicy.MaximumRedeliveries ) _redeliveryDelay = 0; else { // stop the delivery of messages. _unconsumedMessages.Stop(); foreach ( var dispatch in _dispatchedMessages ) _unconsumedMessages.Enqueue( dispatch, true ); if ( _redeliveryDelay > 0 && !_unconsumedMessages.Stopped ) { var deadline = DateTime.Now.AddMilliseconds( _redeliveryDelay ); ThreadPool.QueueUserWorkItem( RollbackHelper, deadline ); } else Start(); } _deliveredCounter -= _dispatchedMessages.Count; _dispatchedMessages.Clear(); } // Only redispatch if there's an async _listener otherwise a synchronous // consumer will pull them from the local queue. if ( _listener != null ) _session.Redispatch( _unconsumedMessages ); } // ReSharper disable once InconsistentNaming private event Action<IBytesMessage> _listener; private void AckLater( MessageDispatch dispatch ) { // Don't acknowledge now, but we may need to let the broker know the // consumer got the message to expand the pre-fetch window if ( _session.IsTransacted ) { _session.DoStartTransaction(); if ( !_synchronizationRegistered ) { _synchronizationRegistered = true; _session.TransactionContext.AddSynchronization( new MessageConsumerSynchronization( this ) ); } } _deliveredCounter++; var oldPendingAck = _pendingAck; _pendingAck = new() { AckType = (Byte) AckType.ConsumedAck, ConsumerId = ConsumerInfo.ConsumerId, Destination = dispatch.Destination, LastMessageId = dispatch.Message.MessageId, MessageCount = _deliveredCounter }; if ( _session.IsTransacted && _session.TransactionContext.InTransaction ) _pendingAck.TransactionId = _session.TransactionContext.TransactionId; if ( oldPendingAck == null ) _pendingAck.FirstMessageId = _pendingAck.LastMessageId; if ( !( 0.5 * ConsumerInfo.PrefetchSize <= _deliveredCounter - _additionalWindowSize ) ) return; _session.SendAck( _pendingAck ); _pendingAck = null; _deliveredCounter = 0; _additionalWindowSize = 0; } private void BeforeMessageIsConsumed( MessageDispatch dispatch ) { lock ( _dispatchedMessages ) _dispatchedMessages.Insert( 0, dispatch ); if ( _session.IsTransacted ) AckLater( dispatch ); } private void Commit() { lock ( _dispatchedMessages ) _dispatchedMessages.Clear(); _redeliveryDelay = 0; } private BytesMessage CreateStompMessage( MessageDispatch dispatch ) { if ( dispatch.Message.Clone() is not BytesMessage message ) throw new($"Message was null => {dispatch.Message}"); message.Connection = _session.Connection; if ( _session.IsClientAcknowledge ) message.Acknowledger += DoClientAcknowledge; else if ( _session.IsIndividualAcknowledge ) message.Acknowledger += DoIndividualAcknowledge; else message.Acknowledger += DoNothingAcknowledge; return message; } private void DoClientAcknowledge( BytesMessage message ) { CheckClosed(); _session.Acknowledge(); } private void DoIndividualAcknowledge( BytesMessage message ) { MessageDispatch dispatch = null; lock ( _dispatchedMessages ) foreach ( var originalDispatch in _dispatchedMessages.Where( originalDispatch => originalDispatch.Message.MessageId.Equals( message.MessageId ) ) ) { dispatch = originalDispatch; _dispatchedMessages.Remove( originalDispatch ); break; } if ( dispatch == null ) { if ( Tracer.IsWarnEnabled ) Tracer.Warn( $"Attempt to Ack MessageId[{message.MessageId}] failed because the original dispatch is not in the Dispatch List" ); return; } var ack = new MessageAck { AckType = (Byte) AckType.IndividualAck, ConsumerId = ConsumerInfo.ConsumerId, Destination = dispatch.Destination, LastMessageId = dispatch.Message.MessageId, MessageCount = 1 }; _session.SendAck( ack ); } private static void DoNothingAcknowledge( BytesMessage message ) { } private MessageAck MakeAckForAllDeliveredMessages() { lock ( _dispatchedMessages ) { if ( _dispatchedMessages.Count == 0 ) return null; var dispatch = _dispatchedMessages.First(); var ack = new MessageAck { AckType = (Byte) AckType.ConsumedAck, ConsumerId = ConsumerInfo.ConsumerId, Destination = dispatch.Destination, LastMessageId = dispatch.Message.MessageId, MessageCount = _dispatchedMessages.Count, FirstMessageId = _dispatchedMessages.First() .Message.MessageId }; return ack; } } private void RollbackHelper( Object arg ) { try { var waitTime = (DateTime) arg - DateTime.Now; if ( waitTime.CompareTo( TimeSpan.Zero ) > 0 ) Thread.Sleep( (Int32) waitTime.TotalMilliseconds ); Start(); } catch ( Exception e ) { if ( !_unconsumedMessages.Stopped ) _session.Connection.OnSessionException( _session, e ); } } #region Fields private readonly Atomic<Boolean> _deliveringAcks = new(); private readonly List<MessageDispatch> _dispatchedMessages = new(); private readonly Atomic<Boolean> _started = new(); private readonly Object _syncRoot = new(); private readonly MessageDispatchChannel _unconsumedMessages = new(); private Int32 _additionalWindowSize; private Boolean _clearDispatchList; private Int32 _deliveredCounter; private Int32 _dispatchedCount; private Boolean _inProgressClearRequiredFlag; private MessageAck _pendingAck; private Int64 _redeliveryDelay; private Session _session; private volatile Boolean _synchronizationRegistered; #endregion #region Property Accessors public ConsumerId ConsumerId => ConsumerInfo.ConsumerId; public ConsumerInfo ConsumerInfo { get; } private Int32 PrefetchSize => ConsumerInfo.PrefetchSize; private IRedeliveryPolicy RedeliveryPolicy { get; } private Boolean IgnoreExpiration { get; } = false; #endregion #region IMessageConsumer Members public event Action<IBytesMessage> Listener { add { CheckClosed(); if ( PrefetchSize == 0 ) throw new StompException( "Cannot set Asynchronous Listener on a Consumer with a zero Prefetch size" ); var wasStarted = _session.Started; if ( wasStarted ) _session.Stop(); _listener += value; _session.Redispatch( _unconsumedMessages ); if ( wasStarted ) _session.Start(); } remove => _listener -= value; } /// <summary> /// If a message is available within the timeout duration it is returned otherwise this method returns null /// </summary> /// <param name="timeout">An optimal timeout, if not specified infinity will be used.</param> /// <returns>Returns the received message, or null in case of a timeout.</returns> public IBytesMessage Receive( TimeSpan? timeout = null ) { timeout ??= TimeSpan.FromMilliseconds( Timeout.Infinite ); CheckClosed(); CheckMessageListener(); var dispatch = Dequeue( timeout.Value ); if ( dispatch == null ) return null; BeforeMessageIsConsumed( dispatch ); AfterMessageIsConsumed( dispatch, false ); return CreateStompMessage( dispatch ); } /// <summary> /// Closes the message consumer. /// </summary> /// <remarks> /// Clients should close message consumers them when they are not needed. /// This call blocks until a receive or message listener in progress has completed. /// A blocked message consumer receive call returns null when this message consumer is closed. /// </remarks> public void Close() { if ( _unconsumedMessages.Stopped ) return; // In case of transaction => close the consumer after the transaction has completed if ( _session.IsTransacted && _session.TransactionContext.InTransaction ) _session.TransactionContext.AddSynchronization( new ConsumerCloseSynchronization( this ) ); else CloseInternal(); } #endregion #region Private Members /// <summary> /// Used to get an enqueued message from the unconsumedMessages list. The /// amount of time this method blocks is based on the timeout value. if /// timeout == Timeout.Infinite then it blocks until a message is received. /// if timeout == 0 then it tries to not block at all, it returns a /// message if it is available if timeout > 0 then it blocks up to timeout /// amount of time. Expired messages will consumed by this method. /// </summary> private MessageDispatch Dequeue( TimeSpan timeout ) { // Calculate the deadline DateTime deadline; if ( timeout > TimeSpan.Zero ) deadline = DateTime.Now + timeout; else deadline = DateTime.MaxValue; while ( true ) { // Check if deadline is reached if ( DateTime.Now > deadline ) return null; // Fetch the message var dispatch = _unconsumedMessages.Dequeue( timeout ); if ( dispatch == null ) { if ( FailureError != null ) throw FailureError.Create(); return null; } if ( dispatch.Message == null ) return null; if ( IgnoreExpiration || !dispatch.Message.IsExpired() ) return dispatch; if ( Tracer.IsWarnEnabled ) Tracer.Warn( $"{ConsumerInfo.ConsumerId} received expired message: {dispatch.Message.MessageId}" ); BeforeMessageIsConsumed( dispatch ); AfterMessageIsConsumed( dispatch, true ); return null; } } /// <summary> /// Closes the consumer, for real. /// </summary> private void CloseInternal() { if ( _unconsumedMessages.Stopped ) return; if ( !_session.IsTransacted ) lock ( _dispatchedMessages ) _dispatchedMessages.Clear(); _unconsumedMessages.Stop(); _session.DisposeOf( ConsumerInfo.ConsumerId ); var removeCommand = new RemoveInfo { ObjectId = ConsumerInfo.ConsumerId }; _session.Connection.Oneway( removeCommand ); _session = null; } /// <summary> /// Checks if the message dispatcher is still open. /// </summary> private void CheckClosed() { if ( _unconsumedMessages.Stopped ) throw new StompException( "The Consumer has been Stopped" ); } /// <summary> /// Checks if the consumer should publish message event or not. /// </summary> /// <remarks> /// You can not perform a manual receive on a consumer with a event listener. /// </remarks> private void CheckMessageListener() { if ( _listener != null ) throw new StompException( "Cannot perform a Synchronous Receive when there is a registered asynchronous _listener." ); } /// <summary> /// Handles the ACK of the given message. /// </summary> /// <param name="dispatch">The message.</param> /// <param name="expired">A value indicating whether the message was expired or not.</param> private void AfterMessageIsConsumed( MessageDispatch dispatch, Boolean expired ) { if ( _unconsumedMessages.Stopped ) return; // Message was expired if ( expired ) { lock ( _dispatchedMessages ) _dispatchedMessages.Remove( dispatch ); return; } // Do noting if ( _session.IsClientAcknowledge || _session.IsIndividualAcknowledge || _session.IsTransacted ) return; if ( !_session.IsAutoAcknowledge ) throw new StompException( "Invalid session state." ); if ( !_deliveringAcks.CompareAndSet( false, true ) ) return; lock ( _dispatchedMessages ) if ( _dispatchedMessages.Count > 0 ) { var ack = new MessageAck { AckType = (Byte) AckType.ConsumedAck, ConsumerId = ConsumerInfo.ConsumerId, Destination = dispatch.Destination, LastMessageId = dispatch.Message.MessageId, MessageCount = 1 }; _session.SendAck( ack ); } _deliveringAcks.Value = false; _dispatchedMessages.Clear(); throw new StompException( "Invalid session state." ); } #endregion #region Nested ISyncronization Types private class MessageConsumerSynchronization : ISynchronization { #region Fields private readonly MessageConsumer _consumer; #endregion #region Ctor public MessageConsumerSynchronization( MessageConsumer consumer ) => _consumer = consumer; #endregion public void AfterCommit() { _consumer.Commit(); _consumer._synchronizationRegistered = false; } public void AfterRollback() { _consumer.Rollback(); _consumer._synchronizationRegistered = false; } public void BeforeEnd() { _consumer.Acknowledge(); _consumer._synchronizationRegistered = false; } } private class ConsumerCloseSynchronization : ISynchronization { #region Fields private readonly MessageConsumer _consumer; #endregion #region Ctor public ConsumerCloseSynchronization( MessageConsumer consumer ) => _consumer = consumer; #endregion public void AfterCommit() => _consumer.CloseInternal(); public void AfterRollback() => _consumer.CloseInternal(); public void BeforeEnd() { } } #endregion } }
34.650667
164
0.506849
[ "MIT" ]
DaveSenn/Stomp.Net
.Src/Stomp.Net/NMS.Stomp/MessageConsumer.cs
25,239
C#
// <copyright file="LoggingTextFormat.cs" company="OpenTelemetry Authors"> // Copyright 2018, OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System; using System.Collections.Generic; using OpenTelemetry.Context.Propagation; using OpenTelemetry.Trace; namespace LoggingTracer { public sealed class LoggingTextFormat : ITextFormat { /// <inheritdoc/> public ISet<string> Fields => null; /// <inheritdoc/> public SpanContext Extract<T>(T carrier, Func<T, string, IEnumerable<string>> getter) { Logger.Log("LoggingTextFormat.Extract(...)"); return SpanContext.Blank; } /// <inheritdoc/> public void Inject<T>(SpanContext spanContext, T carrier, Action<T, string, string> setter) { Logger.Log($"LoggingTextFormat.Inject({spanContext}, ...)"); } } }
34.071429
99
0.682041
[ "Apache-2.0" ]
andy-g/opentelemetry-dotnet
samples/LoggingTracer/LoggingTracer/LoggingTextFormat.cs
1,433
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Door : MonoBehaviour { //public Button button; public bool openDoor; public Collider coolCollider; public float doorSpeed; Vector3 startPosition; // Start is called before the first frame update void Start() { coolCollider = GetComponent<Collider>(); startPosition = transform.position; } // Update is called once per frame void FixedUpdate() { if(openDoor) { Vector3 targetPosition = new Vector3(transform.position.x, -coolCollider.bounds.size.y - 0.2f, transform.position.z); transform.position = Vector3.Lerp(transform.position, targetPosition, doorSpeed); } else { Vector3 targetPosition = startPosition; transform.position = Vector3.Lerp(transform.position, startPosition, doorSpeed); } } }
26.864865
130
0.626761
[ "MIT" ]
Plaonder/2d-3d-platformer
Assets/Scripts/Door.cs
996
C#
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v7/errors/keyword_plan_error.proto // </auto-generated> #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 Google.Ads.GoogleAds.V7.Errors { /// <summary>Holder for reflection information generated from google/ads/googleads/v7/errors/keyword_plan_error.proto</summary> public static partial class KeywordPlanErrorReflection { #region Descriptor /// <summary>File descriptor for google/ads/googleads/v7/errors/keyword_plan_error.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static KeywordPlanErrorReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Cjdnb29nbGUvYWRzL2dvb2dsZWFkcy92Ny9lcnJvcnMva2V5d29yZF9wbGFu", "X2Vycm9yLnByb3RvEh5nb29nbGUuYWRzLmdvb2dsZWFkcy52Ny5lcnJvcnMa", "HGdvb2dsZS9hcGkvYW5ub3RhdGlvbnMucHJvdG8iyAMKFEtleXdvcmRQbGFu", "RXJyb3JFbnVtIq8DChBLZXl3b3JkUGxhbkVycm9yEg8KC1VOU1BFQ0lGSUVE", "EAASCwoHVU5LTk9XThABEh8KG0JJRF9NVUxUSVBMSUVSX09VVF9PRl9SQU5H", "RRACEhAKDEJJRF9UT09fSElHSBADEg8KC0JJRF9UT09fTE9XEAQSIgoeQklE", "X1RPT19NQU5ZX0ZSQUNUSU9OQUxfRElHSVRTEAUSGAoUREFJTFlfQlVER0VU", "X1RPT19MT1cQBhIrCidEQUlMWV9CVURHRVRfVE9PX01BTllfRlJBQ1RJT05B", "TF9ESUdJVFMQBxIRCg1JTlZBTElEX1ZBTFVFEAgSIAocS0VZV09SRF9QTEFO", "X0hBU19OT19LRVlXT1JEUxAJEhwKGEtFWVdPUkRfUExBTl9OT1RfRU5BQkxF", "RBAKEhoKFktFWVdPUkRfUExBTl9OT1RfRk9VTkQQCxIPCgtNSVNTSU5HX0JJ", "RBANEhsKF01JU1NJTkdfRk9SRUNBU1RfUEVSSU9EEA4SHwobSU5WQUxJRF9G", "T1JFQ0FTVF9EQVRFX1JBTkdFEA8SEAoMSU5WQUxJRF9OQU1FEBBC8AEKImNv", "bS5nb29nbGUuYWRzLmdvb2dsZWFkcy52Ny5lcnJvcnNCFUtleXdvcmRQbGFu", "RXJyb3JQcm90b1ABWkRnb29nbGUuZ29sYW5nLm9yZy9nZW5wcm90by9nb29n", "bGVhcGlzL2Fkcy9nb29nbGVhZHMvdjcvZXJyb3JzO2Vycm9yc6ICA0dBQaoC", "Hkdvb2dsZS5BZHMuR29vZ2xlQWRzLlY3LkVycm9yc8oCHkdvb2dsZVxBZHNc", "R29vZ2xlQWRzXFY3XEVycm9yc+oCIkdvb2dsZTo6QWRzOjpHb29nbGVBZHM6", "OlY3OjpFcnJvcnNiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V7.Errors.KeywordPlanErrorEnum), global::Google.Ads.GoogleAds.V7.Errors.KeywordPlanErrorEnum.Parser, null, null, new[]{ typeof(global::Google.Ads.GoogleAds.V7.Errors.KeywordPlanErrorEnum.Types.KeywordPlanError) }, null, null) })); } #endregion } #region Messages /// <summary> /// Container for enum describing possible errors from applying a keyword plan /// resource (keyword plan, keyword plan campaign, keyword plan ad group or /// keyword plan keyword) or KeywordPlanService RPC. /// </summary> public sealed partial class KeywordPlanErrorEnum : pb::IMessage<KeywordPlanErrorEnum> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<KeywordPlanErrorEnum> _parser = new pb::MessageParser<KeywordPlanErrorEnum>(() => new KeywordPlanErrorEnum()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<KeywordPlanErrorEnum> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Ads.GoogleAds.V7.Errors.KeywordPlanErrorReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public KeywordPlanErrorEnum() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public KeywordPlanErrorEnum(KeywordPlanErrorEnum other) : this() { _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public KeywordPlanErrorEnum Clone() { return new KeywordPlanErrorEnum(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as KeywordPlanErrorEnum); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(KeywordPlanErrorEnum other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (_unknownFields != null) { hash ^= _unknownFields.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 !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(KeywordPlanErrorEnum other) { if (other == null) { return; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; } } } #endif #region Nested types /// <summary>Container for nested types declared in the KeywordPlanErrorEnum message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { /// <summary> /// Enum describing possible errors from applying a keyword plan. /// </summary> public enum KeywordPlanError { /// <summary> /// Enum unspecified. /// </summary> [pbr::OriginalName("UNSPECIFIED")] Unspecified = 0, /// <summary> /// The received error code is not known in this version. /// </summary> [pbr::OriginalName("UNKNOWN")] Unknown = 1, /// <summary> /// The plan's bid multiplier value is outside the valid range. /// </summary> [pbr::OriginalName("BID_MULTIPLIER_OUT_OF_RANGE")] BidMultiplierOutOfRange = 2, /// <summary> /// The plan's bid value is too high. /// </summary> [pbr::OriginalName("BID_TOO_HIGH")] BidTooHigh = 3, /// <summary> /// The plan's bid value is too low. /// </summary> [pbr::OriginalName("BID_TOO_LOW")] BidTooLow = 4, /// <summary> /// The plan's cpc bid is not a multiple of the minimum billable unit. /// </summary> [pbr::OriginalName("BID_TOO_MANY_FRACTIONAL_DIGITS")] BidTooManyFractionalDigits = 5, /// <summary> /// The plan's daily budget value is too low. /// </summary> [pbr::OriginalName("DAILY_BUDGET_TOO_LOW")] DailyBudgetTooLow = 6, /// <summary> /// The plan's daily budget is not a multiple of the minimum billable unit. /// </summary> [pbr::OriginalName("DAILY_BUDGET_TOO_MANY_FRACTIONAL_DIGITS")] DailyBudgetTooManyFractionalDigits = 7, /// <summary> /// The input has an invalid value. /// </summary> [pbr::OriginalName("INVALID_VALUE")] InvalidValue = 8, /// <summary> /// The plan has no keyword. /// </summary> [pbr::OriginalName("KEYWORD_PLAN_HAS_NO_KEYWORDS")] KeywordPlanHasNoKeywords = 9, /// <summary> /// The plan is not enabled and API cannot provide mutation, forecast or /// stats. /// </summary> [pbr::OriginalName("KEYWORD_PLAN_NOT_ENABLED")] KeywordPlanNotEnabled = 10, /// <summary> /// The requested plan cannot be found for providing forecast or stats. /// </summary> [pbr::OriginalName("KEYWORD_PLAN_NOT_FOUND")] KeywordPlanNotFound = 11, /// <summary> /// The plan is missing a cpc bid. /// </summary> [pbr::OriginalName("MISSING_BID")] MissingBid = 13, /// <summary> /// The plan is missing required forecast_period field. /// </summary> [pbr::OriginalName("MISSING_FORECAST_PERIOD")] MissingForecastPeriod = 14, /// <summary> /// The plan's forecast_period has invalid forecast date range. /// </summary> [pbr::OriginalName("INVALID_FORECAST_DATE_RANGE")] InvalidForecastDateRange = 15, /// <summary> /// The plan's name is invalid. /// </summary> [pbr::OriginalName("INVALID_NAME")] InvalidName = 16, } } #endregion } #endregion } #endregion Designer generated code
39.603571
303
0.681937
[ "Apache-2.0" ]
deni-skaraudio/google-ads-dotnet
src/V7/Types/KeywordPlanError.cs
11,089
C#
using System.Globalization; using System.Windows; namespace TeamProjectManager.Modules.Activity { public partial class ActivityViewerDialog : Window { public TeamProjectActivityInfo Activity { get; private set; } public ActivityViewerDialog(TeamProjectActivityInfo activity) { InitializeComponent(); this.Activity = activity; this.Title = string.Format(CultureInfo.CurrentCulture, "Activity details for Team Project \"{0}\"", activity.TeamProject); this.DataContext = this.Activity; } private void okButton_Click(object sender, RoutedEventArgs e) { this.DialogResult = true; this.Close(); } } }
31.708333
135
0.628121
[ "MIT" ]
BobSilent/TfsTeamProjectManager
TeamProjectManager.Modules.Activity/ActivityViewerDialog.xaml.cs
763
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swcommands; using SolidWorks.Interop.swconst; using SolidWorks.Interop.swpublished; namespace ChronoEngineAddin { public partial class EditChBody : Form { public bool m_collide; public double m_friction; public double m_rolling_friction; public double m_spinning_friction; public double m_restitution; public double m_collision_margin; public double m_collision_envelope; public int m_collision_family; bool show_conveyor_params; public double m_conveyor_speed; public EditChBody() { show_conveyor_params = false; InitializeComponent(); } private void button_ok_Click(object sender, EventArgs e) { m_collide = this.checkBox_collide.Checked; m_friction = (double)this.numeric_friction.Value; m_rolling_friction = (double)this.numeric_rolling_friction.Value; m_spinning_friction = (double)this.numeric_spinning_friction.Value; m_restitution = (double)this.numeric_restitution.Value; m_collision_margin = (double)this.numeric_collision_margin.Value; m_collision_envelope = (double)this.numeric_collision_envelope.Value; m_collision_family = this.comboBox_collision_family.SelectedIndex; } public void Set_collision_on(bool mval) { m_collide = mval; this.checkBox_collide.Checked = m_collide; // ghost collision-related stuff if collision not enabled this.numeric_friction.Enabled = mval; this.numeric_rolling_friction.Enabled = mval; this.numeric_spinning_friction.Enabled = mval; this.numeric_restitution.Enabled = mval; this.numeric_collision_margin.Enabled = mval; this.numeric_collision_envelope.Enabled = mval; this.comboBox_collision_family.Enabled = mval; } public void Set_friction(double mval) { m_friction = mval; this.numeric_friction.Value = (decimal)m_friction; } public void Set_rolling_friction(double mval) { m_rolling_friction = mval; this.numeric_rolling_friction.Value = (decimal)m_rolling_friction; } public void Set_spinning_friction(double mval) { m_spinning_friction = mval; this.numeric_spinning_friction.Value = (decimal)m_spinning_friction; } public void Set_restitution(double mval) { m_restitution = mval; this.numeric_restitution.Value = (decimal)m_restitution; } public void Set_collision_margin(double mval) { m_collision_margin = mval; this.numeric_collision_margin.Value = (decimal)m_collision_margin; } public void Set_collision_envelope(double mval) { m_collision_envelope = mval; this.numeric_collision_envelope.Value = (decimal)m_collision_envelope; } public void Set_collision_family(int mval) { m_collision_family = mval; this.comboBox_collision_family.SelectedIndex = m_collision_family; } public void Set_conveyor_speed(double mval) { m_conveyor_speed = mval; this.numeric_conveyor_speed.Value = (decimal)m_conveyor_speed; } public void UpdateFromSelection(SelectionMgr swSelMgr, ref AttributeDef mdefattr_chbody)//, ref AttributeDef defattr_chconveyor) { // Fetch current properties from the selected part(s) (i.e. ChBody in C::E) for (int isel = 1; isel <= swSelMgr.GetSelectedObjectCount2(-1); isel++) if ((swSelectType_e)swSelMgr.GetSelectedObjectType3(isel, -1) == swSelectType_e.swSelCOMPONENTS) { //Component2 swPart = (Component2)swSelMgr.GetSelectedObject6(isel, -1); Component2 swPart = swSelMgr.GetSelectedObjectsComponent3(isel, -1); ModelDoc2 swPartModel = (ModelDoc2)swPart.GetModelDoc2(); Component2 swPartcorr = swPartModel.Extension.GetCorresponding(swPart);// ***TODO*** for instanced parts? does not work... swPartcorr = swPart; // ***TODO*** if (swPartModel.GetType() == (int)swDocumentTypes_e.swDocASSEMBLY) { if (swPart.Solving == (int)swComponentSolvingOption_e.swComponentFlexibleSolving) { System.Windows.Forms.MessageBox.Show("Fexible assemblies not supported as ChBody (set as Rigid?)"); return; } if (swPart.Solving == (int)swComponentSolvingOption_e.swComponentRigidSolving) { System.Windows.Forms.MessageBox.Show("Setting props to rigid assembly as ChBody"); AssemblyDoc swAssemblyDoc = (AssemblyDoc)swPartModel; swPart.Select(false); swAssemblyDoc.EditAssembly(); swAssemblyDoc.EditRebuild(); //return; } } // fetch SW attribute with Chrono parameters for ChBody SolidWorks.Interop.sldworks.Attribute myattr = null; if (swPartcorr != null) myattr = (SolidWorks.Interop.sldworks.Attribute)swPart.FindAttribute(mdefattr_chbody, 0); if (myattr == null) { // if not already added to part, create and attach it //System.Windows.Forms.MessageBox.Show("Create data"); myattr = mdefattr_chbody.CreateInstance5(swPartModel, swPartcorr, "Chrono::ChBody_data", 0, (int)swInConfigurationOpts_e.swAllConfiguration); swPartModel.ForceRebuild3(false); // needed, but does not work... //swPartModel.Rebuild((int)swRebuildOptions_e.swRebuildAll); // needed but does not work... if (myattr.GetEntityState((int)swAssociatedEntityStates_e.swIsEntityInvalid)) System.Windows.Forms.MessageBox.Show("swIsEntityInvalid!"); if (myattr.GetEntityState((int)swAssociatedEntityStates_e.swIsEntitySuppressed)) System.Windows.Forms.MessageBox.Show("swIsEntitySuppressed!"); if (myattr.GetEntityState((int)swAssociatedEntityStates_e.swIsEntityAmbiguous)) System.Windows.Forms.MessageBox.Show("swIsEntityAmbiguous!"); if (myattr.GetEntityState((int)swAssociatedEntityStates_e.swIsEntityDeleted)) System.Windows.Forms.MessageBox.Show("swIsEntityDeleted!"); } Set_collision_on(Convert.ToBoolean(((Parameter)myattr.GetParameter( "collision_on")).GetDoubleValue())); Set_friction(((Parameter)myattr.GetParameter( "friction")).GetDoubleValue()); Set_rolling_friction(((Parameter)myattr.GetParameter( "rolling_friction")).GetDoubleValue()); Set_spinning_friction(((Parameter)myattr.GetParameter( "spinning_friction")).GetDoubleValue()); Set_restitution(((Parameter)myattr.GetParameter( "restitution")).GetDoubleValue()); Set_collision_envelope(((Parameter)myattr.GetParameter( "collision_envelope")).GetDoubleValue()); Set_collision_margin(((Parameter)myattr.GetParameter( "collision_margin")).GetDoubleValue()); Set_collision_family((int)((Parameter)myattr.GetParameter( "collision_family")).GetDoubleValue()); // fetch SW attribute with Chrono parameters for ChConveyor /* SolidWorks.Interop.sldworks.Attribute myattr_conv = (SolidWorks.Interop.sldworks.Attribute)swPart.FindAttribute(defattr_chconveyor, 0); if (myattr_conv == null) { // if not already added to part, create and attach it //myattr_conv = defattr_chconveyor.CreateInstance5(swPartModel, swPart, "Chrono::ChConveyor_data", 0, (int)swInConfigurationOpts_e.swThisConfiguration); } */ /* // fetch SW attribute with Chrono parameters for ChConveyor (if any!) SolidWorks.Interop.sldworks.Attribute myattr_conveyor = (SolidWorks.Interop.sldworks.Attribute)swPart.FindAttribute(defattr_chconveyor, 0); if (myattr_conveyor != null) { show_conveyor_params = true; Set_conveyor_speed(((Parameter)myattr_conveyor.GetParameter( "conveyor_speed")).GetDoubleValue()); } */ } } public void StoreToSelection(SelectionMgr swSelMgr, ref AttributeDef mdefattr_chbody)//, ref AttributeDef defattr_chconveyor) { //System.Windows.Forms.MessageBox.Show("StoreToSelection()"); // If user pressed OK, apply settings to all selected parts (i.e. ChBody in C::E): for (int isel = 1; isel <= swSelMgr.GetSelectedObjectCount2(-1); isel++) if ((swSelectType_e)swSelMgr.GetSelectedObjectType3(isel, -1) == swSelectType_e.swSelCOMPONENTS) { //Component2 swPart = (Component2)swSelMgr.GetSelectedObject6(isel, -1); Component2 swPart = swSelMgr.GetSelectedObjectsComponent3(isel, -1); ModelDoc2 swPartModel = (ModelDoc2)swPart.GetModelDoc2(); Component2 swPartcorr = swPartModel.Extension.GetCorresponding(swPart);// ***TODO*** for instanced parts? does not work... swPartcorr = swPart; // ***TODO*** // fetch SW attribute with Chrono parameters for ChBody SolidWorks.Interop.sldworks.Attribute myattr = (SolidWorks.Interop.sldworks.Attribute)swPartcorr.FindAttribute(mdefattr_chbody, 0); if (myattr == null) { // if not already added to part, create and attach it System.Windows.Forms.MessageBox.Show("Create data [should not happen here]"); myattr = mdefattr_chbody.CreateInstance5(swPartModel, swPartcorr, "Chrono::ChBody data", 0, (int)swInConfigurationOpts_e.swThisConfiguration); swPartModel.ForceRebuild3(false); // needed? if (myattr == null) System.Windows.Forms.MessageBox.Show("Error: myattr null in setting!!"); } ((Parameter)myattr.GetParameter("collision_on")).SetDoubleValue2( Convert.ToDouble(m_collide), (int)swInConfigurationOpts_e.swThisConfiguration, ""); ((Parameter)myattr.GetParameter("friction")).SetDoubleValue2( m_friction, (int)swInConfigurationOpts_e.swThisConfiguration, ""); ((Parameter)myattr.GetParameter("rolling_friction")).SetDoubleValue2( m_rolling_friction, (int)swInConfigurationOpts_e.swThisConfiguration, ""); ((Parameter)myattr.GetParameter("spinning_friction")).SetDoubleValue2( m_spinning_friction, (int)swInConfigurationOpts_e.swThisConfiguration, ""); ((Parameter)myattr.GetParameter("restitution")).SetDoubleValue2( m_restitution, (int)swInConfigurationOpts_e.swThisConfiguration, ""); ((Parameter)myattr.GetParameter("collision_margin")).SetDoubleValue2( m_collision_margin, (int)swInConfigurationOpts_e.swThisConfiguration, ""); ((Parameter)myattr.GetParameter("collision_envelope")).SetDoubleValue2( m_collision_envelope, (int)swInConfigurationOpts_e.swThisConfiguration, ""); ((Parameter)myattr.GetParameter("collision_family")).SetDoubleValue2( (double)m_collision_family, (int)swInConfigurationOpts_e.swThisConfiguration, ""); /* // fetch SW attribute with Chrono parameters for ChConveyor SolidWorks.Interop.sldworks.Attribute myattr_conveyor = (SolidWorks.Interop.sldworks.Attribute)swPart.FindAttribute(defattr_chconveyor, 0); if (myattr_conveyor == null) { // if not already added to part, create and attach it myattr_conveyor = defattr_chconveyor.CreateInstance5(swPartModel, swPart, "Chrono ChConveyor data", 0, (int)swInConfigurationOpts_e.swThisConfiguration); if (myattr_conveyor == null) System.Windows.Forms.MessageBox.Show("myattr null in setting!!"); } ((Parameter)myattr_conveyor.GetParameter("conveyor_speed")).SetDoubleValue2( m_conveyor_speed, (int)swInConfigurationOpts_e.swThisConfiguration, ""); */ } } } }
51.412186
177
0.581776
[ "BSD-3-Clause" ]
Timbama/chrono-solidworks
ClassLibrary1/EditChBody.cs
14,346
C#
using System; using System.Collections.Generic; using System.Linq; class LinqSearch { static void Main() { var colors = new List<string> { "Red", "Green", "Blue" }; var newColors = colors.Where(c => c.Contains("e")); foreach (var color in newColors) { Console.WriteLine(color); } var green = colors.Where(c => c.Contains("ee")); foreach (var c in green) { Console.WriteLine(c); } } }
20.666667
65
0.534274
[ "MIT" ]
VisualAcademy/DotNet
DotNet/DotNet/30_LINQ/25_LinqSearch/LinqSearch.cs
498
C#
namespace FootballBettingModels { using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; public class BetGame { [Key] [Column(Order = 0)] public Game Game { get; set; } [Key] [Column(Order = 1)] public Bet Bet { get; set; } public ResultPrediction ResultPrediction { get; set; } } }
21.315789
62
0.607407
[ "MIT" ]
evgeni-tsn/CSharp-Entity-ASP-Web-Development
5.EntityFramework-ORM-DB-Advanced/06.EntityFramework-Relations/FootballBettingDatabase/FootballBettingDatabase/FootballBettingModels/BetGame.cs
407
C#
using System; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using GR.Audit.Abstractions.Extensions; using GR.Core; using GR.Core.Events; using GR.Core.Extensions; using GR.Core.Helpers; using GR.Identity.Abstractions; using GR.Notifications.Abstractions.Models.Notifications; using GR.Notifications.Abstractions.ServiceBuilder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Identity; namespace GR.Notifications.Abstractions.Extensions { public static class ServiceCollectionExtensions { /// <summary> /// Add notification module /// </summary> /// <typeparam name="TNotifyService"></typeparam> /// <typeparam name="TRole"></typeparam> /// <param name="services"></param> /// <returns></returns> public static IServiceCollection AddNotificationModule<TNotifyService, TRole>(this IServiceCollection services) where TNotifyService : class, INotify<TRole> where TRole : IdentityRole<Guid> { services.AddGearTransient<INotify<TRole>, TNotifyService>(); return services; } /// <summary> /// Add notification subscriptions module /// </summary> /// <param name="services"></param> /// <returns></returns> public static INotificationServiceCollection AddNotificationSubscriptionModule<TRepository>(this IServiceCollection services) where TRepository : class, INotificationSubscriptionService { services.AddGearScoped<INotificationSubscriptionService, TRepository>(); return new NotificationServiceCollection(services); } /// <summary> /// Register module storage /// </summary> /// <typeparam name="TContext"></typeparam> /// <param name="services"></param> /// <param name="options"></param> /// <returns></returns> public static INotificationServiceCollection AddNotificationSubscriptionModuleStorage<TContext>(this INotificationServiceCollection services, Action<DbContextOptionsBuilder> options) where TContext : DbContext, INotificationSubscriptionsDbContext { Arg.NotNull(services, nameof(AddNotificationSubscriptionModuleStorage)); services.Services.AddDbContext<TContext>(options); services.Services.AddScopedContextFactory<INotificationSubscriptionsDbContext, TContext>(); services.Services.RegisterAuditFor<INotificationSubscriptionsDbContext>($"{nameof(Notification)} module"); SystemEvents.Database.OnAllMigrate += (sender, args) => { GearApplication.GetHost<IWebHost>().MigrateDbContext<TContext>(); }; return services; } /// <summary> /// Register notificator notification sender /// </summary> /// <param name="services"></param> /// <returns></returns> public static INotificationServiceCollection AddNotificationModuleEvents(this INotificationServiceCollection services) { SystemEvents.Application.OnEvent += (obj, args) => { if (!GearApplication.Configured) return; GearApplication.BackgroundTaskQueue.PushBackgroundWorkItemInQueue(async x => { try { if (string.IsNullOrEmpty(args.EventName)) return; var service = IoC.Resolve<INotificationSubscriptionService>(); var notifier = IoC.Resolve<INotify<GearRole>>(); var subscribedRoles = await service.GetRolesSubscribedToEventAsync(args.EventName); if (!subscribedRoles.IsSuccess) return; var template = await service.GetEventTemplateAsync(args.EventName); if (!template.IsSuccess) return; var templateWithParams = template.Result.Value?.Inject(args.EventArgs); //var engine = new RazorLightEngineBuilder() // .UseMemoryCachingProvider() // .Build(); //var templateWithParams = await engine.CompileRenderAsync($"template_{ev.EventName}", template.Result.Value, ev.EventArgs); var notification = new Notification { Subject = template.Result.Subject, Content = templateWithParams, NotificationTypeId = NotificationType.Info }; await notifier.SendNotificationAsync(subscribedRoles.Result, notification, null); } catch (Exception e) { Console.WriteLine(e); } }); }; SystemEvents.Database.OnSeed += async (obj, args) => { if (!(args.DbContext is INotificationSubscriptionsDbContext)) return; try { var service = IoC.Resolve<INotificationSubscriptionService>(); await service.SeedEventsAsync(); } catch (Exception e) { Console.WriteLine(e); } }; return services; } } }
42.323077
190
0.590876
[ "MIT" ]
indrivo/GEAR
src/GR.Extensions/GR.Notifications.Extension/GR.Notifications.Abstractions/Extensions/ServiceCollectionExtensions.cs
5,504
C#
namespace OneNoteDev.Models.JsonHelpers { public class ParentNotebookJson { public string id { get; set; } public string name { get; set; } public string self { get; set; } } }
24.125
40
0.668394
[ "MIT" ]
OfficeDev/TrainingContent-Archive
O3653/O3653-7 Deep Dive into the Office 365 APIs for OneNote services/Completed project/Exercise 2/OneNoteDev/Models/JsonHelpers/ParentNotebookJson.cs
195
C#
// ---------------------------------------------------------------------------------- // // 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 System; using System.Management.Automation; using Microsoft.Azure.Commands.MachineLearning.Utilities; using Microsoft.Azure.Management.MachineLearning.WebServices.Models; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; namespace Microsoft.Azure.Commands.MachineLearning.Cmdlets { [Cmdlet("Get", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "MlWebServiceKeys")] [OutputType(typeof(WebServiceKeys))] public class GetAzureMLWebServiceKeys : WebServicesCmdletBase { private const string GetKeysByGroupAndName = "GetByNameAndResourceGroup"; private const string GetKeysByInstance = "GetByInstance"; [Parameter( ParameterSetName = GetAzureMLWebServiceKeys.GetKeysByGroupAndName, Mandatory = true, HelpMessage = "The name of the resource group for the Azure ML web services.")] [ResourceGroupCompleter] [ValidateNotNullOrEmpty] public string ResourceGroupName { get; set; } [Parameter( ParameterSetName = GetAzureMLWebServiceKeys.GetKeysByGroupAndName, Mandatory = true, HelpMessage = "The name of the web service.")] [ValidateNotNullOrEmpty] public string Name { get; set; } [Parameter( ParameterSetName = GetAzureMLWebServiceKeys.GetKeysByInstance, Mandatory = true, HelpMessage = "The web service instance to get the keys for.", ValueFromPipeline = true)] [ValidateNotNullOrEmpty] public WebService MlWebService { get; set; } protected override void RunCmdlet() { if (string.Equals( this.ParameterSetName, GetAzureMLWebServiceKeys.GetKeysByInstance, StringComparison.OrdinalIgnoreCase)) { string subscriptionId, resourceGroup, webServiceName; if (!CmdletHelpers.TryParseMlResourceMetadataFromResourceId( this.MlWebService.Id, out subscriptionId, out resourceGroup, out webServiceName)) { throw new ValidationMetadataException(Resources.InvalidWebServiceIdOnObject); } this.ResourceGroupName = resourceGroup; this.Name = webServiceName; } WebServiceKeys storageKeys = this.WebServicesClient.GetAzureMlWebServiceKeys(this.ResourceGroupName, this.Name); this.WriteObject(storageKeys); } } }
44.3875
100
0.601521
[ "MIT" ]
Acidburn0zzz/azure-powershell
src/ResourceManager/MachineLearning/Commands.MachineLearning/Cmdlets/WebServices/GetAzureMLWebServiceKeys.cs
3,474
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the codestar-2017-04-19.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.CodeStar.Model { /// <summary> /// Container for the parameters to the UntagProject operation. /// Removes tags from a project. /// </summary> public partial class UntagProjectRequest : AmazonCodeStarRequest { private string _id; private List<string> _tags = new List<string>(); /// <summary> /// Gets and sets the property Id. /// <para> /// The ID of the project to remove tags from. /// </para> /// </summary> [AWSProperty(Required=true, Min=2, Max=15)] public string Id { get { return this._id; } set { this._id = value; } } // Check to see if Id property is set internal bool IsSetId() { return this._id != null; } /// <summary> /// Gets and sets the property Tags. /// <para> /// The tags to remove from the project. /// </para> /// </summary> [AWSProperty(Required=true)] public List<string> Tags { get { return this._tags; } set { this._tags = value; } } // Check to see if Tags property is set internal bool IsSetTags() { return this._tags != null && this._tags.Count > 0; } } }
28.405063
106
0.600713
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/CodeStar/Generated/Model/UntagProjectRequest.cs
2,244
C#
using System; namespace GeofenceSDK.Common.Models { public class GeofenceLocation { public double Latitude { get; set; } public double Longitude { get; set; } public DateTime Date { get; set; } public double Accuracy { get; set; } public GeofenceLocation() { } public GeofenceLocation(GeofenceLocation geofenceLocation) { Latitude = geofenceLocation.Latitude; Longitude = geofenceLocation.Longitude; Date = geofenceLocation.Date; Accuracy = geofenceLocation.Accuracy; } } }
24.72
66
0.600324
[ "MIT" ]
MarianHristov92/Geofence-Xamarin-SDK
GeofenceSDK.Core/Common/Models/GeofenceLocation.cs
620
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AWSSDK.EC2")] [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon Elastic Compute Cloud. Amazon Elastic Compute Cloud (Amazon EC2) is a web service that provides resizable compute capacity in the cloud. It is designed to make web-scale cloud computing easier for developers.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.3")] [assembly: AssemblyFileVersion("3.7.47.0")]
48.5
295
0.752577
[ "Apache-2.0" ]
EbstaLimited/aws-sdk-net
sdk/code-analysis/ServiceAnalysis/EC2/Properties/AssemblyInfo.cs
1,552
C#