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
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information using System.Runtime.Serialization; namespace Nest { public interface IExplainResponse<out TDocument> : IResponse where TDocument : class { IInlineGet<TDocument> Get { get; } } [DataContract] public class ExplainResponse<TDocument> : ResponseBase, IExplainResponse<TDocument> where TDocument : class { [DataMember(Name ="explanation")] public ExplanationDetail Explanation { get; internal set; } [DataMember(Name ="get")] public IInlineGet<TDocument> Get { get; internal set; } [DataMember(Name ="matched")] public bool Matched { get; internal set; } } }
27.275862
84
0.740834
[ "Apache-2.0" ]
Brightspace/elasticsearch-net
src/Nest/Search/Explain/ExplainResponse.cs
793
C#
// Operations with "maps" // Note that functions are not inlined in editor, so keeping all method unfolded using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; namespace Den.Tools { [Serializable, StructLayout (LayoutKind.Sequential)] //to pass to native public class FloatMatrix : Matrix2D<float> { public float GetInterpolatedValue (Vector2 pos) //for upscaling - gets value in-between two points { int x = Mathf.FloorToInt(pos.x); int z = Mathf.FloorToInt(pos.y); float xPercent = pos.x-x; float zPercent = pos.y-z; //if (!rect.CheckInRange(x+1,z+1)) return 0; float val1 = this[x,z]; float val2 = this[x+1,z]; float val3 = val1*(1-xPercent) + val2*xPercent; float val4 = this[x,z+1]; float val5 = this[x+1,z+1]; float val6 = val4*(1-xPercent) + val5*xPercent; return val3*(1-zPercent) + val6*zPercent; } public float GetAveragedValue (int x, int z, int steps) //for downscaling { float sum = 0; int div = 0; for (int ix=0; ix<steps; ix++) for (int iz=0; iz<steps; iz++) { if (x+ix >= rect.offset.x+rect.size.x) continue; if (z+iz >= rect.offset.z+rect.size.z) continue; sum += this[x+ix, z+iz]; div++; } return sum / div; } #region Overriding constructors and clone public FloatMatrix () { arr = new float[0]; rect = new CoordRect(0,0,0,0); count = 0; } //for serializer public FloatMatrix (int offsetX, int offsetZ, int sizeX, int sizeZ, float[] array=null) { this.rect = new CoordRect(offsetX, offsetZ, sizeX, sizeZ);; count = rect.size.x*rect.size.z; if (array != null && array.Length<count) Debug.Log("Array length: " + array.Length + " is lower then matrix capacity: " + count); if (array != null && array.Length>=count) this.arr = array; else this.arr = new float[count]; } public FloatMatrix (CoordRect rect, float[] array=null) { this.rect = rect; count = rect.size.x*rect.size.z; if (array != null && array.Length<count) Debug.Log("Array length: " + array.Length + " is lower then matrix capacity: " + count); if (array != null && array.Length>=count) this.arr = array; else this.arr = new float[count]; } public FloatMatrix (Coord offset, Coord size, float[] array=null) { rect = new CoordRect(offset, size); count = rect.size.x*rect.size.z; if (array != null && array.Length<count) Debug.Log("Array length: " + array.Length + " is lower then matrix capacity: " + count); if (array != null && array.Length>=count) this.arr = array; else this.arr = new float[count]; } public FloatMatrix (FloatMatrix src) { rect = src.rect; count = src.count; arr = new float[src.arr.Length]; Array.Copy(src.arr, arr, arr.Length); } public override object Clone () //IClonable { FloatMatrix result = new FloatMatrix(rect); //copy params result.rect = rect; result.count = count; //copy array if (result.arr.Length != arr.Length) result.arr = new float[arr.Length]; Array.Copy(arr, result.arr, arr.Length); return result; } [Obsolete] public FloatMatrix Copy (FloatMatrix result=null) { if (result==null) result = new FloatMatrix(rect); //copy params result.rect = rect; result.count = count; //copy array if (result.arr.Length != arr.Length) result.arr = new float[arr.Length]; Array.Copy(arr, result.arr, arr.Length); return result; } public FloatMatrix CopyRegion (CoordRect region, FloatMatrix result=null) //SOON: optimize { if (result==null) result = new FloatMatrix(region); //copy params result.rect = region; result.count = region.Count; //copy array Coord min = region.Min; Coord max = region.Max; for (int x=min.x; x<max.x; x++) for (int z=min.z; z<max.z; z++) { if (x<rect.offset.x || x>rect.offset.x+rect.size.x || z<rect.offset.z || z>rect.offset.z+rect.size.z) continue; result[x,z] = this[x,z]; } return result; } #endregion #region Texture (obsolete) [Obsolete] public Texture2D ToTexture () { Texture2D texture = new Texture2D(rect.size.x, rect.size.z); WriteIntersectingTexture(texture, rect.offset.x, rect.offset.z); return texture; } [Obsolete] public void WriteIntersectingTexture (Texture2D texture, int textureOffsetX, int textureOffsetZ, float rangeMin=0, float rangeMax=1) ///Filling texture using both matrix and texture offsets. Filling only intersecting rect/texture are, leaving other unchanged. { //TODO: use LoadRawTextureData CoordRect textureRect = new CoordRect(textureOffsetX, textureOffsetZ, texture.width, texture.height); CoordRect intersect = CoordRect.Intersected(rect, textureRect); Color[] colors = new Color[intersect.size.x*intersect.size.z]; Coord min = intersect.Min; Coord max = intersect.Max; for (int x=min.x; x<max.x; x++) for (int z=min.z; z<max.z; z++) { float val = this[x,z]; //TODO: direct val -= rangeMin; val /= rangeMax-rangeMin; colors[(z-min.z)*(max.x-min.x) + (x-min.x)] = new Color(val, val, val); //TODO: r should not be == r and ==b, there should be 1 byte diff } texture.SetPixels( intersect.offset.x-textureOffsetX, intersect.offset.z-textureOffsetZ, intersect.size.x, intersect.size.z, colors); texture.Apply(); } [Obsolete] public void WriteTextureInterpolated (Texture2D texture, CoordRect textureRect, CoordRect.TileMode wrap=CoordRect.TileMode.Clamp, float rangeMin=0, float rangeMax=1) { float pixelSizeX = 1f * textureRect.size.x / texture.width; float pixelSizeZ = 1f * textureRect.size.z / texture.height; Rect pixelTextureRect = new Rect(0, 0, texture.width, texture.height); Rect pixelMatrixRect = new Rect( (textureRect.offset.x - rect.offset.x) / pixelSizeX, (textureRect.offset.z - rect.offset.z) / pixelSizeZ, rect.size.x/pixelSizeX, rect.size.z/pixelSizeZ); Rect pixelIntersection = CoordinatesExtensions.Intersect(pixelTextureRect, pixelMatrixRect); CoordRect intersect = new CoordRect( Mathf.CeilToInt(pixelIntersection.x), Mathf.CeilToInt(pixelIntersection.y), Mathf.FloorToInt(pixelIntersection.width), Mathf.FloorToInt(pixelIntersection.height) ); Color[] colors = new Color[intersect.size.x*intersect.size.z]; Coord min = intersect.Min; Coord max = intersect.Max; for (int x=min.x; x<max.x; x++) for (int z=min.z; z<max.z; z++) { float wx = x*pixelSizeX - textureRect.offset.x + rect.offset.x*2; float wz = z*pixelSizeZ - textureRect.offset.z + rect.offset.z*2; //float val = this[x,z]; //TODO: direct float val = GetInterpolated(wx, wz); val -= rangeMin; val /= rangeMax-rangeMin; //val = 1; colors[(z-min.z)*(max.x-min.x) + (x-min.x)] = new Color(val, val, val); //TODO: r should not be == r and ==b, there should be 1 byte diff } texture.SetPixels(intersect.offset.x, intersect.offset.z, intersect.size.x, intersect.size.z, colors); texture.Apply(); } [Obsolete] public Texture2D SimpleToTexture (Texture2D texture=null, Color[] colors=null, float rangeMin=0, float rangeMax=1, string savePath=null) { if (texture == null) texture = new Texture2D(rect.size.x, rect.size.z); if (texture.width != rect.size.x || texture.height != rect.size.z) texture.Resize(rect.size.x, rect.size.z); if (colors == null || colors.Length != rect.size.x*rect.size.z) colors = new Color[rect.size.x*rect.size.z]; for (int i=0; i<count; i++) { float val = arr[i]; val -= rangeMin; val /= rangeMax-rangeMin; colors[i] = new Color(val, val, val); } texture.SetPixels(colors); texture.Apply(); return texture; } [Obsolete] public static FloatMatrix SimpleFromTexture (Texture2D texture) { Color[] colors = texture.GetPixels(); FloatMatrix matrix = new FloatMatrix(0,0, texture.width, texture.height); for (int i=0; i<colors.Length; i++) matrix.arr[i] = colors[i].r; return matrix; } #endregion #region Resize (obsolete) [Obsolete] public FloatMatrix ResizeOld (CoordRect newRect, FloatMatrix result=null) { if (result==null) result = new FloatMatrix(newRect); else result.ChangeRect(newRect); Coord min = result.rect.Min; Coord max = result.rect.Max; for (int x=min.x; x<max.x; x++) for (int z=min.z; z<max.z; z++) { float percentX = 1f*(x-result.rect.offset.x)/result.rect.size.x; float origX = percentX*this.rect.size.x + this.rect.offset.x; float percentZ = 1f*(z-result.rect.offset.z)/result.rect.size.z; float origZ = percentZ*this.rect.size.z + this.rect.offset.z; result[x,z] = this.GetInterpolated(origX, origZ); } return result; } public enum Interpolation { None, Linear, Bicubic } //TODO: Biquadratic [Obsolete] public float GetInterpolatedOld (float x, float z, CoordRect.TileMode wrap=CoordRect.TileMode.Clamp) { //skipping value if it is out of bounds if (wrap==CoordRect.TileMode.Clamp) { if (x<rect.offset.x || x>=rect.offset.x+rect.size.x || z<rect.offset.z || z>=rect.offset.z+rect.size.z) return 0; } //neig coords int px = (int)x; if (x<0) px--; //because (int)-2.5 gives -2, should be -3 int nx = px+1; int pz = (int)z; if (z<0) pz--; int nz = pz+1; //local coordinates (without offset) int lpx = px-rect.offset.x; int lnx = nx-rect.offset.x; int lpz = pz-rect.offset.z; int lnz = nz-rect.offset.z; //wrapping coordinates if (wrap==CoordRect.TileMode.Clamp) { if (lpx<0) lpx=0; if (lpx>=rect.size.x) lpx=rect.size.x-1; if (lnx<0) lnx=0; if (lnx>=rect.size.x) lnx=rect.size.x-1; if (lpz<0) lpz=0; if (lpz>=rect.size.z) lpz=rect.size.z-1; if (lnz<0) lnz=0; if (lnz>=rect.size.z) lnz=rect.size.z-1; } else if (wrap==CoordRect.TileMode.Tile) { lpx = lpx % rect.size.x; if (lpx<0) lpx=rect.size.x+lpx; lpz = lpz % rect.size.z; if (lpz<0) lpz=rect.size.z+lpz; lnx = lnx % rect.size.x; if (lnx<0) lnx=rect.size.x+lnx; lnz = lnz % rect.size.z; if (lnz<0) lnz=rect.size.z+lnz; } else if (wrap==CoordRect.TileMode.PingPong) { lpx = lpx % (rect.size.x*2); if (lpx<0) lpx=rect.size.x*2 + lpx; if (lpx>=rect.size.x) lpx = rect.size.x*2 - lpx - 1; lpz = lpz % (rect.size.z*2); if (lpz<0) lpz=rect.size.z*2 + lpz; if (lpz>=rect.size.z) lpz = rect.size.z*2 - lpz - 1; lnx = lnx % (rect.size.x*2); if (lnx<0) lnx=rect.size.x*2 + lnx; if (lnx>=rect.size.x) lnx = rect.size.x*2 - lnx - 1; lnz = lnz % (rect.size.z*2); if (lnz<0) lnz=rect.size.z*2 + lnz; if (lnz>=rect.size.z) lnz = rect.size.z*2 - lnz - 1; } //reading values float val_pxpz = arr[lpz*rect.size.x + lpx]; float val_nxpz = arr[lpz*rect.size.x + lnx]; //array[pos_fxfz + 1]; //do not use fast calculations as they are not bounds safe float val_pxnz = arr[lnz*rect.size.x + lpx]; //array[pos_fxfz + rect.size.z]; float val_nxnz = arr[lnz*rect.size.x + lnx]; //array[pos_fxfz + rect.size.z + 1]; float percentX = x-px; float percentZ = z-pz; float val_fz = val_pxpz*(1-percentX) + val_nxpz*percentX; float val_cz = val_pxnz*(1-percentX) + val_nxnz*percentX; float val = val_fz*(1-percentZ) + val_cz*percentZ; return val; } [Obsolete] public float GetInterpolatedBicubicOld (float x, float z, CoordRect.TileMode wrap=CoordRect.TileMode.Clamp, float smoothness=0.33f) /// Sorry for the unfolded code, it's editor method that does not support inlining { //skipping value if it is out of bounds //if (wrap==CoordRect.TileMode.Once) //{ // if (x<rect.offset.x || x>=rect.offset.x+rect.size.x || z<rect.offset.z || z>=rect.offset.z+rect.size.z) // return 0; //} //neig coords int px = (int)x; if (x<0) px--; //because (int)-2.5 gives -2, should be -3 int nx = px+1; int ppx = px-1; int nnx = nx+1; int pz = (int)z; if (z<0) pz--; int nz = pz+1; int ppz = pz-1; int nnz = nz+1; float percentX = x-px; float percentZ = z-pz; float invPercentX = 1-percentX; float invPercentZ = 1-percentZ; float sqPercentX = 3*percentX*percentX - 2*percentX*percentX*percentX; float sqPercentZ = 3*percentZ*percentZ - 2*percentZ*percentZ*percentZ; //local coordinates (without offset) px = px-rect.offset.x; nx = nx-rect.offset.x; pz = pz-rect.offset.z; nz = nz-rect.offset.z; ppx = ppx-rect.offset.x; nnx = nnx-rect.offset.x; ppz = ppz-rect.offset.z; nnz = nnz-rect.offset.z; //wrapping coordinates if (wrap==CoordRect.TileMode.Clamp) { if (px<0) px=0; if (px>=rect.size.x) px=rect.size.x-1; if (nx<0) nx=0; if (nx>=rect.size.x) nx=rect.size.x-1; if (pz<0) pz=0; if (pz>=rect.size.z) pz=rect.size.z-1; if (nz<0) nz=0; if (nz>=rect.size.z) nz=rect.size.z-1; if (ppx<0) ppx=0; if (ppx>=rect.size.x) ppx=rect.size.x-1; if (nnx<0) nnx=0; if (nnx>=rect.size.x) nnx=rect.size.x-1; if (ppz<0) ppz=0; if (ppz>=rect.size.z) ppz=rect.size.z-1; if (nnz<0) nnz=0; if (nnz>=rect.size.z) nnz=rect.size.z-1; } float p = arr[pz*rect.size.x + ppx]; float pp = arr[ppz*rect.size.x + ppx]; float n = arr[nz*rect.size.x + ppx]; float nn = arr[nnz*rect.size.x + ppx]; float plvz = (2*p - pp*percentZ + n*percentZ) * 0.5f; float nlvz = (2*n - nn*invPercentZ + p*invPercentZ )*0.5f; float ppvz = plvz*(1-sqPercentZ) + nlvz*(sqPercentZ); p = arr[pz*rect.size.x + px]; pp = arr[ppz*rect.size.x + px]; n = arr[nz*rect.size.x + px]; nn = arr[nnz*rect.size.x + px]; plvz = (2*p - pp*percentZ + n*percentZ) * 0.5f; nlvz = (2*n - nn*invPercentZ + p*invPercentZ )*0.5f; float pvz = plvz*(1-sqPercentZ) + nlvz*(sqPercentZ); p = arr[pz*rect.size.x + nx]; pp = arr[ppz*rect.size.x + nx]; n = arr[nz*rect.size.x + nx]; nn = arr[nnz*rect.size.x + nx]; plvz = (2*p - pp*percentZ + n*percentZ) * 0.5f; nlvz = (2*n - nn*invPercentZ + p*invPercentZ )*0.5f; float nvz = plvz*(1-sqPercentZ) + nlvz*(sqPercentZ); p = arr[pz*rect.size.x + nnx]; pp = arr[ppz*rect.size.x + nnx]; n = arr[nz*rect.size.x + nnx]; nn = arr[nnz*rect.size.x + nnx]; plvz = (2*p - pp*percentZ + n*percentZ) * 0.5f; nlvz = (2*n - nn*invPercentZ + p*invPercentZ )*0.5f; float nnvz = plvz*(1-sqPercentZ) + nlvz*(sqPercentZ); plvz = (2*pvz - ppvz*percentX + nvz*percentX) * 0.5f; nlvz = (2*nvz - nnvz*invPercentX + pvz*invPercentX )*0.5f; return plvz*(1-sqPercentX) + nlvz*(sqPercentX); } //public float GetInterpolatedTiled (float x, float z) #endregion #region Blur (obsolete) [Obsolete] public void Spread (float strength=0.5f, int iterations=4, FloatMatrix copy=null) { Coord min = rect.Min; Coord max = rect.Max; for (int j=0; j<count; j++) arr[j] = Mathf.Clamp(arr[j],-1,1); if (copy==null) copy = Copy(null); else for (int j=0; j<count; j++) copy.arr[j] = arr[j]; for (int i=0; i<iterations; i++) { float prev = 0; for (int x=min.x; x<max.x; x++) { prev = this[x,min.z]; SetPos(x,min.z); for (int z=min.z+1; z<max.z; z++) { prev = (prev+arr[pos])/2; arr[pos] = prev; pos += rect.size.x; } prev = this[x,max.z-1]; SetPos(x,max.z-1); for (int z=max.z-2; z>=min.z; z--) { prev = (prev+arr[pos])/2; arr[pos] = prev; pos -= rect.size.x; } } for (int z=min.z; z<max.z; z++) { prev = this[min.x,z]; SetPos(min.x,z); for (int x=min.x+1; x<max.x; x++) { prev = (prev+arr[pos])/2; arr[pos] = prev; pos += 1; } prev = this[max.x-1,z]; SetPos(max.x-1,z); for (int x=max.x-2; x>=min.x; x--) { prev = (prev+arr[pos])/2; arr[pos] = prev; pos -= 1; } } } for (int j=0; j<count; j++) arr[j] = copy.arr[j] + arr[j]*2*strength; float factor = Mathf.Sqrt(iterations); for (int j=0; j<count; j++) arr[j] /= factor; } [Obsolete] public void Spread (System.Func<float,float,float> spreadFn=null, int iterations=4) { Coord min = rect.Min; Coord max = rect.Max; for (int i=0; i<iterations; i++) { float prev = 0; for (int x=min.x; x<max.x; x++) { prev = this[x,min.z]; SetPos(x,min.z); for (int z=min.z+1; z<max.z; z++) { prev = spreadFn(prev,arr[pos]); arr[pos] = prev; pos += rect.size.x; } prev = this[x,max.z-1]; SetPos(x,max.z-1); for (int z=max.z-2; z>=min.z; z--) { prev = spreadFn(prev,arr[pos]); arr[pos] = prev; pos -= rect.size.x; } } for (int z=min.z; z<max.z; z++) { prev = this[min.x,z]; SetPos(min.x,z); for (int x=min.x+1; x<max.x; x++) { prev = spreadFn(prev,arr[pos]); arr[pos] = prev; pos += 1; } prev = this[max.x-1,z]; SetPos(max.x-1,z); for (int x=max.x-2; x>=min.x; x--) { prev = spreadFn(prev,arr[pos]); arr[pos] = prev; pos -= 1; } } } } [Obsolete] public void SimpleBlur (int iterations, float strength) { Coord min = rect.Min; Coord max = rect.Max; for (int iteration=0; iteration<iterations; iteration++) { for (int z=min.z; z<max.z; z++) { float prev = this[min.x,z]; for (int x=min.x+1; x<max.x-1; x++) { int i = (z-rect.offset.z)*rect.size.x + x - rect.offset.x; float curr = arr[i]; float next = arr[i+1]; float val = (prev+next)/2*strength + curr*(1-strength); arr[i] = val; prev = val; } } for (int x=min.x; x<max.x; x++) { float prev = this[x,min.z]; for (int z=min.z+1; z<max.z-1; z++) { int i = (z-rect.offset.z)*rect.size.x + x - rect.offset.x; float curr = arr[i]; float next = arr[i+rect.size.x]; float val = (prev+next)/2*strength + curr*(1-strength); arr[i] = val; prev = val; } } } } [Obsolete] public void Blur (System.Func<float,float,float,float> blurFn=null, float intensity=0.666f, bool additive=false, bool takemax=false, bool horizontal=true, bool vertical=true, FloatMatrix reference=null) { if (reference==null) reference = this; Coord min = rect.Min; Coord max = rect.Max; if (horizontal) for (int z=min.z; z<max.z; z++) { int pos = (z-rect.offset.z)*rect.size.x + min.x - rect.offset.x; float prev = reference[min.x,z]; float curr = prev; float next = prev; float blurred = 0; for (int x=min.x; x<max.x; x++) { prev = curr; //reference[x-1,z]; curr = next; //reference[x,z]; if (x<max.x-1) next = reference.arr[pos+1]; //reference[x+1,z]; //blurring if (blurFn==null) blurred = (prev+next)/2f; else blurred = blurFn(prev, curr, next); blurred = curr*(1-intensity) + blurred*intensity; //filling if (additive) arr[pos] += blurred; else arr[pos] = blurred; pos++; } } if (vertical) for (int x=min.x; x<max.x; x++) { int pos = (min.z-rect.offset.z)*rect.size.x + x - rect.offset.x; float next = reference[x,min.z]; float curr = next; float prev = next; float blurred = next; for (int z=min.z; z<max.z; z++) { prev = curr; //reference[x-1,z]; curr = next; //reference[x,z]; if (z<max.z-1) next = reference.arr[pos+rect.size.x]; //reference[x+1,z]; //blurring if (blurFn==null) blurred = (prev+next)/2f; else blurred = blurFn(prev, curr, next); blurred = curr*(1-intensity) + blurred*intensity; //filling if (additive) arr[pos] += blurred; else if (takemax) { if (blurred > arr[pos]) arr[pos] = blurred; } else arr[pos] = blurred; pos+=rect.size.x; } } } [Obsolete] public void LossBlur (int step=2, bool horizontal=true, bool vertical=true, FloatMatrix reference=null) { if (reference==null) reference = this; Coord min = rect.Min; Coord max = rect.Max; int stepShift = step + step/2; if (horizontal) for (int z=min.z; z<max.z; z++) { SetPos(min.x, z); float sum = 0; int div = 0; float avg = this.arr[pos]; float oldAvg = this.arr[pos]; for (int x=min.x; x<max.x+stepShift; x++) { //gathering if (x < max.x) sum += reference.arr[pos]; div ++; if (x%step == 0) { oldAvg=avg; if (x < max.x) avg=sum/div; sum=0; div=0; } //filling if (x-stepShift >= min.x) { float percent = 1f*(x%step)/step; if (percent<0) percent += 1; //for negative x this.arr[pos-stepShift] = avg*percent + oldAvg*(1-percent); } pos += 1; } } if (vertical) for (int x=min.x; x<max.x; x++) { SetPos(x, min.z); float sum = 0; int div = 0; float avg = this.arr[pos]; float oldAvg = this.arr[pos]; for (int z=min.z; z<max.z+stepShift; z++) { //gathering if (z < max.z) sum += reference.arr[pos]; div ++; if (z%step == 0) { oldAvg=avg; if (z < max.z) avg=sum/div; sum=0; div=0; } //filling if (z-stepShift >= min.z) { float percent = 1f*(z%step)/step; if (percent<0) percent += 1; this.arr[pos-stepShift*rect.size.x] = avg*percent + oldAvg*(1-percent); } pos += rect.size.x; } } } #region Outdated /*public void OverBlur (int iterations=20) { Matrix blurred = this.Clone(null); for (int i=1; i<=iterations; i++) { if (i==1 || i==2) blurred.Blur(step:1); else if (i==3) { blurred.Blur(step:1); blurred.Blur(step:1); } else blurred.Blur(step:i-2); //i:4, step:2 for (int p=0; p<count; p++) { float b = blurred.array[p] * i; float a = array[p]; array[p] = a + b + a*b; } } }*/ /*public void LossBlur (System.Func<float,float,float,float> blurFn=null, //prev, curr, next = output float intensity=0.666f, int step=1, Matrix reference=null, bool horizontal=true, bool vertical=true) { Coord min = rect.Min; Coord max = rect.Max; if (reference==null) reference = this; int lastX = max.x-1; int lastZ = max.z-1; if (horizontal) for (int z=min.z; z<=lastZ; z++) { float next = reference[min.x,z]; float curr = next; float prev = next; float blurred = next; float lastBlurred = next; for (int x=min.x+step; x<=lastX; x+=step) { //blurring if (blurFn==null) blurred = (prev+next)/2f; else blurred = blurFn(prev, curr, next); blurred = curr*(1-intensity) + blurred*intensity; //shifting values prev = curr; //this[x,z]; curr = next; //this[x+step,z]; try { next = reference[x+step*2,z]; } //this[x+step*2,z]; catch { next = reference[lastX,z]; } //filling between-steps distance if (step==1) this[x,z] = blurred; else for (int i=0; i<step; i++) { float percent = 1f * i / step; this[x-step+i,z] = blurred*percent + lastBlurred*(1-percent); } lastBlurred = blurred; } } if (vertical) for (int x=min.x; x<=lastX; x++) { float next = reference[x,min.z]; float curr = next; float prev = next; float blurred = next; float lastBlurred = next; for (int z=min.z+step; z<=lastZ; z+=step) { //blurring if (blurFn==null) blurred = (prev+next)/2f; else blurred = blurFn(prev, curr, next); blurred = curr*(1-intensity) + blurred*intensity; //shifting values prev = curr; curr = next; try { next = reference[x,z+step*2]; } catch { next = reference[x,lastZ]; } //filling between-steps distance if (step==1) this[x,z] = blurred; else for (int i=0; i<step; i++) { float percent = 1f * i / step; this[x,z-step+i] = blurred*percent + lastBlurred*(1-percent); } lastBlurred = blurred; } } }*/ #endregion #endregion #region Other static public void BlendLayers (FloatMatrix[] matrices, float[] opacity=null) /// Changes splatmaps in photoshop layered style so their summary value does not exceed 1 { //finding any existing matrix int anyMatrixNum = -1; for (int i=0; i<matrices.Length; i++) if (matrices[i]!=null) { anyMatrixNum = i; break; } if (anyMatrixNum == -1) { Debug.LogError("No matrices were found to blend " + matrices.Length); return; } //finding rect CoordRect rect = matrices[anyMatrixNum].rect; //checking rect size #if WDEBUG for (int i=0; i<matrices.Length; i++) if (matrices[i]!=null && matrices[i].rect!=rect) { Debug.LogError("Matrix rect mismatch " + rect + " " + matrices[i].rect); return; } #endif int rectCount = rect.Count; for (int pos=0; pos<rectCount; pos++) { float left = 1; for (int i=matrices.Length-1; i>=0; i--) //layer 0 is background, layer Length-1 is the top one { if (matrices[i] == null) continue; float val = matrices[i].arr[pos]; if (opacity != null) val *= opacity[i]; val = val * left; matrices[i].arr[pos] = val; left -= val; if (left < 0) break; /*float overly = sum + val - 1; if (overly < 0) overly = 0; //faster then calling Math.Clamp if (overly > 1) overly = 1; matrices[i].array[pos] = val - overly; sum += val - overly;*/ } } } static public void NormalizeLayers (FloatMatrix[] matrices, float[] opacity) /// Changes splatmaps so their summary value does not exceed 1 { //finding any existing matrix int anyMatrixNum = -1; for (int i=0; i<matrices.Length; i++) if (matrices[i]!=null) { anyMatrixNum = i; break; } if (anyMatrixNum == -1) { Debug.LogError("No matrices were found to blend " + matrices.Length); return; } //finding rect CoordRect rect = matrices[anyMatrixNum].rect; //checking rect size #if WDEBUG for (int i=0; i<matrices.Length; i++) if (matrices[i]!=null && matrices[i].rect!=rect) { Debug.LogError("Matrix rect mismatch " + rect + " " + matrices[i].rect); return; } #endif int rectCount = rect.Count; for (int pos=0; pos<rectCount; pos++) { for (int i=0; i<matrices.Length; i++) matrices[i].arr[pos] *= opacity[i]; float sum = 0; for (int i=0; i<matrices.Length; i++) sum += matrices[i].arr[pos]; if (sum > 1f) for (int i=0; i<matrices.Length; i++) matrices[i].arr[pos] /= sum; } } static public void Blend (FloatMatrix src, FloatMatrix dst, float factor) { if (dst.rect != src.rect) Debug.LogError("Matrix Blend: maps have different sizes"); for (int i=0; i<dst.count; i++) { dst.arr[i] = dst.arr[i]*factor + src.arr[i]*(1-factor); } } static public void Mask (FloatMatrix src, FloatMatrix dst, FloatMatrix mask) //changes dst, not src { if (src != null && (dst.rect != src.rect || dst.rect != mask.rect)) Debug.LogError("Matrix Mask: maps have different sizes"); for (int i=0; i<dst.count; i++) { float percent = mask.arr[i]; if (percent > 1 || percent < 0) continue; dst.arr[i] = dst.arr[i]*percent + (src==null? 0:src.arr[i]*(1-percent)); } } static public void SafeBorders (FloatMatrix src, FloatMatrix dst, int safeBorders) //changes dst, not src { Coord min = dst.rect.Min; Coord max = dst.rect.Max; for (int x=min.x; x<max.x; x++) for (int z=min.z; z<max.z; z++) { int distFromBorder = Mathf.Min( Mathf.Min(x-min.x,max.x-x), Mathf.Min(z-min.z,max.z-z) ); float percent = 1f*distFromBorder / safeBorders; if (percent > 1) continue; dst[x,z] = dst[x,z]*percent + (src==null? 0:src[x,z]*(1-percent)); } } #endregion #region Histogram public float[] Histogram (int resolution, float max=1, bool normalize=true) /// Evaluates all pixels in matrix and returns an array of pixels count by their value. { float[] quants = new float[resolution]; for (int i=0; i<count; i++) { float val = arr[i]; float percent = val / max; int num = (int)(percent*resolution); if (num==resolution) num--; //this could happen when val==max quants[num]++; } if (normalize) { float maxQuant = 0; for (int i=0; i<resolution; i++) if (quants[i] > maxQuant) maxQuant = quants[i]; for (int i=0; i<resolution; i++) quants[i] /= maxQuant; } return quants; } public float[] Slice (Coord coord, int length, bool vertical) /// A single line (or row) of a matrix to show a vertical slice { if (vertical) return SliceVertical(coord, length); else return SliceHorizontal(coord, length); } public float[] SliceHorizontal (Coord coord, int length) { if (coord.z < rect.offset.z || coord.z >= rect.offset.z+rect.size.z) return new float[0]; if (coord.x < rect.offset.x) { length -= rect.offset.x-coord.x; coord.x = rect.offset.x; } if (length <= 0) return new float[0]; int max = coord.x + length; if (max >= rect.offset.x+rect.size.x) length = rect.offset.x+rect.size.x - coord.x; MatrixLine line = new MatrixLine(coord.x-rect.offset.x, length); line.ReadLine(this, coord.z); return line.arr; } public float[] SliceVertical (Coord coord, int length) { if (coord.x < rect.offset.x || coord.x >= rect.offset.x+rect.size.x) return new float[0]; if (coord.z < rect.offset.z) { length -= rect.offset.z-coord.z; coord.x = rect.offset.z; } if (length <= 0) return new float[0]; int max = coord.z + length; if (max >= rect.offset.z+rect.size.z) length = rect.offset.z+rect.size.z - coord.z; MatrixLine row = new MatrixLine(coord.z-rect.offset.z, length); row.ReadLine(this, coord.x); return row.arr; } public static byte[] HistogramToTextureBytes (float[] quants, int height, byte empty=0, byte top=255, byte filled=128) /// Converts an array from Histogram to texture bytes { int width = quants.Length; byte[] bytes = new byte[width * height]; for (int x=0; x<width; x++) { int max = (int)(quants[x] * height); if (max==height) max--; for (int z=0; z<height; z++) { byte val = empty; if (z==max) val=top; else if (z<max) val=filled; bytes[z*width + x] = val; } } return bytes; } public static Texture2D HistogramToTextureR8 (float[] quants, int height, byte empty=0, byte top=255, byte filled=128) /// Converts an array from Histogram to texture (format R8) { byte[] bytes = HistogramToTextureBytes(quants, height, empty, top, filled); Texture2D tex = new Texture2D(quants.Length, height, TextureFormat.R8, false, linear:true); tex.LoadRawTextureData(bytes); tex.Apply(updateMipmaps:false); return tex; } [Obsolete("Use static method instead")] public byte[] HistogramTexture (int width, int height, byte empty=0, byte top=255, byte filled=128) { float[] quants = Histogram(width); byte[] bytes = HistogramToTextureBytes(quants, height, empty, top, filled); return bytes; } #endregion #region Import public void ImportTexture (Texture2D tex, int channel, bool useRaw=true) { ImportTexture(tex, rect.offset, channel, useRaw); } public void ImportTexture (Texture2D tex, Coord texOffset, int channel, bool useRaw=true) { Coord texSize = new Coord(tex.width, tex.height); //raw bytes TextureFormat format = tex.format; if (useRaw && (format==TextureFormat.RGBA32 || format==TextureFormat.ARGB32 || format==TextureFormat.RGB24 || format==TextureFormat.R8 || format==TextureFormat.R16)) { byte[] bytes = tex.GetRawTextureData(); switch(format) { case TextureFormat.RGBA32: ImportRaw(bytes, texOffset, texSize, channel, 4); break; case TextureFormat.ARGB32: channel++; if (channel == 5) channel = 0; ImportRaw(bytes, texOffset, texSize, channel, 4); break; case TextureFormat.RGB24: ImportRaw(bytes, texOffset, texSize, channel, 3); break; case TextureFormat.R8: ImportRaw(bytes, texOffset, texSize, 0, 1); break; case TextureFormat.R16: ImportRaw16(bytes, texOffset, texSize); break; } } //colors else { CoordRect intersection = CoordRect.Intersected(rect, new CoordRect(texOffset,texSize)); //to get array smaller than the whole texture Color[] colors = tex.GetPixels(intersection.offset.x-texOffset.x, intersection.offset.z-texOffset.z, intersection.size.x, intersection.size.z); ImportColors(colors, intersection.offset, intersection.size, channel); } tex.Apply(); } public void ImportColors (Color[] colors, int width, int height, int channel) { ImportColors(colors, rect.offset, new Coord(width,height), channel); } public void ImportColors (Color[] colors, Coord colorsSize, int channel) { ImportColors(colors, rect.offset, colorsSize, channel); } public void ImportColors (Color[] colors, Coord colorsOffset, Coord colorsSize, int channel) { if (colors.Length != colorsSize.x*colorsSize.z) throw new Exception("Array count does not match texture dimensions"); CoordRect intersection = CoordRect.Intersected(rect, new CoordRect(colorsOffset, colorsSize)); Coord min = intersection.Min; Coord max = intersection.Max; for (int x=min.x; x<max.x; x++) for (int z=min.z; z<max.z; z++) { int matrixPos = (z-rect.offset.z)*rect.size.x + x - rect.offset.x; int colorsPos = (z-colorsOffset.z)*colorsSize.x + x - colorsOffset.x; float val; switch (channel) { case 0: val = colors[colorsPos].r; break; case 1: val = colors[colorsPos].g; break; case 2: val = colors[colorsPos].b; break; case 3: val = colors[colorsPos].a; break; default: val = colors[colorsPos].r; break; //(colors[colorsPos].r + colors[colorsPos].g + colors[colorsPos].b + colors[colorsPos].a); break; } arr[matrixPos] = val; } } public void ImportRaw (byte[] bytes, int width, int height, int start, int step) { ImportRaw(bytes, new Coord(width,height), rect.offset, start, step); } public void ImportRaw (byte[] bytes, Coord bytesSize, int start, int step) { ImportRaw(bytes, bytesSize, rect.offset, start, step); } public void ImportRaw (byte[] bytes, Coord bytesOffset, Coord bytesSize, int start, int step) { if (bytes.Length != bytesSize.x*bytesSize.z*step && (bytes.Length < bytesSize.x*bytesSize.z*step*1.3f || bytes.Length > bytesSize.x*bytesSize.z*step*1.3666f)) //in case of mipmap information throw new Exception("Array count does not match texture dimensions"); CoordRect intersection = CoordRect.Intersected(rect, new CoordRect(bytesOffset, bytesSize)); Coord min = intersection.Min; Coord max = intersection.Max; for (int x=min.x; x<max.x; x++) for (int z=min.z; z<max.z; z++) { int matrixPos = (z-rect.offset.z)*rect.size.x + x - rect.offset.x; int bytesPos = (z-bytesOffset.z)*bytesSize.x + x - bytesOffset.x; bytesPos = bytesPos * step + start; float val = bytes[bytesPos] / 255f; //matrix has the range 0-1 _inclusive_, it could be 1, so using 255 arr[matrixPos] = val; } } public void ImportRaw16 (byte[] bytes, int width, int height) { ImportRaw16(bytes, new Coord(width,height), rect.offset); } public void ImportRaw16 (byte[] bytes, Coord texSize) { ImportRaw16(bytes, texSize, rect.offset); } public void ImportRaw16 (byte[] bytes, Coord texOffset, Coord texSize) { if (texSize.x*texSize.z*2 != bytes.Length) throw new Exception("Array count does not match texture dimensions"); CoordRect intersection = CoordRect.Intersected(rect, new CoordRect(texOffset, texSize)); Coord min = intersection.Min; Coord max = intersection.Max; for (int x=min.x; x<max.x; x++) for (int z=min.z; z<max.z; z++) { int matrixPos = (z-rect.offset.z)*rect.size.x + x - rect.offset.x; int bytesPos = (z-texOffset.z)*texSize.x + x - texOffset.x; bytesPos *= 2; float val = (bytes[bytesPos+1]*255f + bytes[bytesPos]) / 65025f; arr[matrixPos] = val; } } public void ImportHeights (float[,] heights) { ImportHeights(heights, rect.offset); } public void ImportHeights (float[,] heights, Coord heightsOffset) { Coord heightsSize = new Coord(heights.GetLength(1), heights.GetLength(0)); //x and z swapped CoordRect heightsRect = new CoordRect(heightsOffset, heightsSize); CoordRect intersection = CoordRect.Intersected(rect, heightsRect); Coord min = intersection.Min; Coord max = intersection.Max; for (int x=min.x; x<max.x; x++) for (int z=min.z; z<max.z; z++) { int matrixPos = (z-rect.offset.z)*rect.size.x + x - rect.offset.x; int heightsPosZ = x - heightsRect.offset.x; int heightsPosX = z - heightsRect.offset.z; arr[matrixPos] = heights[heightsPosX, heightsPosZ]; } } public void ImportSplats (float[,,] splats, int channel) { ImportSplats(splats, rect.offset, channel); } public void ImportSplats (float[,,] splats, Coord splatsOffset, int channel) { Coord splatsSize = new Coord(splats.GetLength(1), splats.GetLength(0)); //x and z swapped CoordRect splatsRect = new CoordRect(splatsOffset, splatsSize); CoordRect intersection = CoordRect.Intersected(rect, splatsRect); Coord min = intersection.Min; Coord max = intersection.Max; for (int x=min.x; x<max.x; x++) for (int z=min.z; z<max.z; z++) { int matrixPos = (z-rect.offset.z)*rect.size.x + x - rect.offset.x; int heightsPosZ = x - splatsRect.offset.x; int heightsPosX = z - splatsRect.offset.z; arr[matrixPos] = splats[heightsPosX, heightsPosZ, channel]; } } public void ImportData (TerrainData data, int channel=-1) { ImportData (data, rect.offset, channel=-1); } public void ImportData (TerrainData data, Coord dataOffset, int channel=-1) /// Partial terrain data (loading only the part intersecting with matrix). Do not work in thread! /// If channel is -1 getting height { int resolution = channel==-1 ? data.heightmapResolution : data.alphamapResolution; Coord dataSize = new Coord(resolution, resolution); CoordRect dataIntersection = CoordRect.Intersected(rect, new CoordRect(dataOffset, dataSize)); if (dataIntersection.size.x==0 || dataIntersection.size.z==0) return; if (channel == -1) { float[,] heights = data.GetHeights(dataIntersection.offset.x-dataOffset.x, dataIntersection.offset.z-dataOffset.z, dataIntersection.size.x, dataIntersection.size.z); ImportHeights(heights, dataIntersection.offset); } else { float[,,] splats = data.GetAlphamaps(dataIntersection.offset.x-dataOffset.x, dataIntersection.offset.z-dataOffset.z, dataIntersection.size.x, dataIntersection.size.z); ImportSplats(splats, dataIntersection.offset, channel); } } #endregion #region Export public void ExportTexture (Texture2D tex, int channel, bool useRaw=true) { ExportTexture(tex, rect.offset, channel, useRaw); } public void ExportTexture (Texture2D tex, Coord texOffset, int channel, bool useRaw=true) { Coord texSize = new Coord(tex.width, tex.height); //raw bytes TextureFormat format = tex.format; if (useRaw && (format==TextureFormat.RGBA32 || format==TextureFormat.ARGB32 || format==TextureFormat.RGB24 || format==TextureFormat.R8 || format==TextureFormat.R16)) { byte[] bytes = tex.GetRawTextureData(); switch(format) { case TextureFormat.RGBA32: //bytes = new byte[texSize.x*texSize.z*4]; ExportRaw(bytes, texOffset, texSize, channel, 4); break; case TextureFormat.ARGB32: //bytes = new byte[texSize.x*texSize.z*4]; channel++; if (channel == 5) channel = 0; ExportRaw(bytes, texOffset, texSize, channel, 4); break; case TextureFormat.RGB24: //bytes = new byte[texSize.x*texSize.z*3]; ExportRaw(bytes, texOffset, texSize, channel, 3); break; case TextureFormat.R8: //bytes = new byte[texSize.x*texSize.z]; ExportRaw(bytes, texOffset, texSize, 0, 1); break; case TextureFormat.R16: //bytes = new byte[texSize.x*texSize.z*2]; ExportRaw16(bytes, texOffset, texSize); break; } tex.LoadRawTextureData(bytes); } //colors else { CoordRect intersection = CoordRect.Intersected(rect, new CoordRect(texOffset,texSize)); //to get array smaller than the whole texture //Color[] colors = tex.GetPixels(intersection.offset.x-texOffset.x, intersection.offset.z-texOffset.z, intersection.size.x, intersection.size.z); Color[] colors = new Color[intersection.size.x * intersection.size.z]; ExportColors(colors, intersection.offset, intersection.size, channel); tex.SetPixels(intersection.offset.x-texOffset.x, intersection.offset.z-texOffset.z, intersection.size.x, intersection.size.z, colors); } tex.Apply(); } public void ExportColors (Color[] colors, int width, int height, int channel) { ExportColors(colors, rect.offset, new Coord(width,height), channel); } public void ExportColors (Color[] colors, Coord colorsSize, int channel) { ExportColors(colors, rect.offset, colorsSize, channel); } public void ExportColors (Color[] colors, Coord colorsOffset, Coord colorsSize, int channel) { if (colors.Length != colorsSize.x*colorsSize.z) throw new Exception("Array count does not match texture dimensions"); CoordRect intersection = CoordRect.Intersected(rect, new CoordRect(colorsOffset, colorsSize)); Coord min = intersection.Min; Coord max = intersection.Max; for (int x=min.x; x<max.x; x++) for (int z=min.z; z<max.z; z++) { int matrixPos = (z-rect.offset.z)*rect.size.x + x - rect.offset.x; int colorsPos = (z-colorsOffset.z)*colorsSize.x + x - colorsOffset.x; float val = arr[matrixPos]; switch (channel) { case 0: colors[colorsPos].r = val; break; case 1: colors[colorsPos].g = val; break; case 2: colors[colorsPos].b = val; break; case 3: colors[colorsPos].a = val; break; default: colors[colorsPos].r = val; break; //(colors[colorsPos].r + colors[colorsPos].g + colors[colorsPos].b + colors[colorsPos].a); break; } } } public void ExportRaw (byte[] bytes, int width, int height, int start, int step) { ExportRaw(bytes, new Coord(width,height), rect.offset, start, step); } public void ExportRaw (byte[] bytes, Coord bytesSize, int start, int step) { ExportRaw(bytes, bytesSize, rect.offset, start, step); } public void ExportRaw (byte[] bytes, Coord bytesOffset, Coord bytesSize, int start, int step) { if (bytes.Length != bytesSize.x*bytesSize.z*step && (bytes.Length < bytesSize.x*bytesSize.z*step*1.3f || bytes.Length > bytesSize.x*bytesSize.z*step*1.3666f)) //in case of mipmap information throw new Exception("Array count does not match texture dimensions"); CoordRect intersection = CoordRect.Intersected(rect, new CoordRect(bytesOffset, bytesSize)); Coord min = intersection.Min; Coord max = intersection.Max; for (int x=min.x; x<max.x; x++) for (int z=min.z; z<max.z; z++) { int matrixPos = (z-rect.offset.z)*rect.size.x + x - rect.offset.x; int bytesPos = (z-bytesOffset.z)*bytesSize.x + x - bytesOffset.x; bytesPos = bytesPos * step + start; float val = arr[matrixPos]; bytes[bytesPos] = (byte)(val * 255f); //matrix has the range 0-1 _inclusive_, it could be 1 } } public void ExportRaw16 (byte[] bytes, int width, int height) { ExportRaw16(bytes, new Coord(width,height), rect.offset); } public void ExportRaw16 (byte[] bytes, Coord texSize) { ExportRaw16(bytes, texSize, rect.offset); } public void ExportRaw16 (byte[] bytes, Coord texOffset, Coord texSize) { if (texSize.x*texSize.z*2 != bytes.Length) throw new Exception("Array count does not match texture dimensions"); CoordRect intersection = CoordRect.Intersected(rect, new CoordRect(texOffset, texSize)); Coord min = intersection.Min; Coord max = intersection.Max; for (int x=min.x; x<max.x; x++) for (int z=min.z; z<max.z; z++) { int matrixPos = (z-rect.offset.z)*rect.size.x + x - rect.offset.x; int bytesPos = (z-texOffset.z)*texSize.x + x - texOffset.x; bytesPos *= 2; float val = arr[matrixPos]; //this[x+regionRect.offset.x, z+regionRect.offset.z]; int intVal = (int)(val*65025); byte hb = (byte)(intVal/255f); bytes[bytesPos+1] = hb; //TODO: test if the same will work on macs with non-inverted byte order bytes[bytesPos] = (byte)(intVal-hb*255); } } public void ExportHeights (float[,] heights) { ExportHeights(heights, rect.offset); } public void ExportHeights (float[,] heights, Coord heightsOffset) { Coord heightsSize = new Coord(heights.GetLength(1), heights.GetLength(0)); //x and z swapped CoordRect heightsRect = new CoordRect(heightsOffset, heightsSize); CoordRect intersection = CoordRect.Intersected(rect, heightsRect); Coord min = intersection.Min; Coord max = intersection.Max; for (int x=min.x; x<max.x; x++) for (int z=min.z; z<max.z; z++) { int matrixPos = (z-rect.offset.z)*rect.size.x + x - rect.offset.x; int heightsPosZ = x - heightsRect.offset.x; int heightsPosX = z - heightsRect.offset.z; float val = arr[matrixPos]; heights[heightsPosX, heightsPosZ] = val; } } public void ExportSplats (float[,,] splats, int channel) { ExportSplats(splats, rect.offset, channel); } public void ExportSplats (float[,,] splats, Coord splatsOffset, int channel) { Coord splatsSize = new Coord(splats.GetLength(1), splats.GetLength(0)); //x and z swapped CoordRect splatsRect = new CoordRect(splatsOffset, splatsSize); CoordRect intersection = CoordRect.Intersected(rect, splatsRect); Coord min = intersection.Min; Coord max = intersection.Max; for (int x=min.x; x<max.x; x++) for (int z=min.z; z<max.z; z++) { int matrixPos = (z-rect.offset.z)*rect.size.x + x - rect.offset.x; int heightsPosZ = x - splatsRect.offset.x; int heightsPosX = z - splatsRect.offset.z; float val = arr[matrixPos]; splats[heightsPosX, heightsPosZ, channel] = val; } } //partial terrain data (loading only the part intersecting with matrix). Do not work in thread! public void ExportData (TerrainData data) { ExportData (data, rect.offset, -1); } public void ExportData (TerrainData data, int channel) { ExportData (data, rect.offset, channel); } public void ExportData (TerrainData data, Coord dataOffset, int channel) //if channel is -1 getting height { int resolution = channel==-1 ? data.heightmapResolution : data.alphamapResolution; Coord dataSize = new Coord(resolution, resolution); CoordRect dataIntersection = CoordRect.Intersected(rect, new CoordRect(dataOffset, dataSize)); if (dataIntersection.size.x==0 || dataIntersection.size.z==0) return; if (channel == -1) { float[,] heights = new float[dataIntersection.size.z, dataIntersection.size.x]; //x and z swapped ExportHeights(heights, dataIntersection.offset); data.SetHeights(dataIntersection.offset.x-dataOffset.x, dataIntersection.offset.z-dataOffset.z, heights); //while get/set has the right order } else { float[,,] splats = data.GetAlphamaps(dataIntersection.offset.x-dataOffset.x, dataIntersection.offset.z-dataOffset.z, dataIntersection.size.x, dataIntersection.size.z); ExportSplats(splats, dataIntersection.offset, channel); data.SetAlphamaps(dataIntersection.offset.x-dataOffset.x, dataIntersection.offset.z-dataOffset.z, splats); } } #endregion #region Stamp public void Stamp (float centerX, float centerZ, float radius, float hardness, FloatMatrix stamp) /// Applies stamp to this matrix, blending it in a smooth circular way using radius and hardness /// All values are in pixels and using matrix offset /// Center does not need to be the real center, it's just used to calculate fallof /// Hardness is the percent (0-1) of the stamp that has 100% fallof /// Invert fills all matrix except the center area /// Tested { CoordRect intersection = CoordRect.Intersected(rect, stamp.rect); Coord min = intersection.Min; Coord max = intersection.Max; for (int x=min.x; x<max.x; x++) for (int z=min.z; z<max.z; z++) { float dist = Mathf.Sqrt((x-centerX)*(x-centerX) + (z-centerZ)*(z-centerZ)); if (dist > radius) continue; int pos = (z-rect.offset.z)*rect.size.x + x - rect.offset.x; int stampPos = (z-stamp.rect.offset.z)*stamp.rect.size.x + x - stamp.rect.offset.x; if (dist < radius*hardness) { arr[pos] = stamp.arr[stampPos]; continue; } float fallof = (radius - dist) / (radius - radius*hardness); //linear yet if (fallof>1) fallof = 1; if (fallof<0) fallof = 0; fallof = 3*fallof*fallof - 2*fallof*fallof*fallof; arr[pos] = arr[pos]*(1-fallof) + stamp.arr[stampPos]*fallof; } } public void Stamp (float centerX, float centerZ, float radius, float hardness, float value) /// Applies value stamp to this matrix. Same as above, but using uniform value { Coord min = rect.Min; Coord max = rect.Max; for (int x=min.x; x<max.x; x++) for (int z=min.z; z<max.z; z++) { float dist = Mathf.Sqrt((x-centerX)*(x-centerX) + (z-centerZ)*(z-centerZ)); if (dist > radius) continue; int pos = (z-rect.offset.z)*rect.size.x + x - rect.offset.x; if (dist < radius*hardness) { arr[pos] = value; continue; } float fallof = (radius - dist) / (radius - radius*hardness); //linear if (fallof>1) fallof = 1; if (fallof<0) fallof = 0; fallof = 3*fallof*fallof - 2*fallof*fallof*fallof; arr[pos] = arr[pos]*(1-fallof) + value*fallof; } } public void StampInverted (float centerX, float centerZ, float radius, float hardness, float value) /// Applies value to all of the matrix except the area in the center. Changes from the original version by it's "continiue" optimizations { Coord min = rect.Min; Coord max = rect.Max; for (int x=min.x; x<max.x; x++) for (int z=min.z; z<max.z; z++) { int pos = (z-rect.offset.z)*rect.size.x + x - rect.offset.x; float dist = Mathf.Sqrt((x-centerX)*(x-centerX) + (z-centerZ)*(z-centerZ)); if (dist > radius) { arr[pos] = value; continue; } if (dist < radius*hardness) continue; //differs from the original one float fallof = (radius - dist) / (radius - radius*hardness); //linear if (fallof>1) fallof = 1; if (fallof<0) fallof = 0; fallof = 3*fallof*fallof - 2*fallof*fallof*fallof; arr[pos] = arr[pos]*fallof + value*(1-fallof); //differs here too } } #endregion #region Arithmetic (per-pixel operation that does not involve neighbor pixels) public void Mix (FloatMatrix m, float opacity=1) { float invOpacity = 1-opacity; for (int i=0; i<count; i++) arr[i] = m.arr[i]*opacity + arr[i]*invOpacity; } public void Add (FloatMatrix add, float opacity=1) { for (int i=0; i<count; i++) arr[i] += add.arr[i] * opacity; } public void Add (FloatMatrix add, FloatMatrix mask, float opcaity=1) { for (int i=0; i<count; i++) arr[i] += add.arr[i] * mask.arr[i] * opcaity; } public void Add (float add) { for (int i=0; i<count; i++) arr[i] += add; } public void Subtract (FloatMatrix m, float opacity=1) { for (int i=0; i<count; i++) arr[i] -= m.arr[i] * opacity; } public void InvSubtract (FloatMatrix m, float opacity=1) /// subtracting this matrix from m { for (int i=0; i<count; i++) arr[i] = m.arr[i]*opacity - arr[i]; } public void Multiply (FloatMatrix m, float opacity=1) { float invOpacity = 1-opacity; for (int i=0; i<count; i++) arr[i] *= m.arr[i]*opacity + invOpacity; } public void Multiply (float m) { for (int i=0; i<count; i++) arr[i] *= m; } public void Sqrt () { for (int i=0; i<count; i++) arr[i] = Mathf.Sqrt(arr[i]); } public void Fallof () { for (int i=0; i<count; i++) { float val = arr[i]; arr[i] = 3*val*val - 2*val*val*val; } } public void Contrast (float m) /// Mid-matrix (value 0.5) multiply { for (int i=0; i<count; i++) { float val = arr[i]*2 -1; val *= m; arr[i] = (val+1) / 2; } } public void Divide (FloatMatrix m, float opacity=1) { float invOpacity = 1-opacity; for (int i=0; i<count; i++) arr[i] *= opacity/m.arr[i] + invOpacity; } public void Difference (FloatMatrix m, float opacity=1) { for (int i=0; i<count; i++) { float val = arr[i] - m.arr[i]*opacity; if (val < 0) val = -val; arr[i] = val; } } public void Overlay (FloatMatrix m, float opacity=1) { for (int i=0; i<count; i++) { float a = arr[i]; float b = m.arr[i]; b = b*opacity + (0.5f - opacity/2); //enhancing contrast via levels if (a > 0.5f) b = 1 - 2*(1-a)*(1-b); else b = 2*a*b; arr[i] = b;// b*opacity + a*(1-opacity); //the same } } public void HardLight (FloatMatrix m, float opacity=1) /// Same as overlay but estimating b>0.5 { for (int i=0; i<count; i++) { float a = arr[i]; float b = m.arr[i]; if (b > 0.5f) b = 1 - 2*(1-a)*(1-b); else b = 2*a*b; arr[i] = b*opacity + a*(1-opacity); } } public void SoftLight (FloatMatrix m, float opacity=1) { for (int i=0; i<count; i++) { float a = arr[i]; float b = m.arr[i]; b = (1-2*b)*a*a + 2*b*a; arr[i] = b*opacity + a*(1-opacity); } } public void Max (FloatMatrix m, float opacity=1) { for (int i=0; i<count; i++) { float val = m.arr[i]>arr[i] ? m.arr[i] : arr[i]; arr[i] = val*opacity + arr[i]*(1-opacity); } } public void Min (FloatMatrix m, float opacity=1) { for (int i=0; i<count; i++) { float val = m.arr[i]<arr[i] ? m.arr[i] : arr[i]; arr[i] = val*opacity + arr[i]*(1-opacity); } } public new void Fill(float val) { for (int i=0; i<count; i++) arr[i] = val; } public void Fill (FloatMatrix m) { m.arr.CopyTo(arr,0); } public void Invert() { for (int i=0; i<count; i++) arr[i] = -arr[i]; } public void InvertOne() { for (int i=0; i<count; i++) arr[i] = 1-arr[i]; } public void SelectRange (float min0, float min1, float max0, float max1) /// Fill all values within min1-max0 with 1, while min0-1 and max0-1 are filled with blended { for (int i=0; i<arr.Length; i++) { float delta = arr[i]; //if (steepness.x<0.0001f) array[i] = 1-(delta-max0)/(max1-max0); //else { float minVal = (delta-min0)/(min1-min0); float maxVal = 1-(delta-max0)/(max1-max0); float val = minVal>maxVal? maxVal : minVal; if (val<0) val=0; if (val>1) val=1; arr[i] = val; } } } public void Clamp01 () { for (int i=0; i<count; i++) { float val = arr[i]; if (val > 1) arr[i] = 1; else if (val < 0) arr[i] = 0; } } public void ToRange01 () { for (int i=0; i<count; i++) arr[i] = (arr[i]+1) / 2; } public float MaxValue () { float max=-20000000; for (int i=0; i<count; i++) { float val = arr[i]; if (val > max) max = val; } return max; } public float MinValue () { float min=20000000; for (int i=0; i<count; i++) { float val = arr[i]; if (val < min) min = val; } return min; } public virtual bool IsEmpty () /// Better than MinValue since it can quit if matrix is not empty { for (int i=0; i<count; i++) if (arr[i] > 0.0001f) return false; return true; } public virtual bool IsEmpty (float delta) { for (int i=0; i<count; i++) if (arr[i] > delta) return false; return true; } public void BlackWhite (float mid) /// Sets all values bigger than mid to white (1), and those lower to black (0) { for (int i=0; i<count; i++) { float val = arr[i]; if (val > mid) arr[i] = 1; else arr[i] = 0; } } public void Terrace (float[] terraces, float steepness, float intensity) { for (int i=0; i<count; i++) { float val = arr[i]; if (val > 0.999f) continue; //do nothing with values that are out of range int terrNum = 0; for (int t=0; t<terraces.Length-1; t++) { if (terraces[terrNum+1] > val || terrNum+1 == terraces.Length) break; terrNum++; } //kinda curve evaluation float delta = terraces[terrNum+1] - terraces[terrNum]; float relativePos = (val - terraces[terrNum]) / delta; float percent = 3*relativePos*relativePos - 2*relativePos*relativePos*relativePos; percent = (percent-0.5f)*2; bool minus = percent<0; percent = Mathf.Abs(percent); percent = Mathf.Pow(percent,1f-steepness); if (minus) percent = -percent; percent = percent/2 + 0.5f; arr[i] = (terraces[terrNum]*(1-percent) + terraces[terrNum+1]*percent)*intensity + arr[i]*(1-intensity); } } public void Levels (Vector2 min, Vector2 max, float gamma) { for (int i=0; i<count; i++) { float val = arr[i]; if (val < min.x) { arr[i] = 0; continue; } if (val > max.x) { arr[i] = 1; continue; } val = 1 * ( ( val - min.x ) / ( max.x - min.x ) ); if (gamma != 1) // (gamma>1.00001f || gamma<0.9999f) { if (gamma<1) val = Mathf.Pow(val, gamma); else val = Mathf.Pow(val, 1/(2-gamma)); } arr[i] = val; } } public void ReadMatrix (FloatMatrix src, CoordRect.TileMode tileMode = CoordRect.TileMode.Clamp) { Coord min = rect.Min; Coord max = rect.Max; for (int x=min.x; x<max.x; x++) for (int z=min.z; z<max.z; z++) { Coord tiledCoord = src.rect.Tile(new Coord(x,z), tileMode); this[x,z] = src[tiledCoord]; } } /*public Matrix FastDownscaled (int ratio) { CoordRect downRect = new CoordRect( rect.offset, new Coord(rect.size.x/ratio, rect.size.z/ratio) ); Matrix downMatrix = new Matrix(downRect); Coord min = downRect.Min; Coord max = downRect.Max; for (int x=min.x; x<max.x; x++) for (int z=min.z; z<max.z; z++) { float avgVal = 0; for (int sx=0; sx<ratio; sx++) for (int sz=0; sz<ratio; sz++) avgVal += arr[(z*ratio + sz) * rect.size.x + (x*ratio + sx)]; //this[x*ratio + sx, z*ratio + sz]; avgVal /= ratio*ratio; downMatrix[x,z] = avgVal; } return downMatrix; }*/ #endregion #region Simple Conversions /// No offset is used in all the Simple Conversions // TODO: use arrRect public void ReadArray (float[,] arr2D) { int maxX = rect.size.x; if (arr2D.GetLength(1) < maxX) maxX = arr2D.GetLength(1); int maxZ = rect.size.z; if (arr2D.GetLength(0) < maxZ) maxZ = arr2D.GetLength(0); for (int x=0; x<maxX; x++) for (int z=0; z<maxZ; z++) arr[z*rect.size.x + x] = arr2D[z,x]; } public void ApplyArray (float[,] arr2D) { int maxX = rect.size.x; if (arr2D.GetLength(1) < maxX) maxX = arr2D.GetLength(1); int maxZ = rect.size.z; if (arr2D.GetLength(0) < maxZ) maxZ = arr2D.GetLength(0); for (int x=0; x<maxX; x++) for (int z=0; z<maxZ; z++) arr2D[z,x] = arr[z*rect.size.x + x]; } #endregion #region Blend Algorithms public enum BlendAlgorithm { mix=0, add=1, subtract=2, multiply=3, divide=4, difference=5, min=6, max=7, overlay=8, hardLight=9, softLight=10} //not using const arrays or dictionaries for native compatibility public void Blend (FloatMatrix m, BlendAlgorithm algorithm, float opacity=1) { switch (algorithm) { case BlendAlgorithm.mix: default: Mix(m, opacity); break; case BlendAlgorithm.add: Add(m, opacity); break; case BlendAlgorithm.subtract: Subtract(m, opacity); break; case BlendAlgorithm.multiply: Multiply(m, opacity); break; case BlendAlgorithm.divide: Divide(m, opacity); break; case BlendAlgorithm.difference: Difference(m, opacity); break; case BlendAlgorithm.min: Min(m, opacity); break; case BlendAlgorithm.max: Max(m, opacity); break; case BlendAlgorithm.overlay: Overlay(m, opacity); break; case BlendAlgorithm.hardLight: HardLight(m, opacity); break; case BlendAlgorithm.softLight: SoftLight(m, opacity); break; } } public static System.Func<float,float,float> GetBlendAlgorithm (BlendAlgorithm algorithm) { switch (algorithm) { case BlendAlgorithm.mix: return delegate (float a, float b) { return b; }; case BlendAlgorithm.add: return delegate (float a, float b) { return a+b; }; case BlendAlgorithm.subtract: return delegate (float a, float b) { return a-b; }; case BlendAlgorithm.multiply: return delegate (float a, float b) { return a*b; }; case BlendAlgorithm.divide: return delegate (float a, float b) { return a/b; }; case BlendAlgorithm.difference: return delegate (float a, float b) { return Mathf.Abs(a-b); }; case BlendAlgorithm.min: return delegate (float a, float b) { return Mathf.Min(a,b); }; case BlendAlgorithm.max: return delegate (float a, float b) { return Mathf.Max(a,b); }; case BlendAlgorithm.overlay: return delegate (float a, float b) { if (a > 0.5f) return 1 - 2*(1-a)*(1-b); else return 2*a*b; }; case BlendAlgorithm.hardLight: return delegate (float a, float b) { if (b > 0.5f) return 1 - 2*(1-a)*(1-b); else return 2*a*b; }; case BlendAlgorithm.softLight: return delegate (float a, float b) { return (1-2*b)*a*a + 2*b*a; }; default: return delegate (float a, float b) { return b; }; } } #endregion #region Convert public void WriteTexture (Texture2D texture, CoordRect regionRect = new CoordRect()) /// Converts matrix to texture (with rescale if needed). Will crop matrix to regionRect (if specified) before convert { //rescaling if needed FloatMatrix src = this; if (texture.width != regionRect.size.x || texture.height != regionRect.size.z) src = Resized(new Coord(texture.width, texture.height), regionRect); Color[] colors = new Color[texture.width * texture.height]; for (int i=0; i<colors.Length; i++) { float val = src.arr[i]; colors[i] = new Color(val, val, val, 1); } texture.SetPixels(colors); texture.Apply(); } public byte[] ToRawBytes (CoordRect regionRect = new CoordRect()) { if (regionRect.size.x==0 && regionRect.size.z==0) regionRect = rect; Coord min = regionRect.Min; Coord max = regionRect.Max; byte[] bytes = new byte[regionRect.size.x * regionRect.size.z * 2]; int bytePos = 0; for (int z=0; z<regionRect.size.z; z++) { int matrixRowStart = (z+regionRect.offset.z-rect.offset.z)*rect.size.x + regionRect.offset.x-rect.offset.x; for (int x=0; x<regionRect.size.x; x++) { int matrixPos = matrixRowStart + x; float val = arr[matrixPos]; //this[x+regionRect.offset.x, z+regionRect.offset.z]; if (val > 1) val = 1; int intVal = (int)(val*65025); byte hb = (byte)(intVal/255f); bytes[bytePos+1] = hb; //TODO: test if the same will work on macs with non-inverted byte order bytes[bytePos] = (byte)(intVal-hb*255); bytePos+=2; } } return bytes; } public void ReadRawBytes (byte[] bytes, CoordRect regionRect = new CoordRect()) { if (regionRect.size.x==0 && regionRect.size.z==0) regionRect = rect; Coord min = regionRect.Min; Coord max = regionRect.Max; int bytePos = 0; for (int z=0; z<regionRect.size.z; z++) { int matrixRowStart = (z+regionRect.offset.z-rect.offset.z)*rect.size.x + regionRect.offset.x-rect.offset.x; for (int x=0; x<regionRect.size.x; x++) { float val = (bytes[bytePos+1]*256f + bytes[bytePos]) / 65025f; bytePos+=2; arr[matrixRowStart + x] = val; } } } #endregion #region Line Operations (operate with neighbor pixel per-line/row) public FloatMatrix Resized (CoordRect newRect, CoordRect regionRect = new CoordRect()) { FloatMatrix newMatrix = Resized(newRect.size, regionRect); newMatrix.rect.offset = newRect.offset; return newMatrix; } public FloatMatrix Resized (Coord newSize, CoordRect regionRect = new CoordRect()) /// Returns the new matrix of given dstRect size. Will read only srcRect if specified. Downscaling linear, upscaling bicubic. { FloatMatrix dst; if (regionRect.size.x == newSize.x && regionRect.size.z == newSize.z) // returning clone if both sizes match dst = CopyRegion(regionRect); else if (rect.size.z == newSize.z) //if vertical size match dst = ResizedHorizontally(newSize.x, regionRect); else if (rect.size.x == newSize.x) //if horizontal size match dst = ResizedVertically(newSize.z, regionRect); else { FloatMatrix intermediate = ResizedHorizontally(newSize.x, regionRect); dst = intermediate.ResizedVertically(newSize.z); } return dst; } public FloatMatrix ResizedHorizontally (int newWidth, CoordRect regionRect = new CoordRect()) /// Will resize matrix only horizontally. Offset will not change. { if (regionRect.size.x==0 && regionRect.size.z==0) regionRect = rect; Coord min = regionRect.Min; Coord max = regionRect.Max; FloatMatrix result = new FloatMatrix( new CoordRect(regionRect.offset.x, regionRect.offset.z, newWidth, regionRect.size.z) ); MatrixLine src = new MatrixLine(regionRect.offset.x, regionRect.size.x); MatrixLine dst = new MatrixLine(regionRect.offset.x, newWidth); for (int z=min.z; z<max.z; z++) { src.ReadLine(this, z); //srcStart.x); if (dst.length > src.length) MatrixLine.ResampleCubic(src,dst); else MatrixLine.ResampleLinear(src,dst); dst.WriteLine(result, z); } return result; } public FloatMatrix ResizedVertically (int newHeight, CoordRect regionRect = new CoordRect()) /// Will resize matrix only horizontally { if (regionRect.size.x==0 && regionRect.size.z==0) regionRect = rect; Coord min = regionRect.Min; Coord max = regionRect.Max; FloatMatrix result = new FloatMatrix( new CoordRect(regionRect.offset.x, regionRect.offset.z, regionRect.size.x, newHeight) ); MatrixLine src = new MatrixLine(regionRect.offset.z, rect.size.z); MatrixLine dst = new MatrixLine(regionRect.offset.z, newHeight); for (int x=min.x; x<max.x; x++) { src.ReadRow(this, x); if (dst.length > src.length) MatrixLine.ResampleCubic(src,dst); else MatrixLine.ResampleLinear(src,dst); dst.WriteRow(result, x); } return result; } public FloatMatrix FastDownscaled (int ratio, CoordRect regionRect = new CoordRect()) { if (regionRect.size.x==0 && regionRect.size.z==0) regionRect = rect; Coord min = regionRect.Min; Coord max = regionRect.Max; CoordRect intermediateRect = new CoordRect( regionRect.offset, new Coord(regionRect.size.x/ratio, regionRect.size.z) ); FloatMatrix intermediate = new FloatMatrix(intermediateRect); MatrixLine srcH = new MatrixLine(regionRect.offset.x, regionRect.size.x); MatrixLine dstH = new MatrixLine(regionRect.offset.x, intermediateRect.size.x); for (int z=min.z; z<max.z; z++) { srcH.ReadLine(this, z); MatrixLine.DownsampleFast(srcH,dstH,ratio); dstH.WriteLine(intermediate, z); } CoordRect downRect = new CoordRect( regionRect.offset, new Coord(regionRect.size.x/ratio, regionRect.size.z/ratio) ); FloatMatrix downMatrix = new FloatMatrix(downRect); MatrixLine srcV = new MatrixLine(regionRect.offset.z, intermediateRect.size.z); MatrixLine dstV = new MatrixLine(regionRect.offset.z, downRect.size.z); for (int x=min.x; x<min.x+intermediateRect.size.x; x++) { srcV.ReadRow(intermediate, x); MatrixLine.DownsampleFast(srcV,dstV,ratio); dstV.WriteRow(downMatrix, x); } return downMatrix; } public FloatMatrix Cavity (float intensity) { FloatMatrix dstMatrix = new FloatMatrix(rect); Coord min = rect.Min; Coord max = rect.Max; MatrixLine line = new MatrixLine(rect.offset.x, rect.size.x); for (int z=min.z; z<max.z; z++) { line.ReadLine(this,z); line.Cavity(intensity); line.WriteLine(dstMatrix, z); } line = new MatrixLine(rect.offset.z, rect.size.z); for (int x=min.x; x<max.x; x++) { line.ReadRow(this, x); line.Cavity(intensity); //apply row additively (with mid-point 0.5) line.Add(-0.5f); line.AppendRow(dstMatrix, x); } return dstMatrix; } public FloatMatrix NormalRelief (float horizontalHeight=1, float verticalHeight=1) { FloatMatrix dstMatrix = new FloatMatrix(rect); Coord min = rect.Min; Coord max = rect.Max; MatrixLine line = new MatrixLine(rect.offset.x, rect.size.x); for (int z=min.z; z<max.z; z++) { line.ReadLine(this,z); line.Normal(horizontalHeight); line.WriteLine(dstMatrix, z); } line = new MatrixLine(rect.offset.z, rect.size.z); for (int x=min.x; x<max.x; x++) { line.ReadRow(this, x); line.Normal(verticalHeight); line.AppendRow(dstMatrix, x); } dstMatrix.Multiply(0.5f); //each line has range 0-1, and they are combined additively return dstMatrix; } public FloatMatrix Delta () /// For each pixel it evaluates 4 neighbors and sets maximum value delta { FloatMatrix dstMatrix = new FloatMatrix(rect); Coord min = rect.Min; Coord max = rect.Max; MatrixLine line = new MatrixLine(rect.offset.x, rect.size.x); for (int z=min.z; z<max.z; z++) { line.ReadLine(this,z); line.Delta(); line.WriteLine(dstMatrix, z); } MatrixLine src = new MatrixLine(rect.offset.z, rect.size.z); MatrixLine dst = new MatrixLine(rect.offset.z, rect.size.z); for (int x=min.x; x<max.x; x++) { src.ReadRow(this, x); src.Delta(); dst.ReadRow(dstMatrix, x); //reading dst row to compare with horizontal delta src.Max(dst); src.WriteRow(dstMatrix, x); } return dstMatrix; } public void Spread (int iterations, float subtract=0.01f, float multiply=1f) { FloatMatrix dstMatrix = new FloatMatrix(this); Coord min = rect.Min; Coord max = rect.Max; for (int i=0; i<iterations; i++) { dstMatrix.Mix(this, 0.5f); MatrixLine line = new MatrixLine(rect.offset.x, rect.size.x); for (int z=min.z; z<max.z; z++) { line.ReadLine(dstMatrix, z); line.Spread(subtract, multiply); line.WriteLine(dstMatrix, z); } //dstMatrix.GaussianBlur(1); line = new MatrixLine(rect.offset.z, rect.size.z); for (int x=min.x; x<max.x; x++) { line.ReadRow(dstMatrix, x); line.Spread(subtract, multiply); line.WriteRow(dstMatrix, x); } //dstMatrix.GaussianBlur(1); } arr = dstMatrix.arr; } public void GaussianBlur (float blur) { //float[] arr = new float[rect.size.x]; //float[] tmp = new float[rect.size.x]; Coord min = rect.Min; Coord max = rect.Max; MatrixLine line = new MatrixLine(rect.offset.x, rect.size.x); float[] temp = new float[rect.size.x]; for (int z=min.z; z<max.z; z++) { line.ReadLine(this, z); line.GaussianBlur(temp,blur); line.WriteLine(this, z); } line = new MatrixLine(rect.offset.z, rect.size.z); temp = new float[rect.size.z]; for (int x=min.x; x<max.x; x++) { line.ReadRow(this, x); line.GaussianBlur(temp,blur); line.WriteRow(this, x); } } public void DownsampleBlur (int downsample, float blur) { int downsamplePot = (int)Mathf.Pow(2,downsample-1); Coord min = rect.Min; Coord max = rect.Max; MatrixLine hiLine = new MatrixLine(rect.offset.x, rect.size.x); MatrixLine loLine = new MatrixLine(rect.offset.x, rect.size.x / downsample); float[] tmp = new float[rect.size.x / downsample]; for (int z=min.z; z<max.z; z++) { hiLine.ReadLine(this, z); MatrixLine.ResampleLinear(hiLine, loLine); loLine.GaussianBlur(tmp, blur); MatrixLine.ResampleCubic(loLine, hiLine); hiLine.WriteLine(this, z); } hiLine = new MatrixLine(rect.offset.z, rect.size.z); loLine = new MatrixLine(rect.offset.z, rect.size.z / downsample); tmp = new float[rect.size.z / downsample]; for (int x=min.x; x<max.x; x++) { hiLine.ReadRow(this, x); MatrixLine.ResampleLinear(hiLine, loLine); loLine.GaussianBlur(tmp, blur); MatrixLine.ResampleCubic(loLine, hiLine); hiLine.WriteRow(this, x); } } public void DownsampleOverblur (int downsample, float blur=1, float fallof=2) { FloatMatrix mip = this; Clamp01(); for (int i=0; i<downsample; i++) { if (mip.rect.size.x/2 == 0) break; //already at the lowest level mip = mip.Resized( new Coord( mip.rect.size.x/2, mip.rect.size.z/2) ); //downscaling to mip matrix mip.GaussianBlur(blur); mip.Contrast(fallof); FloatMatrix blurred = mip.Resized( this.rect.size ); //float contrast = i*fallof + sharpness; for (int a=0; a<arr.Length; a++) { float valA = arr[a]; float valB = blurred.arr[a]; //apply overlay if (valA<0.5f) valA = 2*valA*valB; else valA = 1 - 2*(1-valA)*(1-valB); //clamp 0-1 preventing over-value in next iterations if (valA > 1) valA = 1; if (valB < 0) valB = 0; arr[a] = valA; } } } public void ExtendCircular (Coord center, int radius, int extendRange, int predictEvaluateRange) { //resetting area out of radius StampInverted(center.x, center.z, radius, 1, -Mathf.Epsilon); //creating radial lines int numLines = Mathf.CeilToInt( Mathf.PI * radius ); //using only the half of the needed lines float angleStep = Mathf.PI * 2 / numLines; //in radians MatrixLine line = new MatrixLine(0, Mathf.CeilToInt(extendRange + predictEvaluateRange + 1)); for (int i=0; i<numLines; i++) { float angle = i*angleStep; Vector2 direction = new Vector2( Mathf.Sin(angle), Mathf.Cos(angle) ); Vector2 start = center.vector2 + direction*(radius-predictEvaluateRange); //making any of the step components equal to 1 Vector2 posDir = new Vector2 ( (direction.x>0 ? direction.x : -direction.x), (direction.y>0 ? direction.y : -direction.y) ); float max = posDir.x>posDir.y ? posDir.x : posDir.y; Vector2 step = direction / max; int predictStart = (int)(predictEvaluateRange * max); line.ReadInclined(this, start, step); line.PredictExtend(predictStart); line.WriteInclined(this, start, step); } //filling gaps between lines line = new MatrixLine(0, (int)(radius+extendRange+1)*2*4); for (int i=(int)(radius*0.7f); i<radius+extendRange; i++) { line.ReadSquare(this, center, i); line.FillGaps(0, i*2*4); line.WriteSquare(this, center, i); } //blurring circular /*float[] tmp = new float[line.length]; Line loLine = new Line(0, line.length); for (int i=(int)radius; i<radius+extendRange; i++) { line.ReadSquare(this, cCenter, i); loLine.length = line.length / 16; //Line.DownsampleFast(line, loLine, 16); for (int j=0; j<16; j++) line.GaussianBlur(tmp, 1f); //Line.ResampleCubic(loLine, line); line.WriteSquare(this, cCenter, i); }*/ } public void SpreadBlurCircular (Coord center, float radius, int blur=2) /// Spread-blurs the circular stamp stroke at the center position (does not need to at matrix center) after the radius value { SpreadBlurCircularCorner(center, radius, blur:blur); SpreadBlurCircularCorner(center, radius, blur:blur, bottom:true); SpreadBlurCircularCorner(center, radius, blur:blur, left:true); SpreadBlurCircularCorner(center, radius, blur:blur, left:true, bottom:true); } private void SpreadBlurCircularCorner (Coord center, float radius, int blur=2, bool left=false, bool bottom=false) /// Circular spread blur iteration, it takes one corner relatively to center only { FloatMatrix src = (FloatMatrix)Clone(); //the maximum possible rect (includes center) CoordRect maxRect = rect; maxRect.Encapsulate(center); //upper left corner CoordRect cornerRect = new CoordRect (center.x, center.z, maxRect.size.x, maxRect.size.z); //creating a maximum corner rect, then intersecting it with real matrix if (left) cornerRect.offset.x -= maxRect.size.x; if (bottom) cornerRect.offset.z -= maxRect.size.z; cornerRect = CoordRect.Intersected(rect, cornerRect); if (cornerRect.size.x ==0 || cornerRect.size.z == 0) return; Coord min = cornerRect.Min; Coord max = cornerRect.Max; Vector2 gradientStart = (center.vector2 - min.vector2) / radius; //the value at which the rect's gradient start (from 0 to 1) Vector2 gradientEnd = (center.vector2 - max.vector2) / radius; if (!left) { gradientStart.x = - gradientStart.x; gradientEnd.x = - gradientEnd.x; } if (!bottom) { gradientStart.y = - gradientStart.y; gradientEnd.y = - gradientEnd.y; } MatrixLine currLine = new MatrixLine(cornerRect.offset.x, cornerRect.size.x); MatrixLine prevLine = new MatrixLine(cornerRect.offset.x, cornerRect.size.x); MatrixLine mask = new MatrixLine(cornerRect.offset.x, cornerRect.size.x); if (bottom) prevLine.ReadLine(src, min.z); else prevLine.ReadLine(src, max.z-1); for (int iz=0; iz<cornerRect.size.z; iz++) { int z = bottom ? max.z-iz-1 : min.z+iz; currLine.ReadLine(src, z); MatrixLine.SpreadBlur(ref currLine, ref prevLine, blur); float gradientPercentZ = 1f * (z-min.z) / (max.z - min.z); float gradientZ = gradientStart.y*(1-gradientPercentZ) + gradientEnd.y*gradientPercentZ; mask.Gradient((gradientStart.x + (1-gradientZ))*0.5f, (gradientEnd.x + (1-gradientZ))*0.5f); //mask.WriteLine(this, z); // to test prevLine.WriteLine(this, z, mask); //writing prev line since lines are swapped now } currLine = new MatrixLine(cornerRect.offset.z, cornerRect.size.z); prevLine = new MatrixLine(cornerRect.offset.z, cornerRect.size.z); mask = new MatrixLine(cornerRect.offset.z, cornerRect.size.z); if (left) prevLine.ReadRow(src, min.x); else prevLine.ReadRow(src, max.x-1); //for (int x=max.x-1; x>=min.x; x--) for (int ix=0; ix<cornerRect.size.x; ix++) { int x = left ? max.x-ix-1 : min.x+ix; currLine.ReadRow(src, x); MatrixLine.SpreadBlur(ref currLine, ref prevLine, blur); float gradientPercentX = 1f * (x-min.x) / (max.x - min.x); float gradientX = gradientStart.x*(1-gradientPercentX) + gradientEnd.x*gradientPercentX; mask.Gradient((gradientStart.y + (1-gradientX))*0.5f, (gradientEnd.y + (1-gradientX))*0.5f); //mask.WriteRow(this, x); // to test prevLine.AppendRow(this, x, mask); //writing prev line since lines are swapped now } } #endregion #region Native (under construction) [DllImport ("NativePlugins", EntryPoint = "MatrixResize")] public static extern void Resize (FloatMatrix src, FloatMatrix dst); [DllImport ("NativePlugins", EntryPoint = "MatrixFastDownscale")] public static extern void FastDownscale (FloatMatrix src, FloatMatrix dst, int ratio); /*public void ReadMatrix (Matrix srcMatrix, CoordRect srcRect = new CoordRect(), CoordRect.TileMode tileMode = CoordRect.TileMode.Clamp, Interpolation upscaleInterpolation = Interpolation.Bicubic, Interpolation downscaleInterpolation = Interpolation.Linear) /// Copies matrix with resize. If rect is defined then copies only the given rect. { if (srcRect.size.x == 0 && srcRect.size.z == 0 && srcRect.offset.x == 0 && srcRect.offset.z == 0) srcRect = srcMatrix.rect; Interpolation interpolation = Interpolation.None; if (rect.size == srcRect.size) interpolation = Interpolation.None; else if (rect.size.x > srcRect.size.x || rect.size.z > srcRect.size.z) interpolation = upscaleInterpolation; else interpolation = downscaleInterpolation; Coord min = rect.Min; Coord max = rect.Max; for (int x=min.x; x<max.x; x++) for (int z=min.z; z<max.z; z++) { double percentX = 1.0 * (x-min.x) / rect.size.x; double percentZ = 1.0 * (z-min.z) / rect.size.z; float srcX = (float)(percentX*srcRect.size.x) + srcRect.offset.x; float srcZ = (float)(percentZ*srcRect.size.z) + srcRect.offset.z; switch (interpolation) { case Interpolation.Linear: this[x,z] = srcMatrix.GetInterpolated(srcX, srcZ, tileMode:tileMode); break; case Interpolation.Bicubic: this[x,z] = srcMatrix.GetInterpolatedBicubic(srcX, srcZ, tileMode:tileMode); break; default: this[x,z] = srcMatrix.GetTiled((int)srcX, (int)srcZ, tileMode); break; } } }*/ #endregion #region Native Per-pixel (outdated?) public float GetInterpolated (float x, float z, CoordRect.TileMode tileMode = CoordRect.TileMode.Clamp) { //neig coords int px = (int)x; if (x<0) px--; //because (int)-2.5 gives -2, should be -3 int nx = px+1; int pz = (int)z; if (z<0) pz--; int nz = pz+1; //blending percent between pixels float percentX = x-px; float percentZ = z-pz; //reading values float val_pxpz = GetTiled(px,pz, tileMode); float val_nxpz = GetTiled(nx,pz, tileMode); float val_fz = val_pxpz*(1-percentX) + val_nxpz*percentX; float val_pxnz = GetTiled(px,nz, tileMode); float val_nxnz = GetTiled(nx,nz, tileMode); float val_cz = val_pxnz*(1-percentX) + val_nxnz*percentX; float val = val_fz*(1-percentZ) + val_cz*percentZ; return val; } public void AddInterpolated (float x, float z, float val) { //neig coords int px = (int)x; if (x<0) px--; //because (int)-2.5 gives -2, should be -3 int nx = px+1; int pz = (int)z; if (z<0) pz--; int nz = pz+1; //blending percent between pixels float percentX = x-px; float percentZ = z-pz; //writing values int pos = (pz-rect.offset.z)*rect.size.x + px - rect.offset.x; arr[pos] += val * (1-percentX) * (1-percentZ); arr[pos+1] += val * percentX * (1-percentZ); arr[pos+rect.size.x] += val * (1-percentX) * percentZ; arr[pos+rect.size.x+1] += val * percentX * percentZ; } public float GetInterpolatedBicubic (float x, float z, CoordRect.TileMode tileMode = CoordRect.TileMode.Clamp) { //neig coords - z axis int p = (int)z; if (z<0) z--; //because (int)-2.5 gives -2, should be -3 int n = p+1; int pp = p-1; int nn = n+1; //blending percent float percent = z-p; //reading values float vp = GetInterpolateCubic (x, p, tileMode); float vpp = GetInterpolateCubic (x, pp, tileMode); float vn = GetInterpolateCubic (x, n, tileMode); float vnn = GetInterpolateCubic (x, nn, tileMode); return vp + 0.5f * percent * (vn - vpp + percent*(2.0f*vpp - 5.0f*vp + 4.0f*vn - vnn + percent*(3.0f*(vp - vn) + vnn - vpp))); } public float GetInterpolateCubic (float x, int z, CoordRect.TileMode tileMode = CoordRect.TileMode.Clamp) /// Gets interpolated result using a horizontal level only { //neig coords - x axis int p = (int)x; if (x<0) p--; //because (int)-2.5 gives -2, should be -3 int n = p+1; int pp = p-1; int nn = n+1; //blending percent float percent = x-p; //reading values float vp = GetTiled(p,z,tileMode); float vpp = GetTiled(pp,z,tileMode); float vn = GetTiled(n,z,tileMode); float vnn = GetTiled(nn,z,tileMode); return vp + 0.5f * percent * (vn - vpp + percent*(2.0f*vpp - 5.0f*vp + 4.0f*vn - vnn + percent*(3.0f*(vp - vn) + vnn - vpp))); } public float GetTiled (Coord coord, CoordRect.TileMode tileMode) /// Returns the usual value if coord is in rect, handles tiling if it is not { if (rect.Contains(coord)) return this[coord]; Coord tiledCoord = rect.Tile(coord, tileMode); return this[tiledCoord]; } public float GetTiled (int x, int z, CoordRect.TileMode tileMode) { return GetTiled(new Coord(x,z), tileMode); } public void AddLine (Vector3 start, Vector3 end, float valStart, float valEnd, bool antialised=false) { float rectSizeX = Mathf.Abs(end.x-start.x); float rectSizeZ = Mathf.Abs(end.z-start.z); int length = (int)(rectSizeX>rectSizeZ ? rectSizeX : rectSizeZ) + 1; float stepX = (end.x-start.x) / length; float stepZ = (end.z-start.z) / length; if (rectSizeX > rectSizeZ) { stepZ /= Mathf.Abs(stepX); stepX = stepX>0 ? 1 : -1; } else { stepX /= Mathf.Abs(stepZ); stepZ = stepZ>0 ? 1 : -1; } for (int i=0; i<length; i++) { float x = start.x + stepX*i; float z = start.z + stepZ*i; int ix = (int)(float)x; if (x<0) ix--; int iz = (int)(float)z; if (z<0) iz--; if (ix<rect.offset.x || ix>=rect.offset.x+rect.size.x || iz<rect.offset.z || iz>=rect.offset.z+rect.size.z ) continue; int pos = (iz-rect.offset.z)*rect.size.x + ix - rect.offset.x; float percent = 1f*i/length; float val = valStart*(1-percent) + valEnd+percent; arr[pos] = val; if (antialised) { if (rectSizeX > rectSizeZ) { arr[pos-rect.size.x] = val*(1-(z-iz)); arr[pos+rect.size.x] = val*(z-iz); } else { arr[pos-1] = val*(1-(x-ix)); arr[pos+1] = val*(x-ix); } } } } #endregion } }//namespace
32.143808
205
0.620858
[ "MIT" ]
AJ213/Awitu
Assets/MapMagic/Tools/Matrix/Outdated/FloatMatrix.cs
86,951
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Управление общими сведениями о сборке осуществляется с помощью // набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения, // связанные со сборкой. [assembly: AssemblyTitle("NeuroVoting")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NeuroVoting")] [assembly: AssemblyCopyright("Copyright © 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Параметр ComVisible со значением FALSE делает типы в сборке невидимыми // для COM-компонентов. Если требуется обратиться к типу в этой сборке через // COM, задайте атрибуту ComVisible значение TRUE для этого типа. [assembly: ComVisible(false)] // Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM [assembly: Guid("cd090150-6d69-43f0-aa63-0fd9808075e5")] // Сведения о версии сборки состоят из следующих четырех значений: // // Основной номер версии // Дополнительный номер версии // Номер сборки // Редакция // // Можно задать все значения или принять номера сборки и редакции по умолчанию // используя "*", как показано ниже: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.027027
99
0.759062
[ "Apache-2.0" ]
MSPripotnev/NeuroVoting
NeuroVoting/NeuroVoting/Properties/AssemblyInfo.cs
1,967
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MovingPlatform : MonoBehaviour { // Start is called before the first frame update public List<Transform> points; public Transform platform; int goalPoint = 0; public float moveSpeed = 2; void Update() { MoveToNextPoint(); } void MoveToNextPoint() { platform.position = Vector2.MoveTowards(platform.position,points[goalPoint].position,Time.deltaTime*moveSpeed); if(Vector2.Distance(platform.position,points[goalPoint].position)<0.1f) { if (goalPoint == points.Count - 1) goalPoint = 0; else goalPoint++; } } }
23.606061
119
0.602054
[ "Apache-2.0" ]
VRSDevs/XO-Rivals
XO Rivals/Assets/Scripts/PlatformMinigame/MovingPlatform.cs
779
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("ratclient")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ratclient")] [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("cffef095-ef0a-4c4d-b050-b8c09c457e74")] // 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")]
37.459459
84
0.746753
[ "MIT" ]
apollon33/ratclient
ratclient/Properties/AssemblyInfo.cs
1,389
C#
namespace RabanSoft.SocketNetwork.Default { /// <summary> /// Simple XOR obfuscation implementation on top of <see cref="ProtocolMessage"/> /// </summary> public class EncryptedProtocolMessage : ProtocolMessage { /// <summary> /// Deobfuscates the network message before it forwarded to <see cref="ProtocolMessage"/> and protocol implementation. /// </summary> public override byte[] GetFinalized() { var data = base.GetFinalized(); // deobfuscate the data before the finalized packet is being processed MessageEncryption.Xor(data); return data; } /// <summary> /// Obfuscates the data before it is forwarded to <see cref="ProtocolMessage"/>. /// </summary> public override void SetFinalized(byte[] messageData) { // obfuscate the data before its being finalized to be sent MessageEncryption.Xor(messageData); base.SetFinalized(messageData); } } }
35.758621
126
0.620058
[ "MIT" ]
DrabanL/SocketNetwork
SocketNetwork/Default/EncryptedProtocolMessage.cs
1,039
C#
namespace dbversion.Tasks.Sql { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.IO; using System.Diagnostics; using System.Text.RegularExpressions; using dbversion.Property; using dbversion.Version; using NHibernate; public class ScriptTask : BaseTask, IEqualityComparer<ScriptTask> { /// <summary> /// The string that separates the script into batches. /// </summary> private const string BatchSeparator = "go"; /// <summary> /// The regex to use to split the script into batches. /// </summary> private const string SeparatorRegexFormat = "{0}{1}|{0}{1}{0}|{1}{0}"; /// <summary> /// The name of the command timeout property. /// </summary> public const string CommandTimeoutPropertyName = "dbversion.sql.command_timeout"; /// <summary> /// The regex object created from the regex format. /// </summary> private readonly Regex StringSplitRegex; /// <summary> /// The database version that specifies that the script should be run. /// </summary> private readonly IDatabaseVersion version; private readonly IPropertyService propertyService; protected override string GetTaskDescription() { return string.Format("Executing script \"{0}\"", this.GetScriptPath()); } /// <summary> /// The Timeout in seconds for the task /// </summary> /// <returns>The Timeout in seconds or if none set null</returns> public int? TaskTimeout { get { return this.propertyService.GetInt(CommandTimeoutPropertyName); } } public ScriptTask(string fileName, int executionOrder, IDatabaseVersion version, IMessageService messageService, IPropertyService propertyService) : base(fileName, executionOrder, messageService) { this.version = version; this.propertyService = propertyService; this.StringSplitRegex = GetStringSplitRegex(); } private static Regex GetStringSplitRegex() { return new Regex(string.Format(SeparatorRegexFormat, Environment.NewLine, BatchSeparator), RegexOptions.IgnoreCase); } protected override void ExecuteTask(ISession session) { string filePath = this.GetScriptPath(); Stream fileStream = this.version.Archive.GetFile(filePath); if (fileStream == null) { string message = string.Format("The script file \"{0}\" does not exist in the archive.", filePath); MessageService.WriteLine(message); throw new TaskExecutionException(message); } this.ExecuteScript(session, filePath, fileStream); } private string GetScriptPath() { return this.version.Archive.GetScriptPath(this.version.ManifestPath, this.FileName); } private void ExecuteScript(ISession session, string filePath, Stream fileStream) { //TODO: Shouldn't need to do this as we should already be at the beginning fileStream.Position = 0; using (StreamReader reader = new StreamReader(fileStream, Encoding.Default, true)) { IEnumerable<string> batches = GetQueryBatches(reader.ReadToEnd()); int i = 0, count = batches.Count(); foreach (string batch in batches) { i++; try { LogBatchStart(i, count); this.ExecuteQueryBatch(batch, session); LogBatchStop(i, count); } catch (Exception e) { string exceptionMessage = string.Format("Failed to execute Batch {0} of script \"{1}\". {2}", i, filePath, e.Message); MessageService.WriteExceptionLine(exceptionMessage, e); throw new TaskExecutionException(exceptionMessage, e); } } } } private IEnumerable<string> GetQueryBatches(string scriptContents) { return this.StringSplitRegex .Split(scriptContents) .Where(b => !string.IsNullOrWhiteSpace(b)) .Select(b => b.Trim()); } private void ExecuteQueryBatch(string batch, ISession session) { MessageService.WriteDebugLine(String.Format("{0}", batch)); using (var command = session.Connection.CreateCommand()) { session.Transaction.Enlist(command); if (TaskTimeout.HasValue) command.CommandTimeout = TaskTimeout.Value; command.CommandText = batch; command.ExecuteNonQuery(); } } public bool Equals(ScriptTask x, ScriptTask y) { return x.FileName.Equals(y.FileName, StringComparison.InvariantCultureIgnoreCase); } public int GetHashCode(ScriptTask obj) { return obj.FileName.GetHashCode(); } } }
34.201258
154
0.570614
[ "MIT" ]
ResDiary/dbversion
src/DatabaseVersion/Tasks/Sql/ScriptTask.cs
5,438
C#
using UnityEngine; namespace muShell.ItemSystem { [CreateAssetMenu(fileName = "New Item", menuName = "Item")] public class ItemSO : ScriptableObject { [SerializeField] private Sprite Thumbnail; [SerializeField] private string Name; [SerializeField] private int MaxStack = 1; /// <summary> /// Gets thumbnail. /// </summary> public Sprite GetThumbnail() { return this.Thumbnail; } /// <summary> /// Gets name. /// </summary> public string GetName() { return this.Name; } /// <summary> /// Gets max stack. /// </summary> public int GetMaxStack() { return this.MaxStack; } } }
21.594595
63
0.508135
[ "MIT" ]
Mohaxx-dev/muShellUnityPackage
src/ItemSystem/ItemSO.cs
801
C#
using CustomTools.Extensions.Core; namespace CustomTools { public sealed class WrappedArray<T> { T[] array = new T[ 0 ]; public WrappedArray() { } WrappedArray( T[] array ) { this.array = array; } public WrappedArray( int capacity ) { array = new T[ capacity ]; } public WrappedArray( T fillValue ) { for ( var i = 0; i < array.Length; i++ ) { array[ i ] = fillValue; } } public int Length { get { return array.Length; } } public bool IsEmpty { get { return array.Length.Equals( 0 ); } } public T this[ int index ] { get { if ( (index < 0) || (index > array.Length) ) { throw new System.ArgumentOutOfRangeException(); } return array[ index ]; } set { if ( (index < 0) || (index > array.Length) ) { throw new System.ArgumentOutOfRangeException(); } array[ index ] = value; } } public T Add( T item ) { System.Array.Resize( ref array, (array.Length + 1) ); return array[ array.Length - 1 ] = item; } public void AddRange( T[] range ) { if ( range.IsNull() ) { throw new System.NullReferenceException(); } var start = array.Length; System.Array.Resize( ref array, (array.Length + range.Length) ); for ( var i = start; i < (range.Length + start); i++ ) { array[ i ] = range[ i - start ]; } } public void Insert( int index, T item ) { if ( (index < 0) || (index > array.Length) ) { throw new System.ArgumentOutOfRangeException(); } System.Array.Resize( ref array, (array.Length + 1) ); for ( var i = (array.Length - 1); i > index; i-- ) { array[ i ] = array[ i - 1 ]; } array[ index ] = item; } public void InsertRange( int index, T[] range ) { if ( range.IsNull() ) { throw new System.NullReferenceException(); } if ( (index < 0) || (index > array.Length) ) { throw new System.ArgumentOutOfRangeException(); } System.Array.Resize( ref array, (array.Length + range.Length) ); for ( var i = (array.Length - 1); i > (index + range.Length); i-- ) { array[ i ] = array[ i - range.Length - 1 ]; } for ( var i = index; i < (range.Length + index); i++ ) { array[ i ] = range[ i - index ]; } } public void RemoveAt( int index ) { if ( (index < 0) || (index >= array.Length) ) { throw new System.ArgumentOutOfRangeException(); } for ( var i = index; i < (array.Length - 1); i++ ) { array[ i ] = array[ i + 1 ]; } if ( array.Length > 0 ) { System.Array.Resize( ref array, (array.Length - 1) ); } } public bool Remove( T item ) { var index = System.Array.IndexOf( array, item ); if ( index >= 0 ) { RemoveAt( index ); return true; } return false; } public int RemoveAll( System.Predicate<T> match ) { if ( match.IsNull() ) { throw new System.NullReferenceException(); } var result = 0; for ( var i = 0; i < array.Length; i++ ) { if ( match.Invoke( array[ i ] ) ) { RemoveAt( i ); result++; i--; } } return result; } public void Clear() { System.Array.Resize( ref array, 0 ); } public WrappedArray<T> Fill( T value ) { for ( var i = 0; i < array.Length; i++ ) { array[ i ] = value; } return this; } public WrappedArray<T> Swap( int fromIndex, int toIndex ) { if ( (fromIndex < 0) || (fromIndex >= array.Length) ) { throw new System.ArgumentOutOfRangeException(); } if ( (toIndex < 0) || (toIndex >= array.Length) ) { throw new System.ArgumentOutOfRangeException(); } var temp = array[ fromIndex ]; array[ fromIndex ] = array[ toIndex ]; array[ toIndex ] = temp; return this; } public WrappedArray<T> Sort( System.Comparison<T> comparison = null ) { if ( comparison.IsNull() ) { System.Array.Sort( array ); } else { System.Array.Sort( array, comparison ); } return this; } public WrappedArray<T> Concat( params T[][] range ) { if ( range.IsNull() ) { throw new System.NullReferenceException(); } var newSize = array.Length; for ( var i = 0; i < range.Length; i++ ) { newSize += range[ i ].Or( new T[ 0 ] ).Length; } var result = new WrappedArray<T>( newSize ); for ( var i = 0; i < array.Length; i++ ) { result.array[ i ] = array[ i ]; } var offset = array.Length; for ( var i = 0; i < range.Length; i++ ) { for ( var j = 0; j < range[ i ].Or( new T[ 0 ] ).Length; j++ ) { result.array[ offset + j ] = range[ i ][ j ]; } offset += range[ i ].Or( new T[ 0 ] ).Length; } return result; } public WrappedArray<T> Concat( params WrappedArray<T>[] range ) { if ( range.IsNull() ) { throw new System.NullReferenceException(); } var newSize = array.Length; for ( var i = 0; i < range.Length; i++ ) { newSize += range[ i ].Or( new WrappedArray<T>() ).array.Length; } var result = new WrappedArray<T>( newSize ); for ( var i = 0; i < array.Length; i++ ) { result.array[ i ] = array[ i ]; } var offset = array.Length; for ( var i = 0; i < range.Length; i++ ) { for ( var j = 0; j < range[ i ].Or( new WrappedArray<T>() ).array.Length; j++ ) { result.array[ offset + j ] = range[ i ].array[ j ]; } offset += range[ i ].Or( new WrappedArray<T>() ).array.Length; } return result; } public WrappedArray<T> Slice( int fromIndex, int count ) { if ( (fromIndex < 0) || (fromIndex >= array.Length) ) { throw new System.ArgumentOutOfRangeException( "fromIndex" ); } if ( (count <= 0) || (count > array.Length) ) { throw new System.ArgumentOutOfRangeException( "count" ); } if ( fromIndex >= count ) { throw new System.ArgumentException( "fromIndex >= count" ); } var result = new WrappedArray<T>( count - fromIndex ); for ( var i = fromIndex; i < count; i++ ) { result.array[ i - fromIndex ] = array[ i ]; } return result; } public WrappedArray<T> Slice( int fromIndex = 0 ) { return Slice( fromIndex, Length ); } public WrappedArray<T> Copy() { var result = new WrappedArray<T>( array.Length ); for ( var i = 0; i < array.Length; i++ ) { result.array[ i ] = array[ i ]; } return result; } public WrappedArray<U> ConvertAll<U>( System.Converter<T, U> converter ) { return new WrappedArray<U>( (array.Length > 0) ? System.Array.ConvertAll( array, converter ) : new U[ 0 ] ); } public bool Contains( T item ) { return System.Array.IndexOf( array, item ) >= 0; } public int IndexOf( T item ) { return System.Array.IndexOf( array, item ); } public bool Exists( System.Predicate<T> match ) { if ( match.IsNull() ) { throw new System.NullReferenceException(); } for ( var i = 0; i < array.Length; i++ ) { if ( match.Invoke( array[ i ] ) ) { return true; } } return false; } public T Find( System.Predicate<T> match ) { if ( match.IsNull() ) { throw new System.NullReferenceException(); } return System.Array.Find( array, match ); } public WrappedArray<T> FindAll( System.Predicate<T> match ) { if ( match.IsNull() ) { throw new System.NullReferenceException(); } return new WrappedArray<T>( System.Array.FindAll( array, match ) ); } public int FindIndex( System.Predicate<T> match ) { if ( match.IsNull() ) { throw new System.NullReferenceException(); } return System.Array.FindIndex( array, match ); } public T First() { if ( IsEmpty ) { if ( typeof( T ).IsClass ) { return default( T ); } throw new System.ArgumentOutOfRangeException(); } return array[ 0 ]; } public T Last() { if ( IsEmpty ) { if ( typeof( T ).IsClass ) { return default( T ); } throw new System.ArgumentOutOfRangeException(); } return array[ array.Length - 1 ]; } public T Next( T item ) { var index = System.Array.IndexOf( array, item ); if ( (index >= 0) && (index < (array.Length - 1)) ) { return array[ index + 1 ]; } if ( typeof( T ).IsClass ) { return default( T ); } throw new System.ArgumentOutOfRangeException(); } public T NextLoop( T item ) { var index = System.Array.IndexOf( array, item ); if ( index >= 0 ) { return array[ (index + 1) % array.Length ]; } if ( typeof( T ).IsClass ) { return default( T ); } throw new System.ArgumentOutOfRangeException(); } public T Previous( T item ) { var index = System.Array.IndexOf( array, item ); if ( index > 0 ) { return array[ index - 1 ]; } if ( typeof( T ).IsClass ) { return default( T ); } throw new System.ArgumentOutOfRangeException(); } public T PreviousLoop( T item ) { var index = System.Array.IndexOf( array, item ); if ( index >= 0 ) { return array[ (index - 1 + array.Length) % array.Length ]; } if ( typeof( T ).IsClass ) { return default( T ); } throw new System.ArgumentOutOfRangeException(); } public string ToString( string separator = null ) { var builder = new System.Text.StringBuilder(); for ( var i = 0; i < array.Length; i++ ) { if ( typeof( T ).IsClass && System.Collections.Generic.EqualityComparer<T>.Default.Equals( array[ i ], default( T ) ) ) { builder.Append( "null" ); } else { builder.Append( array[ i ].ToString() ); } if ( !separator.IsNullOrEmpty() && (i < (array.Length - 1)) ) { builder.Append( separator ); } } return builder.ToString(); } public void DoForAll( System.Action<T> action ) { if ( !action.IsNull() ) { for ( var i = 0; i < array.Length; i++ ) { action.Invoke( array[ i ] ); } } } } }
26.354223
125
0.576096
[ "MIT" ]
echoprotocol/echo-unity-lib
Plugins/CustomTools/WrappedArray.cs
9,674
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using System.Windows; using Microsoft.EnterpriseManagement.ConsoleFramework; using Microsoft.EnterpriseManagement; using Microsoft.EnterpriseManagement.Configuration; using Microsoft.EnterpriseManagement.Common; using Microsoft.EnterpriseManagement.UI.SdkDataAccess; using Microsoft.EnterpriseManagement.UI.DataModel; using Microsoft.EnterpriseManagement.GenericForm; using Microsoft.EnterpriseManagement.UI.SdkDataAccess.DataAdapters; namespace SMCenter.NetworkTasks { public class ConnectionsFormAction : Microsoft.EnterpriseManagement.UI.SdkDataAccess.ConsoleCommand { public override void ExecuteCommand(IList<Microsoft.EnterpriseManagement.ConsoleFramework.NavigationModelNodeBase> nodes, Microsoft.EnterpriseManagement.ConsoleFramework.NavigationModelNodeTask task, ICollection<string> parameters) { try { IDataItem dataItem = null; //There will only ever be one item because we are going to limit this task to single select foreach (NavigationModelNodeBase node in nodes) { //Check if task was started from form bool startedFromForm = FormUtilities.Instance.IsNodeWithinForm(nodes[0]); //If started from form if (startedFromForm) { dataItem = FormUtilities.Instance.GetFormDataContext(node); } //Else started from view else { dataItem = node; } } //var newWindow = new ConnectionsForm(dataItem); var newWindow = new ConnectionsForm(dataItem); newWindow.Show(); } catch (Exception ex) { System.Windows.MessageBox.Show(DateTime.Now + " : " + "ExecuteCommand Error : " + ex.Message); } } } public class MapFormAction : Microsoft.EnterpriseManagement.UI.SdkDataAccess.ConsoleCommand { public override void ExecuteCommand(IList<Microsoft.EnterpriseManagement.ConsoleFramework.NavigationModelNodeBase> nodes, Microsoft.EnterpriseManagement.ConsoleFramework.NavigationModelNodeTask task, ICollection<string> parameters) { try { IDataItem dataItem = null; //There will only ever be one item because we are going to limit this task to single select foreach (NavigationModelNodeBase node in nodes) { //Check if task was started from form bool startedFromForm = FormUtilities.Instance.IsNodeWithinForm(nodes[0]); //If started from form if (startedFromForm) { dataItem = FormUtilities.Instance.GetFormDataContext(node); } //Else started from view else { dataItem = node; } } //var newWindow = new ConnectionsForm(dataItem); var newWindow = new MapForm(dataItem); newWindow.Show(); } catch (Exception ex) { System.Windows.MessageBox.Show(DateTime.Now + " : " + "ExecuteCommand Error : " + ex.Message); } } } public class RelatedFormAction : Microsoft.EnterpriseManagement.UI.SdkDataAccess.ConsoleCommand { public override void ExecuteCommand(IList<Microsoft.EnterpriseManagement.ConsoleFramework.NavigationModelNodeBase> nodes, Microsoft.EnterpriseManagement.ConsoleFramework.NavigationModelNodeTask task, ICollection<string> parameters) { try { IDataItem dataItem = null; //There will only ever be one item because we are going to limit this task to single select foreach (NavigationModelNodeBase node in nodes) { //Check if task was started from form bool startedFromForm = FormUtilities.Instance.IsNodeWithinForm(nodes[0]); //If started from form if (startedFromForm) { dataItem = FormUtilities.Instance.GetFormDataContext(node); } //Else started from view else { dataItem = node; } } //var newWindow = new ConnectionsForm(dataItem); var newWindow = new ConnectionsForm(dataItem); newWindow.Show(); // Guid G = new Guid(SelectedTreeItem.Tag.ToString()); //EMO = emg.EntityObjects.GetObject<EnterpriseManagementObject>(G, ObjectQueryOptions.Default); ////Guid Id_NA = new Guid(); //if (EMO.IsInstanceOf(classModule)) //{ // EnterpriseManagementObjectDataType dataType = new EnterpriseManagementObjectDataType(classModule); // IDataItem itemIdentity = dataType.CreateProxyInstance(EMO); // Microsoft.EnterpriseManagement.GenericForm.FormUtilities.Instance.PopoutForm(itemIdentity); //} } catch (Exception ex) { System.Windows.MessageBox.Show(DateTime.Now + " : " + "ExecuteCommand Error : " + ex.Message); } } } }
42.262774
239
0.575302
[ "MIT" ]
Daniloveb/SMCenter.C3
SMCenter.NetworkTasks/TaskAction.cs
5,792
C#
using System; using System.Collections.Concurrent; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using System.Windows.Input; namespace Hi.Core.Command { /// <summary> /// a class of <see cref="RelayCommandAsync{TParameter}"/> /// </summary> /// <typeparam name="TParameter"></typeparam> public class RelayCommandAsync<TParameter> : ICommand { [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal bool isExecuting; [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal Action<Exception> exceptionCallback; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private ConcurrentDictionary<Func<TParameter, Task>, string> executeFuncs = new(); [DebuggerBrowsable(DebuggerBrowsableState.Never)] private Func<TParameter, bool> canExecuteFunc; /// <summary> /// /// </summary> ~RelayCommandAsync() { canExecuteFunc = null; executeFuncs.Clear(); executeFuncs = null; } /// <summary> /// create a new instance /// </summary> /// <param name="executeFunc">command body</param> /// <param name="canExecuteFunc">can execute fnction</param> /// <param name="exceptionCallback">exception callbase</param> public RelayCommandAsync(Func<TParameter, Task> executeFunc, Func<TParameter, bool> canExecuteFunc = null, Action<Exception> exceptionCallback = null) { executeFuncs[executeFunc ?? throw new ArgumentNullException(nameof(executeFunc))] = "_DEFAULT_COMMAND"; this.canExecuteFunc = canExecuteFunc; this.exceptionCallback = exceptionCallback; } /// <summary> /// Append an other command into the Command body /// </summary> /// <param name="executeFunc">an other command body</param> /// <param name="cammandName"></param> /// <returns></returns> /// <exception cref="ArgumentNullException"></exception> public RelayCommandAsync<TParameter> Append(Func<TParameter, Task> executeFunc, string cammandName = null) { executeFuncs[executeFunc ?? throw new ArgumentNullException(nameof(executeFunc))] = cammandName; return this; } public event EventHandler CanExecuteChanged; /// <summary> /// can execute of the command /// </summary> /// <param name="parameter"></param> /// <returns></returns> bool ICommand.CanExecute(object parameter) { if (parameter is TParameter target) { return CanExecute(target); } return false; } /// <summary> /// can execute of the command /// </summary> /// <param name="parameter"></param> /// <returns></returns> public bool CanExecute(TParameter parameter) { return canExecuteFunc?.Invoke(parameter) ?? true; } /// <summary> /// execute Command /// </summary> /// <param name="parameter"></param> async void ICommand.Execute(object parameter) { if (parameter is TParameter target) { await ExecuteAsync(target); } } /// <summary> /// Execute Command /// </summary> /// <param name="parameter"></param> public async Task ExecuteAsync(TParameter parameter) { lock (executeFuncs) { if (executeFuncs.Count == 0 || isExecuting) { return; } isExecuting = true; } try { if (CanExecute(parameter) == false) { return; } System.Collections.Generic.KeyValuePair<Task, string>[] tasks = executeFuncs.ToDictionary(i => i.Key.Invoke(parameter), i => i.Value).Where(i => i.Key != null).ToArray(); foreach (System.Collections.Generic.KeyValuePair<Task, string> task in tasks) { try { await task.Key; } catch (Exception e) { if (exceptionCallback is null) { throw; } exceptionCallback.Invoke(e); } } tasks = null; } finally { isExecuting = false; } } } }
31.381579
186
0.527044
[ "MIT" ]
ismyhy/Hi
src/Hi.Core/Command/RelayCommandGenericAsync.cs
4,772
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WatchDog.Changes; namespace WatchDog { public interface IWatcher { string Path { get; } Action<IChangeSet> OnChange { get; } bool Start(); bool Stop(); } }
19.058824
44
0.654321
[ "MIT" ]
ralphy15/WatchDog
WatchDog/IWatcher.cs
326
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Microsoft Azure Resource Graph Library")] [assembly: AssemblyDescription("Provides Microsoft Azure Resource Graph operations.")] [assembly: AssemblyVersion("0.10.0.0")] [assembly: AssemblyFileVersion("0.10.0.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Microsoft Azure .NET SDK")] [assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")]
38.095238
95
0.78125
[ "MIT" ]
AnanyShah/azure-sdk-for-net
src/SDKs/ResourceGraph/Management/Management.ResourceGraph/Properties/AssemblyInfo.cs
800
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30311.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace RandomSchoolAsync.Filters { public partial class EnumerationFilter { protected global::System.Web.UI.WebControls.DropDownList SFFilter_DropDownList1; } }
38.2
88
0.507853
[ "Apache-2.0" ]
jbwilliamson/MaximiseWFScaffolding
RandomSchoolAsync/RandomSchoolAsync/DynamicData/Filters/Enumeration.ascx.designer.cs
575
C#
namespace SchoolSystem.Tests.School { using Fakes; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using SchoolSystem; using System; using System.Collections.Generic; [TestClass] public class RemoveCourse_Should { [TestMethod] public void ThrowNullReferenceException_WhenPassedNullParameter() { // Arrange string validName = "Vasil Levski"; var school = new School(validName); // Act and Assert Assert.ThrowsException<NullReferenceException>(() => school.RemoveCourse(null)); } [TestMethod] public void ThrowInvalidOperationException_WhenPassedCourseDoesNotExistInSchoolCourses() { // Arrange string validName = "Vasil Levski"; var schoolFake = new SchoolFake(validName); var existingCourseStub = new Mock<ICourse>().Object; var nonexistingCourseStub = new Mock<ICourse>().Object; schoolFake.ExposedCourses = new List<ICourse> { existingCourseStub}; // Act and Assert Assert.ThrowsException<InvalidOperationException>(() => schoolFake.RemoveCourse(nonexistingCourseStub)); } [TestMethod] public void RemovePassedCourseFromCourses_WhenCourseExists() { // Arrange string validName = "Vasil Levski"; var schoolFake = new SchoolFake(validName); int expectedCoursesCount = 1; var courseOneStub = new Mock<ICourse>().Object; var courseTwoStub = new Mock<ICourse>().Object; schoolFake.ExposedCourses = new List<ICourse> { courseOneStub, courseTwoStub }; // Act schoolFake.RemoveCourse(courseOneStub); // Assert Assert.AreEqual(expectedCoursesCount, schoolFake.Courses.Count); } } }
37.039216
116
0.634198
[ "MIT" ]
vasilvalkov/CSharp-Unit-Testing
01 Unit Testing/01 Students and Courses/SchoolSystem.Tests/Models/School/RemoveCourse_Should.cs
1,891
C#
// Copyright (C) 2017 Dmitry Yakimenko (detunized@gmail.com). // Licensed under the terms of the MIT license. See LICENCE for details. using System; using System.IO; using System.Text; namespace StickyPassword { internal static class Extensions { // // string // public static byte[] ToBytes(this string s) { return Encoding.UTF8.GetBytes(s); } public static byte[] Decode64(this string s) { return Convert.FromBase64String(s); } // // byte[] // public static string ToUtf8(this byte[] x) { return Encoding.UTF8.GetString(x); } public static string Encode64(this byte[] x) { return Convert.ToBase64String(x); } // // Stream // public static byte[] ReadAll(this Stream stream, uint bufferSize = 4096) { if (bufferSize < 1) throw new ArgumentOutOfRangeException("bufferSize", "Buffer size must be positive"); var buffer = new byte[bufferSize]; using (var memoryStream = new MemoryStream()) { int bytesRead; while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0) memoryStream.Write(buffer, 0, bytesRead); return memoryStream.ToArray(); } } } }
23.516129
100
0.530178
[ "MIT" ]
detunized/stickypassword-sharp
src/Extensions.cs
1,458
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace CMS.Models { using System; using System.Collections.Generic; public partial class SinglePage { public SinglePage() { this.EnableComment = true; } public int Id { get; set; } public string Title { get; set; } public int Views { get; set; } public string Content { get; set; } public bool EnableComment { get; set; } public Nullable<bool> EnableAttachment { get; set; } public bool HasImageAttachments { get; set; } } }
31.419355
85
0.51232
[ "MIT" ]
BndyNet/CMS-Models
src/CMS.Models/SinglePage.cs
974
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Orleans.Streams; using Orleans.Runtime.Scheduler; namespace Orleans.Runtime { internal class TypeManager : SystemTarget, IClusterTypeManager, ISiloTypeManager, ISiloStatusListener { private readonly Logger logger = LogManager.GetLogger("TypeManager"); private readonly GrainTypeManager grainTypeManager; private readonly ISiloStatusOracle statusOracle; private readonly ImplicitStreamSubscriberTable implicitStreamSubscriberTable; private readonly OrleansTaskScheduler scheduler; private bool hasToRefreshClusterGrainInterfaceMap; private readonly AsyncTaskSafeTimer refreshClusterGrainInterfaceMapTimer; internal TypeManager( SiloAddress myAddr, GrainTypeManager grainTypeManager, ISiloStatusOracle oracle, OrleansTaskScheduler scheduler, TimeSpan refreshClusterMapTimeout, ImplicitStreamSubscriberTable implicitStreamSubscriberTable) : base(Constants.TypeManagerId, myAddr) { if (grainTypeManager == null) throw new ArgumentNullException(nameof(grainTypeManager)); if (oracle == null) throw new ArgumentNullException(nameof(oracle)); if (scheduler == null) throw new ArgumentNullException(nameof(scheduler)); if (implicitStreamSubscriberTable == null) throw new ArgumentNullException(nameof(implicitStreamSubscriberTable)); this.grainTypeManager = grainTypeManager; this.statusOracle = oracle; this.implicitStreamSubscriberTable = implicitStreamSubscriberTable; this.scheduler = scheduler; this.hasToRefreshClusterGrainInterfaceMap = true; this.refreshClusterGrainInterfaceMapTimer = new AsyncTaskSafeTimer( OnRefreshClusterMapTimer, null, TimeSpan.Zero, // Force to do it once right now refreshClusterMapTimeout); } public Task<IGrainTypeResolver> GetClusterTypeCodeMap() { return Task.FromResult<IGrainTypeResolver>(grainTypeManager.ClusterGrainInterfaceMap); } public Task<GrainInterfaceMap> GetSiloTypeCodeMap() { return Task.FromResult(grainTypeManager.GetTypeCodeMap()); } public Task<ImplicitStreamSubscriberTable> GetImplicitStreamSubscriberTable(SiloAddress silo) { return Task.FromResult(implicitStreamSubscriberTable); } public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status) { hasToRefreshClusterGrainInterfaceMap = true; } private async Task OnRefreshClusterMapTimer(object _) { // Check if we have to refresh if (!hasToRefreshClusterGrainInterfaceMap) { logger.Verbose3("OnRefreshClusterMapTimer: no refresh required"); return; } hasToRefreshClusterGrainInterfaceMap = false; logger.Info("OnRefreshClusterMapTimer: refresh start"); var activeSilos = statusOracle.GetApproximateSiloStatuses(onlyActive: true); var knownSilosClusterGrainInterfaceMap = grainTypeManager.GrainInterfaceMapsBySilo; // Build the new map. Always start by himself var newSilosClusterGrainInterfaceMap = new Dictionary<SiloAddress, GrainInterfaceMap> { {this.Silo, grainTypeManager.GetTypeCodeMap()} }; var getGrainInterfaceMapTasks = new List<Task<KeyValuePair<SiloAddress, GrainInterfaceMap>>>(); foreach (var siloAddress in activeSilos.Keys) { if (siloAddress.Equals(this.Silo)) continue; GrainInterfaceMap value; if (knownSilosClusterGrainInterfaceMap.TryGetValue(siloAddress, out value)) { logger.Verbose3($"OnRefreshClusterMapTimer: value already found locally for {siloAddress}"); newSilosClusterGrainInterfaceMap[siloAddress] = value; } else { // Value not found, let's get it logger.Verbose3($"OnRefreshClusterMapTimer: value not found locally for {siloAddress}"); getGrainInterfaceMapTasks.Add(GetTargetSiloGrainInterfaceMap(siloAddress)); } } if (getGrainInterfaceMapTasks.Any()) { foreach (var keyValuePair in await Task.WhenAll(getGrainInterfaceMapTasks)) { if (keyValuePair.Value != null) newSilosClusterGrainInterfaceMap.Add(keyValuePair.Key, keyValuePair.Value); } } grainTypeManager.SetInterfaceMapsBySilo(newSilosClusterGrainInterfaceMap); } private async Task<KeyValuePair<SiloAddress, GrainInterfaceMap>> GetTargetSiloGrainInterfaceMap(SiloAddress siloAddress) { try { var remoteTypeManager = InsideRuntimeClient.Current.InternalGrainFactory.GetSystemTarget<ISiloTypeManager>(Constants.TypeManagerId, siloAddress); var siloTypeCodeMap = await scheduler.QueueTask(() => remoteTypeManager.GetSiloTypeCodeMap(), SchedulingContext); return new KeyValuePair<SiloAddress, GrainInterfaceMap>(siloAddress, siloTypeCodeMap); } catch (Exception ex) { // Will be retried on the next timer hit logger.Error(ErrorCode.TypeManager_GetSiloGrainInterfaceMapError, $"Exception when trying to get GrainInterfaceMap for silos {siloAddress}", ex); hasToRefreshClusterGrainInterfaceMap = true; return new KeyValuePair<SiloAddress, GrainInterfaceMap>(siloAddress, null); } } } }
43.15493
161
0.64752
[ "MIT" ]
andmattia/orleans
src/OrleansRuntime/GrainTypeManager/TypeManager.cs
6,128
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ModelDimensionElementAttribute.cs" company="Kephas Software SRL"> // Copyright (c) Kephas Software SRL. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> // <summary> // Attribute marking dimension elements. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Kephas.Model.AttributedModel { using System; /// <summary> /// Attribute marking dimension elements. /// </summary> [AttributeUsage(AttributeTargets.Interface, AllowMultiple = false, Inherited = false)] public class ModelDimensionElementAttribute : Attribute { } }
40.272727
120
0.523702
[ "MIT" ]
kephas-software/kephas
src/Kephas.Model/AttributedModel/ModelDimensionElementAttribute.cs
888
C#
using System; using System.Linq; using EventStore.Core.Data; using EventStore.Core.Services.Storage.ReaderIndex; using EventStore.Core.Tests.TransactionLog.Scavenging.Helpers; using EventStore.Core.TransactionLog.LogRecords; using NUnit.Framework; namespace EventStore.Core.Tests.TransactionLog.Scavenging { [TestFixture] public class when_having_stream_with_both_max_age_and_max_count_with_stricter_max_age_specified : ScavengeTestScenario { protected override DbResult CreateDb(TFChunkDbCreationHelper dbCreator) { return dbCreator .Chunk( Rec.Prepare(3, "$$bla", metadata: new StreamMetadata(5, TimeSpan.FromMinutes(5), null, null, null)), Rec.Commit(3, "$$bla"), Rec.Prepare(0, "bla"), Rec.Commit(0, "bla"), Rec.Prepare(1, "bla", timestamp: DateTime.UtcNow - TimeSpan.FromMinutes(100)), Rec.Prepare(1, "bla", timestamp: DateTime.UtcNow - TimeSpan.FromMinutes(90)), Rec.Prepare(1, "bla", timestamp: DateTime.UtcNow - TimeSpan.FromMinutes(60)), Rec.Prepare(1, "bla", timestamp: DateTime.UtcNow - TimeSpan.FromMinutes(40)), Rec.Prepare(1, "bla", timestamp: DateTime.UtcNow - TimeSpan.FromMinutes(30)), Rec.Commit(1, "bla"), Rec.Prepare(2, "bla", timestamp: DateTime.UtcNow - TimeSpan.FromMinutes(20)), Rec.Prepare(2, "bla", timestamp: DateTime.UtcNow - TimeSpan.FromMinutes(3)), Rec.Prepare(2, "bla", timestamp: DateTime.UtcNow - TimeSpan.FromMinutes(2)), Rec.Prepare(2, "bla", timestamp: DateTime.UtcNow - TimeSpan.FromMinutes(1)), Rec.Commit(2, "bla")) .CompleteLastChunk() .CreateDb(); } protected override LogRecord[][] KeptRecords(DbResult dbResult) { return new[] { dbResult.Recs[0].Where((x, i) => new[] {0, 1, 11, 12, 13, 14}.Contains(i)).ToArray() }; } [Test] public void expired_prepares_are_scavenged() { CheckRecords(); } } }
39.680851
109
0.708847
[ "Apache-2.0", "CC0-1.0" ]
01100010011001010110010101110000/EventStore
src/EventStore.Core.Tests/TransactionLog/Scavenging/when_having_stream_with_both_max_age_and_max_count_with_stricted_max_age_specified.cs
1,867
C#
using System; namespace MHTimer { public class FileDataObject { public string Name { get; set; } = ""; public TimeSpan TotalTime { get; set; } public TimeSpan TimeFromLaunched { get; set; } public bool IsCountStarted { get; set; } = false; public string GetTime { get { return AppDataObject.GetFormattedStringFromTimeSpan(TotalTime); } } public void AccumulateTime() { TimeFromLaunched = TimeFromLaunched.Add(TimeSpan.FromSeconds(Settings.CountingSecondsInterval)); //指定した時間が経過していたら、データの記録を開始 if (TimeFromLaunched.TotalSeconds >= Settings.MinCountStartTime) { if (!IsCountStarted) { TotalTime = TotalTime.Add(TimeSpan.FromSeconds(Settings.MinCountStartTime)); IsCountStarted = true; } else { TotalTime = TotalTime.Add(TimeSpan.FromSeconds(Settings.CountingSecondsInterval)); } } } public override bool Equals(object obj) { if (obj == null || this.GetType() != obj.GetType()) { return false; } FileDataObject data = (FileDataObject)obj; return (data.Name == this.Name); } public override int GetHashCode() { return Name.GetHashCode(); } } }
27.571429
108
0.514896
[ "MIT" ]
kanchi0914/MillionHoursTimer
MHTImer/FileDataObject.cs
1,594
C#
namespace MassTransit.RabbitMqTransport.Configuration { using System; using System.Collections.Generic; using Configurators; using Definition; using GreenPipes; using Integration; using MassTransit.Configuration; using MassTransit.Configurators; using MassTransit.Topology; using RabbitMQ.Client.Exceptions; using Topology; using Topology.Settings; using Topology.Topologies; using Transport; using Util; public class RabbitMqHostConfiguration : BaseHostConfiguration<IRabbitMqReceiveEndpointConfiguration, IRabbitMqReceiveEndpointConfigurator>, IRabbitMqHostConfiguration { readonly IRabbitMqBusConfiguration _busConfiguration; readonly Recycle<IConnectionContextSupervisor> _connectionContext; readonly IRabbitMqHostTopology _hostTopology; RabbitMqHostSettings _hostSettings; public RabbitMqHostConfiguration(IRabbitMqBusConfiguration busConfiguration, IRabbitMqTopologyConfiguration topologyConfiguration) : base(busConfiguration) { _busConfiguration = busConfiguration; _hostSettings = new ConfigurationHostSettings { Host = "localhost", VirtualHost = "/", Port = 5672, Username = "guest", Password = "guest" }; var exchangeTypeSelector = topologyConfiguration.Publish.ExchangeTypeSelector; var messageNameFormatter = new RabbitMqMessageNameFormatter(); _hostTopology = new RabbitMqHostTopology(this, exchangeTypeSelector, messageNameFormatter, _hostSettings.HostAddress, topologyConfiguration); _connectionContext = new Recycle<IConnectionContextSupervisor>(() => new ConnectionContextSupervisor(this, topologyConfiguration)); } public IConnectionContextSupervisor ConnectionContextSupervisor => _connectionContext.Supervisor; public override Uri HostAddress => _hostSettings.HostAddress; public bool PublisherConfirmation => _hostSettings.PublisherConfirmation; public BatchSettings BatchSettings => _hostSettings.BatchSettings; IRabbitMqHostTopology IRabbitMqHostConfiguration.HostTopology => _hostTopology; public override IRetryPolicy ReceiveTransportRetryPolicy { get { return Retry.CreatePolicy(x => { x.Handle<ConnectionException>(); x.Ignore<AuthenticationFailureException>(); x.Exponential(1000, TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(3)); }); } } public override IHostTopology HostTopology => _hostTopology; public RabbitMqHostSettings Settings { get => _hostSettings; set => _hostSettings = value ?? throw new ArgumentNullException(nameof(value)); } public void ApplyEndpointDefinition(IRabbitMqReceiveEndpointConfigurator configurator, IEndpointDefinition definition) { if (definition.IsTemporary) { configurator.AutoDelete = true; configurator.Durable = false; } if (definition.PrefetchCount.HasValue) configurator.PrefetchCount = (ushort)definition.PrefetchCount.Value; if (definition.ConcurrentMessageLimit.HasValue) { var concurrentMessageLimit = definition.ConcurrentMessageLimit.Value; // if there is a prefetchCount, and it is greater than the concurrent message limit, we need a filter if (!definition.PrefetchCount.HasValue || definition.PrefetchCount.Value > concurrentMessageLimit) { configurator.UseConcurrencyLimit(concurrentMessageLimit); // we should determine a good value to use based upon the concurrent message limit if (definition.PrefetchCount.HasValue == false) { var calculatedPrefetchCount = concurrentMessageLimit * 12 / 10; configurator.PrefetchCount = (ushort)calculatedPrefetchCount; } } } definition.Configure(configurator); } public IRabbitMqReceiveEndpointConfiguration CreateReceiveEndpointConfiguration(string queueName, Action<IRabbitMqReceiveEndpointConfigurator> configure) { var settings = new RabbitMqReceiveSettings(queueName, _busConfiguration.Topology.Consume.ExchangeTypeSelector.DefaultExchangeType, true, false); var endpointConfiguration = _busConfiguration.CreateEndpointConfiguration(); return CreateReceiveEndpointConfiguration(settings, endpointConfiguration, configure); } public IRabbitMqReceiveEndpointConfiguration CreateReceiveEndpointConfiguration(RabbitMqReceiveSettings settings, IRabbitMqEndpointConfiguration endpointConfiguration, Action<IRabbitMqReceiveEndpointConfigurator> configure) { if (settings == null) throw new ArgumentNullException(nameof(settings)); if (endpointConfiguration == null) throw new ArgumentNullException(nameof(endpointConfiguration)); var configuration = new RabbitMqReceiveEndpointConfiguration(this, settings, endpointConfiguration); configure?.Invoke(configuration); Observers.EndpointConfigured(configuration); Add(configuration); return configuration; } public ISendTransportProvider CreateSendTransportProvider(IModelContextSupervisor modelContextSupervisor) { return new RabbitMqSendTransportProvider(ConnectionContextSupervisor, modelContextSupervisor); } public IPublishTransportProvider CreatePublishTransportProvider(IModelContextSupervisor modelContextSupervisor) { return new RabbitMqPublishTransportProvider(ConnectionContextSupervisor, modelContextSupervisor); } public override void ReceiveEndpoint(IEndpointDefinition definition, IEndpointNameFormatter endpointNameFormatter, Action<IRabbitMqReceiveEndpointConfigurator> configureEndpoint = null) { var queueName = definition.GetEndpointName(endpointNameFormatter ?? DefaultEndpointNameFormatter.Instance); ReceiveEndpoint(queueName, configurator => { ApplyEndpointDefinition(configurator, definition); configureEndpoint?.Invoke(configurator); }); } public override void ReceiveEndpoint(string queueName, Action<IRabbitMqReceiveEndpointConfigurator> configureEndpoint) { CreateReceiveEndpointConfiguration(queueName, configureEndpoint); } public override IEnumerable<ValidationResult> Validate() { foreach (var result in base.Validate()) yield return result; if (_hostSettings.BatchSettings.Enabled) { if (_hostSettings.BatchSettings.Timeout < TimeSpan.Zero || _hostSettings.BatchSettings.Timeout > TimeSpan.FromSeconds(1)) yield return this.Failure("BatchTimeout", "must be >= 0 and <= 1s"); if (_hostSettings.BatchSettings.MessageLimit <= 1 || _hostSettings.BatchSettings.MessageLimit > 100) yield return this.Failure("BatchMessageLimit", "must be >= 1 and <= 100"); if (_hostSettings.BatchSettings.SizeLimit < 1024 || _hostSettings.BatchSettings.MessageLimit > 256 * 1024) yield return this.Failure("BatchSizeLimit", "must be >= 1K and <= 256K"); } } public override IReceiveEndpointConfiguration CreateReceiveEndpointConfiguration(string queueName, Action<IReceiveEndpointConfigurator> configure = null) { return CreateReceiveEndpointConfiguration(queueName, configure); } public override IHost Build() { var host = new RabbitMqHost(this, _hostTopology); foreach (var endpointConfiguration in Endpoints) endpointConfiguration.Build(host); return host; } } }
41.307317
156
0.667336
[ "ECL-2.0", "Apache-2.0" ]
Aerodynamite/MassTrans
src/Transports/MassTransit.RabbitMqTransport/Configuration/Configuration/RabbitMqHostConfiguration.cs
8,468
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; namespace WebApplication1 { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); config.EnableCors(); config.Formatters.JsonFormatter.SupportedMediaTypes .Add(new MediaTypeHeaderValue("text/html")); } } }
24.625
66
0.59264
[ "MIT" ]
patilraveendra/racks
ASP.NET Files/APP_START/WebApiConfig.cs
790
C#
using Microsoft.Extensions.DependencyInjection; using System; using UnityEngine; namespace Injecter.Unity.Tests.Arrange.InjectorAwakeCalledFirst { [DefaultExecutionOrder(-999)] public sealed class AwakeCalledFirstInjector : InjectStarter { #pragma warning disable 649 [SerializeField] private AwakeLogger _logger; #pragma warning restore 649 protected override IServiceProvider CreateServiceProvider() { _logger.CallerTypes.Add(GetType()); return new ServiceCollection().AddSceneInjector().BuildServiceProvider(); } } }
27.090909
85
0.729866
[ "MIT" ]
KuraiAndras/Injecter
UnityProject/Injecter.Unity/Assets/Injecter.Unity.Tests/Arrange/InjectorAwakeCalledFirst/AwakeCalledFirstInjector.cs
598
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** 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.Aws.Ec2.Inputs { public sealed class GetKeyPairFilterArgs : Pulumi.InvokeArgs { /// <summary> /// The name of the filter field. Valid values can be found in the [EC2 DescribeKeyPairs API Reference](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeKeyPairs.html). /// </summary> [Input("name", required: true)] public string Name { get; set; } = null!; [Input("values", required: true)] private List<string>? _values; /// <summary> /// Set of values that are accepted for the given filter field. Results will be selected if any given value matches. /// </summary> public List<string> Values { get => _values ?? (_values = new List<string>()); set => _values = value; } public GetKeyPairFilterArgs() { } } }
32.210526
194
0.630719
[ "ECL-2.0", "Apache-2.0" ]
RafalSumislawski/pulumi-aws
sdk/dotnet/Ec2/Inputs/GetKeyPairFilter.cs
1,224
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; namespace SteffenTools.NodeSystem { [CustomEditor(typeof(AttackPattern))] public class AttackPatternEditor : Editor { public override void OnInspectorGUI() { base.OnInspectorGUI(); var ap = target as AttackPattern; if (GUILayout.Button("reset")) { ap.Pattern = new bool[0][]; } if (ap.Pattern.Length != ap.sizeX || ap.Pattern[0].Length != ap.sizeY) ap.Pattern = new bool[0][]; GUILayout.BeginVertical(); for (int y = 0; y < ap.sizeY; y++) { GUILayout.BeginHorizontal(); for (int x = 0; x < ap.sizeX; x++) { GUILayout.Label($"{x}, {y} - "); ap.Pattern[x][y] = EditorGUILayout.Toggle(ap.Pattern[x][y]); } GUILayout.EndHorizontal(); } GUILayout.EndVertical(); } } }
27.3
82
0.495421
[ "MIT" ]
spikar1/SteffenTools
Assets/2D_Grid/Editor/AttackPatternEditor.cs
1,094
C#
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // Ogólne informacje o zestawie są kontrolowane poprzez następujący // zestaw atrybutów. Zmień wartości tych atrybutów, aby zmodyfikować informacje // powiązane z zestawem. [assembly: AssemblyTitle("Tiels")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Tiels")] [assembly: AssemblyCopyright("Copyright © 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Ustawienie elementu ComVisible na wartość false sprawia, że typy w tym zestawie są niewidoczne // dla składników COM. Jeśli potrzebny jest dostęp do typu w tym zestawie z // COM, ustaw wartość true dla atrybutu ComVisible tego typu. [assembly: ComVisible(false)] //Aby rozpocząć kompilację aplikacji możliwych do zlokalizowania, ustaw //<UICulture>Kultura_używana_podczas_kodowania</UICulture> w pliku csproj //w grupie <PropertyGroup>. Jeśli na przykład jest używany język angielski (USA) //w plikach źródłowych ustaw dla elementu <UICulture> wartość en-US. Następnie usuń komentarz dla //poniższego atrybutu NeutralResourceLanguage. Zaktualizuj wartość „en-US” w //poniższej linii tak, aby dopasować ustawienie UICulture w pliku projektu. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //gdzie znajdują się słowniki zasobów specyficznych dla motywów //(używane, jeśli nie można odnaleźć zasobu na stronie, // lub słowniki zasobów aplikacji) ResourceDictionaryLocation.SourceAssembly //gdzie znajduje się słownik zasobów ogólnych //(używane, jeśli nie można odnaleźć zasobu na stronie, // aplikacji lub słowników zasobów specyficznych dla motywów) )] // Informacje o wersji zestawu zawierają następujące cztery wartości: // // Wersja główna // Wersja pomocnicza // Numer kompilacji // Rewizja // // Możesz określić wszystkie wartości lub użyć domyślnych numerów kompilacji i poprawki // przy użyciu symbolu „*”, tak jak pokazano poniżej: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
44.357143
107
0.729066
[ "MIT" ]
DcZipPL/DwOverlay
Tiels/Properties/AssemblyInfo.cs
2,577
C#
only a test ... <<<<<<< HEAD other line ... ======= >>>>>>> 2d756a255b010adaff4bddd0026b6e45e51d72cf
17
48
0.607843
[ "MIT" ]
jozadaquebatista/CSHARP-Overview
teste.cs
102
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using JX.Core; using JX.Core.Entity; namespace JX.EF.Repository { /// <summary> /// 数据库表:Comment 的仓储实现类. /// </summary> public partial class CommentRepository : Repository<Comment>, ICommentRepository { /// <summary> /// 构造器注入 /// </summary> public CommentRepository(ApplicationDbContext Context) : base(Context) { } } }
19.130435
81
0.709091
[ "Apache-2.0" ]
lixiong24/IPS2.1
CodeSmith/output/Repository/CommentRepository.cs
474
C#
using System; using System.Collections.Generic; using System.Text; namespace Easter.Models.Bunnies { public class HappyBunny : Bunny { private const int InitialEnergy = 100; public HappyBunny(string name) : base(name, InitialEnergy) { } } }
17.705882
46
0.621262
[ "MIT" ]
dimitar-yo-dimitrov/SoftUni-Software-Engineering
C# OOP/Exams/CSharpOOPRetakeExam-18April2021/Easter/Models/Bunnies/HappyBunny.cs
303
C#
using System.Web; namespace Movies.Services.Contracts { public interface IFileConverter { byte[] PostedToByteArray(HttpPostedFileBase postedFile); byte[] GetDefaultPicture(); } }
19
64
0.69378
[ "MIT" ]
SimeonGerginov/Movies
Movies/Movies.Services/Contracts/IFileConverter.cs
211
C#
// ---------------------------------------------------------------------------------- // Copyright daenet Gesellschaft für Informationstechnologie mbH // 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 DurableTask; using DurableTask.Core; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Daenet.DurableTaskMicroservices.Core { public class MicroserviceState { public OrchestrationState OrchestrationState { get; set; } } }
38.655172
87
0.644068
[ "MIT" ]
JTOne123/DurableTaskMicroservices
Daenet.DurableTaskMicroservices/Daenet.DurableTaskMicroservices/MicroserviceState.cs
1,124
C#
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Reflection; using Nini.Config; using OpenSim.Framework; using OpenSim.Services.Interfaces; using OpenMetaverse; using Nwc.XmlRpc; using GridRegion = OpenSim.Services.Interfaces.GridRegion; namespace OpenSim.Services.Connectors { public class LandServicesConnector : ILandService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); protected IGridService m_GridService = null; public LandServicesConnector() { } public LandServicesConnector(IGridService gridServices) { Initialise(gridServices); } public virtual void Initialise(IGridService gridServices) { m_GridService = gridServices; } public virtual LandData GetLandData(UUID scopeID, ulong regionHandle, uint x, uint y, out byte regionAccess) { LandData landData = null; IList paramList = new ArrayList(); regionAccess = 42; // Default to adult. Better safe... try { uint xpos = 0, ypos = 0; Util.RegionHandleToWorldLoc(regionHandle, out xpos, out ypos); GridRegion info = m_GridService.GetRegionByPosition(scopeID, (int)xpos, (int)ypos); if (info != null) // just to be sure { string targetHandlestr = info.RegionHandle.ToString(); if( ypos == 0 ) //HG proxy? { // this is real region handle on hg proxies hack targetHandlestr = info.RegionSecret; } Hashtable hash = new Hashtable(); hash["region_handle"] = targetHandlestr; hash["x"] = x.ToString(); hash["y"] = y.ToString(); paramList.Add(hash); XmlRpcRequest request = new XmlRpcRequest("land_data", paramList); XmlRpcResponse response = request.Send(info.ServerURI, 10000); if (response.IsFault) { m_log.ErrorFormat("[LAND CONNECTOR]: remote call returned an error: {0}", response.FaultString); } else { hash = (Hashtable)response.Value; try { landData = new LandData(); landData.AABBMax = Vector3.Parse((string)hash["AABBMax"]); landData.AABBMin = Vector3.Parse((string)hash["AABBMin"]); landData.Area = Convert.ToInt32(hash["Area"]); landData.AuctionID = Convert.ToUInt32(hash["AuctionID"]); landData.Description = (string)hash["Description"]; landData.Flags = Convert.ToUInt32(hash["Flags"]); landData.GlobalID = new UUID((string)hash["GlobalID"]); landData.Name = (string)hash["Name"]; landData.OwnerID = new UUID((string)hash["OwnerID"]); landData.SalePrice = Convert.ToInt32(hash["SalePrice"]); landData.SnapshotID = new UUID((string)hash["SnapshotID"]); landData.UserLocation = Vector3.Parse((string)hash["UserLocation"]); if (hash["RegionAccess"] != null) regionAccess = (byte)Convert.ToInt32((string)hash["RegionAccess"]); if(hash["Dwell"] != null) landData.Dwell = Convert.ToSingle((string)hash["Dwell"]); //m_log.DebugFormat("[LAND CONNECTOR]: Got land data for parcel {0}", landData.Name); } catch (Exception e) { m_log.ErrorFormat( "[LAND CONNECTOR]: Got exception while parsing land-data: {0} {1}", e.Message, e.StackTrace); } } } else m_log.WarnFormat("[LAND CONNECTOR]: Couldn't find region with handle {0}", regionHandle); } catch (Exception e) { m_log.ErrorFormat( "[LAND CONNECTOR]: Couldn't contact region {0}: {1} {2}", regionHandle, e.Message, e.StackTrace); } return landData; } } }
44.648276
120
0.561477
[ "BSD-3-Clause" ]
BillBlight/consortium
OpenSim/Services/Connectors/Land/LandServicesConnector.cs
6,474
C#
namespace Zu.TypeScript.Change { public enum NodeChangeType { InsertBefore, Change, Delete, InsertAfter } }
15.2
31
0.565789
[ "Apache-2.0" ]
MerifondNewMarkets/TypeScriptAST
TypeScriptAST/Change/NodeChangeType.cs
154
C#
using CadEditor; using System; using System.Drawing; public class Data { public OffsetRec getScreensOffset() { return new OffsetRec(0xa2f9, 1 , 80*7, 80, 7); } public bool isBuildScreenFromSmallBlocks() { return true; } public bool isBigBlockEditorEnabled() { return false; } public bool isBlockEditorEnabled() { return true; } public bool isEnemyEditorEnabled() { return false; } public OffsetRec getVideoOffset() { return new OffsetRec(0x2c010, 1, 0x1000); } public OffsetRec getPalOffset() { return new OffsetRec(0xa069, 16, 16 ); } public GetVideoPageAddrFunc getVideoPageAddrFunc() { return Utils.getChrAddress; } public GetVideoChunkFunc getVideoChunkFunc() { return Utils.getVideoChunk; } public SetVideoChunkFunc setVideoChunkFunc() { return Utils.setVideoChunk; } public OffsetRec getBlocksOffset() { return new OffsetRec(0xab89 , 1 , 0x1000); } public int getBlocksCount() { return 256; } public int getBigBlocksCount() { return 256; } public int getPalBytesAddr() { return 0xaa89; } public GetBlocksFunc getBlocksFunc() { return Utils.getBlocksFromTiles16Pal1;} public SetBlocksFunc setBlocksFunc() { return Utils.setBlocksFromTiles16Pal1;} public GetPalFunc getPalFunc() { return Utils.getPalleteLinear;} public SetPalFunc setPalFunc() { return Utils.setPalleteLinear;} }
48.5
92
0.694845
[ "MIT" ]
spiiin/CadEditor
CadEditor/settings_nes/robocop_2/Settings_RoboCop2-10.cs
1,455
C#
using System; using System.Xml.Serialization; namespace Aop.Api.Domain { /// <summary> /// AlipayOpenPublicTemplateMessageIndustryModifyModel Data Structure. /// </summary> [Serializable] public class AlipayOpenPublicTemplateMessageIndustryModifyModel : AopObject { /// <summary> /// 服务窗消息模板所属主行业一/二级编码 /// </summary> [XmlElement("primary_industry_code")] public string PrimaryIndustryCode { get; set; } /// <summary> /// 服务窗消息模板所属主行业一/二级名称(参数说明如下:) |主行业| 副行业 |代码| IT科技/互联网|电子商务 10001/20101 IT科技/IT软件与服务 10001/20102 IT科技/IT软件与设备 10001/20103 IT科技/电子技术 10001/20104 IT科技/通信与运营商 10001/20105 IT科技/网络游戏 10001/20106 金融业/银行 10002/20201 金融业/证券|基金|理财|信托 10002/20202 金融业/保险 10002/20203 餐饮/餐饮 10003/20301 酒店旅游/酒店 10004/20401 酒店旅游/旅游 10004/20401 运输与仓储/快递 10005/20501 运输与仓储/物流 10005/20501 运输与仓储/仓储 10005/20501 教育/培训 10006/20601 教育/院校 10006/20602 政府与公共事业/学术科研 10007/20701 政府与公共事业/交警 10007/20702 政府与公共事业/博物馆 10007/20703 政府与公共事业/政府公共事业非盈利机构 10007/20704 医药护理/医药医疗 10008/20801 医药护理/护理美容 10008/20802 医药护理/保健与卫生 10008/20803 交通工具/汽车相关 10009/20901 交通工具/摩托车相关 10009/20902 交通工具/火车相关 10009/20903 交通工具/飞机相关 10009/20904 房地产/房地产|建筑 10010/21001 房地产/物业 10010/21002 消费品/消费品 10011/21101 商业服务/法律 10012/21201 商业服务/广告会展 10012/21201 商业服务/中介服务 10012/21202 商业服务/检测|认证 10012/21203 商业服务/会计|审计 10012/21204 文体娱乐/文化|传媒 10013/21301 文体娱乐/体育 10013/21302 文体娱乐/娱乐休闲 10013/21303 印刷/打印|印刷 10014/21401 其它/其它 10015/21501 /// </summary> [XmlElement("primary_industry_name")] public string PrimaryIndustryName { get; set; } /// <summary> /// 服务窗消息模板所属副行业一/二级编码 /// </summary> [XmlElement("secondary_industry_code")] public string SecondaryIndustryCode { get; set; } /// <summary> /// 服务窗消息模板所属副行业一/二级名称 /// </summary> [XmlElement("secondary_industry_name")] public string SecondaryIndustryName { get; set; } } }
53.810811
999
0.686087
[ "MIT" ]
BJDIIL/DiiL
Sdk/AlipaySdk/Domain/AlipayOpenPublicTemplateMessageIndustryModifyModel.cs
2,765
C#
using PrimeWeb.Files; namespace PrimeWeb.Testing { public static class AppTester { public static void TestFinance() { var testdata = Testdata.FinanceApp; for (int i = 1206; i > 12; i-=4) { //var testID = new StructId(testdata.SubArray(i, 4)); //var testreal = new HP_Real(testdata.SubArray(i, 12)); //testreal.Parse(i); } } } }
15
59
0.618667
[ "MIT" ]
BeatSkip/PrimeDev
PrimeWeb/Testing/AppTester.cs
377
C#
using System; using System.Diagnostics.CodeAnalysis; namespace NP.ObjectComparison.Exceptions { /// <summary> /// /// </summary> [Serializable] [ExcludeFromCodeCoverage] public class ObjectComparisonException: Exception { /// <summary> /// /// </summary> public ObjectComparisonException() : base() { } /// <summary> /// /// </summary> /// <param name="message"></param> public ObjectComparisonException(string message) : base(message) { } /// <summary> /// /// </summary> /// <param name="message"></param> /// <param name="inner"></param> public ObjectComparisonException(string message, Exception inner) : base(message, inner) { } // A constructor is needed for serialization when an // exception propagates from a remoting server to the client. /// <summary> /// /// </summary> /// <param name="info"></param> /// <param name="context"></param> protected ObjectComparisonException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } } }
26.658537
94
0.669716
[ "MIT" ]
NickPolyder/NP.ObjectComparison
src/NP.ObjectComparison/Exceptions/ObjectComparisonException.cs
1,095
C#
namespace MishMashWebPREP.ViewModels.Users { using System; using System.Collections.Generic; using System.Text; public class RegisterInputViewModel { public string Username { get; set; } public string Password { get; set; } public string ConfirmPassword { get; set; } public string Email { get; set; } } }
20.388889
51
0.640327
[ "MIT" ]
bodyquest/SoftwareUniversity-Bulgaria
C# Web Jan2020/11. Examprep/2018/EXAM Prep MISH MASH - N.Kostov/Apps/MishMashWebPREP/ViewModels/Users/RegisterInputViewModel.cs
369
C#
using Newtonsoft.Json; namespace JackboxGPT3.Games.Fibbage3.Models { public struct SendEntryRequest { public SendEntryRequest(string entry) { Entry = entry; } [JsonProperty("entry")] public string Entry { get; set; } } }
18.5
45
0.570946
[ "MIT" ]
itetcetera/JackboxGPT3
src/Games/Fibbage3/Models/SendEntryRequest.cs
298
C#
using System; using System.IO; using Minsk.CodeAnalysis.Syntax; using Minsk.IO; namespace Minsk.CodeAnalysis.Symbols { internal static class SymbolPrinter { public static void WriteTo(Symbol symbol, TextWriter writer) { switch (symbol.Kind) { case SymbolKind.Function: WriteFunctionTo((FunctionSymbol)symbol, writer); break; case SymbolKind.GlobalVariable: WriteGlobalVariableTo((GlobalVariableSymbol)symbol, writer); break; case SymbolKind.LocalVariable: WriteLocalVariableTo((LocalVariableSymbol)symbol, writer); break; case SymbolKind.Parameter: WriteParameterTo((ParameterSymbol)symbol, writer); break; case SymbolKind.Type: WriteTypeTo((TypeSymbol)symbol, writer); break; default: throw new Exception($"Unexpected symbol: {symbol.Kind}"); } } private static void WriteFunctionTo(FunctionSymbol symbol, TextWriter writer) { writer.WriteKeyword(SyntaxKind.FunctionKeyword); writer.WriteSpace(); writer.WriteIdentifier(symbol.Name); writer.WritePunctuation(SyntaxKind.OpenParenthesisToken); for (int i = 0; i < symbol.Parameters.Length; i++) { if (i > 0) { writer.WritePunctuation(SyntaxKind.CommaToken); writer.WriteSpace(); } symbol.Parameters[i].WriteTo(writer); } writer.WritePunctuation(SyntaxKind.CloseParenthesisToken); if (symbol.Type != TypeSymbol.Void) { writer.WritePunctuation(SyntaxKind.ColonToken); writer.WriteSpace(); symbol.Type.WriteTo(writer); } } private static void WriteGlobalVariableTo(GlobalVariableSymbol symbol, TextWriter writer) { writer.WriteKeyword(symbol.IsReadOnly ? SyntaxKind.LetKeyword : SyntaxKind.VarKeyword); writer.WriteSpace(); writer.WriteIdentifier(symbol.Name); writer.WritePunctuation(SyntaxKind.ColonToken); writer.WriteSpace(); symbol.Type.WriteTo(writer); } private static void WriteLocalVariableTo(LocalVariableSymbol symbol, TextWriter writer) { writer.WriteKeyword(symbol.IsReadOnly ? SyntaxKind.LetKeyword : SyntaxKind.VarKeyword); writer.WriteSpace(); writer.WriteIdentifier(symbol.Name); writer.WritePunctuation(SyntaxKind.ColonToken); writer.WriteSpace(); symbol.Type.WriteTo(writer); } private static void WriteParameterTo(ParameterSymbol symbol, TextWriter writer) { writer.WriteIdentifier(symbol.Name); writer.WritePunctuation(SyntaxKind.ColonToken); writer.WriteSpace(); symbol.Type.WriteTo(writer); } private static void WriteTypeTo(TypeSymbol symbol, TextWriter writer) { writer.WriteIdentifier(symbol.Name); } } }
35.6
99
0.573329
[ "MIT" ]
CBenghi/minsk
src/Minsk/CodeAnalysis/Symbols/SymbolPrinter.cs
3,382
C#
#pragma checksum "D:\Windows10493\IoTCoreDefaultApp\CS\IoTCoreDefaultApp\Views\MainPage.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "8BA55DD5DA53DE27FA4039FB6D25E776" //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace IoTCoreDefaultApp { partial class MainPage : global::Windows.UI.Xaml.Controls.Page, global::Windows.UI.Xaml.Markup.IComponentConnector, global::Windows.UI.Xaml.Markup.IComponentConnector2 { /// <summary> /// Connect() /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public void Connect(int connectionId, object target) { switch(connectionId) { case 1: { this.rootPage = (global::Windows.UI.Xaml.Controls.Page)(target); } break; case 2: { this.NetworkInfoPanelTemplate = (global::Windows.UI.Xaml.Controls.ItemsPanelTemplate)(target); } break; case 3: { this.NetworkInfoDataTemplate = (global::Windows.UI.Xaml.DataTemplate)(target); } break; case 4: { this.mainGrid = (global::Windows.UI.Xaml.Controls.Grid)(target); } break; case 5: { this.player = (global::Windows.UI.Xaml.Controls.Grid)(target); } break; case 6: { this.MessageGrid = (global::Windows.UI.Xaml.Controls.Grid)(target); } break; case 7: { this.HeaderRow = (global::Windows.UI.Xaml.Controls.Grid)(target); } break; case 8: { this.SecurityNoticeRow = (global::Windows.UI.Xaml.Controls.Grid)(target); } break; case 9: { this.ContentRow = (global::Windows.UI.Xaml.Controls.ScrollViewer)(target); } break; case 10: { this.BoardName = (global::Windows.UI.Xaml.Controls.TextBlock)(target); } break; case 11: { this.AppxVersion = (global::Windows.UI.Xaml.Controls.TextBlock)(target); } break; case 12: { this.ConnectedDevices = (global::Windows.UI.Xaml.Controls.ItemsControl)(target); } break; case 13: { this.DeviceName = (global::Windows.UI.Xaml.Controls.TextBox)(target); #line 202 "..\..\..\Views\MainPage.xaml" ((global::Windows.UI.Xaml.Controls.TextBox)this.DeviceName).FocusEngaged += this.DeviceName_FocusEngaged; #line default } break; case 14: { this.NetworkNameCaption = (global::Windows.UI.Xaml.Controls.TextBlock)(target); } break; case 15: { this.NetworkName1 = (global::Windows.UI.Xaml.Controls.TextBlock)(target); } break; case 16: { this.IPAddressCaption = (global::Windows.UI.Xaml.Controls.TextBlock)(target); } break; case 17: { this.IPAddress1 = (global::Windows.UI.Xaml.Controls.TextBlock)(target); } break; case 18: { this.OSVersionCaption = (global::Windows.UI.Xaml.Controls.TextBlock)(target); } break; case 19: { this.OSVersion = (global::Windows.UI.Xaml.Controls.TextBlock)(target); } break; case 20: { this.NetworkInfo = (global::Windows.UI.Xaml.Controls.ListView)(target); } break; case 21: { this.WebAddress = (global::Windows.UI.Xaml.Controls.TextBox)(target); } break; case 22: { this.WebAddressButton = (global::Windows.UI.Xaml.Controls.Button)(target); #line 164 "..\..\..\Views\MainPage.xaml" ((global::Windows.UI.Xaml.Controls.Button)this.WebAddressButton).Click += this.Button_Click; #line default } break; case 23: { this.BoardImage = (global::Windows.UI.Xaml.Controls.Image)(target); } break; case 24: { this.SecurityNoticeLearnMoreButton = (global::Windows.UI.Xaml.Controls.Button)(target); #line 125 "..\..\..\Views\MainPage.xaml" ((global::Windows.UI.Xaml.Controls.Button)this.SecurityNoticeLearnMoreButton).Click += this.SecurityNoticeLearnMoreButton_Click; #line default } break; case 25: { this.CloseNoticeButton = (global::Windows.UI.Xaml.Controls.Button)(target); #line 126 "..\..\..\Views\MainPage.xaml" ((global::Windows.UI.Xaml.Controls.Button)this.CloseNoticeButton).Click += this.CloseNoticeButton_Click; #line default } break; case 26: { this.TopBar = (global::IoTCoreDefaultApp.TopBarUC)(target); } break; case 27: { this.MessageBox = (global::Windows.UI.Xaml.Controls.TextBlock)(target); } break; case 28: { this.defaultImage = (global::Windows.UI.Xaml.Controls.Image)(target); } break; case 29: { this.imageViewer = (global::Windows.UI.Xaml.Controls.Image)(target); } break; case 30: { this.videoPlayer = (global::Windows.UI.Xaml.Controls.MediaElement)(target); } break; case 31: { this.webBrowser = (global::Windows.UI.Xaml.Controls.WebView)(target); } break; default: break; } this._contentLoaded = true; } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public global::Windows.UI.Xaml.Markup.IComponentConnector GetBindingConnector(int connectionId, object target) { global::Windows.UI.Xaml.Markup.IComponentConnector returnValue = null; return returnValue; } } }
37.809524
170
0.453904
[ "MIT" ]
WiproDS2018/DS_FR
Code/DigitalSignage_v1.0/Device Code/UWP Code/IoTCoreDefaultApp/obj/ARM/Release/Views/MainPage.g.cs
7,942
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 kms-2014-11-01.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.KeyManagementService.Model { /// <summary> /// The request was rejected because of the <code>ConnectionState</code> of the custom /// key store. To get the <code>ConnectionState</code> of a custom key store, use the /// <a>DescribeCustomKeyStores</a> operation. /// /// /// <para> /// This exception is thrown under the following conditions: /// </para> /// <ul> <li> /// <para> /// You requested the <a>CreateKey</a> or <a>GenerateRandom</a> operation in a custom /// key store that is not connected. These operations are valid only when the custom key /// store <code>ConnectionState</code> is <code>CONNECTED</code>. /// </para> /// </li> <li> /// <para> /// You requested the <a>UpdateCustomKeyStore</a> or <a>DeleteCustomKeyStore</a> operation /// on a custom key store that is not disconnected. This operation is valid only when /// the custom key store <code>ConnectionState</code> is <code>DISCONNECTED</code>. /// </para> /// </li> <li> /// <para> /// You requested the <a>ConnectCustomKeyStore</a> operation on a custom key store with /// a <code>ConnectionState</code> of <code>DISCONNECTING</code> or <code>FAILED</code>. /// This operation is valid for all other <code>ConnectionState</code> values. /// </para> /// </li> </ul> /// </summary> #if !NETSTANDARD [Serializable] #endif public partial class CustomKeyStoreInvalidStateException : AmazonKeyManagementServiceException { /// <summary> /// Constructs a new CustomKeyStoreInvalidStateException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public CustomKeyStoreInvalidStateException(string message) : base(message) {} /// <summary> /// Construct instance of CustomKeyStoreInvalidStateException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public CustomKeyStoreInvalidStateException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of CustomKeyStoreInvalidStateException /// </summary> /// <param name="innerException"></param> public CustomKeyStoreInvalidStateException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of CustomKeyStoreInvalidStateException /// </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 CustomKeyStoreInvalidStateException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of CustomKeyStoreInvalidStateException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public CustomKeyStoreInvalidStateException(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 CustomKeyStoreInvalidStateException 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 CustomKeyStoreInvalidStateException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } /// <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); } #endif } }
48.306667
178
0.677201
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/KeyManagementService/Generated/Model/CustomKeyStoreInvalidStateException.cs
7,246
C#
#region License // Distributed under the MIT License // ============================================================ // Copyright (c) 2016 Hotcakes Commerce, LLC // // 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 using System; using System.Collections.Generic; namespace Hotcakes.Shipping.USPostal.v4 { [Serializable] public class DomesticRequest { public DomesticRequest() { ApiUrl = USPostalConstants.ApiUrl; UserId = USPostalConstants.ApiUsername; Revision = "2"; Packages = new List<DomesticPackage>(); } public string ApiUrl { get; set; } public string UserId { get; set; } public string Revision { get; set; } public List<DomesticPackage> Packages { get; set; } } }
39.212766
101
0.683125
[ "MIT" ]
ketangarala/core
Libraries/Hotcakes.Shipping.USPostal/v4/DomesticRequest.cs
1,845
C#
using Entatea.Annotations; namespace Entatea.Tests.Entities { [Table("CitiesManual")] public class CityManual { [KeyType(KeyType.Assigned)] [Required] public string CityCode { get; set; } [Column("Name")] [Required] public string CityName { get; set; } } }
19.058824
44
0.58642
[ "MIT" ]
MalcolmJohnston/Entatea
Entatea/Entatea.Tests/Entities/CityManual.cs
326
C#
namespace Shibusa.Maths { public static partial class Calculate { /// <summary> /// Determines the number of permutations of a certain size within a certain set.. /// </summary> /// <param name="sizeOfSet">The size of the set.</param> /// <param name="sizeOfPermutations">The size of each permutation.</param> /// <returns>The number of permutations.</returns> public static ulong NumberOfPermutations(int sizeOfSet, int sizeOfPermutations) => Factorial(sizeOfSet) / Factorial(sizeOfSet - sizeOfPermutations); } }
39.6
90
0.651515
[ "MIT" ]
shibusavic/Shibusa.Common
Shibusa.Maths/Permutations.cs
594
C#
// ------------------------------------------------------- // Copyright (C) 施维串 版权所有。 // 创建标识:2013-11-11 10:53:36 Created by 施维串 // 功能说明: // 注意事项: // // 更新记录: // ------------------------------------------------------- using System; using System.IO; using System.Data; using System.Xml; using System.Data.Odbc; using System.Collections; namespace shiwch.util { /// <summary> /// The OdbcHelper class is intended to encapsulate high performance, scalable best practices for /// common uses of OdbcClient. /// </summary> public static class OdbcHelper { #region private utility methods /// <summary> /// This method is used to attach array of OdbcParameters to a OdbcCommand. /// /// This method will assign a value of DbNull to any parameter with a direction of /// InputOutput and a value of null. /// /// This behavior will prevent default values from being used, but /// this will be the less common case than an intended pure output parameter (derived as InputOutput) /// where the user provided no input value. /// </summary> /// <param name="command">The command to which the parameters will be added</param> /// <param name="commandParameters">an array of OdbcParameters tho be added to command</param> private static void AttachParameters(OdbcCommand command, OdbcParameter[] commandParameters) { foreach (OdbcParameter p in commandParameters) { //check for derived output value with no value assigned if ((p.Direction == ParameterDirection.InputOutput) && (p.Value == null)) { p.Value = DBNull.Value; } command.Parameters.Add(p); } } /// <summary> /// This method assigns an array of values to an array of OdbcParameters. /// </summary> /// <param name="commandParameters">array of OdbcParameters to be assigned values</param> /// <param name="parameterValues">array of objects holding the values to be assigned</param> private static void AssignParameterValues(OdbcParameter[] commandParameters, object[] parameterValues) { if ((commandParameters == null) || (parameterValues == null)) { //do nothing if we get no data return; } // we must have the same number of values as we pave parameters to put them in if (commandParameters.Length != parameterValues.Length) { throw new ArgumentException("Parameter count does not match Parameter Value count."); } //iterate through the OdbcParameters, assigning the values from the corresponding position in the //value array for (int i = 0, j = commandParameters.Length; i < j; i++) { commandParameters[i].Value = parameterValues[i]; } } /// <summary> /// This method opens (if necessary) and assigns a connection, transaction, command type and parameters /// to the provided command. /// </summary> /// <param name="command">the OdbcCommand to be prepared</param> /// <param name="connection">a valid OdbcConnection, on which to execute this command</param> /// <param name="transaction">a valid OdbcTransaction, or 'null'</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <param name="commandParameters">an array of OdbcParameters to be associated with the command or 'null' if no parameters are required</param> private static void PrepareCommand(OdbcCommand command, OdbcConnection connection, OdbcTransaction transaction, CommandType commandType, string commandText, OdbcParameter[] commandParameters) { //if the provided connection is not open, we will open it if (connection.State != ConnectionState.Open) { connection.Open(); } //associate the connection with the command command.Connection = connection; //set the command text (stored procedure name or SQL statement) command.CommandText = commandText; //if we were provided a transaction, assign it. if (transaction != null) { command.Transaction = transaction; } //set the command type command.CommandType = commandType; //attach the command parameters if they are provided if (commandParameters != null) { AttachParameters(command, commandParameters); } return; } #endregion private utility methods & constructors #region ExecuteNonQuery /// <summary> /// Execute a OdbcCommand (that returns no resultset and takes no parameters) against the database specified in /// the connection string. /// </summary> /// <remarks> /// e.g.: /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders"); /// </remarks> /// <param name="connectionString">a valid connection string for a OdbcConnection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <returns>an int representing the number of rows affected by the command</returns> public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText) { //pass through the call providing null for the set of OdbcParameters return ExecuteNonQuery(connectionString, commandType, commandText, (OdbcParameter[])null); } /// <summary> /// Execute a OdbcCommand (that returns no resultset) against the database specified in the connection string /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new OdbcParameter("@prodid", 24)); /// </remarks> /// <param name="connectionString">a valid connection string for a OdbcConnection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <param name="commandParameters">an array of OdbcParamters used to execute the command</param> /// <returns>an int representing the number of rows affected by the command</returns> public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText, params OdbcParameter[] commandParameters) { //create & open a OdbcConnection, and dispose of it after we are done. using (OdbcConnection cn = new OdbcConnection(connectionString)) { cn.Open(); //call the overload that takes a connection in place of the connection string return ExecuteNonQuery(cn, commandType, commandText, commandParameters); } } /// <summary> /// Execute a stored procedure via a OdbcCommand (that returns no resultset) against the database specified in /// the connection string using the provided parameter values. This method will query the database to discover the parameters for the /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order. /// </summary> /// <remarks> /// This method provides no access to output parameters or the stored procedure's return value parameter. /// /// e.g.: /// int result = ExecuteNonQuery(connString, "PublishOrders", 24, 36); /// </remarks> /// <param name="connectionString">a valid connection string for a OdbcConnection</param> /// <param name="spName">the name of the stored prcedure</param> /// <param name="parameterValues">an array of objects to be assigned as the input values of the stored procedure</param> /// <returns>an int representing the number of rows affected by the command</returns> public static int ExecuteNonQuery(string connectionString, string spName, params object[] parameterValues) { //if we receive parameter values, we need to figure out where they go if ((parameterValues != null) && (parameterValues.Length > 0)) { //pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache) OdbcParameter[] commandParameters = OdbcHelperParameterCache.GetSpParameterSet(connectionString, spName); //assign the provided values to these parameters based on parameter order AssignParameterValues(commandParameters, parameterValues); //call the overload that takes an array of OdbcParameters return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName, commandParameters); } //otherwise we can just call the SP without params else { return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName); } } /// <summary> /// Execute a OdbcCommand (that returns no resultset and takes no parameters) against the provided OdbcConnection. /// </summary> /// <remarks> /// e.g.: /// int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders"); /// </remarks> /// <param name="connection">a valid OdbcConnection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <returns>an int representing the number of rows affected by the command</returns> public static int ExecuteNonQuery(OdbcConnection connection, CommandType commandType, string commandText) { //pass through the call providing null for the set of OdbcParameters return ExecuteNonQuery(connection, commandType, commandText, (OdbcParameter[])null); } /// <summary> /// Execute a OdbcCommand (that returns no resultset) against the specified OdbcConnection /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders", new OdbcParameter("@prodid", 24)); /// </remarks> /// <param name="connection">a valid OdbcConnection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <param name="commandParameters">an array of OdbcParamters used to execute the command</param> /// <returns>an int representing the number of rows affected by the command</returns> public static int ExecuteNonQuery(OdbcConnection connection, CommandType commandType, string commandText, params OdbcParameter[] commandParameters) { //create a command and prepare it for execution OdbcCommand cmd = new OdbcCommand(); PrepareCommand(cmd, connection, (OdbcTransaction)null, commandType, commandText, commandParameters); //finally, execute the command. int retval = cmd.ExecuteNonQuery(); // detach the OdbcParameters from the command object, so they can be used again. cmd.Parameters.Clear(); return retval; } /// <summary> /// Execute a stored procedure via a OdbcCommand (that returns no resultset) against the specified OdbcConnection /// using the provided parameter values. This method will query the database to discover the parameters for the /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order. /// </summary> /// <remarks> /// This method provides no access to output parameters or the stored procedure's return value parameter. /// /// e.g.: /// int result = ExecuteNonQuery(conn, "PublishOrders", 24, 36); /// </remarks> /// <param name="connection">a valid OdbcConnection</param> /// <param name="spName">the name of the stored procedure</param> /// <param name="parameterValues">an array of objects to be assigned as the input values of the stored procedure</param> /// <returns>an int representing the number of rows affected by the command</returns> public static int ExecuteNonQuery(OdbcConnection connection, string spName, params object[] parameterValues) { //if we receive parameter values, we need to figure out where they go if ((parameterValues != null) && (parameterValues.Length > 0)) { //pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache) OdbcParameter[] commandParameters = OdbcHelperParameterCache.GetSpParameterSet(connection.ConnectionString, spName); //assign the provided values to these parameters based on parameter order AssignParameterValues(commandParameters, parameterValues); //call the overload that takes an array of OdbcParameters return ExecuteNonQuery(connection, CommandType.StoredProcedure, spName, commandParameters); } //otherwise we can just call the SP without params else { return ExecuteNonQuery(connection, CommandType.StoredProcedure, spName); } } /// <summary> /// Execute a OdbcCommand (that returns no resultset and takes no parameters) against the provided OdbcTransaction. /// </summary> /// <remarks> /// e.g.: /// int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "PublishOrders"); /// </remarks> /// <param name="transaction">a valid OdbcTransaction</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <returns>an int representing the number of rows affected by the command</returns> public static int ExecuteNonQuery(OdbcTransaction transaction, CommandType commandType, string commandText) { //pass through the call providing null for the set of OdbcParameters return ExecuteNonQuery(transaction, commandType, commandText, (OdbcParameter[])null); } /// <summary> /// Execute a OdbcCommand (that returns no resultset) against the specified OdbcTransaction /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "GetOrders", new OdbcParameter("@prodid", 24)); /// </remarks> /// <param name="transaction">a valid OdbcTransaction</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <param name="commandParameters">an array of OdbcParamters used to execute the command</param> /// <returns>an int representing the number of rows affected by the command</returns> public static int ExecuteNonQuery(OdbcTransaction transaction, CommandType commandType, string commandText, params OdbcParameter[] commandParameters) { //create a command and prepare it for execution OdbcCommand cmd = new OdbcCommand(); PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters); //finally, execute the command. int retval = cmd.ExecuteNonQuery(); // detach the OdbcParameters from the command object, so they can be used again. cmd.Parameters.Clear(); return retval; } /// <summary> /// Execute a stored procedure via a OdbcCommand (that returns no resultset) against the specified /// OdbcTransaction using the provided parameter values. This method will query the database to discover the parameters for the /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order. /// </summary> /// <remarks> /// This method provides no access to output parameters or the stored procedure's return value parameter. /// /// e.g.: /// int result = ExecuteNonQuery(conn, trans, "PublishOrders", 24, 36); /// </remarks> /// <param name="transaction">a valid OdbcTransaction</param> /// <param name="spName">the name of the stored procedure</param> /// <param name="parameterValues">an array of objects to be assigned as the input values of the stored procedure</param> /// <returns>an int representing the number of rows affected by the command</returns> public static int ExecuteNonQuery(OdbcTransaction transaction, string spName, params object[] parameterValues) { //if we receive parameter values, we need to figure out where they go if ((parameterValues != null) && (parameterValues.Length > 0)) { //pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache) OdbcParameter[] commandParameters = OdbcHelperParameterCache.GetSpParameterSet(transaction.Connection.ConnectionString, spName); //assign the provided values to these parameters based on parameter order AssignParameterValues(commandParameters, parameterValues); //call the overload that takes an array of OdbcParameters return ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName, commandParameters); } //otherwise we can just call the SP without params else { return ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName); } } #endregion ExecuteNonQuery #region ExecuteDataSet /// <summary> /// Execute a OdbcCommand (that returns a resultset and takes no parameters) against the database specified in /// the connection string. /// </summary> /// <remarks> /// e.g.: /// DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders"); /// </remarks> /// <param name="connectionString">a valid connection string for a OdbcConnection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <returns>a dataset containing the resultset generated by the command</returns> public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText) { //pass through the call providing null for the set of OdbcParameters return ExecuteDataset(connectionString, commandType, commandText, (OdbcParameter[])null); } /// <summary> /// Execute a OdbcCommand (that returns a resultset) against the database specified in the connection string /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders", new OdbcParameter("@prodid", 24)); /// </remarks> /// <param name="connectionString">a valid connection string for a OdbcConnection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <param name="commandParameters">an array of OdbcParamters used to execute the command</param> /// <returns>a dataset containing the resultset generated by the command</returns> public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText, params OdbcParameter[] commandParameters) { //create & open a OdbcConnection, and dispose of it after we are done. using (OdbcConnection cn = new OdbcConnection(connectionString)) { cn.Open(); //call the overload that takes a connection in place of the connection string return ExecuteDataset(cn, commandType, commandText, commandParameters); } } /// <summary> /// Execute a stored procedure via a OdbcCommand (that returns a resultset) against the database specified in /// the connection string using the provided parameter values. This method will query the database to discover the parameters for the /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order. /// </summary> /// <remarks> /// This method provides no access to output parameters or the stored procedure's return value parameter. /// /// e.g.: /// DataSet ds = ExecuteDataset(connString, "GetOrders", 24, 36); /// </remarks> /// <param name="connectionString">a valid connection string for a OdbcConnection</param> /// <param name="spName">the name of the stored procedure</param> /// <param name="parameterValues">an array of objects to be assigned as the input values of the stored procedure</param> /// <returns>a dataset containing the resultset generated by the command</returns> public static DataSet ExecuteDataset(string connectionString, string spName, params object[] parameterValues) { //if we receive parameter values, we need to figure out where they go if ((parameterValues != null) && (parameterValues.Length > 0)) { //pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache) OdbcParameter[] commandParameters = OdbcHelperParameterCache.GetSpParameterSet(connectionString, spName); //assign the provided values to these parameters based on parameter order AssignParameterValues(commandParameters, parameterValues); //call the overload that takes an array of OdbcParameters return ExecuteDataset(connectionString, CommandType.StoredProcedure, spName, commandParameters); } //otherwise we can just call the SP without params else { return ExecuteDataset(connectionString, CommandType.StoredProcedure, spName); } } /// <summary> /// Execute a OdbcCommand (that returns a resultset and takes no parameters) against the provided OdbcConnection. /// </summary> /// <remarks> /// e.g.: /// DataSet ds = ExecuteDataset(conn, CommandType.StoredProcedure, "GetOrders"); /// </remarks> /// <param name="connection">a valid OdbcConnection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <returns>a dataset containing the resultset generated by the command</returns> public static DataSet ExecuteDataset(OdbcConnection connection, CommandType commandType, string commandText) { //pass through the call providing null for the set of OdbcParameters return ExecuteDataset(connection, commandType, commandText, (OdbcParameter[])null); } /// <summary> /// Execute a OdbcCommand (that returns a resultset) against the specified OdbcConnection /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// DataSet ds = ExecuteDataset(conn, CommandType.StoredProcedure, "GetOrders", new OdbcParameter("@prodid", 24)); /// </remarks> /// <param name="connection">a valid OdbcConnection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <param name="commandParameters">an array of OdbcParamters used to execute the command</param> /// <returns>a dataset containing the resultset generated by the command</returns> public static DataSet ExecuteDataset(OdbcConnection connection, CommandType commandType, string commandText, params OdbcParameter[] commandParameters) { //create a command and prepare it for execution OdbcCommand cmd = new OdbcCommand(); PrepareCommand(cmd, connection, (OdbcTransaction)null, commandType, commandText, commandParameters); //create the DataAdapter & DataSet OdbcDataAdapter da = new OdbcDataAdapter(cmd); DataSet ds = new DataSet(); //fill the DataSet using default values for DataTable names, etc. da.Fill(ds); // detach the OdbcParameters from the command object, so they can be used again. cmd.Parameters.Clear(); //return the dataset return ds; } /// <summary> /// Execute a stored procedure via a OdbcCommand (that returns a resultset) against the specified OdbcConnection /// using the provided parameter values. This method will query the database to discover the parameters for the /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order. /// </summary> /// <remarks> /// This method provides no access to output parameters or the stored procedure's return value parameter. /// /// e.g.: /// DataSet ds = ExecuteDataset(conn, "GetOrders", 24, 36); /// </remarks> /// <param name="connection">a valid OdbcConnection</param> /// <param name="spName">the name of the stored procedure</param> /// <param name="parameterValues">an array of objects to be assigned as the input values of the stored procedure</param> /// <returns>a dataset containing the resultset generated by the command</returns> public static DataSet ExecuteDataset(OdbcConnection connection, string spName, params object[] parameterValues) { //if we receive parameter values, we need to figure out where they go if ((parameterValues != null) && (parameterValues.Length > 0)) { //pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache) OdbcParameter[] commandParameters = OdbcHelperParameterCache.GetSpParameterSet(connection.ConnectionString, spName); //assign the provided values to these parameters based on parameter order AssignParameterValues(commandParameters, parameterValues); //call the overload that takes an array of OdbcParameters return ExecuteDataset(connection, CommandType.StoredProcedure, spName, commandParameters); } //otherwise we can just call the SP without params else { return ExecuteDataset(connection, CommandType.StoredProcedure, spName); } } /// <summary> /// Execute a OdbcCommand (that returns a resultset and takes no parameters) against the provided OdbcTransaction. /// </summary> /// <remarks> /// e.g.: /// DataSet ds = ExecuteDataset(trans, CommandType.StoredProcedure, "GetOrders"); /// </remarks> /// <param name="transaction">a valid OdbcTransaction</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <returns>a dataset containing the resultset generated by the command</returns> public static DataSet ExecuteDataset(OdbcTransaction transaction, CommandType commandType, string commandText) { //pass through the call providing null for the set of OdbcParameters return ExecuteDataset(transaction, commandType, commandText, (OdbcParameter[])null); } /// <summary> /// Execute a OdbcCommand (that returns a resultset) against the specified OdbcTransaction /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// DataSet ds = ExecuteDataset(trans, CommandType.StoredProcedure, "GetOrders", new OdbcParameter("@prodid", 24)); /// </remarks> /// <param name="transaction">a valid OdbcTransaction</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <param name="commandParameters">an array of OdbcParamters used to execute the command</param> /// <returns>a dataset containing the resultset generated by the command</returns> public static DataSet ExecuteDataset(OdbcTransaction transaction, CommandType commandType, string commandText, params OdbcParameter[] commandParameters) { //create a command and prepare it for execution OdbcCommand cmd = new OdbcCommand(); PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters); //create the DataAdapter & DataSet OdbcDataAdapter da = new OdbcDataAdapter(cmd); DataSet ds = new DataSet(); //fill the DataSet using default values for DataTable names, etc. da.Fill(ds); // detach the OdbcParameters from the command object, so they can be used again. cmd.Parameters.Clear(); //return the dataset return ds; } /// <summary> /// Execute a stored procedure via a OdbcCommand (that returns a resultset) against the specified /// OdbcTransaction using the provided parameter values. This method will query the database to discover the parameters for the /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order. /// </summary> /// <remarks> /// This method provides no access to output parameters or the stored procedure's return value parameter. /// /// e.g.: /// DataSet ds = ExecuteDataset(trans, "GetOrders", 24, 36); /// </remarks> /// <param name="transaction">a valid OdbcTransaction</param> /// <param name="spName">the name of the stored procedure</param> /// <param name="parameterValues">an array of objects to be assigned as the input values of the stored procedure</param> /// <returns>a dataset containing the resultset generated by the command</returns> public static DataSet ExecuteDataset(OdbcTransaction transaction, string spName, params object[] parameterValues) { //if we receive parameter values, we need to figure out where they go if ((parameterValues != null) && (parameterValues.Length > 0)) { //pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache) OdbcParameter[] commandParameters = OdbcHelperParameterCache.GetSpParameterSet(transaction.Connection.ConnectionString, spName); //assign the provided values to these parameters based on parameter order AssignParameterValues(commandParameters, parameterValues); //call the overload that takes an array of OdbcParameters return ExecuteDataset(transaction, CommandType.StoredProcedure, spName, commandParameters); } //otherwise we can just call the SP without params else { return ExecuteDataset(transaction, CommandType.StoredProcedure, spName); } } #endregion ExecuteDataSet #region ExecuteReader /// <summary> /// this enum is used to indicate whether the connection was provided by the caller, or created by OdbcHelper, so that /// we can set the appropriate CommandBehavior when calling ExecuteReader() /// </summary> private enum OdbcConnectionOwnership { /// <summary>Connection is owned and managed by OdbcHelper</summary> Internal, /// <summary>Connection is owned and managed by the caller</summary> External } /// <summary> /// Create and prepare a OdbcCommand, and call ExecuteReader with the appropriate CommandBehavior. /// </summary> /// <remarks> /// If we created and opened the connection, we want the connection to be closed when the DataReader is closed. /// /// If the caller provided the connection, we want to leave it to them to manage. /// </remarks> /// <param name="connection">a valid OdbcConnection, on which to execute this command</param> /// <param name="transaction">a valid OdbcTransaction, or 'null'</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <param name="commandParameters">an array of OdbcParameters to be associated with the command or 'null' if no parameters are required</param> /// <param name="connectionOwnership">indicates whether the connection parameter was provided by the caller, or created by OdbcHelper</param> /// <returns>OdbcDataReader containing the results of the command</returns> private static OdbcDataReader ExecuteReader(OdbcConnection connection, OdbcTransaction transaction, CommandType commandType, string commandText, OdbcParameter[] commandParameters, OdbcConnectionOwnership connectionOwnership) { //create a command and prepare it for execution OdbcCommand cmd = new OdbcCommand(); PrepareCommand(cmd, connection, transaction, commandType, commandText, commandParameters); //create a reader OdbcDataReader dr; // call ExecuteReader with the appropriate CommandBehavior if (connectionOwnership == OdbcConnectionOwnership.External) { dr = cmd.ExecuteReader(); } else { dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); } // detach the OdbcParameters from the command object, so they can be used again. cmd.Parameters.Clear(); return dr; } /// <summary> /// Execute a OdbcCommand (that returns a resultset and takes no parameters) against the database specified in /// the connection string. /// </summary> /// <remarks> /// e.g.: /// OdbcDataReader dr = ExecuteReader(connString, CommandType.StoredProcedure, "GetOrders"); /// </remarks> /// <param name="connectionString">a valid connection string for a OdbcConnection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <returns>a OdbcDataReader containing the resultset generated by the command</returns> public static OdbcDataReader ExecuteReader(string connectionString, CommandType commandType, string commandText) { //pass through the call providing null for the set of OdbcParameters return ExecuteReader(connectionString, commandType, commandText, (OdbcParameter[])null); } /// <summary> /// Execute a OdbcCommand (that returns a resultset) against the database specified in the connection string /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// OdbcDataReader dr = ExecuteReader(connString, CommandType.StoredProcedure, "GetOrders", new OdbcParameter("@prodid", 24)); /// </remarks> /// <param name="connectionString">a valid connection string for a OdbcConnection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <param name="commandParameters">an array of OdbcParamters used to execute the command</param> /// <returns>a OdbcDataReader containing the resultset generated by the command</returns> public static OdbcDataReader ExecuteReader(string connectionString, CommandType commandType, string commandText, params OdbcParameter[] commandParameters) { //create & open a OdbcConnection OdbcConnection cn = new OdbcConnection(connectionString); cn.Open(); try { //call the private overload that takes an internally owned connection in place of the connection string return ExecuteReader(cn, null, commandType, commandText, commandParameters, OdbcConnectionOwnership.Internal); } catch { //if we fail to return the OdbcDatReader, we need to close the connection ourselves cn.Close(); throw; } } /// <summary> /// Execute a stored procedure via a OdbcCommand (that returns a resultset) against the database specified in /// the connection string using the provided parameter values. This method will query the database to discover the parameters for the /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order. /// </summary> /// <remarks> /// This method provides no access to output parameters or the stored procedure's return value parameter. /// /// e.g.: /// OdbcDataReader dr = ExecuteReader(connString, "GetOrders", 24, 36); /// </remarks> /// <param name="connectionString">a valid connection string for a OdbcConnection</param> /// <param name="spName">the name of the stored procedure</param> /// <param name="parameterValues">an array of objects to be assigned as the input values of the stored procedure</param> /// <returns>a OdbcDataReader containing the resultset generated by the command</returns> public static OdbcDataReader ExecuteReader(string connectionString, string spName, params object[] parameterValues) { //if we receive parameter values, we need to figure out where they go if ((parameterValues != null) && (parameterValues.Length > 0)) { //pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache) OdbcParameter[] commandParameters = OdbcHelperParameterCache.GetSpParameterSet(connectionString, spName); //assign the provided values to these parameters based on parameter order AssignParameterValues(commandParameters, parameterValues); //call the overload that takes an array of OdbcParameters return ExecuteReader(connectionString, CommandType.StoredProcedure, spName, commandParameters); } //otherwise we can just call the SP without params else { return ExecuteReader(connectionString, CommandType.StoredProcedure, spName); } } /// <summary> /// Execute a OdbcCommand (that returns a resultset and takes no parameters) against the provided OdbcConnection. /// </summary> /// <remarks> /// e.g.: /// OdbcDataReader dr = ExecuteReader(conn, CommandType.StoredProcedure, "GetOrders"); /// </remarks> /// <param name="connection">a valid OdbcConnection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <returns>a OdbcDataReader containing the resultset generated by the command</returns> public static OdbcDataReader ExecuteReader(OdbcConnection connection, CommandType commandType, string commandText) { //pass through the call providing null for the set of OdbcParameters return ExecuteReader(connection, commandType, commandText, (OdbcParameter[])null); } /// <summary> /// Execute a OdbcCommand (that returns a resultset) against the specified OdbcConnection /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// OdbcDataReader dr = ExecuteReader(conn, CommandType.StoredProcedure, "GetOrders", new OdbcParameter("@prodid", 24)); /// </remarks> /// <param name="connection">a valid OdbcConnection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <param name="commandParameters">an array of OdbcParamters used to execute the command</param> /// <returns>a OdbcDataReader containing the resultset generated by the command</returns> public static OdbcDataReader ExecuteReader(OdbcConnection connection, CommandType commandType, string commandText, params OdbcParameter[] commandParameters) { //pass through the call to the private overload using a null transaction value and an externally owned connection return ExecuteReader(connection, (OdbcTransaction)null, commandType, commandText, commandParameters, OdbcConnectionOwnership.External); } /// <summary> /// Execute a stored procedure via a OdbcCommand (that returns a resultset) against the specified OdbcConnection /// using the provided parameter values. This method will query the database to discover the parameters for the /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order. /// </summary> /// <remarks> /// This method provides no access to output parameters or the stored procedure's return value parameter. /// /// e.g.: /// OdbcDataReader dr = ExecuteReader(conn, "GetOrders", 24, 36); /// </remarks> /// <param name="connection">a valid OdbcConnection</param> /// <param name="spName">the name of the stored procedure</param> /// <param name="parameterValues">an array of objects to be assigned as the input values of the stored procedure</param> /// <returns>a OdbcDataReader containing the resultset generated by the command</returns> public static OdbcDataReader ExecuteReader(OdbcConnection connection, string spName, params object[] parameterValues) { //if we receive parameter values, we need to figure out where they go if ((parameterValues != null) && (parameterValues.Length > 0)) { OdbcParameter[] commandParameters = OdbcHelperParameterCache.GetSpParameterSet(connection.ConnectionString, spName); AssignParameterValues(commandParameters, parameterValues); return ExecuteReader(connection, CommandType.StoredProcedure, spName, commandParameters); } //otherwise we can just call the SP without params else { return ExecuteReader(connection, CommandType.StoredProcedure, spName); } } /// <summary> /// Execute a OdbcCommand (that returns a resultset and takes no parameters) against the provided OdbcTransaction. /// </summary> /// <remarks> /// e.g.: /// OdbcDataReader dr = ExecuteReader(trans, CommandType.StoredProcedure, "GetOrders"); /// </remarks> /// <param name="transaction">a valid OdbcTransaction</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <returns>a OdbcDataReader containing the resultset generated by the command</returns> public static OdbcDataReader ExecuteReader(OdbcTransaction transaction, CommandType commandType, string commandText) { //pass through the call providing null for the set of OdbcParameters return ExecuteReader(transaction, commandType, commandText, (OdbcParameter[])null); } /// <summary> /// Execute a OdbcCommand (that returns a resultset) against the specified OdbcTransaction /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// OdbcDataReader dr = ExecuteReader(trans, CommandType.StoredProcedure, "GetOrders", new OdbcParameter("@prodid", 24)); /// </remarks> /// <param name="transaction">a valid OdbcTransaction</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <param name="commandParameters">an array of OdbcParamters used to execute the command</param> /// <returns>a OdbcDataReader containing the resultset generated by the command</returns> public static OdbcDataReader ExecuteReader(OdbcTransaction transaction, CommandType commandType, string commandText, params OdbcParameter[] commandParameters) { //pass through to private overload, indicating that the connection is owned by the caller return ExecuteReader(transaction.Connection, transaction, commandType, commandText, commandParameters, OdbcConnectionOwnership.External); } /// <summary> /// Execute a stored procedure via a OdbcCommand (that returns a resultset) against the specified /// OdbcTransaction using the provided parameter values. This method will query the database to discover the parameters for the /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order. /// </summary> /// <remarks> /// This method provides no access to output parameters or the stored procedure's return value parameter. /// /// e.g.: /// OdbcDataReader dr = ExecuteReader(trans, "GetOrders", 24, 36); /// </remarks> /// <param name="transaction">a valid OdbcTransaction</param> /// <param name="spName">the name of the stored procedure</param> /// <param name="parameterValues">an array of objects to be assigned as the input values of the stored procedure</param> /// <returns>a OdbcDataReader containing the resultset generated by the command</returns> public static OdbcDataReader ExecuteReader(OdbcTransaction transaction, string spName, params object[] parameterValues) { //if we receive parameter values, we need to figure out where they go if ((parameterValues != null) && (parameterValues.Length > 0)) { OdbcParameter[] commandParameters = OdbcHelperParameterCache.GetSpParameterSet(transaction.Connection.ConnectionString, spName); AssignParameterValues(commandParameters, parameterValues); return ExecuteReader(transaction, CommandType.StoredProcedure, spName, commandParameters); } //otherwise we can just call the SP without params else { return ExecuteReader(transaction, CommandType.StoredProcedure, spName); } } #endregion ExecuteReader #region ExecuteScalar /// <summary> /// Execute a OdbcCommand (that returns a 1x1 resultset and takes no parameters) against the database specified in /// the connection string. /// </summary> /// <remarks> /// e.g.: /// int orderCount = (int)ExecuteScalar(connString, CommandType.StoredProcedure, "GetOrderCount"); /// </remarks> /// <param name="connectionString">a valid connection string for a OdbcConnection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <returns>an object containing the value in the 1x1 resultset generated by the command</returns> public static object ExecuteScalar(string connectionString, CommandType commandType, string commandText) { //pass through the call providing null for the set of OdbcParameters return ExecuteScalar(connectionString, commandType, commandText, (OdbcParameter[])null); } /// <summary> /// Execute a OdbcCommand (that returns a 1x1 resultset) against the database specified in the connection string /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// int orderCount = (int)ExecuteScalar(connString, CommandType.StoredProcedure, "GetOrderCount", new OdbcParameter("@prodid", 24)); /// </remarks> /// <param name="connectionString">a valid connection string for a OdbcConnection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <param name="commandParameters">an array of OdbcParamters used to execute the command</param> /// <returns>an object containing the value in the 1x1 resultset generated by the command</returns> public static object ExecuteScalar(string connectionString, CommandType commandType, string commandText, params OdbcParameter[] commandParameters) { //create & open a OdbcConnection, and dispose of it after we are done. using (OdbcConnection cn = new OdbcConnection(connectionString)) { cn.Open(); //call the overload that takes a connection in place of the connection string return ExecuteScalar(cn, commandType, commandText, commandParameters); } } /// <summary> /// Execute a stored procedure via a OdbcCommand (that returns a 1x1 resultset) against the database specified in /// the connection string using the provided parameter values. This method will query the database to discover the parameters for the /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order. /// </summary> /// <remarks> /// This method provides no access to output parameters or the stored procedure's return value parameter. /// /// e.g.: /// int orderCount = (int)ExecuteScalar(connString, "GetOrderCount", 24, 36); /// </remarks> /// <param name="connectionString">a valid connection string for a OdbcConnection</param> /// <param name="spName">the name of the stored procedure</param> /// <param name="parameterValues">an array of objects to be assigned as the input values of the stored procedure</param> /// <returns>an object containing the value in the 1x1 resultset generated by the command</returns> public static object ExecuteScalar(string connectionString, string spName, params object[] parameterValues) { //if we receive parameter values, we need to figure out where they go if ((parameterValues != null) && (parameterValues.Length > 0)) { //pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache) OdbcParameter[] commandParameters = OdbcHelperParameterCache.GetSpParameterSet(connectionString, spName); //assign the provided values to these parameters based on parameter order AssignParameterValues(commandParameters, parameterValues); //call the overload that takes an array of OdbcParameters return ExecuteScalar(connectionString, CommandType.StoredProcedure, spName, commandParameters); } //otherwise we can just call the SP without params else { return ExecuteScalar(connectionString, CommandType.StoredProcedure, spName); } } /// <summary> /// Execute a OdbcCommand (that returns a 1x1 resultset and takes no parameters) against the provided OdbcConnection. /// </summary> /// <remarks> /// e.g.: /// int orderCount = (int)ExecuteScalar(conn, CommandType.StoredProcedure, "GetOrderCount"); /// </remarks> /// <param name="connection">a valid OdbcConnection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <returns>an object containing the value in the 1x1 resultset generated by the command</returns> public static object ExecuteScalar(OdbcConnection connection, CommandType commandType, string commandText) { //pass through the call providing null for the set of OdbcParameters return ExecuteScalar(connection, commandType, commandText, (OdbcParameter[])null); } /// <summary> /// Execute a OdbcCommand (that returns a 1x1 resultset) against the specified OdbcConnection /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// int orderCount = (int)ExecuteScalar(conn, CommandType.StoredProcedure, "GetOrderCount", new OdbcParameter("@prodid", 24)); /// </remarks> /// <param name="connection">a valid OdbcConnection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <param name="commandParameters">an array of OdbcParamters used to execute the command</param> /// <returns>an object containing the value in the 1x1 resultset generated by the command</returns> public static object ExecuteScalar(OdbcConnection connection, CommandType commandType, string commandText, params OdbcParameter[] commandParameters) { //create a command and prepare it for execution OdbcCommand cmd = new OdbcCommand(); PrepareCommand(cmd, connection, (OdbcTransaction)null, commandType, commandText, commandParameters); //execute the command & return the results object retval = cmd.ExecuteScalar(); // detach the OdbcParameters from the command object, so they can be used again. cmd.Parameters.Clear(); return retval; } /// <summary> /// Execute a stored procedure via a OdbcCommand (that returns a 1x1 resultset) against the specified OdbcConnection /// using the provided parameter values. This method will query the database to discover the parameters for the /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order. /// </summary> /// <remarks> /// This method provides no access to output parameters or the stored procedure's return value parameter. /// /// e.g.: /// int orderCount = (int)ExecuteScalar(conn, "GetOrderCount", 24, 36); /// </remarks> /// <param name="connection">a valid OdbcConnection</param> /// <param name="spName">the name of the stored procedure</param> /// <param name="parameterValues">an array of objects to be assigned as the input values of the stored procedure</param> /// <returns>an object containing the value in the 1x1 resultset generated by the command</returns> public static object ExecuteScalar(OdbcConnection connection, string spName, params object[] parameterValues) { //if we receive parameter values, we need to figure out where they go if ((parameterValues != null) && (parameterValues.Length > 0)) { //pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache) OdbcParameter[] commandParameters = OdbcHelperParameterCache.GetSpParameterSet(connection.ConnectionString, spName); //assign the provided values to these parameters based on parameter order AssignParameterValues(commandParameters, parameterValues); //call the overload that takes an array of OdbcParameters return ExecuteScalar(connection, CommandType.StoredProcedure, spName, commandParameters); } //otherwise we can just call the SP without params else { return ExecuteScalar(connection, CommandType.StoredProcedure, spName); } } /// <summary> /// Execute a OdbcCommand (that returns a 1x1 resultset and takes no parameters) against the provided OdbcTransaction. /// </summary> /// <remarks> /// e.g.: /// int orderCount = (int)ExecuteScalar(trans, CommandType.StoredProcedure, "GetOrderCount"); /// </remarks> /// <param name="transaction">a valid OdbcTransaction</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <returns>an object containing the value in the 1x1 resultset generated by the command</returns> public static object ExecuteScalar(OdbcTransaction transaction, CommandType commandType, string commandText) { //pass through the call providing null for the set of OdbcParameters return ExecuteScalar(transaction, commandType, commandText, (OdbcParameter[])null); } /// <summary> /// Execute a OdbcCommand (that returns a 1x1 resultset) against the specified OdbcTransaction /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// int orderCount = (int)ExecuteScalar(trans, CommandType.StoredProcedure, "GetOrderCount", new OdbcParameter("@prodid", 24)); /// </remarks> /// <param name="transaction">a valid OdbcTransaction</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <param name="commandParameters">an array of OdbcParamters used to execute the command</param> /// <returns>an object containing the value in the 1x1 resultset generated by the command</returns> public static object ExecuteScalar(OdbcTransaction transaction, CommandType commandType, string commandText, params OdbcParameter[] commandParameters) { //create a command and prepare it for execution OdbcCommand cmd = new OdbcCommand(); PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters); //execute the command & return the results object retval = cmd.ExecuteScalar(); // detach the OdbcParameters from the command object, so they can be used again. cmd.Parameters.Clear(); return retval; } /// <summary> /// Execute a stored procedure via a OdbcCommand (that returns a 1x1 resultset) against the specified /// OdbcTransaction using the provided parameter values. This method will query the database to discover the parameters for the /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order. /// </summary> /// <remarks> /// This method provides no access to output parameters or the stored procedure's return value parameter. /// /// e.g.: /// int orderCount = (int)ExecuteScalar(trans, "GetOrderCount", 24, 36); /// </remarks> /// <param name="transaction">a valid OdbcTransaction</param> /// <param name="spName">the name of the stored procedure</param> /// <param name="parameterValues">an array of objects to be assigned as the input values of the stored procedure</param> /// <returns>an object containing the value in the 1x1 resultset generated by the command</returns> public static object ExecuteScalar(OdbcTransaction transaction, string spName, params object[] parameterValues) { //if we receive parameter values, we need to figure out where they go if ((parameterValues != null) && (parameterValues.Length > 0)) { //pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache) OdbcParameter[] commandParameters = OdbcHelperParameterCache.GetSpParameterSet(transaction.Connection.ConnectionString, spName); //assign the provided values to these parameters based on parameter order AssignParameterValues(commandParameters, parameterValues); //call the overload that takes an array of OdbcParameters return ExecuteScalar(transaction, CommandType.StoredProcedure, spName, commandParameters); } //otherwise we can just call the SP without params else { return ExecuteScalar(transaction, CommandType.StoredProcedure, spName); } } #endregion ExecuteScalar #region ExecuteXmlReader /// <summary> /// Execute a OdbcCommand (that returns a resultset and takes no parameters) against the provided OdbcConnection. /// </summary> /// <remarks> /// e.g.: /// XmlReader r = ExecuteXmlReader(conn, CommandType.StoredProcedure, "GetOrders"); /// </remarks> /// <param name="connection">a valid OdbcConnection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command using "FOR XML AUTO"</param> /// <returns>an XmlReader containing the resultset generated by the command</returns> public static XmlReader ExecuteXmlReader(OdbcConnection connection, CommandType commandType, string commandText) { //pass through the call providing null for the set of OdbcParameters return ExecuteXmlReader(connection, commandType, commandText, (OdbcParameter[])null); } /// <summary> /// Execute a OdbcCommand (that returns a resultset) against the specified OdbcConnection /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// XmlReader r = ExecuteXmlReader(conn, CommandType.StoredProcedure, "GetOrders", new OdbcParameter("@prodid", 24)); /// </remarks> /// <param name="connection">a valid OdbcConnection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command using "FOR XML AUTO"</param> /// <param name="commandParameters">an array of OdbcParamters used to execute the command</param> /// <returns>an XmlReader containing the resultset generated by the command</returns> public static XmlReader ExecuteXmlReader(OdbcConnection connection, CommandType commandType, string commandText, params OdbcParameter[] commandParameters) { //create a command and prepare it for execution OdbcCommand cmd = new OdbcCommand(); PrepareCommand(cmd, connection, (OdbcTransaction)null, commandType, commandText, commandParameters); //create the DataAdapter & DataSet DataSet ds = ExecuteDataset(connection, commandType, commandText, commandParameters); XmlReader retval = new XmlTextReader(new StringReader(ds.GetXml())); // detach the OdbcParameters from the command object, so they can be used again. cmd.Parameters.Clear(); return retval; } /// <summary> /// Execute a stored procedure via a OdbcCommand (that returns a resultset) against the specified OdbcConnection /// using the provided parameter values. This method will query the database to discover the parameters for the /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order. /// </summary> /// <remarks> /// This method provides no access to output parameters or the stored procedure's return value parameter. /// /// e.g.: /// XmlReader r = ExecuteXmlReader(conn, "GetOrders", 24, 36); /// </remarks> /// <param name="connection">a valid OdbcConnection</param> /// <param name="spName">the name of the stored procedure using "FOR XML AUTO"</param> /// <param name="parameterValues">an array of objects to be assigned as the input values of the stored procedure</param> /// <returns>an XmlReader containing the resultset generated by the command</returns> public static XmlReader ExecuteXmlReader(OdbcConnection connection, string spName, params object[] parameterValues) { //if we receive parameter values, we need to figure out where they go if ((parameterValues != null) && (parameterValues.Length > 0)) { //pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache) OdbcParameter[] commandParameters = OdbcHelperParameterCache.GetSpParameterSet(connection.ConnectionString, spName); //assign the provided values to these parameters based on parameter order AssignParameterValues(commandParameters, parameterValues); //call the overload that takes an array of OdbcParameters return ExecuteXmlReader(connection, CommandType.StoredProcedure, spName, commandParameters); } //otherwise we can just call the SP without params else { return ExecuteXmlReader(connection, CommandType.StoredProcedure, spName); } } /// <summary> /// Execute a OdbcCommand (that returns a resultset and takes no parameters) against the provided OdbcTransaction. /// </summary> /// <remarks> /// e.g.: /// XmlReader r = ExecuteXmlReader(trans, CommandType.StoredProcedure, "GetOrders"); /// </remarks> /// <param name="transaction">a valid OdbcTransaction</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command using "FOR XML AUTO"</param> /// <returns>an XmlReader containing the resultset generated by the command</returns> public static XmlReader ExecuteXmlReader(OdbcTransaction transaction, CommandType commandType, string commandText) { //pass through the call providing null for the set of OdbcParameters return ExecuteXmlReader(transaction, commandType, commandText, (OdbcParameter[])null); } /// <summary> /// Execute a OdbcCommand (that returns a resultset) against the specified OdbcTransaction /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// XmlReader r = ExecuteXmlReader(trans, CommandType.StoredProcedure, "GetOrders", new OdbcParameter("@prodid", 24)); /// </remarks> /// <param name="transaction">a valid OdbcTransaction</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command using "FOR XML AUTO"</param> /// <param name="commandParameters">an array of OdbcParamters used to execute the command</param> /// <returns>an XmlReader containing the resultset generated by the command</returns> public static XmlReader ExecuteXmlReader(OdbcTransaction transaction, CommandType commandType, string commandText, params OdbcParameter[] commandParameters) { //create a command and prepare it for execution OdbcCommand cmd = new OdbcCommand(); PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters); //create the DataAdapter & DataSet DataSet ds = ExecuteDataset(transaction, commandType, commandText, commandParameters); XmlReader retval = new XmlTextReader(new StringReader(ds.GetXml())); // detach the OdbcParameters from the command object, so they can be used again. cmd.Parameters.Clear(); return retval; } /// <summary> /// Execute a stored procedure via a OdbcCommand (that returns a resultset) against the specified /// OdbcTransaction using the provided parameter values. This method will query the database to discover the parameters for the /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order. /// </summary> /// <remarks> /// This method provides no access to output parameters or the stored procedure's return value parameter. /// /// e.g.: /// XmlReader r = ExecuteXmlReader(trans, "GetOrders", 24, 36); /// </remarks> /// <param name="transaction">a valid OdbcTransaction</param> /// <param name="spName">the name of the stored procedure</param> /// <param name="parameterValues">an array of objects to be assigned as the input values of the stored procedure</param> /// <returns>a dataset containing the resultset generated by the command</returns> public static XmlReader ExecuteXmlReader(OdbcTransaction transaction, string spName, params object[] parameterValues) { //if we receive parameter values, we need to figure out where they go if ((parameterValues != null) && (parameterValues.Length > 0)) { //pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache) OdbcParameter[] commandParameters = OdbcHelperParameterCache.GetSpParameterSet(transaction.Connection.ConnectionString, spName); //assign the provided values to these parameters based on parameter order AssignParameterValues(commandParameters, parameterValues); //call the overload that takes an array of OdbcParameters return ExecuteXmlReader(transaction, CommandType.StoredProcedure, spName, commandParameters); } //otherwise we can just call the SP without params else { return ExecuteXmlReader(transaction, CommandType.StoredProcedure, spName); } } #endregion ExecuteXmlReader } /// <summary> /// OdbcHelperParameterCache provides functions to leverage a static cache of procedure parameters, and the /// ability to discover parameters for stored procedures at run-time. /// </summary> public class OdbcHelperParameterCache { #region private methods, variables, and constructors //Since this class provides only static methods, make the default constructor private to prevent //instances from being created with "new OdbcHelperParameterCache()". private OdbcHelperParameterCache() { } private static Hashtable paramCache = Hashtable.Synchronized(new Hashtable()); /// <summary> /// resolve at run time the appropriate set of OdbcParameters for a stored procedure /// </summary> /// <param name="connectionString">a valid connection string for a OdbcConnection</param> /// <param name="spName">the name of the stored procedure</param> /// <param name="includeReturnValueParameter">whether or not to include their return value parameter</param> /// <returns></returns> private static OdbcParameter[] DiscoverSpParameterSet(string connectionString, string spName, bool includeReturnValueParameter) { using (OdbcConnection cn = new OdbcConnection(connectionString)) using (OdbcCommand cmd = new OdbcCommand(spName, cn)) { cn.Open(); cmd.CommandType = CommandType.StoredProcedure; OdbcCommandBuilder.DeriveParameters(cmd); if (!includeReturnValueParameter) { cmd.Parameters.RemoveAt(0); } OdbcParameter[] discoveredParameters = new OdbcParameter[cmd.Parameters.Count]; ; cmd.Parameters.CopyTo(discoveredParameters, 0); return discoveredParameters; } } //deep copy of cached OdbcParameter array private static OdbcParameter[] CloneParameters(OdbcParameter[] originalParameters) { OdbcParameter[] clonedParameters = new OdbcParameter[originalParameters.Length]; for (int i = 0, j = originalParameters.Length; i < j; i++) { clonedParameters[i] = (OdbcParameter)((ICloneable)originalParameters[i]).Clone(); } return clonedParameters; } #endregion private methods, variables, and constructors #region caching functions /// <summary> /// add parameter array to the cache /// </summary> /// <param name="connectionString">a valid connection string for a OdbcConnection</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <param name="commandParameters">an array of OdbcParamters to be cached</param> public static void CacheParameterSet(string connectionString, string commandText, params OdbcParameter[] commandParameters) { string hashKey = connectionString + ":" + commandText; paramCache[hashKey] = commandParameters; } /// <summary> /// retrieve a parameter array from the cache /// </summary> /// <param name="connectionString">a valid connection string for a OdbcConnection</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <returns>an array of OdbcParamters</returns> public static OdbcParameter[] GetCachedParameterSet(string connectionString, string commandText) { string hashKey = connectionString + ":" + commandText; OdbcParameter[] cachedParameters = (OdbcParameter[])paramCache[hashKey]; if (cachedParameters == null) { return null; } else { return CloneParameters(cachedParameters); } } #endregion caching functions #region Parameter Discovery Functions /// <summary> /// Retrieves the set of OdbcParameters appropriate for the stored procedure /// </summary> /// <remarks> /// This method will query the database for this information, and then store it in a cache for future requests. /// </remarks> /// <param name="connectionString">a valid connection string for a OdbcConnection</param> /// <param name="spName">the name of the stored procedure</param> /// <returns>an array of OdbcParameters</returns> public static OdbcParameter[] GetSpParameterSet(string connectionString, string spName) { return GetSpParameterSet(connectionString, spName, false); } /// <summary> /// Retrieves the set of OdbcParameters appropriate for the stored procedure /// </summary> /// <remarks> /// This method will query the database for this information, and then store it in a cache for future requests. /// </remarks> /// <param name="connectionString">a valid connection string for a OdbcConnection</param> /// <param name="spName">the name of the stored procedure</param> /// <param name="includeReturnValueParameter">a bool value indicating whether the return value parameter should be included in the results</param> /// <returns>an array of OdbcParameters</returns> public static OdbcParameter[] GetSpParameterSet(string connectionString, string spName, bool includeReturnValueParameter) { string hashKey = connectionString + ":" + spName + (includeReturnValueParameter ? ":include ReturnValue Parameter" : ""); OdbcParameter[] cachedParameters; cachedParameters = (OdbcParameter[])paramCache[hashKey]; if (cachedParameters == null) { cachedParameters = (OdbcParameter[])(paramCache[hashKey] = DiscoverSpParameterSet(connectionString, spName, includeReturnValueParameter)); } return CloneParameters(cachedParameters); } #endregion Parameter Discovery Functions } }
54.898015
232
0.646386
[ "MIT" ]
q120582371/gameserver
shiwch.util/OdbcHelper.cs
80,268
C#
#region License // Copyright 2004-2010 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion namespace Castle.Facilities.NHibernateIntegration.Internal { using System.IO; using System.Text; using Core.Resource; /// <summary> /// Resource for a file or an assembly resource /// </summary> public class FileAssemblyResource : IResource { /// <summary> /// Depending on the resource type, <see cref="AssemblyResource"/> or <see cref="FileResource"/> is decorated. /// </summary> /// <param name="resource"></param> public FileAssemblyResource(string resource) { if (File.Exists(resource)) { innerResource = new FileResource(resource); } else { innerResource = new AssemblyResource(resource); } } private readonly IResource innerResource; #region IResource Members /// <summary> /// Returns an instance of Castle.Core.Resource.IResource created according to the relativePath using itself as the root. /// </summary> /// <param name="relativePath"></param> /// <returns></returns> public IResource CreateRelative(string relativePath) { return innerResource.CreateRelative(relativePath); } /// <summary> /// Only valid for resources that can be obtained through relative paths /// </summary> public string FileBasePath { get { return innerResource.FileBasePath; } } /// <summary> /// Returns a reader for the stream /// </summary> /// <param name="encoding"></param> /// <returns></returns> public TextReader GetStreamReader(Encoding encoding) { return innerResource.GetStreamReader(encoding); } /// <summary> /// Returns a reader for the stream /// </summary> /// <returns></returns> public TextReader GetStreamReader() { return innerResource.GetStreamReader(); } #endregion #region IDisposable Members /// <summary> /// Disposes the allocated resources /// </summary> public void Dispose() { innerResource.Dispose(); } #endregion } }
25.196078
123
0.69144
[ "Apache-2.0" ]
ByteDecoder/Castle.Facilities.NHibernateIntegration
src/Castle.Facilities.NHibernateIntegration/Internal/FileAssemblyResource.cs
2,572
C#
internal interface ITouchable { void OnClick(); }
13.5
30
0.703704
[ "MIT" ]
marce1994/MovilesTP2
game/Assets/Scripts/ITouchable.cs
56
C#
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; namespace TygaSoft.IDAL { public interface IContentDetail { #region 成员方法 /// <summary> /// 添加数据到数据库 /// </summary> /// <param name="model"></param> /// <returns></returns> int Insert(Model.ContentDetailInfo model); /// <summary> /// 修改数据 /// </summary> /// <param name="model"></param> /// <returns></returns> int Update(Model.ContentDetailInfo model); /// <summary> /// 删除对应数据 /// </summary> /// <param name="numberId"></param> /// <returns></returns> int Delete(string numberId); /// <summary> /// 批量删除数据(启用事务 /// </summary> /// <param name="list"></param> /// <returns></returns> bool DeleteBatch(IList<string> list); /// <summary> /// 获取对应的数据 /// </summary> /// <param name="numberId"></param> /// <returns></returns> Model.ContentDetailInfo GetModel(string numberId); /// <summary> /// 获取数据分页列表,并返回所有记录数 /// </summary> /// <param name="pageIndex"></param> /// <param name="pageSize"></param> /// <param name="totalCount"></param> /// <param name="sqlWhere"></param> /// <param name="commandParameters"></param> /// <returns></returns> IList<Model.ContentDetailInfo> GetList(int pageIndex, int pageSize, out int totalCount, string sqlWhere, params SqlParameter[] commandParameters); /// <summary> /// 获取数据分页列表,并返回所有记录数 /// </summary> /// <param name="pageIndex"></param> /// <param name="pageSize"></param> /// <param name="totalCount"></param> /// <param name="sqlWhere"></param> /// <param name="commandParameters"></param> /// <returns></returns> DataSet GetDataSet(int pageIndex, int pageSize, out int totalCount, string sqlWhere, params SqlParameter[] commandParameters); /// <summary> /// 获取内容列表 /// </summary> /// <returns></returns> List<Model.ContentDetailInfo> GetList(); /// <summary> /// 获取当前根节点下的所有内容类型和内容 /// </summary> /// <param name="typeName"></param> /// <returns></returns> List<Model.ContentDetailInfo> GetSiteContent(string typeName); #endregion } }
29.738095
154
0.536429
[ "MIT" ]
qq283335746/ECShop
src/TygaSoft/IDAL/IContentDetail.cs
2,694
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace UXStudy { public class Instructions : BaseViewModel { private Visibility visibility; public Visibility Visibility { get { return visibility; } set { SetProperty(ref visibility, value); } } private string instructions; public string InstructionString { get { return instructions; } set { SetProperty(ref instructions, value); } } public string Preamble { get; private set; } public Instructions() { Visibility = Visibility.Hidden; InstructionString = String.Empty; Preamble = createInstructionPreamble(); } public void setInstructions(List<IGameControl> wanted) { StringBuilder sb = new StringBuilder(); randomizeControls(wanted); foreach (IGameControl control in wanted) { sb.AppendLine("- "+control.Instructions); } InstructionString = sb.ToString(); } private string createInstructionPreamble() { return "Instructions \n \n" + "Complete all of the following tasks to proceed \n \n"; } private void randomizeControls(List<IGameControl> wanted) { Random random = new Random(); int index = wanted.Count - 1; while (index > 0) { int next = random.Next(index + 1); IGameControl temp = wanted[next]; wanted[next] = wanted[index]; wanted[index] = temp; index--; } } public void launchInstructions() { Visibility = Visibility.Visible; } public void closeInstructions() { Visibility = Visibility.Hidden; } } }
27.081081
77
0.552894
[ "Apache-2.0" ]
NathanielBeen/UXStudy
UXStudy/UXStudy/Instructions.cs
2,006
C#
using System; using System.Web.Mvc; using Umbraco.Web.Routing; namespace Umbraco.Web.Mvc { /// <summary> /// Represents the data required to route to a specific controller/action during an Umbraco request /// </summary> internal class RouteDefinition { public string ControllerName { get; set; } public string ActionName { get; set; } /// <summary> /// The Controller instance found for routing to /// </summary> public ControllerBase Controller { get; set; } /// <summary> /// The Controller type found for routing to /// </summary> public Type ControllerType { get; set; } /// <summary> /// The current RenderModel found for the request /// </summary> public PublishedContentRequest PublishedContentRequest { get; set; } /// <summary> /// Gets/sets whether the current request has a hijacked route/user controller routed for it /// </summary> public bool HasHijackedRoute { get; set; } } }
27.722222
101
0.653307
[ "MIT" ]
AndyButland/Umbraco-CMS
src/Umbraco.Web/Mvc/RouteDefinition.cs
998
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Text.Json.Serialization.Converters { internal sealed class SByteConverter : JsonConverter<sbyte> { public override sbyte Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return reader.GetSByte(); } public override void Write(Utf8JsonWriter writer, sbyte value, JsonSerializerOptions options) { writer.WriteNumberValue(value); } internal override sbyte ReadWithQuotes(ref Utf8JsonReader reader) { return reader.GetSByteWithQuotes(); } internal override void WriteWithQuotes(Utf8JsonWriter writer, sbyte value, JsonSerializerOptions options, ref WriteStack state) { writer.WritePropertyName(value); } } }
32.862069
135
0.679958
[ "MIT" ]
71221-maker/runtime
src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/SByteConverter.cs
953
C#
// IScanFilter.cs // // Copyright 2006 John Reilly // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. namespace ICSharpCode.SharpZipLib.Core { /// <summary> /// Scanning filters support filtering of names. /// </summary> public interface IScanFilter { /// <summary> /// Test a name to see if it 'matches' the filter. /// </summary> /// <param name="name">The name to test.</param> /// <returns>Returns true if the name matches the filter, false if it does not match.</returns> bool IsMatch(string name); } }
44.568627
104
0.706555
[ "MIT" ]
Acidburn0zzz/flashdevelop
External/Tools/AppMan/ZipLib/Core/IScanFilter.cs
2,225
C#
using System; using System.Collections.Generic; using ReMi.BusinessEntities.ReleasePlan; namespace ReMi.DataAccess.BusinessEntityGateways.ReleasePlan { public interface ICheckListGateway : IDisposable { IEnumerable<CheckListItemView> GetCheckList(Guid releaseWindowId); List<CheckListQuestion> GetCheckListAdditionalQuestions(Guid releaseWindowId); List<String> GetCheckListQuestions(); CheckListItemView GetCheckListItem(Guid checkListId); void Create(Guid releaseWindowId); void UpdateAnswer(CheckListItem checkListItem); void UpdateComment(CheckListItem checkListItem); void AddCheckListQuestions(IEnumerable<CheckListQuestion> questions, Guid releaseWindowId); void AssociateCheckListQuestionWithPackage(IEnumerable<CheckListQuestion> questions, Guid releaseWindowId); void RemoveCheckListQuestion(Guid checkListItemId); void RemoveCheckListQuestionForPackage(Guid checkListItemId); } }
43.173913
115
0.783484
[ "MIT" ]
vishalishere/remi
ReMi.Api/DataAccess/ReMi.DataAccess/BusinessEntityGateways/ReleasePlan/ICheckListGateway.cs
993
C#
namespace WebServer.ByTheCakeApplication.Data { internal class Configuration { internal static string ConnectionString => @""; } }
19
55
0.684211
[ "MIT" ]
PeterAsenov22/My-Cool-Web-Server
WebServer/ByTheCakeApplication/Data/Configuration.cs
154
C#
using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Security.Claims; using System.Text.Json; using System.Threading.Tasks; using System.Web; using System.Web.Helpers; using System.Web.Mvc; using System.Web.Routing; using GSS.Authentication.CAS; using GSS.Authentication.CAS.Owin; using GSS.Authentication.CAS.Security; using GSS.Authentication.CAS.Validation; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Owin; using Microsoft.Owin.Host.SystemWeb; using Microsoft.Owin.Security; using Microsoft.Owin.Security.Cookies; using NLog; using NLog.Owin.Logging; using Owin; using Owin.OAuthGeneric; [assembly: OwinStartup(typeof(OwinSingleSignOutSample.Startup))] namespace OwinSingleSignOutSample { public class Startup { private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); private static IConfiguration _configuration; private static IServiceProvider _resolver; public void Configuration(IAppBuilder app) { var env = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Production"; _configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .AddJsonFile($"appsettings.{env}.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); var services = new ServiceCollection(); ConfigureServices(services); _resolver = services.BuildServiceProvider(); // MVC GlobalFilters.Filters.Add(new AuthorizeAttribute()); GlobalFilters.Filters.Add(new HandleErrorAttribute()); RouteTable.Routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier; // configure nlog.config per environment var configFile = new FileInfo(Path.Combine(AppContext.BaseDirectory, $"NLog.{env}.config")); LogManager.LoadConfiguration(configFile.Exists ? configFile.Name : "NLog.config"); app.UseNLog(); app.UseCasSingleSignOut(_resolver.GetRequiredService<IAuthenticationSessionStore>()); app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions { LoginPath = CookieAuthenticationDefaults.LoginPath, LogoutPath = CookieAuthenticationDefaults.LogoutPath, // https://github.com/aspnet/AspNetKatana/wiki/System.Web-response-cookie-integration-issues CookieManager = new SystemWebCookieManager(), SessionStore = _resolver.GetRequiredService<IAuthenticationSessionStore>(), Provider = new CookieAuthenticationProvider { OnResponseSignOut = context => { // Single Sign-Out var casUrl = new Uri(_configuration["Authentication:CAS:ServerUrlBase"]); var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext); var serviceUrl = urlHelper.Action("Index", "Home", null, HttpContext.Current.Request.Url.Scheme); var redirectUri = new UriBuilder(casUrl); redirectUri.Path += "/logout"; redirectUri.Query = $"service={Uri.EscapeDataString(serviceUrl)}"; var logoutRedirectContext = new CookieApplyRedirectContext ( context.OwinContext, context.Options, redirectUri.Uri.AbsoluteUri ); context.Options.Provider.ApplyRedirect(logoutRedirectContext); } } }); app.UseCasAuthentication(options => { options.CasServerUrlBase = _configuration["Authentication:CAS:ServerUrlBase"]; options.ServiceUrlBase = _configuration.GetValue<Uri>("Authentication:CAS:ServiceUrlBase"); // https://github.com/aspnet/AspNetKatana/wiki/System.Web-response-cookie-integration-issues options.CookieManager = new SystemWebCookieManager(); // required for CasSingleSignOutMiddleware options.UseAuthenticationSessionStore = true; var protocolVersion = _configuration.GetValue("Authentication:CAS:ProtocolVersion", 3); if (protocolVersion != 3) { switch (protocolVersion) { case 1: options.ServiceTicketValidator = new Cas10ServiceTicketValidator(options); break; case 2: options.ServiceTicketValidator = new Cas20ServiceTicketValidator(options); break; } } options.Provider = new CasAuthenticationProvider { OnCreatingTicket = context => { var assertion = (context.Identity as CasIdentity)?.Assertion; if (assertion == null) return Task.CompletedTask; // Map claims from assertion context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, assertion.PrincipalName)); if (assertion.Attributes.TryGetValue("display_name", out var displayName)) { context.Identity.AddClaim(new Claim(ClaimTypes.Name, displayName)); } if (assertion.Attributes.TryGetValue("email", out var email)) { context.Identity.AddClaim(new Claim(ClaimTypes.Email, email)); } return Task.CompletedTask; }, OnRemoteFailure = context => { var failure = context.Failure; _logger.Error(failure, failure.Message); context.Response.Redirect("/Account/ExternalLoginFailure"); context.HandleResponse(); return Task.CompletedTask; } }; }); app.UseOAuthAuthentication(options => { options.ClientId = _configuration["Authentication:OAuth:ClientId"]; options.ClientSecret = _configuration["Authentication:OAuth:ClientSecret"]; options.AuthorizationEndpoint = _configuration["Authentication:OAuth:AuthorizationEndpoint"]; options.TokenEndpoint = _configuration["Authentication:OAuth:TokenEndpoint"]; options.UserInformationEndpoint = _configuration["Authentication:OAuth:UserInformationEndpoint"]; options.Events = new OAuthEvents { OnCreatingTicket = async context => { // Get the OAuth user using var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken); using var response = await context.Backchannel.SendAsync(request, context.Request.CallCancelled).ConfigureAwait(false); if (!response.IsSuccessStatusCode || response.Content?.Headers?.ContentType?.MediaType.StartsWith("application/json") != true) { var responseText = response.Content == null ? string.Empty : await response.Content.ReadAsStringAsync().ConfigureAwait(false); _logger.Error($"An error occurred when retrieving OAuth user information ({response.StatusCode}). {responseText}"); return; } using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); using var json = await JsonDocument.ParseAsync(stream).ConfigureAwait(false); var user = json.RootElement; if (user.TryGetProperty("id", out var id)) { context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, id.GetString())); } if (user.TryGetProperty("attributes", out var attributes)) { if (attributes.TryGetProperty("display_name", out var displayName)) { context.Identity.AddClaim(new Claim(ClaimTypes.Name, displayName.GetString())); } if (attributes.TryGetProperty("email", out var email)) { context.Identity.AddClaim(new Claim(ClaimTypes.Email, email.GetString())); } } }, OnRemoteFailure = context => { var failure = context.Failure; _logger.Error(failure, failure.Message); context.Response.Redirect("/Account/ExternalLoginFailure"); context.HandleResponse(); return Task.CompletedTask; } }; }); } private static void ConfigureServices(IServiceCollection services) { var redisConfiguration = _configuration.GetConnectionString("Redis"); if (!string.IsNullOrWhiteSpace(redisConfiguration)) { services.AddStackExchangeRedisCache(options => options.Configuration = redisConfiguration); } else { services.AddDistributedMemoryCache(); } services .AddSingleton(_configuration) .AddSingleton<IServiceTicketStore, DistributedCacheServiceTicketStore>() .AddSingleton<IAuthenticationSessionStore, AuthenticationSessionStoreWrapper>() .BuildServiceProvider(); } } }
49.120536
150
0.558757
[ "MIT" ]
ahmadh21/GSS.Authentication.CAS
samples/OwinSingleSignOutSample/Startup.cs
11,003
C#
using System; using System.Collections.Generic; using Newtonsoft.Json; using Stripe.Infrastructure; namespace Stripe { public class StripeSubscriptionCreateOptions : SubscriptionSharedOptions { /// <summary> /// A future date to anchor the subscription’s <see href="https://stripe.com/docs/subscriptions/billing-cycle">billing cycle</see>. This is used to determine the date of the first full invoice, and, for plans with <c>month</c> or <c>year</c> intervals, the day of the month for subsequent invoices. /// </summary> public DateTime? BillingCycleAnchor { get; set; } [JsonProperty("billing_cycle_anchor")] internal long? BillingCycleAnchorInternal { get { if (!BillingCycleAnchor.HasValue) return null; return EpochTime.ConvertDateTimeToEpoch(BillingCycleAnchor.Value); } } /// <summary> /// REQUIRED: The identifier of the customer to subscribe. /// </summary> [JsonProperty("customer")] public string CustomerId { get; set; } /// <summary> /// List of subscription items, each with an attached plan. /// </summary> // this will actually send `items`. this is to flag it for the middleware // to process it as a plugin [JsonProperty("subscription_items_array")] public List<StripeSubscriptionItemOption> Items { get; set; } /// <summary> /// Integer representing the number of trial period days before the customer is charged for the first time. /// </summary> [JsonProperty("trial_period_days")] public int? TrialPeriodDays { get; set; } } }
36.93617
306
0.633065
[ "Apache-2.0" ]
TrueNorthIT/stripe-dotnet
src/Stripe.net/Services/Subscriptions/StripeSubscriptionCreateOptions.cs
1,740
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Diagnostics; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.Identity.Test.Common.Core.Helpers { public class PerformanceValidator : IDisposable { private readonly long _maxMilliseconds; private readonly string _message; private readonly Stopwatch _stopwatch; public PerformanceValidator(long maxMilliseconds, string message) { _maxMilliseconds = maxMilliseconds; _message = message; _stopwatch = Stopwatch.StartNew(); } public void Dispose() { _stopwatch.Stop(); long elapsedMilliseconds = _stopwatch.ElapsedMilliseconds; if (elapsedMilliseconds > _maxMilliseconds) { Assert.Fail( $"Measured performance time EXCEEDED. Max allowed: {_maxMilliseconds}ms. Elapsed: {elapsedMilliseconds}. {_message}"); } else { Debug.WriteLine( $"Measured performance time OK. Max allowed: {_maxMilliseconds}ms. Elapsed: {elapsedMilliseconds}. {_message}"); } } } }
31.634146
142
0.615266
[ "MIT" ]
SpillChek2/microsoft-authentication-library-for-dotnet
tests/Microsoft.Identity.Test.Common/Core/Helpers/PerformanceValidator.cs
1,299
C#
using Forum.Application.Common; using Forum.Application.PublicUsers.Posts; using Forum.Application.PublicUsers.Posts.Queries.Details; using MediatR; using System.Threading; using System.Threading.Tasks; namespace Forum.Application.PublicUsers.Users.Queries.Common { public class PostDetailsQuery : EntityCommand<int>, IRequest<PostDetailsOutputModel> { public class PostDetailsQueryHandler : IRequestHandler<PostDetailsQuery, PostDetailsOutputModel> { private readonly IPostQueryRepository postRepository; private readonly IPublicUserQueryRepository userRepository; public PostDetailsQueryHandler( IPostQueryRepository postRepository, IPublicUserQueryRepository userRepository) { this.postRepository = postRepository; this.userRepository = userRepository; } public async Task<PostDetailsOutputModel> Handle( PostDetailsQuery request, CancellationToken cancellationToken) { var postDetails = await this.postRepository.GetDetails( request.Id, cancellationToken); postDetails.UserName = (await this.userRepository.GetDetailsByPostId( request.Id, cancellationToken)).UserName; return postDetails; } } } }
34.857143
104
0.64276
[ "Apache-2.0" ]
StanilDimitrov/Forum
src/Application/Forum.Application/PublicUsers/Posts/Queries/Details/PostDetailsQuery.cs
1,466
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using ILRuntime.CLR.TypeSystem; using ILRuntime.CLR.Method; using ILRuntime.Runtime.Enviorment; using ILRuntime.Runtime.Intepreter; using ILRuntime.Runtime.Stack; using ILRuntime.Reflection; using ILRuntime.CLR.Utils; namespace ILRuntime.Runtime.Generated { unsafe class UnityEngine_RaycastHit_Binding { public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app) { BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; MethodBase method; Type[] args; Type type = typeof(UnityEngine.RaycastHit); args = new Type[]{}; method = type.GetMethod("get_point", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_point_0); app.RegisterCLRCreateDefaultInstance(type, () => new UnityEngine.RaycastHit()); } static void WriteBackInstance(ILRuntime.Runtime.Enviorment.AppDomain __domain, StackObject* ptr_of_this_method, IList<object> __mStack, ref UnityEngine.RaycastHit instance_of_this_method) { ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method); switch(ptr_of_this_method->ObjectType) { case ObjectTypes.Object: { __mStack[ptr_of_this_method->Value] = instance_of_this_method; } break; case ObjectTypes.FieldReference: { var ___obj = __mStack[ptr_of_this_method->Value]; if(___obj is ILTypeInstance) { ((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = instance_of_this_method; } else { var t = __domain.GetType(___obj.GetType()) as CLRType; t.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, instance_of_this_method); } } break; case ObjectTypes.StaticFieldReference: { var t = __domain.GetType(ptr_of_this_method->Value); if(t is ILType) { ((ILType)t).StaticInstance[ptr_of_this_method->ValueLow] = instance_of_this_method; } else { ((CLRType)t).SetStaticFieldValue(ptr_of_this_method->ValueLow, instance_of_this_method); } } break; case ObjectTypes.ArrayReference: { var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as UnityEngine.RaycastHit[]; instance_of_arrayReference[ptr_of_this_method->ValueLow] = instance_of_this_method; } break; } } static StackObject* get_point_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method); UnityEngine.RaycastHit instance_of_this_method = (UnityEngine.RaycastHit)typeof(UnityEngine.RaycastHit).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); var result_of_this_method = instance_of_this_method.point; ptr_of_this_method = ILIntepreter.Minus(__esp, 1); WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method); __intp.Free(ptr_of_this_method); return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method); } } }
43.349515
196
0.581411
[ "MIT" ]
InMyBload/et6.0-ilruntime
Unity/Assets/Clod/ILBinding/UnityEngine_RaycastHit_Binding.cs
4,465
C#
#region BSD License /* * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE.md file or at * https://github.com/Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.450/blob/master/LICENSE * */ #endregion using ComponentFactory.Krypton.Toolkit; using System; using System.ComponentModel; using System.Drawing; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; namespace ExtendedControls.ExtendedToolkit.Controls { /// <summary> /// A KryptonCommandLink button. /// Boilerplate code from (https://blogs.msdn.microsoft.com/knom/2007/03/12/vista-command-link-control-with-c-windows-forms/) /// </summary> /// <remarks> /// If used on Windows Vista or higher, the button will be a CommandLink: Basically the same functionality as a Button but looks different. /// </remarks> [DesignerCategory("Code")] [DisplayName("Krypton Command Link")] [Description("A Krypton Command Link Button.")] [ToolboxItem(true)] [ToolboxBitmap(typeof(KryptonButton))] public class KryptonCommandLinkVersion2 : KryptonButton { #region Variables private bool _showUACShield = false; #endregion #region Properties /// <summary> /// Gets or sets the shield icon visibility of the command link. /// </summary> [Category("Command Link"), Description("Gets or sets the shield icon visibility of the command link."), DefaultValue(false)] public bool ShowUACShield { get { return _showUACShield; } set { _showUACShield = value; SendMessage(new HandleRef(this, this.Handle), BCM_SETSHIELD, IntPtr.Zero, _showUACShield); } } /// <summary> /// Gets or sets the note text of the command link. /// </summary> [Category("Command Link"), Description("Gets or sets the note text of the command link."), DefaultValue("")] public string NoteText { get { return GetNoteText(); } set { SetNoteText(value); } } #endregion #region WIN32 Calls [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern int SendMessage(HandleRef hWnd, UInt32 msg, ref int wParam, StringBuilder lParam); [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern int SendMessage(HandleRef hWnd, UInt32 msg, IntPtr wParam, string lParam); [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern int SendMessage(HandleRef hWnd, UInt32 msg, IntPtr wParam, bool lParam); [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern int SendMessage(HandleRef hWnd, UInt32 msg, IntPtr wParam, IntPtr lParam); #endregion #region Constants const int BS_COMMANDLINK = 0x0000000E, BCM_SETNOTE = 0x00001609, BCM_GETNOTE = 0x0000160A, BCM_GETNOTELENGTH = 0x0000160B, BCM_SETSHIELD = 0x0000160C; #endregion #region Constructor /// <summary> /// Initialises a new instance of the <see cref="KryptonCommandLinkVersion2"/> class. /// </summary> public KryptonCommandLinkVersion2() { } #endregion #region Overrides protected override Size DefaultSize { get { return new Size(160, 60); } } protected override CreateParams CreateParams { get { CreateParams createParams = base.CreateParams; createParams.Style |= BS_COMMANDLINK; return createParams; } } #endregion #region Setter and Getter Methods /// <summary> /// Sets the NoteText to the value of value. /// </summary> /// <param name="value">The desired value of NoteText.</param> private void SetNoteText(string value) { SendMessage(new HandleRef(this, this.Handle), BCM_SETNOTE, IntPtr.Zero, value); } /// <summary> /// Returns the value of the NoteText. /// </summary> /// <returns>The value of the NoteText.</returns> private string GetNoteText() { int _length = SendMessage(new HandleRef(this, this.Handle), BCM_GETNOTELENGTH, IntPtr.Zero, IntPtr.Zero) + 1; StringBuilder stringBuilder = new StringBuilder(_length); SendMessage(new HandleRef(this, this.Handle), BCM_GETNOTE, ref _length, stringBuilder); return stringBuilder.ToString(); } #endregion } }
31.907895
158
0.603093
[ "BSD-3-Clause" ]
Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.450
Source/Krypton Toolkit Suite Extended/Full Toolkit/Extended Controls/ExtendedToolkit/Controls/Krypton Controls/KryptonCommandLinkVersion2.cs
4,852
C#
using Microsoft.Azure.ServiceManagemenet.Common.Models; using Microsoft.WindowsAzure.Commands.ScenarioTest; using Xunit; namespace Microsoft.Azure.Commands.Compute.Test.ScenarioTests { public class SqlIaaSExtensionTests { XunitTracingInterceptor _logger; public SqlIaaSExtensionTests(Xunit.Abstractions.ITestOutputHelper output) { _logger = new XunitTracingInterceptor(output); XunitTracingInterceptor.AddToContext(_logger); } #if NETSTANDARD [Fact(Skip = "Resources -> ResourceManager, needs re-recorded")] [Trait(Category.RunType, Category.DesktopOnly)] #else [Fact] #endif [Trait(Category.AcceptanceType, Category.CheckIn)] public void TestSqlIaaSExtension() { ComputeTestController.NewInstance.RunPsTest(_logger, "Test-SetAzureRmVMSqlServerExtension"); } #if NETSTANDARD [Fact(Skip = "Resources -> ResourceManager, needs re-recorded")] [Trait(Category.RunType, Category.DesktopOnly)] #else [Fact] #endif [Trait(Category.AcceptanceType, Category.CheckIn)] public void TestSqlIaaSAKVExtension() { ComputeTestController.NewInstance.RunPsTest(_logger, "Test-SetAzureRmVMSqlServerAKVExtension"); } #if NETSTANDARD [Fact(Skip = "Resources -> ResourceManager, needs re-recorded")] [Trait(Category.RunType, Category.DesktopOnly)] #else [Fact] #endif [Trait(Category.AcceptanceType, Category.CheckIn)] public void TestSqlIaaSExtensionWith2016Image() { ComputeTestController.NewInstance.RunPsTest(_logger, "Test-SetAzureRmVMSqlServerExtensionWith2016Image"); } } }
33.148148
118
0.670391
[ "MIT" ]
PrakharSaxena-31/azure-powershell
src/ResourceManager/Compute/Commands.Compute.Test/ScenarioTests/SqlIaaSExtensionTests.cs
1,739
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("YTSubConverter.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("YTSubConverter.Tests")] [assembly: AssemblyCopyright("Copyright © 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、このアセンブリ内の型は COM コンポーネントから // 参照できなくなります。COM からこのアセンブリ内の型にアクセスする必要がある場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります [assembly: Guid("1a6d0829-801d-428b-b04b-65dd35b9f4f0")] // アセンブリのバージョン情報は、以下の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // リビジョン // // すべての値を指定するか、次を使用してビルド番号とリビジョン番号を既定に設定できます // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
30.648649
57
0.728395
[ "MIT" ]
Meigyoku-Thmn/YTSubConverter
YTSubConverter.Tests/Properties/AssemblyInfo.cs
1,735
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** 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.Aws.WafV2.Inputs { public sealed class WebAclRuleStatementOrStatementStatementOrStatementStatementOrStatementStatementRegexPatternSetReferenceStatementFieldToMatchArgs : Pulumi.ResourceArgs { /// <summary> /// Inspect all query arguments. /// </summary> [Input("allQueryArguments")] public Input<Inputs.WebAclRuleStatementOrStatementStatementOrStatementStatementOrStatementStatementRegexPatternSetReferenceStatementFieldToMatchAllQueryArgumentsArgs>? AllQueryArguments { get; set; } /// <summary> /// Inspect the request body, which immediately follows the request headers. /// </summary> [Input("body")] public Input<Inputs.WebAclRuleStatementOrStatementStatementOrStatementStatementOrStatementStatementRegexPatternSetReferenceStatementFieldToMatchBodyArgs>? Body { get; set; } /// <summary> /// Inspect the HTTP method. The method indicates the type of operation that the request is asking the origin to perform. /// </summary> [Input("method")] public Input<Inputs.WebAclRuleStatementOrStatementStatementOrStatementStatementOrStatementStatementRegexPatternSetReferenceStatementFieldToMatchMethodArgs>? Method { get; set; } /// <summary> /// Inspect the query string. This is the part of a URL that appears after a `?` character, if any. /// </summary> [Input("queryString")] public Input<Inputs.WebAclRuleStatementOrStatementStatementOrStatementStatementOrStatementStatementRegexPatternSetReferenceStatementFieldToMatchQueryStringArgs>? QueryString { get; set; } /// <summary> /// Inspect a single header. See Single Header below for details. /// </summary> [Input("singleHeader")] public Input<Inputs.WebAclRuleStatementOrStatementStatementOrStatementStatementOrStatementStatementRegexPatternSetReferenceStatementFieldToMatchSingleHeaderArgs>? SingleHeader { get; set; } /// <summary> /// Inspect a single query argument. See Single Query Argument below for details. /// </summary> [Input("singleQueryArgument")] public Input<Inputs.WebAclRuleStatementOrStatementStatementOrStatementStatementOrStatementStatementRegexPatternSetReferenceStatementFieldToMatchSingleQueryArgumentArgs>? SingleQueryArgument { get; set; } /// <summary> /// Inspect the request URI path. This is the part of a web request that identifies a resource, for example, `/images/daily-ad.jpg`. /// </summary> [Input("uriPath")] public Input<Inputs.WebAclRuleStatementOrStatementStatementOrStatementStatementOrStatementStatementRegexPatternSetReferenceStatementFieldToMatchUriPathArgs>? UriPath { get; set; } public WebAclRuleStatementOrStatementStatementOrStatementStatementOrStatementStatementRegexPatternSetReferenceStatementFieldToMatchArgs() { } } }
52.967742
211
0.744823
[ "ECL-2.0", "Apache-2.0" ]
Otanikotani/pulumi-aws
sdk/dotnet/WafV2/Inputs/WebAclRuleStatementOrStatementStatementOrStatementStatementOrStatementStatementRegexPatternSetReferenceStatementFieldToMatchArgs.cs
3,284
C#
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using MyTryHard.Models; using MyTryHard.Models.Chart; using MyTryHard.Models.Tracker; using MyTryHard.ViewModels.Tracker; using System; using System.Collections.Generic; using System.Linq; namespace MyTryHard.Controllers { [Authorize] public class TrackerController : Controller { private ApplicationDbContext _ctx; private readonly UserManager<ApplicationUser> _userManager; private static Random _ran = new Random(); public TrackerController( UserManager<ApplicationUser> userManager, ApplicationDbContext ctx) { _userManager = userManager; _ctx = ctx; } public IActionResult Index() { TrackerViewModel tvm = new TrackerViewModel(); var userId = _userManager.GetUserId(HttpContext.User); tvm.Entries = _ctx.Tracker.GetEntriesForUser(Guid.Parse(userId)); tvm.SportsList = _ctx.Tracker.GetSportsList(); ViewBag.PieData = new ChartData<string, double>(); GeneratePieItemsFromTracker(tvm, ViewBag.PieData); ViewBag.PieData.Title = "Proportions de suivi des sports"; return View(tvm); } [HttpPost] public IActionResult Save() { DateTime dtStart = new DateTime(int.Parse(Request.Form["startYear"]), int.Parse(Request.Form["startMonth"]), int.Parse(Request.Form["startDay"]), int.Parse(Request.Form["startHour"]), int.Parse(Request.Form["startMinute"]), int.Parse(Request.Form["startSecond"]), int.Parse(Request.Form["startMillis"])); DateTime dtEnd = new DateTime(int.Parse(Request.Form["endYear"]), int.Parse(Request.Form["endMonth"]), int.Parse(Request.Form["endDay"]), int.Parse(Request.Form["endHour"]), int.Parse(Request.Form["endMinute"]), int.Parse(Request.Form["endSecond"]), int.Parse(Request.Form["endMillis"])); int distance = int.Parse(Request.Form["distance"]); int sportId = int.Parse(Request.Form["SportId"]); var userId = _userManager.GetUserId(HttpContext.User); _ctx.Tracker.SaveEntryForUser(Guid.Parse(userId), dtStart, dtEnd, distance, sportId); return RedirectToAction("index"); } public IActionResult Add() { ViewBag.SportsList = _ctx.Tracker.GetSportsList(); return View(); } [Route("tracker/sport/{sportId:int?}")] public IActionResult Entries(int sportId = -1) { if (sportId == -1) return RedirectToAction("index"); TrackerViewModel tvm = new TrackerViewModel(); var userId = _userManager.GetUserId(HttpContext.User); tvm.Entries = _ctx.Tracker.GetEntriesForUserAndSport(Guid.Parse(userId), sportId); tvm.SportsList = _ctx.Tracker.GetSportsList(); ViewBag.SportId = sportId; return View("Index", tvm); } public IActionResult EntriesRedirect(int sportId) { return RedirectToAction("entries", new { sportId = sportId }); } public IActionResult GetSportDistributionGraph() { TrackerViewModel tvm = new TrackerViewModel(); var userId = _userManager.GetUserId(HttpContext.User); tvm.Entries = _ctx.Tracker.GetEntriesForUser(Guid.Parse(userId)); tvm.SportsList = _ctx.Tracker.GetSportsList(); ChartData<string, double> pie = new ChartData<string, double>(); GeneratePieItemsFromTracker(tvm, pie); return PartialView("Chart/PieChart", pie); } private static void GeneratePieItemsFromTracker(TrackerViewModel tvm, ChartData<string, double> pie) { foreach (KeyValuePair<int, string> kvp in tvm.SportsList) { double value = tvm.Entries.Where(x => x.SportId == kvp.Key).Count(); if (value == 0) continue; ChartItem<string, double> slice = new ChartItem<string, double>(); slice.ValueY = value; slice.LabelY = kvp.Value; slice.ValueX = kvp.Value; slice.LabelX = kvp.Value; slice.Color = ChartColorHelper.GetColorFromId(kvp.Key); pie.Items.Add(slice); } } } }
37.214286
108
0.593943
[ "BSD-2-Clause" ]
mrtryhard/mytryhard
src/MyTryHard/Controllers/TrackerController.cs
4,691
C#
namespace KmLog.Server.Blazor.Shared { public partial class LoginDisplay { } }
13.142857
37
0.673913
[ "MIT" ]
JPineker/km-log
KmLog.Server/KmLog.Server.Blazor/Shared/LoginDisplay.razor.cs
94
C#
using Microsoft.Win32; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using System.Windows; namespace NegativeEncoder.FileSelector { public delegate void FileListChangeEvent(int pos); public class FileSelector { public ObservableCollection<FileInfo> Files { get; set; } = new ObservableCollection<FileInfo>(); public event FileListChangeEvent OnFileListChange; public int BrowseImportFiles() { var ofd = new OpenFileDialog { CheckFileExists = true, CheckPathExists = true, Multiselect = true }; if (ofd.ShowDialog() == true) { return AddFiles(ofd.FileNames); } return -1; } public int AddFiles(string[] fileNames) { var succ = 0; var firstPos = Files.Count; var notFiles = new List<string>(); var errFiles = new List<string>(); foreach (var file in fileNames) { var newFile = new FileInfo(file); if (!System.IO.File.Exists(file)) { notFiles.Add(file); } else if (Files.Contains(newFile)) { errFiles.Add(file); } else { Files.Add(newFile); succ++; } } if (errFiles.Count > 0 || notFiles.Count > 0) { var msg = ""; if (errFiles.Count > 0) { msg += $"以下 {errFiles.Count} 个文件已存在于列表中,未能导入:\n{string.Join("\n", errFiles)}\n\n"; } if (notFiles.Count > 0) { msg += $"以下 {notFiles.Count} 个文件是不支持的格式或无法读取,未能导入:\n{string.Join("\n", notFiles)}\n\n"; } MessageBox.Show(msg, "文件导入中出现问题", MessageBoxButton.OK, MessageBoxImage.Asterisk); } if (succ > 0) return firstPos; else return -1; } public List<FileInfo> RemoveFiles(System.Collections.IList files) { var tempRemoveList = new List<FileInfo>(); if (files != null && files.Count > 0) { foreach (var f in files) { tempRemoveList.Add(f as FileInfo); } if (tempRemoveList.Count > 0) { foreach(var tf in tempRemoveList) { Files.Remove(tf); } } } return tempRemoveList; } public void NotifyChanged(int pos) { OnFileListChange?.Invoke(pos); } public void Clear() { Files.Clear(); } } public class FileInfo : IEquatable<FileInfo> { public string Path { get; set; } public string Filename { get; set; } public FileInfo(string path) { Path = path; Filename = System.IO.Path.GetFileNameWithoutExtension(path); } public override bool Equals(object obj) { return Equals(obj as FileInfo); } public bool Equals(FileInfo other) { return other != null && Path == other.Path; } public override int GetHashCode() { return Path.GetHashCode(); } } }
26.815603
107
0.448294
[ "MIT" ]
hoshinohikari/NegativeEncoder
NegativeEncoder/FileSelector/FileSelector.cs
3,883
C#
namespace PointerPlace.Scheduler { /// <summary> /// Parses a cron style schedule string into a Schedule so that the engine /// can determine the next value in the schedule. /// </summary> public interface IScheduleParser { /// <summary> /// Parses the provided schedule string into a Schedule /// </summary> /// <param name="scheduleString">The schedule string to parse into a Schedule</param> /// <returns>The Schedule that was parsed from the provided schedule string</returns> Schedule ParseSchedule(string scheduleString); } }
38
93
0.657895
[ "Apache-2.0" ]
ivanpointer/Scheduler
PointerPlace.Scheduler/PointerPlace.Scheduler/IScheduleParser.cs
610
C#
using System; using System.Collections; using System.Collections.Generic; using System.IO; namespace HP_Core { //https://www.codeguru.com/csharp/.net/net_general/creating-a-most-recently-used-menu-list-in-.net.html class Program { private static Queue<string> menuList = new Queue<string>(); static void Main(string[] args) { //menuList.Enqueue("Kevin"); //menuList.Enqueue("Jerry"); //menuList.Enqueue("Adam"); //menuList.Enqueue("Julio"); //// Most recetnly used Menu List. //menuList.Dequeue(); foreach (var check in menuList) { Console.WriteLine(check); } } private void SaveRecentFile(string strPath) { // clear drop down or whatever. // Load Recent List(); // if menu list eimpty..? // menu list Enqueue (path); // while menu list is equal or larger than 5. // then dequeue call menulist.Dequeue(); //foreach (string strItem in MRUlist) //{ // ToolStripMenuItem tsRecent = new // ToolStripMenuItem(strItem, null); // RecentToolStripMenuItem.DropDownItems.Add(tsRecent); //} StreamWriter strToWRite = new StreamWriter(System.Environment.CurrentDirectory + @"\Recent.txt"); foreach (string item in menuList) { strToWRite.WriteLine(item); } strToWRite.Flush(); strToWRite.Close(); } private void LoadRecentList() { menuList.Clear(); try { StreamReader srStream = new StreamReader (Environment.CurrentDirectory + @"\Recent.txt"); string strLine = ""; while ((InlineAssignHelper(ref strLine, srStream.ReadLine())) != null) //MRUlist.Enqueue(strLine); srStream.Close(); } catch (Exception ex) { Console.WriteLine(ex.Message); //MessageBox.Show("Error"); } } private static T InlineAssignHelper<T>(ref T target, T value) { target = value; return value; } } }
26.769231
109
0.502874
[ "MIT" ]
hyunbin7303/HPCoreApp
HP_Core/HP_Core/Program.cs
2,438
C#
using System; namespace Arbiter.Areas.HelpPage { /// <summary> /// This represents a preformatted text sample on the help page. There's a display template named TextSample associated with this class. /// </summary> public class TextSample { public TextSample(string text) { if (text == null) { throw new ArgumentNullException("text"); } Text = text; } public string Text { get; private set; } public override bool Equals(object obj) { TextSample other = obj as TextSample; return other != null && Text == other.Text; } public override int GetHashCode() { return Text.GetHashCode(); } public override string ToString() { return Text; } } }
23.864865
140
0.531144
[ "MIT" ]
lilin19/Arbiter.net
Arbiter/Areas/HelpPage/SampleGeneration/TextSample.cs
883
C#
#region using System; using System.Collections.Generic; using Confuser.Core; using Confuser.Core.Services; using Confuser.DynCipher; using Confuser.DynCipher.AST; using Confuser.DynCipher.Generation; using Confuser.Renamer; using dnlib.DotNet; using dnlib.DotNet.Emit; using dnlib.DotNet.Writer; using MethodBody = dnlib.DotNet.Writer.MethodBody; #endregion namespace Confuser.Protections.ReferenceProxy { internal class x86Encoding : IRPEncoding { private readonly Dictionary<MethodDef, Tuple<MethodDef, Func<int, int>>> keys = new Dictionary<MethodDef, Tuple<MethodDef, Func<int, int>>>(); private readonly List<Tuple<MethodDef, byte[], MethodBody>> nativeCodes = new List<Tuple<MethodDef, byte[], MethodBody>>(); private bool addedHandler; public Instruction[] EmitDecode(MethodDef init, RPContext ctx, Instruction[] arg) { var key = GetKey(ctx, init); var repl = new List<Instruction>(); repl.AddRange(arg); repl.Add(Instruction.Create(OpCodes.Call, key.Item1)); return repl.ToArray(); } public int Encode(MethodDef init, RPContext ctx, int value) { var key = GetKey(ctx, init); return key.Item2(value); } private void Compile(RPContext ctx, out Func<int, int> expCompiled, out MethodDef native) { var var = new Variable("{VAR}"); var result = new Variable("{RESULT}"); var int32 = ctx.Module.CorLibTypes.Int32; native = new MethodDefUser(ctx.Context.Registry.GetService<INameService>().RandomName(), MethodSig.CreateStatic(int32, int32), MethodAttributes.PinvokeImpl | MethodAttributes.PrivateScope | MethodAttributes.Static); native.ImplAttributes = MethodImplAttributes.Native | MethodImplAttributes.Unmanaged | MethodImplAttributes.PreserveSig; ctx.Module.GlobalType.Methods.Add(native); ctx.Context.Registry.GetService<IMarkerService>().Mark(native, ctx.Protection); ctx.Context.Registry.GetService<INameService>().SetCanRename(native, false); x86Register? reg; var codeGen = new x86CodeGen(); Expression expression, inverse; do { ctx.DynCipher.GenerateExpressionPair( ctx.Random, new VariableExpression {Variable = var}, new VariableExpression {Variable = result}, ctx.Depth, out expression, out inverse); reg = codeGen.GenerateX86(inverse, (v, r) => { return new[] {x86Instruction.Create(x86OpCode.POP, new x86RegisterOperand(r))}; }); } while(reg == null); var code = CodeGenUtils.AssembleCode(codeGen, reg.Value); expCompiled = new DMCodeGen(typeof(int), new[] {Tuple.Create("{VAR}", typeof(int))}) .GenerateCIL(expression) .Compile<Func<int, int>>(); nativeCodes.Add(Tuple.Create(native, code, (MethodBody) null)); if(!addedHandler) { ctx.Context.CurrentModuleWriterListener.OnWriterEvent += InjectNativeCode; addedHandler = true; } } private void InjectNativeCode(object sender, ModuleWriterListenerEventArgs e) { var writer = (ModuleWriterBase) sender; if(e.WriterEvent == ModuleWriterEvent.MDEndWriteMethodBodies) for(var n = 0; n < nativeCodes.Count; n++) nativeCodes[n] = new Tuple<MethodDef, byte[], MethodBody>( nativeCodes[n].Item1, nativeCodes[n].Item2, writer.MethodBodies.Add(new MethodBody(nativeCodes[n].Item2))); else if(e.WriterEvent == ModuleWriterEvent.EndCalculateRvasAndFileOffsets) foreach(var native in nativeCodes) { var rid = writer.MetaData.GetRid(native.Item1); writer.MetaData.TablesHeap.MethodTable[rid].RVA = (uint) native.Item3.RVA; } } private Tuple<MethodDef, Func<int, int>> GetKey(RPContext ctx, MethodDef init) { Tuple<MethodDef, Func<int, int>> ret; if(!keys.TryGetValue(init, out ret)) { Func<int, int> keyFunc; MethodDef native; Compile(ctx, out keyFunc, out native); keys[init] = ret = Tuple.Create(native, keyFunc); } return ret; } private class CodeGen : CILCodeGen { private readonly Instruction[] arg; public CodeGen(Instruction[] arg, MethodDef method, IList<Instruction> instrs) : base(method, instrs) { this.arg = arg; } protected override void LoadVar(Variable var) { if(var.Name == "{RESULT}") foreach(var instr in arg) Emit(instr); else base.LoadVar(var); } } } }
39.189394
227
0.586507
[ "MIT" ]
Dekryptor/KoiVM-Virtualization
Confuser.Protections/ReferenceProxy/x86Encoding.cs
5,175
C#
//------------------------------------------------------------ // Game Framework v3.x // Copyright © 2013-2017 Jiang Yin. All rights reserved. // Homepage: http://gameframework.cn/ // Feedback: mailto:jiangyin@gameframework.cn //------------------------------------------------------------ using System.Reflection; using UnityEditor; using UnityGameFramework.Runtime; namespace UnityGameFramework.Editor { [CustomEditor(typeof(ResourceComponent))] internal sealed class ResourceComponentInspector : GameFrameworkInspector { private SerializedProperty m_ResourceMode = null; private SerializedProperty m_ReadWritePathType = null; private SerializedProperty m_UnloadUnusedAssetsInterval = null; private SerializedProperty m_AssetAutoReleaseInterval = null; private SerializedProperty m_AssetCapacity = null; private SerializedProperty m_AssetExpireTime = null; private SerializedProperty m_AssetPriority = null; private SerializedProperty m_ResourceAutoReleaseInterval = null; private SerializedProperty m_ResourceCapacity = null; private SerializedProperty m_ResourceExpireTime = null; private SerializedProperty m_ResourcePriority = null; private SerializedProperty m_UpdatePrefixUri = null; private SerializedProperty m_UpdateRetryCount = null; private SerializedProperty m_InstanceRoot = null; private SerializedProperty m_LoadResourceAgentHelperCount = null; private FieldInfo m_EditorResourceModeFieldInfo = null; private string[] m_ResourceModeNames = new string[] { "Package", "Updatable" }; private int m_ResourceModeIndex = 0; private HelperInfo<ResourceHelperBase> m_ResourceHelperInfo = new HelperInfo<ResourceHelperBase>("Resource"); private HelperInfo<LoadResourceAgentHelperBase> m_LoadResourceAgentHelperInfo = new HelperInfo<LoadResourceAgentHelperBase>("LoadResourceAgent"); public override void OnInspectorGUI() { base.OnInspectorGUI(); serializedObject.Update(); ResourceComponent t = (ResourceComponent)target; bool isEditorResourceMode = (bool)m_EditorResourceModeFieldInfo.GetValue(target); if (isEditorResourceMode) { EditorGUILayout.HelpBox("Editor resource mode is enabled. Some options are disabled.", MessageType.Warning); } EditorGUI.BeginDisabledGroup(EditorApplication.isPlayingOrWillChangePlaymode); { if (EditorApplication.isPlaying && PrefabUtility.GetPrefabType(t.gameObject) != PrefabType.Prefab) { EditorGUILayout.EnumPopup("Resource Mode", t.ResourceMode); } else { int selectedIndex = EditorGUILayout.Popup("Resource Mode", m_ResourceModeIndex, m_ResourceModeNames); if (selectedIndex != m_ResourceModeIndex) { m_ResourceModeIndex = selectedIndex; m_ResourceMode.enumValueIndex = selectedIndex + 1; } } m_ReadWritePathType.enumValueIndex = (int)(ReadWritePathType)EditorGUILayout.EnumPopup("Read Write Path Type", t.ReadWritePathType); } EditorGUI.EndDisabledGroup(); float unloadUnusedAssetsInterval = EditorGUILayout.Slider("Unload Unused Assets Interval", m_UnloadUnusedAssetsInterval.floatValue, 0f, 3600f); if (unloadUnusedAssetsInterval != m_UnloadUnusedAssetsInterval.floatValue) { if (EditorApplication.isPlaying) { t.UnloadUnusedAssetsInterval = unloadUnusedAssetsInterval; } else { m_UnloadUnusedAssetsInterval.floatValue = unloadUnusedAssetsInterval; } } EditorGUI.BeginDisabledGroup(EditorApplication.isPlaying && isEditorResourceMode); { float assetAutoReleaseInterval = EditorGUILayout.DelayedFloatField("Asset Auto Release Interval", m_AssetAutoReleaseInterval.floatValue); if (assetAutoReleaseInterval != m_AssetAutoReleaseInterval.floatValue) { if (EditorApplication.isPlaying) { t.AssetAutoReleaseInterval = assetAutoReleaseInterval; } else { m_AssetAutoReleaseInterval.floatValue = assetAutoReleaseInterval; } } int assetCapacity = EditorGUILayout.DelayedIntField("Asset Capacity", m_AssetCapacity.intValue); if (assetCapacity != m_AssetCapacity.intValue) { if (EditorApplication.isPlaying) { t.AssetCapacity = assetCapacity; } else { m_AssetCapacity.intValue = assetCapacity; } } float assetExpireTime = EditorGUILayout.DelayedFloatField("Asset Expire Time", m_AssetExpireTime.floatValue); if (assetExpireTime != m_AssetExpireTime.floatValue) { if (EditorApplication.isPlaying) { t.AssetExpireTime = assetExpireTime; } else { m_AssetExpireTime.floatValue = assetExpireTime; } } int assetPriority = EditorGUILayout.DelayedIntField("Asset Priority", m_AssetPriority.intValue); if (assetPriority != m_AssetPriority.intValue) { if (EditorApplication.isPlaying) { t.AssetPriority = assetPriority; } else { m_AssetPriority.intValue = assetPriority; } } float resourceAutoReleaseInterval = EditorGUILayout.DelayedFloatField("Resource Auto Release Interval", m_ResourceAutoReleaseInterval.floatValue); if (resourceAutoReleaseInterval != m_ResourceAutoReleaseInterval.floatValue) { if (EditorApplication.isPlaying) { t.ResourceAutoReleaseInterval = resourceAutoReleaseInterval; } else { m_ResourceAutoReleaseInterval.floatValue = resourceAutoReleaseInterval; } } int resourceCapacity = EditorGUILayout.DelayedIntField("Resource Capacity", m_ResourceCapacity.intValue); if (resourceCapacity != m_ResourceCapacity.intValue) { if (EditorApplication.isPlaying) { t.ResourceCapacity = resourceCapacity; } else { m_ResourceCapacity.intValue = resourceCapacity; } } float resourceExpireTime = EditorGUILayout.DelayedFloatField("Resource Expire Time", m_ResourceExpireTime.floatValue); if (resourceExpireTime != m_ResourceExpireTime.floatValue) { if (EditorApplication.isPlaying) { t.ResourceExpireTime = resourceExpireTime; } else { m_ResourceExpireTime.floatValue = resourceExpireTime; } } int resourcePriority = EditorGUILayout.DelayedIntField("Resource Priority", m_ResourcePriority.intValue); if (resourcePriority != m_ResourcePriority.intValue) { if (EditorApplication.isPlaying) { t.ResourcePriority = resourcePriority; } else { m_ResourcePriority.intValue = resourcePriority; } } if (m_ResourceModeIndex == 1) { string updatePrefixUri = EditorGUILayout.DelayedTextField("Update Prefix Uri", m_UpdatePrefixUri.stringValue); if (updatePrefixUri != m_UpdatePrefixUri.stringValue) { if (EditorApplication.isPlaying) { t.UpdatePrefixUri = updatePrefixUri; } else { m_UpdatePrefixUri.stringValue = updatePrefixUri; } } int updateRetryCount = EditorGUILayout.DelayedIntField("Update Retry Count", m_UpdateRetryCount.intValue); if (updateRetryCount != m_UpdateRetryCount.intValue) { if (EditorApplication.isPlaying) { t.UpdateRetryCount = resourceCapacity; } else { m_UpdateRetryCount.intValue = resourceCapacity; } } } } EditorGUI.EndDisabledGroup(); EditorGUI.BeginDisabledGroup(EditorApplication.isPlayingOrWillChangePlaymode); { EditorGUILayout.PropertyField(m_InstanceRoot); m_ResourceHelperInfo.Draw(); m_LoadResourceAgentHelperInfo.Draw(); m_LoadResourceAgentHelperCount.intValue = EditorGUILayout.IntSlider("Load Resource Agent Helper Count", m_LoadResourceAgentHelperCount.intValue, 1, 64); } EditorGUI.EndDisabledGroup(); if (EditorApplication.isPlaying && PrefabUtility.GetPrefabType(t.gameObject) != PrefabType.Prefab) { EditorGUILayout.LabelField("Read Only Path", t.ReadOnlyPath.ToString()); EditorGUILayout.LabelField("Read Write Path", t.ReadWritePath.ToString()); EditorGUILayout.LabelField("Current Variant", t.CurrentVariant ?? "<Unknwon>"); EditorGUILayout.LabelField("Applicable Game Version", isEditorResourceMode ? "N/A" : t.ApplicableGameVersion ?? "<Unknwon>"); EditorGUILayout.LabelField("Internal Resource Version", isEditorResourceMode ? "N/A" : t.InternalResourceVersion.ToString()); EditorGUILayout.LabelField("Asset Count", isEditorResourceMode ? "N/A" : t.AssetCount.ToString()); EditorGUILayout.LabelField("Resource Count", isEditorResourceMode ? "N/A" : t.ResourceCount.ToString()); EditorGUILayout.LabelField("Resource Group Count", isEditorResourceMode ? "N/A" : t.ResourceGroupCount.ToString()); if (m_ResourceModeIndex == 1) { EditorGUILayout.LabelField("Update Waiting Count", isEditorResourceMode ? "N/A" : t.UpdateWaitingCount.ToString()); EditorGUILayout.LabelField("Updating Count", isEditorResourceMode ? "N/A" : t.UpdatingCount.ToString()); } EditorGUILayout.LabelField("Load Total Agent Count", isEditorResourceMode ? "N/A" : t.LoadTotalAgentCount.ToString()); EditorGUILayout.LabelField("Load Free Agent Count", isEditorResourceMode ? "N/A" : t.LoadFreeAgentCount.ToString()); EditorGUILayout.LabelField("Load Working Agent Count", isEditorResourceMode ? "N/A" : t.LoadWorkingAgentCount.ToString()); EditorGUILayout.LabelField("Load Waiting Task Count", isEditorResourceMode ? "N/A" : t.LoadWaitingTaskCount.ToString()); } serializedObject.ApplyModifiedProperties(); Repaint(); } protected override void OnCompileComplete() { base.OnCompileComplete(); RefreshTypeNames(); } private void OnEnable() { m_ResourceMode = serializedObject.FindProperty("m_ResourceMode"); m_ReadWritePathType = serializedObject.FindProperty("m_ReadWritePathType"); m_UnloadUnusedAssetsInterval = serializedObject.FindProperty("m_UnloadUnusedAssetsInterval"); m_AssetAutoReleaseInterval = serializedObject.FindProperty("m_AssetAutoReleaseInterval"); m_AssetCapacity = serializedObject.FindProperty("m_AssetCapacity"); m_AssetExpireTime = serializedObject.FindProperty("m_AssetExpireTime"); m_AssetPriority = serializedObject.FindProperty("m_AssetPriority"); m_ResourceAutoReleaseInterval = serializedObject.FindProperty("m_ResourceAutoReleaseInterval"); m_ResourceCapacity = serializedObject.FindProperty("m_ResourceCapacity"); m_ResourceExpireTime = serializedObject.FindProperty("m_ResourceExpireTime"); m_ResourcePriority = serializedObject.FindProperty("m_ResourcePriority"); m_UpdatePrefixUri = serializedObject.FindProperty("m_UpdatePrefixUri"); m_UpdateRetryCount = serializedObject.FindProperty("m_UpdateRetryCount"); m_InstanceRoot = serializedObject.FindProperty("m_InstanceRoot"); m_LoadResourceAgentHelperCount = serializedObject.FindProperty("m_LoadResourceAgentHelperCount"); m_EditorResourceModeFieldInfo = target.GetType().GetField("m_EditorResourceMode", BindingFlags.NonPublic | BindingFlags.Instance); m_ResourceHelperInfo.Init(serializedObject); m_LoadResourceAgentHelperInfo.Init(serializedObject); RefreshModes(); RefreshTypeNames(); } private void RefreshModes() { m_ResourceModeIndex = (m_ResourceMode.enumValueIndex > 0 ? m_ResourceMode.enumValueIndex - 1 : 0); } private void RefreshTypeNames() { m_ResourceHelperInfo.Refresh(); m_LoadResourceAgentHelperInfo.Refresh(); serializedObject.ApplyModifiedProperties(); } } }
47.583062
168
0.583584
[ "MIT" ]
Echoflyer/ILGameFramework
Assets/Framework/Scripts/Editor/Inspector/ResourceComponentInspector.cs
14,611
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("2. SoftUni Karaoke")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("2. SoftUni Karaoke")] [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("cf212a70-65e4-4950-a0b2-574e6c3dee3b")] // 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.081081
84
0.74308
[ "MIT" ]
DimitarIvanov8/software-university
Programming Fundamentals - Exam preparation/2. SoftUni Karaoke/Properties/AssemblyInfo.cs
1,412
C#
// Copyright (c) Martin Costello, 2016. All rights reserved. // Licensed under the MIT license. See the LICENSE file in the project root for full license information. namespace MartinCostello.Api.Swagger; /// <summary> /// Defines an example request for an API method. This class cannot be inherited. /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false)] internal sealed class SwaggerRequestExampleAttribute : Attribute { /// <summary> /// Initializes a new instance of the <see cref="SwaggerRequestExampleAttribute"/> class. /// </summary> /// <param name="requestType">The type of the request.</param> /// <param name="exampleType">The type of the example.</param> public SwaggerRequestExampleAttribute(Type requestType, Type exampleType) { RequestType = requestType; ExampleType = exampleType; } /// <summary> /// Gets the type of the request. /// </summary> public Type RequestType { get; } /// <summary> /// Gets the type of the example. /// </summary> public Type ExampleType { get; } }
34
105
0.684492
[ "MIT" ]
martincostello/api
src/API/Swagger/SwaggerRequestExampleAttribute.cs
1,124
C#
using DotnetSpider.Core.Infrastructure; using System.Configuration; using System.Linq; namespace DotnetSpider.Extension.Infrastructure { /// <summary> /// 从中间数据库中获取数据库连接设置的实现, 此功能用在使用一个公用数据库存储实际数据库连接字符串, 当实际数据库的用户名密码有变时, 则把新的 /// 连接字符串更新到公用数据库中, 则实现所有爬虫实际更新的功能 /// </summary> public class DbConnectionStringSettingsRefresher : IConnectionStringSettingsRefresher { /// <summary> /// 连接字符串 /// </summary> public string ConnectionString { get; set; } /// <summary> /// 数据库类型 /// </summary> public Database DataSource { get; set; } = Database.MySql; /// <summary> /// 查询的SQL语句 /// </summary> public string QueryString { get; set; } /// <summary> /// 获取新的数据库连接设置 /// </summary> /// <returns>数据库连接设置</returns> public ConnectionStringSettings GetNew() { using (var conn = DatabaseExtensions.CreateDbConnection(DataSource, ConnectionString)) { ConnectionStringSettings connectString = conn.MyQuery<ConnectionStringSettings>(QueryString).FirstOrDefault(); return connectString; } } } }
24.952381
89
0.708015
[ "MIT" ]
DavidAlphaFox/DotnetSpider
src/DotnetSpider.Extension/Infrastructure/DbConnectionStringSettingsRefresher.cs
1,300
C#
// %BANNER_BEGIN% // --------------------------------------------------------------------- // %COPYRIGHT_BEGIN% // <copyright file = "MLCameraCaptureSettings.cs" company="Magic Leap"> // // Copyright (c) 2018-present, Magic Leap, Inc. All Rights Reserved. // // </copyright> // // %COPYRIGHT_END% // --------------------------------------------------------------------- // %BANNER_END% #if PLATFORM_LUMIN namespace UnityEngine.XR.MagicLeap { using System; /// <summary> /// Settings that are specific to a submitted capture /// </summary> [Obsolete("Use MLCamera.CaptureSettings instead.", true)] public sealed class MLCameraCaptureSettings { } } #endif
23.758621
72
0.532656
[ "Apache-2.0" ]
kedarshashi/UnityTemplate
Assets/MagicLeap/Lumin/Deprecated/MLCameraCaptureSettings.cs
689
C#
using HFEA.Web.ViewModel.API; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HFEA.Web.ViewModel.Search { public class ContentTagValue : ContentTag { public bool IsChecked { get; set; } } }
19.333333
45
0.727586
[ "BSD-3-Clause" ]
hfea/Website-Public
Source/HFEA.Web.ViewModel/Search/ContentTagValue.cs
292
C#
namespace Plus.Communication.RCON { using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using Commands; public class RconSocket { private readonly List<string> _allowedConnections; private readonly CommandManager _commands; private readonly int _musPort; private readonly Socket _musSocket; private string _musIp; public RconSocket(string musIp, int musPort, string[] allowedConnections) { _musIp = musIp; _musPort = musPort; _allowedConnections = new List<string>(); foreach (var ipAddress in allowedConnections) { _allowedConnections.Add(ipAddress); } try { _musSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _musSocket.Bind(new IPEndPoint(IPAddress.Any, _musPort)); _musSocket.Listen(0); _musSocket.BeginAccept(OnCallBack, _musSocket); } catch (Exception e) { throw new ArgumentException("Could not set up RCON socket:\n" + e); } _commands = new CommandManager(); } private void OnCallBack(IAsyncResult iAr) { try { var socket = ((Socket) iAr.AsyncState).EndAccept(iAr); var ip = socket.RemoteEndPoint.ToString().Split(':')[0]; if (_allowedConnections.Contains(ip)) { new RconConnection(socket); } else { socket.Close(); } } catch (Exception) { } _musSocket.BeginAccept(OnCallBack, _musSocket); } public CommandManager GetCommands() => _commands; } }
29.878788
105
0.528398
[ "Apache-2.0" ]
dotsudo/plus-clean
Communication/RCON/RCONSocket.cs
1,974
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Symbol representing a using alias appearing in a compilation unit or within a namespace /// declaration. Generally speaking, these symbols do not appear in the set of symbols reachable /// from the unnamed namespace declaration. In other words, when a using alias is used in a /// program, it acts as a transparent alias, and the symbol to which it is an alias is used in /// the symbol table. For example, in the source code /// <pre> /// namespace NS /// { /// using o = System.Object; /// partial class C : o {} /// partial class C : object {} /// partial class C : System.Object {} /// } /// </pre> /// all three declarations for class C are equivalent and result in the same symbol table object /// for C. However, these using alias symbols do appear in the results of certain SemanticModel /// APIs. Specifically, for the base clause of the first of C's class declarations, the /// following APIs may produce a result that contains an AliasSymbol: /// <pre> /// SemanticInfo SemanticModel.GetSemanticInfo(ExpressionSyntax expression); /// SemanticInfo SemanticModel.BindExpression(CSharpSyntaxNode location, ExpressionSyntax expression); /// SemanticInfo SemanticModel.BindType(CSharpSyntaxNode location, ExpressionSyntax type); /// SemanticInfo SemanticModel.BindNamespaceOrType(CSharpSyntaxNode location, ExpressionSyntax type); /// </pre> /// Also, the following are affected if container==null (and, for the latter, when arity==null /// or arity==0): /// <pre> /// IList&lt;string&gt; SemanticModel.LookupNames(CSharpSyntaxNode location, NamespaceOrTypeSymbol container = null, LookupOptions options = LookupOptions.Default, List&lt;string> result = null); /// IList&lt;Symbol&gt; SemanticModel.LookupSymbols(CSharpSyntaxNode location, NamespaceOrTypeSymbol container = null, string name = null, int? arity = null, LookupOptions options = LookupOptions.Default, List&lt;Symbol> results = null); /// </pre> /// </summary> internal sealed class AliasSymbol : Symbol, IAliasSymbol { private readonly SyntaxToken _aliasName; private readonly Binder _binder; private SymbolCompletionState _state; private NamespaceOrTypeSymbol _aliasTarget; private readonly ImmutableArray<Location> _locations; // NOTE: can be empty for the "global" alias. // lazy binding private readonly NameSyntax _aliasTargetName; private readonly bool _isExtern; private DiagnosticBag _aliasTargetDiagnostics; private AliasSymbol(Binder binder, NamespaceOrTypeSymbol target, SyntaxToken aliasName, ImmutableArray<Location> locations) { _aliasName = aliasName; _locations = locations; _aliasTarget = target; _binder = binder; _state.NotePartComplete(CompletionPart.AliasTarget); } private AliasSymbol(Binder binder, SyntaxToken aliasName) { _aliasName = aliasName; _locations = ImmutableArray.Create(aliasName.GetLocation()); _binder = binder; } internal AliasSymbol(Binder binder, UsingDirectiveSyntax syntax) : this(binder, syntax.Alias.Name.Identifier) { _aliasTargetName = syntax.Name; } internal AliasSymbol(Binder binder, ExternAliasDirectiveSyntax syntax) : this(binder, syntax.Identifier) { _isExtern = true; } // For the purposes of SemanticModel, it is convenient to have an AliasSymbol for the "global" namespace that "global::" binds // to. This alias symbol is returned only when binding "global::" (special case code). internal static AliasSymbol CreateGlobalNamespaceAlias(NamespaceSymbol globalNamespace, Binder globalNamespaceBinder) { SyntaxToken aliasName = SyntaxFactory.Identifier(SyntaxFactory.TriviaList(), SyntaxKind.GlobalKeyword, "global", "global", SyntaxFactory.TriviaList()); return new AliasSymbol(globalNamespaceBinder, globalNamespace, aliasName, ImmutableArray<Location>.Empty); } internal static AliasSymbol CreateCustomDebugInfoAlias(NamespaceOrTypeSymbol targetSymbol, SyntaxToken aliasToken, Binder binder) { return new AliasSymbol(binder, targetSymbol, aliasToken, ImmutableArray.Create(aliasToken.GetLocation())); } internal AliasSymbol ToNewSubmission(CSharpCompilation compilation) { Debug.Assert(_binder.Compilation.IsSubmission); // We can pass basesBeingResolved: null because base type cycles can't cross // submission boundaries - there's no way to depend on a subsequent submission. var previousTarget = GetAliasTarget(basesBeingResolved: null); if (previousTarget.Kind != SymbolKind.Namespace) { return this; } var expandedGlobalNamespace = compilation.GlobalNamespace; var expandedNamespace = Imports.ExpandPreviousSubmissionNamespace((NamespaceSymbol)previousTarget, expandedGlobalNamespace); var binder = new InContainerBinder(expandedGlobalNamespace, new BuckStopsHereBinder(compilation)); return new AliasSymbol(binder, expandedNamespace, _aliasName, _locations); } public override string Name { get { return _aliasName.ValueText; } } public override SymbolKind Kind { get { return SymbolKind.Alias; } } /// <summary> /// Gets the <see cref="NamespaceOrTypeSymbol"/> for the /// namespace or type referenced by the alias. /// </summary> public NamespaceOrTypeSymbol Target { get { return GetAliasTarget(basesBeingResolved: null); } } public override ImmutableArray<Location> Locations { get { return _locations; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return GetDeclaringSyntaxReferenceHelper<UsingDirectiveSyntax>(_locations); } } public override bool IsExtern { get { return _isExtern; } } public override bool IsSealed { get { return false; } } public override bool IsAbstract { get { return false; } } public override bool IsOverride { get { return false; } } public override bool IsVirtual { get { return false; } } public override bool IsStatic { get { return false; } } /// <summary> /// Returns data decoded from Obsolete attribute or null if there is no Obsolete attribute. /// This property returns ObsoleteAttributeData.Uninitialized if attribute arguments haven't been decoded yet. /// </summary> internal sealed override ObsoleteAttributeData ObsoleteAttributeData { get { return null; } } public override Accessibility DeclaredAccessibility { get { return Accessibility.NotApplicable; } } /// <summary> /// Using aliases in C# are always contained within a namespace declaration, or at the top /// level within a compilation unit, within the implicit unnamed namespace declaration. We /// return that as the "containing" symbol, even though the alias isn't a member of the /// namespace as such. /// </summary> public override Symbol ContainingSymbol { get { return _binder.ContainingMemberOrLambda; } } internal override TResult Accept<TArg, TResult>(CSharpSymbolVisitor<TArg, TResult> visitor, TArg a) { return visitor.VisitAlias(this, a); } public override void Accept(CSharpSymbolVisitor visitor) { visitor.VisitAlias(this); } public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor) { return visitor.VisitAlias(this); } // basesBeingResolved is only used to break circular references. internal NamespaceOrTypeSymbol GetAliasTarget(ConsList<Symbol> basesBeingResolved) { if (!_state.HasComplete(CompletionPart.AliasTarget)) { // the target is not yet bound. If it is an ordinary alias, bind the target // symbol. If it is an extern alias then find the target in the list of metadata references. var newDiagnostics = DiagnosticBag.GetInstance(); NamespaceOrTypeSymbol symbol = this.IsExtern ? ResolveExternAliasTarget(newDiagnostics) : ResolveAliasTarget(_binder, _aliasTargetName, newDiagnostics, basesBeingResolved); if ((object)Interlocked.CompareExchange(ref _aliasTarget, symbol, null) == null) { // Note: It's important that we don't call newDiagnosticsToReadOnlyAndFree here. That call // can force the prompt evaluation of lazy initialized diagnostics. That in turn can // call back into GetAliasTarget on the same thread resulting in a dead lock scenario. bool won = Interlocked.Exchange(ref _aliasTargetDiagnostics, newDiagnostics) == null; Debug.Assert(won, "Only one thread can win the alias target CompareExchange"); _state.NotePartComplete(CompletionPart.AliasTarget); // we do not clear this.aliasTargetName, as another thread might be about to use it for ResolveAliasTarget(...) } else { newDiagnostics.Free(); // Wait for diagnostics to have been reported if another thread resolves the alias _state.SpinWaitComplete(CompletionPart.AliasTarget, default(CancellationToken)); } } return _aliasTarget; } internal DiagnosticBag AliasTargetDiagnostics { get { GetAliasTarget(null); Debug.Assert(_aliasTargetDiagnostics != null); return _aliasTargetDiagnostics; } } internal void CheckConstraints(DiagnosticBag diagnostics) { var target = this.Target as TypeSymbol; if ((object)target != null && _locations.Length > 0) { var corLibrary = this.ContainingAssembly.CorLibrary; var conversions = new TypeConversions(corLibrary); target.CheckAllConstraints(conversions, _locations[0], diagnostics); } } private NamespaceSymbol ResolveExternAliasTarget(DiagnosticBag diagnostics) { NamespaceSymbol target; if (!_binder.Compilation.GetExternAliasTarget(_aliasName.ValueText, out target)) { diagnostics.Add(ErrorCode.ERR_BadExternAlias, _aliasName.GetLocation(), _aliasName.ValueText); } Debug.Assert((object)target != null); return target; } private static NamespaceOrTypeSymbol ResolveAliasTarget(Binder binder, NameSyntax syntax, DiagnosticBag diagnostics, ConsList<Symbol> basesBeingResolved) { var declarationBinder = binder.WithAdditionalFlags(BinderFlags.SuppressConstraintChecks | BinderFlags.SuppressObsoleteChecks); return declarationBinder.BindNamespaceOrTypeSymbol(syntax, diagnostics, basesBeingResolved); } public override bool Equals(object obj) { if (ReferenceEquals(this, obj)) { return true; } if (ReferenceEquals(obj, null)) { return false; } AliasSymbol other = obj as AliasSymbol; return (object)other != null && Equals(this.Locations.FirstOrDefault(), other.Locations.FirstOrDefault()) && this.ContainingAssembly == other.ContainingAssembly; } public override int GetHashCode() { if (this.Locations.Length > 0) return this.Locations.First().GetHashCode(); else return Name.GetHashCode(); } internal override bool RequiresCompletion { get { return true; } } #region IAliasSymbol Members INamespaceOrTypeSymbol IAliasSymbol.Target { get { return this.Target; } } #endregion #region ISymbol Members public override void Accept(SymbolVisitor visitor) { visitor.VisitAlias(this); } public override TResult Accept<TResult>(SymbolVisitor<TResult> visitor) { return visitor.VisitAlias(this); } #endregion } }
36.950777
245
0.608147
[ "Apache-2.0" ]
0x53A/roslyn
src/Compilers/CSharp/Portable/Symbols/AliasSymbol.cs
14,265
C#
using EvtGraph; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; using UnityEngine.UI; using UnityEngine.Events; using GamePlay; using DiaGraph; [RequireComponent(typeof(NavMeshAgent))] [RequireComponent(typeof(BoxCollider))] public class NpcController : ControllerBased { [Header("Dialogue")] public DialogueGraph NoThingTalk; public DialogueGraph MedicalKit; public DialogueGraph JoinIn; public DialogueGraph HealPriDia; public int Stage = 0; bool isEnemyEnter = false; public bool inAnimState = false; public bool IsPrisoner = false; public bool isGuard = false; public bool isGrabbingGuardName = false; public bool isPrristNeedHeal = false; public bool NeedRemoveMenu = true; public bool Flashing; public float FlashingSpeed; bool IsIncreaseing; public string AnimStateName = string.Empty; public bool SendEventWhenGetOutLocker = false; #region Inspector View [System.Serializable] public class Status { public string npcName; public string description; public float maxHealth = 100; public float currentHealth = 0; public float getUpHealth = 50; public float maxStamina = 100; public float minStamina = 1; public float currentStamina = 0; public float maxCredit = 0; public float currentCredit = 0; public float fixRate = 5; public List<EventSO> toDoList; public Item_SO.ItemType CarryItem = Item_SO.ItemType.None; public string code; public float healAmount = 0; public bool isStruggling = false; } public Status status = null; [SerializeField] float boostSpeed = 0; [SerializeField] float limpingLimit = 0; [SerializeField] [Tooltip("The rest distance before reach destination. ")] float restDistance = 0.2f; [Header("Visual Setting")] [SerializeField] [Tooltip("The Ray to detect current Room")] [Range(0f, 50f)] float detectRay = 0; [SerializeField] [Range(0f, 100f)] float alertRadius = 0; [SerializeField] [Range(0f, 100f)] float bannedRadius = 0; [Header("Dodging Setting")] [SerializeField] LayerMask needDodged = 0; [SerializeField] LayerMask canBlocked = 0; [SerializeField] float dodgeAngle = 0; [Header("Rescuing Setting")] [SerializeField] float discoverAngle = 0; [Header("Idle Setting")] [SerializeField] float restTime = 0; [SerializeField] float recoverTime = 0; bool IsRandomTalking = false; Vector3 TalkingPos = Vector3.zero; public bool IsHighP; public NpcController HighP; public DialogueGraph Graph1; public DialogueGraph Graph1_5; public EventSO PuEvt; #endregion #region Fields [HideInInspector] public StringRestrictedFiniteStateMachine m_fsm; [HideInInspector] public Animator animator; [HideInInspector] public NavMeshAgent navAgent; RoomTracker currentRoomTracker; NavMeshPath path; #endregion #region Value [HideInInspector] public Vector3 currentTerminalPos; [HideInInspector] public Transform fixTargetTransform; Vector3 recordColliderSize; public bool isSafe = false; public bool isEnemyChasing = false; public bool isRoomCalled = false; float recordRestTimer, recordRecoverTimer, recordSpeed; bool MoveAcrossNavMeshesStarted; bool inAngle, isBlocked; List<RoomTracker> roomScripts = new List<RoomTracker>(); [HideInInspector] public GameObject fixTarget; GameObject RescuingTarget, HealingTarget; RaycastHit hit; Collider[] hitObjects = null; BoxCollider boxCollider; bool justEnterEvent = true; public AudioSource source; public float audioTimer = 0.5f; RoomTracker recordRoom; #endregion #region InteractWithItem [Header("Interact Item")] public float DampPosSpeed = 0.2f; public float DampRotSpeed = 0.2f; [HideInInspector] public Interact_SO CurrentInteractObject; [HideInInspector] public LocatorList locatorList = null; [HideInInspector] public Locators locators = null; int GrabOutIndex; bool IsGrabbing = true, isSitting = false; [HideInInspector] public Item_SO CurrentInteractItem; [HideInInspector] public bool HasInteract = false; public float resetTimer; float VelocityPosX; float VelocityPosZ; float timer; List<Transform> escWayponits = new List<Transform>(); #endregion public void Awake() { AudioSource[] sources = GetComponentsInChildren<AudioSource>(); if (sources.Length > 0) source = sources[0]; outline = GetComponent<Outline>(); boxCollider = GetComponent<BoxCollider>(); recordColliderSize = boxCollider.size; navAgent = GetComponent<NavMeshAgent>(); path = new NavMeshPath(); animator = GetComponent<Animator>(); status.toDoList.Clear(); recordRestTimer = restTime; recordRecoverTimer = recoverTime; recordSpeed = navAgent.speed; timer = resetTimer; #region StringRestrictedFiniteStateMachine Dictionary<string, List<string>> NPCDictionary = new Dictionary<string, List<string>>() { { "Patrol", new List<string> { "Rest", "Event", "Dispatch", "Dodging", "Hiding", "Escaping", "InteractWithItem", "Healing", "GotAttacked", "Rescuing", "Idle", "Fixing", "Anim", "OnFloor", "Death" } }, { "Rest", new List<string> { "Patrol", "Event", "Dispatch", "Dodging", "Hiding", "Escaping", "InteractWithItem", "Healing", "GotAttacked", "Rescuing", "Idle", "Fixing", "Anim", "OnFloor", "Death" } }, { "Event", new List<string> { "Patrol", "Rest", "Dispatch", "Dodging", "Hiding", "Escaping", "InteractWithItem", "Healing", "GotAttacked", "Rescuing", "Idle", "Fixing", "Anim", "OnFloor", "Death" } }, { "Dispatch", new List<string> { "Patrol", "Rest", "Event", "Dodging", "Hiding", "Escaping", "InteractWithItem", "Healing", "GotAttacked", "Rescuing", "Idle", "Fixing", "Anim", "OnFloor", "Death" } }, { "Dodging", new List<string> { "Patrol", "Rest", "Event", "Dispatch", "Hiding", "Escaping", "InteractWithItem", "Healing", "GotAttacked", "Rescuing", "Idle", "Fixing", "Anim", "OnFloor", "Death" } }, { "Hiding", new List<string> { "Patrol", "Rest", "Event", "Dispatch", "Dodging", "Escaping", "InteractWithItem", "Healing", "GotAttacked", "Rescuing", "Idle", "Fixing", "Anim", "OnFloor", "Death" } }, { "Escaping", new List<string> { "Patrol", "Rest", "Event", "Dispatch", "Dodging", "Hiding", "InteractWithItem", "Healing", "GotAttacked", "Rescuing", "Idle", "Fixing", "Anim", "OnFloor", "Death" } }, { "InteractWithItem", new List<string> { "Patrol", "Rest", "Event", "Dispatch", "Dodging", "Hiding", "Escaping", "Healing", "GotAttacked", "Rescuing", "Idle", "Fixing", "Anim", "OnFloor", "Death" } }, { "Healing", new List<string> { "Patrol", "Rest", "Event", "Dispatch", "Dodging", "Hiding", "Escaping", "InteractWithItem", "GotAttacked", "Rescuing", "Idle", "Fixing", "Anim", "OnFloor", "Death" } }, { "GotAttacked", new List<string> { "Patrol", "Rest", "Event", "Dispatch", "Dodging", "Hiding", "Escaping", "InteractWithItem", "Healing", "Rescuing", "Idle", "Fixing", "Anim", "OnFloor", "Death" } }, { "Rescuing", new List<string> { "Patrol", "Rest", "Event", "Dispatch", "Dodging", "Hiding", "Escaping", "InteractWithItem", "Healing", "GotAttacked", "Idle", "Fixing", "Anim", "OnFloor", "Death" } }, { "Idle", new List<string> { "Patrol", "Rest", "Event", "Dispatch", "Dodging", "Hiding", "Escaping", "InteractWithItem", "Healing", "GotAttacked", "Rescuing", "Fixing", "Anim", "OnFloor", "Death" } }, { "Fixing", new List<string> { "Patrol", "Rest", "Event", "Dispatch", "Dodging", "Hiding", "Escaping", "InteractWithItem", "Healing", "GotAttacked", "Rescuing", "Idle", "Anim", "OnFloor", "Death" } }, { "Anim", new List<string> { "Patrol", "Rest", "Event", "Dispatch", "Dodging", "Hiding", "Escaping", "InteractWithItem", "Healing", "GotAttacked", "Rescuing", "Idle", "Fixing", "OnFloor", "Death" } }, { "OnFloor", new List<string> { "Patrol", "Rest", "Event", "Dispatch", "Dodging", "Hiding", "Escaping", "InteractWithItem", "Healing", "GotAttacked", "Rescuing", "Idle", "Fixing", "Anim", "Death" } }, { "Death", new List<string> { "Patrol", "Rest", "Event", "Dispatch", "Dodging", "Hiding", "Escaping", "InteractWithItem", "Healing", "GotAttacked", "Rescuing", "Idle", "Fixing", "Anim", "OnFloor" } } }; #endregion #region RightClickMenu //AddMenu("Move", "Move", false, ReadyForDispatch); //AddMenu("HideAll", "Hide All", false, TriggerHiding); //TODO NPC集体躲进去。Call一个方法,这个方法给GM发消息,带上自己在的房间,然后GM就会识别你带的房间,然后给本房间内所有的NPC发消息,让他们躲起来 AddMenu("Interact", "Interact", true, ReceiveInteractCall, 1 << LayerMask.NameToLayer("HiddenPos") | 1 << LayerMask.NameToLayer("RestingPos") | 1 << LayerMask.NameToLayer("TerminalPos") | 1 << LayerMask.NameToLayer("SwitchPos") | 1 << LayerMask.NameToLayer("Item") | 1 << LayerMask.NameToLayer("CBord") | 1 << LayerMask.NameToLayer("StoragePos")); #endregion m_fsm = new StringRestrictedFiniteStateMachine(NPCDictionary, "Patrol"); if (inAnimState) { SwitchAnimState(true, AnimStateName); } } public void Start() { DetectRoom(); navAgent.speed *= ((status.currentStamina / 100) * 0.4f + 0.6f); currentTerminalPos = NewDestination(); EventCenter.GetInstance().EventTriggered("GM.NPC.Add", this); Invoke("GenerateList", 0.00001f); } public void PlayAudio(string str) { AudioMgr.GetInstance().PlayAudio(source, str, 1f, false, null); } void GenerateList() { foreach (RoomTracker temp in GameManager.GetInstance().Rooms) { roomScripts.Add(temp); } } public void Update() { #region GameplayEvent if(IsPrisoner) { if (currentRoomTracker.isEnemyDetected()) { isEnemyEnter = true; } if (!currentRoomTracker.isEnemyDetected() && isEnemyEnter) { if(CurrentInteractObject != null) CurrentInteractObject.IsInteracting = false; EventCenter.GetInstance().DiaEventTrigger("01_PrisonerSafe"); IsPrisoner = false; } } if (Flashing) { AlwaysOutline = true; SetOutline(true); if (outline.OutlineWidth - Time.deltaTime <= 0f) IsIncreaseing = true; else if (outline.OutlineWidth + Time.deltaTime >= OutlineWidth) IsIncreaseing = false; if (IsIncreaseing) { outline.OutlineWidth += Time.deltaTime * FlashingSpeed; } else { outline.OutlineWidth -= Time.deltaTime * FlashingSpeed; } } else { AlwaysOutline = false; } #endregion if (m_fsm.GetCurrentState() != "Anim") { audioTimer -= Time.deltaTime; CheckEvent(); AddStopMenu(); if (navAgent.isOnOffMeshLink && !MoveAcrossNavMeshesStarted) { StartCoroutine(MoveAcrossNavMeshLink()); MoveAcrossNavMeshesStarted = true; } } #region StringRestrictedFiniteStateMachine Update switch (m_fsm.GetCurrentState()) { case "Patrol": DetectRoom(); if (currentRoomTracker != null) { if (!currentRoomTracker.isEnemyDetected()) { restTime -= Time.deltaTime; } } if (restTime > 0) { Dispatch(currentTerminalPos); GenerateNewDestination(); TriggerDodging(); } else { if (navAgent.enabled) navAgent.ResetPath(); recoverTime = recordRecoverTimer; m_fsm.ChangeState("Idle"); } break; case "Idle": recoverTime -= Time.deltaTime * status.currentStamina / 100; TriggerDodging(); animator.Play("Idle", 0); if (recoverTime <= 0) { BackToPatrol(); } break; case "Rest": if (CurrentInteractObject != null) { switch (CurrentInteractObject.type) { case Interact_SO.InteractType.Bed: if(status.currentHealth >= status.getUpHealth && status.currentStamina == status.maxStamina) { CurrentInteractObject.NPCInteractFinish(CurrentInteractObject); } break; default: break; } } break; case "Dispatch": CompleteDispatching(); break; case "Anim": break; case "Event": Event(); ReachDestination(); FacingEachOther(); break; case "Dodging": Dodging(); break; case "Hiding": Hiding(); break; case "Escaping": Escaping(); CompleteEscaping(); break; case "InteractWithItem": PlayGetInAnim(); break; case "Healing": if (HealingTarget != null) { HealOther(); } break; case "GotAttacked": if (navAgent.enabled) navAgent.ResetPath(); break; case "Rescuing": RescuingProcess(); break; case "Fixing": Fixing(); break; case "OnFloor": if (Distance() < restDistance && !isSitting) { animator.Play("Sitting On Floor", 0); if (MenuContains("Interact") >= 0) { RemoveAndInsertMenu("Interact", "Leave", "Leave", false, LeaveFloor); } isSitting = true; } hitObjects = Physics.OverlapSphere(transform.position, alertRadius, needDodged); if (hitObjects.Length != 0 && isSitting) { animator.Play("Sitting Off Floor", 0); isSitting = false; } break; default: break; } #endregion } public void CheckEvent() { if (status.toDoList != null) { if (status.toDoList.Count != 0) { m_fsm.ChangeState("Event"); } } } void AddStopMenu() { if (m_fsm.GetCurrentState() == "Hiding" || m_fsm.GetCurrentState() == "Escaping" || m_fsm.GetCurrentState() == "InteractWithItem" || m_fsm.GetCurrentState() == "Healing" || m_fsm.GetCurrentState() == "Fixing") { if (Distance() > restDistance + 2) { if (MenuContains("Stop") >= 0) return; else { InsertMenu(rightClickMenus.Count, "Stop", "Stop", false, Stop); } } } else if (MenuContains("Stop") >= 0) { RemoveMenu("Stop"); } } public void Stop(object obj) { if (navAgent.enabled) { if(locatorList != null) locatorList.npc = null; CurrentInteractObject = null; RescuingTarget = null; HealingTarget = null; CurrentInteractItem = null; fixTarget = null; fixTargetTransform = null; locatorList = null; boxCollider.isTrigger = false; IsInteracting = false; switch (status.CarryItem) { case Item_SO.ItemType.None: break; case Item_SO.ItemType.MedicalKit: break; default: break; } RemoveMenu("Stop"); BackToPatrol(); if (MenuContains("Interact") >= 0) return; else AddMenu("Interact", "Interact", true, ReceiveInteractCall, 1 << LayerMask.NameToLayer("HiddenPos") | 1 << LayerMask.NameToLayer("RestingPos") | 1 << LayerMask.NameToLayer("TerminalPos") | 1 << LayerMask.NameToLayer("SwitchPos") | 1 << LayerMask.NameToLayer("Item") | 1 << LayerMask.NameToLayer("CBord") | 1 << LayerMask.NameToLayer("StoragePos")); } } public void SwitchAnimState(bool inState, string animName = "") { inAnimState = inState; AnimStateName = animName; if (inState) { if(navAgent.isOnNavMesh) navAgent.ResetPath(); CurrentInteractObject = null; CurrentInteractItem = null; RescuingTarget = null; HealingTarget = null; fixTarget = null; fixTargetTransform = null; locatorList = null; if(NeedRemoveMenu) RemoveAllMenu(); m_fsm.ChangeState("Anim"); animator.Play(animName, 0); } else { navAgent.enabled = true; boxCollider.isTrigger = false; HasInteract = false; DetectRoom(); BackToPatrol(); RemoveAllMenu(); AddMenu("Interact", "Interact", true, ReceiveInteractCall, 1 << LayerMask.NameToLayer("HiddenPos") | 1 << LayerMask.NameToLayer("RestingPos") | 1 << LayerMask.NameToLayer("TerminalPos") | 1 << LayerMask.NameToLayer("SwitchPos") | 1 << LayerMask.NameToLayer("Item") | 1 << LayerMask.NameToLayer("CBord") | 1 << LayerMask.NameToLayer("StoragePos")); switch (status.CarryItem) { case Item_SO.ItemType.None: break; case Item_SO.ItemType.MedicalKit: InsertMenu(rightClickMenus.Count, "Heal", "Heal", true, Heal, 1 << LayerMask.NameToLayer("NPC")); break; default: break; } } } #region Move public void BackToPatrol(object obj = null) { TalkingStop(); restTime = recordRestTimer; navAgent.speed = recordSpeed; currentTerminalPos = NewDestination(); navAgent.speed *= (status.currentStamina / 100) * 0.4f + 0.6f; m_fsm.ChangeState("Patrol"); IsRandomTalking = false; if (MenuContains("Leave") >= 0) { RemoveMenu("Leave"); } if (MenuContains("Interact") >= 0) return; else { AddMenu("Interact", "Interact", true, ReceiveInteractCall, 1 << LayerMask.NameToLayer("HiddenPos") | 1 << LayerMask.NameToLayer("RestingPos") | 1 << LayerMask.NameToLayer("TerminalPos") | 1 << LayerMask.NameToLayer("SwitchPos") | 1 << LayerMask.NameToLayer("Item") | 1 << LayerMask.NameToLayer("CBord") | 1 << LayerMask.NameToLayer("StoragePos")); } } public float Distance() { float a = navAgent.destination.x - transform.position.x; float b = navAgent.destination.z - transform.position.z; float c = Mathf.Sqrt(Mathf.Pow(a, 2) + Mathf.Pow(b, 2)); return c; } public Vector3 NewDestination() { Vector3 tempPos = Vector3.zero; if (currentRoomTracker != null) { int tempInt = Random.Range(0, currentRoomTracker.tempWayPoints.Count); float x = Random.Range(currentRoomTracker.tempWayPoints[tempInt].position.x, transform.position.x); float z = Random.Range(currentRoomTracker.tempWayPoints[tempInt].position.z, transform.position.z); tempPos = new Vector3(x, transform.position.y, z); } return tempPos; } private void GenerateNewDestination() { float a = currentTerminalPos.x - transform.position.x; float b = currentTerminalPos.z - transform.position.z; float c = Mathf.Sqrt(Mathf.Pow(a, 2) + Mathf.Pow(b, 2)); if (navAgent.autoRepath && Mathf.Abs(c) < restDistance || !navAgent.CalculatePath(currentTerminalPos, path) || !navAgent.hasPath) { currentTerminalPos = NewDestination(); } } public void LimpingChange(string type) { if (type == "Walk") { if (status.currentHealth <= limpingLimit) { animator.Play("Limping Walk", 0); if (audioTimer <= 0) { PlayAudio("Walk Hard " + Random.Range(1, 7).ToString()); audioTimer = 1.2f; } } else { animator.Play("Walk", 0); if (audioTimer <= 0) { PlayAudio("Walk Hard " + Random.Range(1, 7).ToString()); audioTimer = 0.8f; } } } else if (type == "Run") { if (status.currentHealth <= limpingLimit) { animator.Play("Limping Run", 0); if (audioTimer <= 0) { PlayAudio("Run Hard " + Random.Range(1, 7).ToString()); audioTimer = 1f; } } else { animator.Play("Run", 0); if (audioTimer <= 0) { PlayAudio("Run Hard " + Random.Range(1, 7).ToString()); audioTimer = 0.6f; } } } } IEnumerator MoveAcrossNavMeshLink() { OffMeshLinkData data = navAgent.currentOffMeshLinkData; Vector3 startPos = navAgent.transform.position; Vector3 endPos = data.endPos + Vector3.up * navAgent.baseOffset; float duration = (endPos - startPos).magnitude / navAgent.velocity.magnitude; float t = 0.0f; float tStep = 1.0f / duration; while (t < 1.0f) { transform.position = Vector3.Lerp(startPos, endPos, t); t += tStep * Time.deltaTime; yield return null; } transform.position = endPos; navAgent.CompleteOffMeshLink(); MoveAcrossNavMeshesStarted = false; } void DetectRoom() { Physics.Raycast(transform.position + new Vector3 (0, 3, 0), -transform.up * detectRay, out hit, 1 << LayerMask.NameToLayer("Room")); if(hit.collider.gameObject != null) { currentRoomTracker = hit.collider.gameObject.GetComponent<RoomTracker>(); } } public void Dispatch(object newPos) { navAgent.enabled = true; navAgent.SetDestination((Vector3)newPos); if (m_fsm.GetCurrentState() != "InteractWithItem") { if (navAgent.velocity.magnitude >= 0.1f || navAgent.isOnOffMeshLink) { if (m_fsm.GetCurrentState() == "Patrol") { LimpingChange("Walk"); } else { LimpingChange("Run"); } } else if (!navAgent.isOnOffMeshLink) { animator.Play("Idle", 0); } } } public void ReadyForDispatch(object newPos) { LimpingChange("Run"); Debug.Log("Ready for Dispatch"); navAgent.SetDestination((Vector3)newPos); m_fsm.ChangeState("Dispatch"); } public void CompleteDispatching() { if (Distance() < restDistance) { if(navAgent.enabled) navAgent.ResetPath(); BackToPatrol(); } } #endregion #region Random Resting public void TriggerBedResting(GameObject obj) { if (!isRoomCalled) { ReceiveInteractCall(obj); isRoomCalled = true; } } public void TriggerRandomResting() { if (!isRoomCalled) { switch (Random.Range(0, 3)) { case (0): //Sitting Chair if (currentRoomTracker != null) { foreach (var item in currentRoomTracker.RestingPos()) { Interact_SO interact_SO = item.GetComponent<Interact_SO>(); switch (interact_SO.type) { case Interact_SO.InteractType.Chair: ReceiveInteractCall(item.gameObject); break; default: break; } } } else { Debug.LogWarning("No CurrentRoomTracker" + gameObject); } break; case (1): //Sitting on the floor Dispatch(NewDestination()); m_fsm.ChangeState("OnFloor"); break; case (2): //Patrol BackToPatrol(); break; default: break; } isRoomCalled = true; } } void LeaveFloor(object obj) { animator.Play("Sitting Off Floor", 0); RemoveMenu("Leave"); } void SittingOffFloor() { restTime = recordRestTimer; navAgent.speed = recordSpeed; currentTerminalPos = NewDestination(); navAgent.speed *= (status.currentStamina / 100) * 0.4f + 0.6f; if (MenuContains("Interact") < 0) { AddMenu("Interact", "Interact", true, ReceiveInteractCall, 1 << LayerMask.NameToLayer("HiddenPos") | 1 << LayerMask.NameToLayer("RestingPos") | 1 << LayerMask.NameToLayer("TerminalPos") | 1 << LayerMask.NameToLayer("SwitchPos") | 1 << LayerMask.NameToLayer("Item") | 1 << LayerMask.NameToLayer("CBord") | 1 << LayerMask.NameToLayer("StoragePos")); } if (MenuContains("Leave") >= 0) { RemoveMenu("Leave"); } IsRandomTalking = false; m_fsm.ChangeState("Patrol"); } #endregion #region Hiding public void TriggerHiding(object obj = null) { if(navAgent.enabled != false) { if (navAgent.enabled) navAgent.ResetPath(); navAgent.speed *= ((status.currentStamina / 100) * 0.4f + 0.6f) * boostSpeed; m_fsm.ChangeState("Hiding"); } } void Hiding() { bool isEmpty = false; float minDistance = Mathf.Infinity; foreach (GameObject temp in currentRoomTracker.HiddenPos()) { Interact_SO hpos = temp.GetComponent<Interact_SO>(); for (int i = 0; i < hpos.Locators.Count; i++) { if (hpos.Locators[i].npc != null) continue; isEmpty = true; float a = hpos.Locators[i].Locator.position.x - transform.position.x; float b = hpos.Locators[i].Locator.position.z - transform.position.z; float c = Mathf.Sqrt(Mathf.Pow(a, 2) + Mathf.Pow(b, 2)); float distance = Mathf.Abs(c); if (distance < minDistance) { minDistance = distance; CurrentInteractObject = hpos; currentTerminalPos = hpos.Locators[i].Locator.position; locatorList = hpos.Locators[i]; } } } if (!isEmpty) { CurrentInteractObject = null; locatorList = null; BackToPatrol(); } Dispatch(currentTerminalPos); if (Distance() < restDistance || !navAgent.enabled) { HasInteract = false; CurrentInteractObject.Locators.Find((x) => (x == locatorList)).npc = this; m_fsm.ChangeState("InteractWithItem"); } } #endregion #region Event public void TriggerEvent() { if (navAgent.enabled) navAgent.ResetPath(); m_fsm.ChangeState("Event"); justEnterEvent = true; } public void RandomTalk() { if (status.toDoList.Count > 0) { EventSO evt = status.toDoList[0]; for (int i = 0; i < evt.NPCTalking.Count; i++) { for (int a = 0; a < evt.NPCTalking[i].moveToClasses.Count; a++) { if (evt.NPCTalking[i].moveToClasses[a].Obj == gameObject) { int index = 0; int b = 0; do { index++; b = Random.Range(0, evt.NPCTalking[i].moveToClasses.Count); } while (b == a && index < 50); if (index > 50) { TalkingPos = currentRoomTracker.cameraLists[currentRoomTracker.CurrentCameraIndex].roomCamera.gameObject.transform.position; } else { TalkingPos = evt.NPCTalking[i].moveToClasses[b].Obj.transform.position; } } } } } IsRandomTalking = true; switch (Random.Range(0, 3)) { case (0): animator.Play("Talking1", 0); break; case (1): animator.Play("Talking2", 0); break; case (2): animator.Play("Talking3", 0); break; default: break; } } public void Talking1() { AudioMgr.GetInstance().PlayAudio(source, "Talking long", 0.5f, true, null); } public void Talking2() { AudioMgr.GetInstance().PlayAudio(source, "Talking_long_VG", 0.5f, true, null); } public void Talking3() { AudioMgr.GetInstance().PlayAudio(source, "Talking_long_VG", 0.5f, true, null); } public void TalkingStop() { source.Stop(); } private void Event() { if(status.toDoList.Count > 0) { EventSO evt = status.toDoList[0]; if (justEnterEvent) { justEnterEvent = false; switch (evt.doingWithNPC) { case DoingWithNPC.Talking: for (int a = 0; a < evt.NPCTalking.Count; a++) { for (int b = 0; b < evt.NPCTalking[a].moveToClasses.Count; b++) { if (evt.NPCTalking[a].moveToClasses[b].Obj == gameObject) { Dispatch(evt.NPCTalking[a].moveToClasses[b].MoveTO.position); LimpingChange("Run"); IsInteracting = true; } } } break; case DoingWithNPC.MoveTo: for (int a = 0; a < evt.NPCWayPoint.Count; a++) { if (evt.NPCWayPoint[a].Obj == gameObject) { Dispatch(evt.NPCWayPoint[a].MoveTO.position); LimpingChange("Run"); IsInteracting = true; } } break; case DoingWithNPC.Patrol: break; case DoingWithNPC.Interact: break; case DoingWithNPC.AnimState: default: break; } } else { switch (evt.doingWithNPC) { case DoingWithNPC.Talking: for (int a = 0; a < evt.NPCTalking.Count; a++) { if(evt.NPCTalking[a].room.DiaPlay.currentGraph != evt.NPCTalking[a].Graph && evt.NPCTalking[a].room.WaitingGraph != evt.NPCTalking[a].Graph) { IsInteracting = false; status.toDoList.Remove(evt); } } break; case DoingWithNPC.MoveTo: break; case DoingWithNPC.Patrol: break; case DoingWithNPC.Interact: break; case DoingWithNPC.AnimState: break; default: break; } } } if (status.toDoList.Count <= 0) { IsInteracting = false; BackToPatrol(); } } public void ReachDestination() { //Vector3 temp = Vector3.zero; //foreach (var item in status.toDoList) //{ //} //float a = locatorList.Locator.position.x - transform.position.x; //float b = locatorList.Locator.position.z - transform.position.z; //float c = Mathf.Sqrt(Mathf.Pow(a, 2) + Mathf.Pow(b, 2)); if (Distance() <= restDistance) { EventCenter.GetInstance().EventTriggered("GM.NPCArrive", status.npcName); if (navAgent.enabled) navAgent.ResetPath(); } //else if (navAgent.autoRepath) //{ // //TODO: Cant Reach // Debug.Log("I cant go there"); //} } #endregion #region Dodging public void TriggerDodging() { hitObjects = Physics.OverlapSphere(transform.position, alertRadius, needDodged); if (hitObjects.Length != 0) { navAgent.speed *= ((status.currentStamina / 100) * 0.4f + 0.6f) * boostSpeed; m_fsm.ChangeState("Dodging"); } } private void Dodging() { hitObjects = Physics.OverlapSphere(transform.position, alertRadius, needDodged); for (int i = 0; i < hitObjects.Length; i++) { Vector3 enemyDirection = (transform.position - hitObjects[i].gameObject.transform.position).normalized; Vector3 movingDirection = (currentTerminalPos - transform.position).normalized; float a = currentTerminalPos.x - transform.position.x; float b = currentTerminalPos.z - transform.position.z; float c = Mathf.Sqrt(Mathf.Pow(a, 2) + Mathf.Pow(b, 2)); if (Vector3.Angle(enemyDirection, movingDirection) > dodgeAngle / 2 || Mathf.Abs(c) < bannedRadius) { currentTerminalPos = NewDestination(); } } Dispatch(currentTerminalPos); if (hitObjects.Length == 0) { BackToPatrol(); } } #endregion #region Escaping public void TriggerEscaping() { if (navAgent.enabled != false) { if (navAgent.enabled) navAgent.ResetPath(); navAgent.speed *= ((status.currentStamina / 100) * 0.4f + 0.6f) * boostSpeed; escWayponits.Clear(); m_fsm.ChangeState("Escaping"); } } void Escaping() { Vector3 pos = Vector3.zero; foreach (var item in roomScripts) { if (item.isEnemyDetected()) continue; foreach (var point in item.tempWayPoints) { if(!escWayponits.Contains(point)) escWayponits.Add(point); } } float minDistance = Mathf.Infinity; foreach (var wayPoint in escWayponits) { float a = wayPoint.position.x - transform.position.x; float b = wayPoint.position.z - transform.position.z; float c = Mathf.Sqrt(Mathf.Pow(a, 2) + Mathf.Pow(b, 2)); float distance = Mathf.Abs(c); if (distance < minDistance) { minDistance = distance; pos = wayPoint.position; } } Dispatch(pos); } public void CompleteEscaping() { if (Distance() < restDistance) { if (navAgent.enabled) navAgent.ResetPath(); BackToPatrol(); } } #endregion #region Healing public void Heal(object obj) { if (navAgent.enabled) navAgent.ResetPath(); GameObject gameObj = (GameObject)obj; NpcController NPC = gameObj.GetComponent<NpcController>(); m_fsm.ChangeState("Healing"); if (NPC != this) { //Heal Other HealingTarget = gameObj; navAgent.speed *= ((status.currentStamina / 100) * 0.4f + 0.6f) * boostSpeed; Dispatch(HealingTarget.transform.position); } else { //Heal Self switch (Random.Range(0, 2)) { case (0): animator.Play("Stand Heal Self", 0); break; case (1): animator.Play("Squat Heal Self", 0); break; default: break; } } } void HealOther() { float a = HealingTarget.transform.position.x - transform.position.x; float b = HealingTarget.transform.position.z - transform.position.z; float c = Mathf.Sqrt(Mathf.Pow(a, 2) + Mathf.Pow(b, 2)); if (c < restDistance && HealingTarget != null) { bool Damping = false; Vector3 dir = (HealingTarget.transform.position - transform.position).normalized; dir.y = 0; Quaternion rotation = Quaternion.LookRotation(dir); if (Quaternion.Angle(transform.rotation, rotation) >= 1) { transform.rotation = Quaternion.Slerp(transform.rotation, rotation, DampRotSpeed); Damping = true; } if (Damping) { //Debug.Log("Damping"); } else if (HealingTarget.GetComponent<NpcController>().m_fsm.GetCurrentState() == "Rest") { animator.Play("Squat Heal Other", 0); if (isPrristNeedHeal) { HealingTarget.GetComponent<NpcController>().navAgent.ResetPath(); HealingTarget.GetComponent<NpcController>().AnimStateName = "Talking1"; HealingTarget.GetComponent<NpcController>().inAnimState = true; HealingTarget.GetComponent<NpcController>().IsInteracting = true; HealingTarget.GetComponent<NpcController>().FacingEachOtherCoro(transform); navAgent.ResetPath(); AnimStateName = "Talking2"; inAnimState = true; IsInteracting = true; FacingEachOtherCoro(HealingTarget.transform); isPrristNeedHeal = false; currentRoomTracker.PlayingDialogue(HealPriDia); } } else { if (HealingTarget.GetComponent<NpcController>().navAgent.enabled) HealingTarget.GetComponent<NpcController>().navAgent.ResetPath(); animator.Play("Stand Heal Other", 0); } } else if (navAgent.velocity.magnitude >= 0.1 || navAgent.isOnOffMeshLink) { LimpingChange("Run"); Dispatch(HealingTarget.transform.position); } else if (!navAgent.isOnOffMeshLink && !HasInteract) { animator.Play("Idle", 0); timer -= Time.deltaTime; if (timer <= 0) { HealingTarget = null; timer = resetTimer; //TODO: Cant Reach Destination Debug.Log("Cant Reach Destination"); BackToPatrol(); } } } #endregion #region Got Attacked public void GotHurt() { SetOutline(false); animator.Play("Got Hurt", 0); PlayAudio("Hurt Sound " + Random.Range(1, 7).ToString()); } void Death() { Flashing = false; if(outline != null) { outline.OutlineWidth = 0f; SetOutline(false); } boxCollider.enabled = false;Flashing = false; if(outline != null) { outline.OutlineWidth = 0f; SetOutline(false); } boxCollider.enabled = false; animator.Play("Death", 0); if(navAgent.enabled) navAgent.ResetPath(); status.isStruggling = false; gameObject.layer = LayerMask.NameToLayer("Dead"); m_fsm.ChangeState("Death"); ResMgr.GetInstance().LoadAsync<GameObject>("DeadBox", (x) => { x.transform.position = transform.position; DeadBox deadBox = x.GetComponent<DeadBox>(); deadBox.type = status.CarryItem; switch (status.CarryItem) { case Item_SO.ItemType.None: Destroy(x); break; case Item_SO.ItemType.MedicalKit: deadBox.HPRecovery = status.healAmount; break; case Item_SO.ItemType.RepairedPart: break; case Item_SO.ItemType.Key: deadBox.code = status.code; break; default: break; } }); } public void CurrentObjectAnimPlay(object obj) { if(CurrentInteractObject != null) { CurrentInteractObject.NPCInteractFinish(obj); } } #endregion #region Rescuing public void TriggerRescuing(object obj) { RescuingTarget = (GameObject)obj; if (RescuingTarget != null) { if (!navAgent.enabled) navAgent.enabled = true; Debug.Log("I am coming!"); Dispatch(RescuingTarget.transform.position); navAgent.speed *= ((status.currentStamina / 100) * 0.4f + 0.6f) * boostSpeed; m_fsm.ChangeState("Rescuing"); } } public void RescuingProcess() { Collider[] hits = Physics.OverlapSphere(transform.position, alertRadius, 1 << LayerMask.NameToLayer("NPC") | 1 << LayerMask.NameToLayer("Dead")); foreach (var item in hits) { if (item.gameObject == RescuingTarget) { isBlocked = Physics.Linecast(transform.position, item.transform.position, canBlocked); Vector3 direction = (item.transform.position - transform.position).normalized; float targetAngle = Vector3.Angle(transform.forward, direction); inAngle = targetAngle <= discoverAngle / 2 ? true : false; NpcController target = item.GetComponent<NpcController>(); if (!navAgent.autoRepath && inAngle && !isBlocked) { if (target.status.currentHealth <= 0) { Debug.Log("Too Late"); RescuingTarget = null; BackToPatrol(); } else if (Distance() <= restDistance + 0.5f) { Debug.Log("Got U"); target.status.isStruggling = false; RescuingTarget = null; BackToPatrol(); } } else if (navAgent.velocity.magnitude >= 0.1 || navAgent.isOnOffMeshLink) { LimpingChange("Run"); } else if (!navAgent.isOnOffMeshLink && !HasInteract) { animator.Play("Idle", 0); timer -= Time.deltaTime; if (timer <= 0) { RescuingTarget = null; timer = resetTimer; //TODO: Cant Reach Destination Debug.Log("Cant Reach Destination"); BackToPatrol(); } } } } } public void Alive() { restTime = recordRestTimer; navAgent.speed = recordSpeed; currentTerminalPos = NewDestination(); IsRandomTalking = false; m_fsm.ChangeState("Patrol"); } #endregion #region Fixing public void TriggerFixing() { HasInteract = false; navAgent.speed *= ((status.currentStamina / 100) * 0.4f + 0.6f) * boostSpeed; m_fsm.ChangeState("Fixing"); } void Fixing() { if (fixTarget != null && fixTargetTransform != null) { float a = fixTargetTransform.position.x - transform.position.x; float b = fixTargetTransform.position.z - transform.position.z; float c = Mathf.Sqrt(Mathf.Pow(a, 2) + Mathf.Pow(b, 2)); if (c < restDistance + 1 || !navAgent.enabled) { IsInteracting = true; bool Damping = false; Vector3 TraPos = new Vector3(transform.position.x, 0, transform.position.z); Vector3 IntPos = new Vector3(fixTargetTransform.position.x, 0, fixTargetTransform.position.z); if ((TraPos - IntPos).sqrMagnitude >= 0.001) { transform.position = new Vector3(Mathf.SmoothDamp(transform.position.x, fixTargetTransform.position.x, ref VelocityPosX, DampPosSpeed) , transform.position.y , Mathf.SmoothDamp(transform.position.z, fixTargetTransform.position.z, ref VelocityPosZ, DampPosSpeed)); Damping = true; } if (Quaternion.Angle(transform.rotation, fixTargetTransform.rotation) >= 0.2) { transform.rotation = Quaternion.Slerp(transform.rotation, fixTargetTransform.rotation, DampRotSpeed); Damping = true; } if (Damping) { //Debug.Log("Damping"); } else if (!HasInteract) { if (fixTarget.GetComponent<DoorController>() != null) { Debug.Log("Fixing Door"); DoorController door = fixTarget.GetComponent<DoorController>(); door.isFixing = true; door.currentHealth += status.fixRate * Time.deltaTime; foreach (var item in door.Locators) { if (item.npc != null) continue; item.npc = this; } animator.Play("Squat Terminal", 0); if (door.currentHealth >= door.maxHealth) { if (door.cBord != null) { if (door.cBord.GetComponent<CBordPos>().isPowerOff) { Debug.Log("Need Fix CBord ASAP"); fixTarget = door.cBord.gameObject; fixTargetTransform = door.cBord.Locators[0].Locator; IsInteracting = false; foreach (var item in door.Locators) { item.npc = null; } RemoveMenu("Interact"); AddStopMenu(); Dispatch(door.cBord.Locators[0].Locator.position); } else { Debug.Log("Fixed Door"); foreach (var item in door.Locators) { item.npc = null; } door.RemoveAndInsertMenu("Repair", "SwitchStates", "Lock", false, door.SwtichStates, 1 << LayerMask.GetMask("Door")); IsInteracting = false; fixTarget = null; fixTargetTransform = null; HasInteract = true; BackToPatrol(); } } else { Debug.Log("Fixed Door"); foreach (var item in door.Locators) { item.npc = null; } door.RemoveAndInsertMenu("Repair", "SwitchStates", "Lock", false, door.SwtichStates, 1 << LayerMask.GetMask("Door")); IsInteracting = false; fixTarget = null; fixTargetTransform = null; HasInteract = true; BackToPatrol(); } } } else if (fixTarget.GetComponent<CBordPos>() != null) { Debug.Log("Fixing CBord"); CBordPos cBord = fixTarget.GetComponent<CBordPos>(); cBord.isFixing = true; cBord.currentHealth += status.fixRate * Time.deltaTime; cBord.Locators[0].npc = this; animator.Play("Squat Terminal", 0); if (!cBord.isPowerOff) { Debug.Log("Fixed CBord"); cBord.RemoveAndInsertMenu("Repair", "Operate", "Operate", true,cBord.CallNPC, 1 << LayerMask.NameToLayer("NPC")); if (!cBord.isLocked) { if(cBord.door != null) { DoorController door = cBord.door.GetComponent<DoorController>(); door.RemoveAndInsertMenu("Repair", "SwitchStates", "Lock", false, door.SwtichStates, 1 << LayerMask.GetMask("Door")); } } cBord.Locators[0].npc = null; fixTarget = null; fixTargetTransform = null; cBord.isFixing = false; HasInteract = true; IsInteracting = false; if (!navAgent.enabled) { navAgent.enabled = true; } BackToPatrol(); } } } } else if (navAgent.velocity.magnitude >= 0.1 || navAgent.isOnOffMeshLink) { LimpingChange("Run"); if (fixTarget.GetComponent<CBordPos>() != null) { if(fixTarget.GetComponent<CBordPos>().Locators[0].npc != null) { BackToPatrol(); } } else if (fixTarget.GetComponent<DoorController>() != null) { DoorController door = fixTarget.GetComponent<DoorController>(); foreach (var item in door.Locators) { if (item.npc != null) { BackToPatrol(); } } } } else if (!navAgent.isOnOffMeshLink && !HasInteract) { animator.Play("Idle", 0); timer -= Time.deltaTime; if (timer <= 0) { fixTarget = null; fixTargetTransform = null; timer = resetTimer; //TODO: Cant Reach Destination Debug.Log("Cant Reach Destination"); BackToPatrol(); } } } } #endregion #region Receive Call public void ReceiveInteractCall(object obj) { Flashing = false; outline.OutlineWidth = 0; SetOutline(false); if (navAgent.enabled) { GameObject gameObj = (GameObject)obj; if (gameObj.GetComponent<Item_SO>() != null) { ReceiveItemCall(gameObj); } else { Interact_SO item = gameObj.GetComponent<Interact_SO>(); StoragePos storge = item as StoragePos; if (item != null) { Debug.Log("Receive Interact Call"); Vector3 Pos = Vector3.zero; float minDistance = Mathf.Infinity; bool isEmpty = false; for (int i = 0; i < item.Locators.Count; i++) { if (item.Locators[i].npc != null) continue; isEmpty = true; float a = item.Locators[i].Locator.position.x - transform.position.x; float b = item.Locators[i].Locator.position.z - transform.position.z; float c = Mathf.Sqrt(Mathf.Pow(a, 2) + Mathf.Pow(b, 2)); float distance = Mathf.Abs(c); if (distance < minDistance) { minDistance = distance; Pos = item.Locators[i].Locator.position; locatorList = item.Locators[i]; } } if (!isEmpty) return; if (storge != null) { IsGrabbing = false; } CurrentInteractObject = item; HasInteract = false; Dispatch(Pos); navAgent.speed *= ((status.currentStamina / 100) * 0.4f + 0.6f) * boostSpeed; RemoveMenu("Interact"); m_fsm.ChangeState("InteractWithItem"); } } } } public void ReceiveItemCall(object obj) { if (status.CarryItem == Item_SO.ItemType.None) { GameObject gameObj = (GameObject)obj; Item_SO item = gameObj.GetComponent<Item_SO>(); if (item != null) { Debug.Log("Receive Item Call"); } CurrentInteractObject = null; CurrentInteractItem = item; HasInteract = false; Dispatch(CurrentInteractItem.gameObject.transform.position); navAgent.speed *= ((status.currentStamina / 100) * 0.4f + 0.6f) * boostSpeed; m_fsm.ChangeState("InteractWithItem"); } else { Debug.Log("Leave it alone, dont be too greedy"); } } public void InteractMoment() { if (CurrentInteractObject != null) { CurrentInteractObject.NPCInteract(0); PlayAudio("light_lever"); } } public void ReceiveGrabOut(StoragePos storgePos, int Index, bool Grabbing) { Vector3 Pos = Vector3.zero; float minDistance = Mathf.Infinity; bool isEmpty = false; for (int i = 0; i < storgePos.Locators.Count; i++) { if (storgePos.Locators[i].npc != null) continue; isEmpty = true; float a = storgePos.Locators[i].Locator.position.x - transform.position.x; float b = storgePos.Locators[i].Locator.position.z - transform.position.z; float c = Mathf.Sqrt(Mathf.Pow(a, 2) + Mathf.Pow(b, 2)); float distance = Mathf.Abs(c); if (distance < minDistance) { minDistance = distance; Pos = storgePos.Locators[i].Locator.position; locatorList = storgePos.Locators[i]; } } if (!isEmpty) return; IsGrabbing = Grabbing; CurrentInteractObject = storgePos; if (Grabbing) { GrabOutIndex = Index; } else { if (status.CarryItem == Item_SO.ItemType.None) { Debug.Log(status.npcName + ": I don't have Item to store"); return; } } HasInteract = false; Dispatch(Pos); navAgent.speed *= ((status.currentStamina / 100) * 0.4f + 0.6f) * boostSpeed; m_fsm.ChangeState("InteractWithItem"); } #endregion #region Play Animation void PlayGetInAnim() { if (CurrentInteractObject != null) { float a = locatorList.Locator.position.x - transform.position.x; float b = locatorList.Locator.position.z - transform.position.z; float c = Mathf.Sqrt(Mathf.Pow(a, 2) + Mathf.Pow(b, 2)); if (c < restDistance || !navAgent.enabled) { boxCollider.isTrigger = true; IsInteracting = true; navAgent.enabled = false; bool Damping = false; Vector3 TraPos = new Vector3(transform.position.x, 0, transform.position.z); Vector3 IntPos = new Vector3(locatorList.Locator.position.x, 0, locatorList.Locator.position.z); if ((TraPos - IntPos).sqrMagnitude >= 0.01f) { transform.position = new Vector3(Mathf.SmoothDamp(transform.position.x, locatorList.Locator.position.x, ref VelocityPosX, DampPosSpeed) , transform.position.y , Mathf.SmoothDamp(transform.position.z, locatorList.Locator.position.z, ref VelocityPosZ, DampPosSpeed)); Damping = true; } if (Quaternion.Angle(transform.rotation, locatorList.Locator.rotation) >= 0.2f) { transform.rotation = Quaternion.Slerp(transform.rotation, locatorList.Locator.rotation, DampRotSpeed); Damping = true; } if (Damping) { //Debug.Log("Damping"); } else if (!HasInteract) { switch (CurrentInteractObject.type) { case Interact_SO.InteractType.ServerPos: CurrentInteractObject.Locators.Find((x) => (x == locatorList)).npc = this; animator.Play("UnlockTerminal", 0); HasInteract = true; break; case Interact_SO.InteractType.Locker: if (IsPrisoner) { EventCenter.GetInstance().DiaEventTrigger("01_HideIn"); CurrentInteractObject.IsInteracting = true; } CurrentInteractObject.NPCInteract(0); CurrentInteractObject.Locators.Find((x) => (x == locatorList)).npc = this; animator.Play("Get In Locker", 0); HasInteract = true; break; case Interact_SO.InteractType.Box: CurrentInteractObject.NPCInteract(0); CurrentInteractObject.Locators.Find((x) => (x == locatorList)).npc = this; animator.Play("Get In Box", 0); HasInteract = true; break; case Interact_SO.InteractType.Bed: CurrentInteractObject.NPCInteract(0); foreach (var item in CurrentInteractObject.GetComponent<Interact_SO>().Locators) { item.npc = this; } if (locatorList.Locator.name == "locatorL") animator.Play("Bed Left On", 0); else animator.Play("Bed Right On", 0); HasInteract = true; break; case Interact_SO.InteractType.Chair: CurrentInteractObject.NPCInteract(0); CurrentInteractObject.Locators.Find((x) => (x == locatorList)).npc = this; animator.Play("Sitting On Chair"); HasInteract = true; break; case Interact_SO.InteractType.Terminal: CurrentInteractObject.NPCInteract(0); animator.Play("UnlockTerminal", 0); CurrentInteractObject.Locators.Find((x) => (x == locatorList)).npc = this; HasInteract = true; break; case Interact_SO.InteractType.Switch: if (IsPrisoner) EventCenter.GetInstance().DiaEventTrigger("01_CloseDoor"); animator.Play("Stand Switch", 0); CurrentInteractObject.Locators.Find((x) => (x == locatorList)).npc = this; HasInteract = true; break; case Interact_SO.InteractType.Storage: HasInteract = true; StoragePos sto = CurrentInteractObject.GetComponent<StoragePos>(); if (IsGrabbing) { animator.Play("Grab Item"); if (status.CarryItem != Item_SO.ItemType.Key) { if (status.CarryItem != Item_SO.ItemType.None) { Item_SO.ItemType GrabOutItem = sto.StorageItem[GrabOutIndex]; Item_SO.ItemType PutInItem = status.CarryItem; RemoveAllMenu(); AddMenu("Interact", "Interact", true, ReceiveInteractCall, 1 << LayerMask.NameToLayer("HiddenPos") | 1 << LayerMask.NameToLayer("RestingPos") | 1 << LayerMask.NameToLayer("TerminalPos") | 1 << LayerMask.NameToLayer("SwitchPos") | 1 << LayerMask.NameToLayer("Item") | 1 << LayerMask.NameToLayer("CBord") | 1 << LayerMask.NameToLayer("StoragePos")); status.CarryItem = GrabOutItem; switch (GrabOutItem) { case Item_SO.ItemType.None: break; case Item_SO.ItemType.MedicalKit: InsertMenu(rightClickMenus.Count, "Heal", "Heal", true, Heal, 1 << LayerMask.NameToLayer("NPC")); status.healAmount = 70; Debug.Log("Got MedicalKit"); break; case Item_SO.ItemType.RepairedPart: break; default: break; } sto.StorageItem.Add(PutInItem); sto.StorageItem.Remove(GrabOutItem); sto.UpdateMenu(); } else { status.CarryItem = sto.StorageItem[GrabOutIndex]; switch (sto.StorageItem[GrabOutIndex]) { case Item_SO.ItemType.None: break; case Item_SO.ItemType.MedicalKit: InsertMenu(rightClickMenus.Count, "Heal", "Heal", true, Heal, 1 << LayerMask.NameToLayer("NPC")); status.healAmount = 70; Debug.Log("Got MedicalKit"); break; case Item_SO.ItemType.RepairedPart: break; default: break; } sto.StorageItem.Remove(sto.StorageItem[GrabOutIndex]); sto.UpdateMenu(); } } else Debug.Log("I cant give up this key"); } else { animator.Play("Grab Item"); if (status.CarryItem != Item_SO.ItemType.None) { if (status.CarryItem != Item_SO.ItemType.Key) { if (sto.StorageItem.Count + 1 <= sto.MaxStorage) { sto.StorageItem.Add(status.CarryItem); sto.UpdateMenu(); switch (status.CarryItem) { case Item_SO.ItemType.MedicalKit: if (MenuContains("Heal") >= 0) { RemoveMenu("Heal"); } status.healAmount = 0; break; case Item_SO.ItemType.RepairedPart: break; case Item_SO.ItemType.Key: break; default: break; } status.CarryItem = Item_SO.ItemType.None; } else { Debug.Log("It is full"); } } else Debug.Log("Cant store this"); } else Debug.Log("I dont have any to store"); } break; case Interact_SO.InteractType.CBoard: CurrentInteractObject.Locators.Find((x) => (x == locatorList)).npc = this; CBordPos cBord = CurrentInteractObject as CBordPos; if (cBord != null) { if (cBord.isPowerOff) { fixTarget = CurrentInteractObject.gameObject; fixTargetTransform = cBord.Locators[0].Locator; navAgent.enabled = true; boxCollider.isTrigger = false; Dispatch(cBord.Locators[0].Locator.position); CurrentInteractObject = null; m_fsm.ChangeState("Fixing"); } else { if (cBord.isLocked) { animator.Play("UnlockTerminal", 0); CurrentInteractObject.NPCInteract(0); HasInteract = true; } else { animator.Play("UnlockTerminal", 0); HasInteract = true; } } } else Debug.LogWarning("No CBord", gameObject); break; default: break; } } } else if (navAgent.velocity.magnitude >= 0.1 || navAgent.isOnOffMeshLink) { LimpingChange("Run"); if (locatorList.npc != null) { BackToPatrol(); } } else if (!navAgent.isOnOffMeshLink) { animator.Play("Idle", 0); timer -= Time.deltaTime; if (timer <= 0) { CurrentInteractObject = null; locatorList = null; timer = resetTimer; //TODO: Cant Reach Destination Debug.Log("Cant Reach Destination"); BackToPatrol(); } } } else if (CurrentInteractItem != null) { float a = CurrentInteractItem.transform.position.x - transform.position.x; float b = CurrentInteractItem.transform.position.z - transform.position.z; float c = Mathf.Sqrt(Mathf.Pow(a, 2) + Mathf.Pow(b, 2)); if (c <= restDistance) { bool Damping = false; Vector3 dir = (CurrentInteractItem.transform.position - transform.position).normalized; dir.y = 0; Quaternion rotation = Quaternion.LookRotation(dir); if (Quaternion.Angle(transform.rotation, rotation) >= 1) { transform.rotation = Quaternion.Slerp(transform.rotation, rotation, DampRotSpeed); Damping = true; } if (Damping) { //Debug.Log("Damping"); } else if (!HasInteract) { boxCollider.isTrigger = true; IsInteracting = true; navAgent.enabled = false; HasInteract = true; switch (CurrentInteractItem.type) { case Item_SO.ItemType.MedicalKit: Debug.Log("Got MedicalKit"); animator.Play("Grab Item", 0); break; case Item_SO.ItemType.Key: Debug.Log("Key"); animator.Play("Grab Item", 0); break; case Item_SO.ItemType.RepairedPart: Debug.Log("RepairedPart"); animator.Play("Grab Item", 0); break; default: break; } } } else if (navAgent.velocity.magnitude >= 0.1 || navAgent.isOnOffMeshLink) { LimpingChange("Run"); } else if (!navAgent.isOnOffMeshLink && !HasInteract) { animator.Play("Idle", 0); timer -= Time.deltaTime; if (timer <= 0) { CurrentInteractItem = null; timer = resetTimer; //TODO: Cant Reach Destination Debug.Log("Cant Reach Destination"); BackToPatrol(); } } } } public void PlayGetOutAnim(object obj) { GameObject gameObj = (GameObject)obj; Interact_SO item = gameObj.GetComponent<Interact_SO>(); switch (item.type) { case Interact_SO.InteractType.Locker: animator.Play("Get Out Locker", 0); transform.eulerAngles += new Vector3(0, 180, 0); break; case Interact_SO.InteractType.Box: animator.Play("Get Out Box", 0); transform.eulerAngles += new Vector3(0, 180, 0); break; case Interact_SO.InteractType.Bed: if (locatorList.Locator.name == "locatorL") animator.Play("Bed Left Off", 0); else animator.Play("Bed Right Off", 0); break; case Interact_SO.InteractType.Chair: animator.Play("Sitting Off Chair"); break; case Interact_SO.InteractType.Terminal: break; case Interact_SO.InteractType.Switch: break; default: break; } CurrentInteractObject = item; } public void CompleteGetInItemAction() { Debug.Log("Get In Animation Done"); switch (CurrentInteractObject.type) { case Interact_SO.InteractType.Locker: boxCollider.size = new Vector3(0.001f, 0.001f, 0.001f); isSafe = true; if (IsPrisoner) CurrentInteractObject.IsInteracting = true; break; case Interact_SO.InteractType.Box: isSafe = true; break; case Interact_SO.InteractType.Bed: break; case Interact_SO.InteractType.Chair: CurrentInteractObject.GetComponent<BoxCollider>().size = CurrentInteractObject.newColliderSize; CurrentInteractObject.GetComponent<BoxCollider>().center = CurrentInteractObject.newColliderCenter; boxCollider.size = new Vector3(0.001f, 0.001f, 0.001f); break; case Interact_SO.InteractType.Terminal: break; case Interact_SO.InteractType.Switch: break; case Interact_SO.InteractType.Storage: break; case Interact_SO.InteractType.CBoard: break; default: break; } CurrentInteractObject.Locators.Find((x) => (x == locatorList)).npc = this; m_fsm.ChangeState("Rest"); } public void CompleteGetOutItemAction() { Debug.Log("Get Out Animation Done"); boxCollider.isTrigger = false; IsInteracting = false; navAgent.enabled = true; if (CurrentInteractObject != null) { switch (CurrentInteractObject.type) { case Interact_SO.InteractType.ServerPos: if(status.CarryItem == Item_SO.ItemType.RepairedPart) { ServerPos server = CurrentInteractObject as ServerPos; server.isUnlocked = true; if (server.RedLight != null && server.GreenLight != null) { foreach (var item in server.RedLight) { item.SetActive(false); } foreach (var item in server.GreenLight) { item.SetActive(true); } } server.IsInteracting = true; Debug.Log("Server unlocked"); status.CarryItem = Item_SO.ItemType.None; } else { Debug.Log("I dont have RepairedPart"); } break; case Interact_SO.InteractType.Locker: if(SendEventWhenGetOutLocker) { SendEventWhenGetOutLocker = false; EventCenter.GetInstance().EventTriggered("01_03DiaPlay"); } CurrentInteractObject.RemoveAndInsertMenu("Leave", "Hide In", "Hide In", true, CurrentInteractObject.CallNPC, 1 << LayerMask.NameToLayer("NPC")); boxCollider.size = recordColliderSize; CurrentInteractObject.IsInteracting = false; isSafe = false; break; case Interact_SO.InteractType.Box: CurrentInteractObject.RemoveAndInsertMenu("Leave", "Hide In", "Hide In", true, CurrentInteractObject.CallNPC, 1 << LayerMask.NameToLayer("NPC")); isSafe = false; CurrentInteractObject.IsInteracting = false; break; case Interact_SO.InteractType.Bed: CurrentInteractObject.RemoveAndInsertMenu("Leave", "RestIn", "RestIn", true, CurrentInteractObject.CallNPC, 1 << LayerMask.NameToLayer("NPC")); CurrentInteractObject.IsInteracting = false; break; case Interact_SO.InteractType.Chair: CurrentInteractObject.RemoveAndInsertMenu("Leave", "RestIn", "RestIn", true, CurrentInteractObject.CallNPC, 1 << LayerMask.NameToLayer("NPC")); CurrentInteractObject.GetComponent<BoxCollider>().size = CurrentInteractObject.recordColliderSize; CurrentInteractObject.GetComponent<BoxCollider>().center = CurrentInteractObject.recordColliderCenter; boxCollider.size = recordColliderSize; CurrentInteractObject.IsInteracting = false; break; case Interact_SO.InteractType.Terminal: CurrentInteractObject.RemoveAndInsertMenu("Leave", "Operate", "Operate", false, CurrentInteractObject.CallNPC, 1 << LayerMask.NameToLayer("NPC")); CurrentInteractObject.IsInteracting = false; if (status.CarryItem != Item_SO.ItemType.None) { Debug.Log("I dont have place to get this"); break; } else { TerminalPos terminal = CurrentInteractObject as TerminalPos; if(terminal.code == "") { Debug.Log("There is no Key"); } else { status.CarryItem = Item_SO.ItemType.Key; status.code = terminal.code; terminal.code = ""; } } break; case Interact_SO.InteractType.Switch: CurrentInteractObject.IsInteracting = false; break; case Interact_SO.InteractType.CBoard: CurrentInteractObject.IsInteracting = false; CBordPos cBord = CurrentInteractObject as CBordPos; if (cBord != null) { if (!cBord.isPowerOff) { if (!cBord.isLocked) { Debug.Log("It is unlocked"); } else { if (status.code != "") { if (status.code == cBord.code) { Debug.Log("Right Key"); status.CarryItem = Item_SO.ItemType.None; status.code = ""; if(cBord.door != null) { DoorController door = cBord.door.GetComponent<DoorController>(); door.currentHealth = door.maxHealth; door.isPowerOff = false; door.isLocked = false; door.navOb.enabled = false; door.AddMenu("SwitchStates", "Lock", false, door.SwtichStates, 1 << LayerMask.GetMask("Door")); } if(cBord.swtich != null) { SwitchPos swtich = cBord.swtich.GetComponent<SwitchPos>(); swtich.AddMenu("SwtichState", "Lock Door", true, swtich.CallNPC, 1 << LayerMask.NameToLayer("NPC")); } cBord.isLocked = false; if(IsHighP) { Debug.Log("IsHighP"); if (status.npcName == "Stephanus Lentinus") { Debug.Log("Ste"); PuEvt.NPCTalking[0].Graph = Graph1; PuEvt.NPCTalking[0].moveToClasses[1].Obj = gameObject; HighP.status.toDoList.Add(PuEvt); HighP.TriggerEvent(); status.toDoList.Add(PuEvt); TriggerEvent(); PuEvt.NPCTalking[0].room.NPCAgentList.Add(status.npcName, false); PuEvt.NPCTalking[0].room.NPCAgentList.Add(HighP.status.npcName, false); } else { Debug.Log("Common"); PuEvt.NPCTalking[0].Graph = Graph1_5; PuEvt.NPCTalking[0].moveToClasses[1].Obj = gameObject; HighP.status.toDoList.Add(PuEvt); HighP.TriggerEvent(); status.toDoList.Add(PuEvt); TriggerEvent(); PuEvt.NPCTalking[0].room.NPCAgentList.Add(status.npcName, false); PuEvt.NPCTalking[0].room.NPCAgentList.Add(HighP.status.npcName, false); } PuEvt.NPCTalking[0].room.WaitingGraph = PuEvt.NPCTalking[0].Graph; if (GameManager.GetInstance().CurrentRoom != PuEvt.NPCTalking[0].room) { EventCenter.GetInstance().EventTriggered(PuEvt.NPCTalking[0].room.RoomName() + (0).ToString() + "CameraEvent"); } List<NpcController> nptrrr = GameManager.GetInstance().NPC; foreach (var item in nptrrr) { item.IsHighP = false; } } GameManager.GetInstance().SetupStage(2); } else { Debug.Log("Wrong Key"); break; } } else { Debug.Log("No Key"); break; } } } } else Debug.LogWarning("No CBord", gameObject); break; default: break; } CurrentInteractObject = null; locatorList.npc = null; locatorList = null; } else if (CurrentInteractItem != null && status.CarryItem == Item_SO.ItemType.None) { Debug.Log("Grabing"); switch (CurrentInteractItem.type) { case Item_SO.ItemType.None: CurrentInteractItem = null; break; case Item_SO.ItemType.MedicalKit: status.CarryItem = CurrentInteractItem.type; if (CurrentInteractItem.GetComponent<MedicalKit>() != null) status.healAmount = CurrentInteractItem.GetComponent<MedicalKit>().HPRecovery; else status.healAmount = CurrentInteractItem.GetComponent<DeadBox>().HPRecovery; InsertMenu(rightClickMenus.Count, "Heal", "Heal", true, Heal, 1 << LayerMask.NameToLayer("NPC")); CurrentInteractItem.NPCInteract(0); CurrentInteractItem = null; break; case Item_SO.ItemType.Key: status.CarryItem = CurrentInteractItem.type; status.code = CurrentInteractItem.GetComponent<DeadBox>().code; CurrentInteractItem.NPCInteract(0); break; case Item_SO.ItemType.RepairedPart: status.CarryItem = CurrentInteractItem.type; CurrentInteractItem.NPCInteract(0); break; default: break; } } else if (CurrentInteractItem == null && status.CarryItem != Item_SO.ItemType.None) { switch (status.CarryItem) { case Item_SO.ItemType.None: break; case Item_SO.ItemType.MedicalKit: Debug.Log("Healing"); if (HealingTarget != null) { NpcController npc = HealingTarget.GetComponent<NpcController>(); if(npc.status.currentHealth< npc.status.maxHealth) { HealingTarget.GetComponent<NpcController>().ApplyHealth(status.healAmount); HealingTarget = null; status.CarryItem = Item_SO.ItemType.None; status.healAmount = 0; RemoveMenu("Heal"); } else { Debug.Log("No need Heal"); HealingTarget = null; } } else { ApplyHealth(status.healAmount); status.CarryItem = Item_SO.ItemType.None; status.healAmount = 0; RemoveMenu("Heal"); } break; default: break; } } else if (CurrentInteractItem != null && status.CarryItem != Item_SO.ItemType.None) { CurrentInteractItem = null; } if (m_fsm.GetCurrentState() != "GotAttacked" && (!inAnimState || IsPrisoner)) BackToPatrol(); else { SwitchAnimState(true, AnimStateName); isGuard = false; } } public void FacingEachOther(bool IsFacingCamera = false) { Vector3 dir = Vector3.zero; if (!IsFacingCamera) { dir = (TalkingPos - transform.position).normalized; } else { dir = (currentRoomTracker.cameraLists[currentRoomTracker.CurrentCameraIndex].roomCamera.gameObject.transform.position - transform.position).normalized; } bool Damping = false; dir.y = 0; Quaternion rotation = Quaternion.LookRotation(dir); if (Quaternion.Angle(transform.rotation, rotation) >= 1) { transform.rotation = Quaternion.Slerp(transform.rotation, rotation, DampRotSpeed); Damping = true; } if (Damping) { //Debug.Log("Damping"); } } public void DeathCutScene() { Flashing = false; if (outline != null) { outline.OutlineWidth = 0f; SetOutline(false); } boxCollider.enabled = false; gameObject.layer = LayerMask.NameToLayer("Dead"); gameObject.layer = LayerMask.NameToLayer("Dead"); } public void FacingEachOther(Transform tran) { Vector3 dir = (tran.position - transform.position).normalized; dir.y = 0; Quaternion rotation = Quaternion.LookRotation(dir); if (Quaternion.Angle(transform.rotation, rotation) >= 1) { transform.rotation = Quaternion.Slerp(transform.rotation, rotation, DampRotSpeed); } } public void FacingEachOtherCoro(Transform tran) { Vector3 dir = (tran.position - transform.position).normalized; StartCoroutine(FacingEachOtherCoro(dir)); } public void FacingEachOtherCoro() { Vector3 dir = (currentRoomTracker.cameraLists[currentRoomTracker.CurrentCameraIndex].roomCamera.gameObject.transform.position - transform.position).normalized; StartCoroutine(FacingEachOtherCoro(dir)); } IEnumerator FacingEachOtherCoro(Vector3 dir) { bool Damping = true; dir.y = 0; Quaternion rotation = Quaternion.LookRotation(dir); while (Damping) { if (Quaternion.Angle(transform.rotation, rotation) >= 1) { transform.rotation = Quaternion.Slerp(transform.rotation, rotation, DampRotSpeed); Damping = true; } else { Damping = false; } yield return null; } } #endregion #region Status Change public void ApplyHealth(float healthAmount) { status.currentHealth = status.currentHealth + healthAmount > status.maxHealth ? status.maxHealth : status.currentHealth += healthAmount; } public void ApplyStamina(float staminaAmount) { status.currentStamina = status.currentStamina + staminaAmount > status.maxStamina ? status.maxStamina : status.currentStamina += staminaAmount; } public void ApplyCredit(float creditAmount) { status.currentCredit = status.currentCredit + creditAmount > status.maxCredit ? status.maxCredit : status.currentCredit += creditAmount; } public void RecoverStamina(float rate) { status.currentStamina = status.currentStamina + rate * Time.deltaTime > status.maxStamina ? status.maxStamina : status.currentStamina += rate * Time.deltaTime; } public void TakeDamage(float damageAmount) { status.currentHealth -= damageAmount; if (status.currentHealth <= 0) { Death(); } } public void IsStruggling(float rate) { status.currentHealth -= rate * Time.deltaTime; if (status.currentHealth <= 0) { PlayAudio("Dead_Simple " + Random.Range(1, 5).ToString()); Death(); } } public void ConsumeStamina(float staminaAmount) { status.currentStamina = status.currentStamina - staminaAmount <= 0 ? 0 : status.currentStamina -= staminaAmount; } public void ReduceCredit(float creditAmount) { status.currentCredit = status.currentCredit - creditAmount <= 0 ? 0 : status.currentCredit -= creditAmount; } #endregion #region Gizmos public void OnDrawGizmosSelected() { Gizmos.color = Color.blue; Gizmos.DrawWireSphere(currentTerminalPos, 1); Gizmos.color = Color.blue; Gizmos.DrawWireSphere(transform.position, bannedRadius); Gizmos.color = Color.red; Gizmos.DrawWireSphere(transform.position, alertRadius); Gizmos.color = Color.green; Gizmos.DrawRay(transform.position + new Vector3(0, 3, 0), -transform.up * detectRay); if (RescuingTarget != null) { if (isBlocked) { Gizmos.color = Color.blue; } else { Gizmos.color = inAngle ? Color.red : Color.green; } Gizmos.DrawLine(transform.position + new Vector3(0, 3, 0), RescuingTarget.transform.position + new Vector3(0, 3, 0)); } Gizmos.color = Color.white; if(navAgent != null) Gizmos.DrawSphere(navAgent.destination, 1); } #endregion #region SpecialTalking public void SpecialTalking(object obj) { switch (Stage) { case 0: GameManager.GetInstance().CurrentRoom.PlayingDialogue(NoThingTalk); break; case 1: GameManager.GetInstance().CurrentRoom.PlayingDialogue(MedicalKit); break; case 2: GameManager.GetInstance().CurrentRoom.PlayingDialogue(JoinIn); break; default: break; } } #endregion }
39.176494
212
0.452004
[ "MIT" ]
ShenKSPZ/Devetober-2020
Devtober 2020/Assets/Scritps/AI/NpcController.cs
100,455
C#
using Codeuctivity.OpenXmlPowerTools; using Codeuctivity.OpenXmlPowerTools.OpenXMLWordprocessingMLToHtmlConverter; using DocumentFormat.OpenXml.Packaging; using System; using System.IO; using System.Linq; using System.Text; using System.Xml; using System.Xml.Linq; namespace HtmlToWmlConverter02 { internal class Program { private static void Main() { var n = DateTime.Now; var tempDi = new DirectoryInfo(string.Format("ExampleOutput-{0:00}-{1:00}-{2:00}-{3:00}{4:00}{5:00}", n.Year - 2000, n.Month, n.Day, n.Hour, n.Minute, n.Second)); tempDi.Create(); var templateDoc = new FileInfo("../../TemplateDocument.docx"); var dataFile = new FileInfo(Path.Combine(tempDi.FullName, "Data.xml")); // The following method generates a large data file with random data. // In a real world scenario, this is where you would query your data source and produce XML that will drive your document generation process. var numberOfDocumentsToGenerate = 100; var data = GenerateDataFromDataSource(dataFile, numberOfDocumentsToGenerate); var wmlDoc = new WmlDocument(templateDoc.FullName); var count = 1; foreach (var customer in data.Elements("Customer")) { var assembledDoc = new FileInfo(Path.Combine(tempDi.FullName, string.Format("Letter-{0:0000}.docx", count++))); Console.WriteLine("Generating {0}", assembledDoc.Name); var wmlAssembledDoc = DocumentAssembler.AssembleDocument(wmlDoc, customer, out var templateError); if (templateError) { Console.WriteLine("Errors in template."); Console.WriteLine("See {0} to determine the errors in the template.", assembledDoc.Name); } wmlAssembledDoc.SaveAs(assembledDoc.FullName); Console.WriteLine("Converting to HTML {0}", assembledDoc.Name); var htmlFileName = ConvertToHtml(assembledDoc.FullName, tempDi.FullName); Console.WriteLine("Converting back to DOCX {0}", htmlFileName.Name); ConvertToDocx(htmlFileName.FullName, tempDi.FullName); } } private static readonly string[] s_productNames = new[] { "Unicycle", "Bicycle", "Tricycle", "Skateboard", "Roller Blades", "Hang Glider", }; private static XElement GenerateDataFromDataSource(FileInfo dataFi, int numberOfDocumentsToGenerate) { var customers = new XElement("Customers"); var r = new Random(); for (var i = 0; i < numberOfDocumentsToGenerate; ++i) { var customer = new XElement("Customer", new XElement("CustomerID", i + 1), new XElement("Name", "Eric White"), new XElement("HighValueCustomer", r.Next(2) == 0 ? "True" : "False"), new XElement("Orders")); var orders = customer.Element("Orders"); var numberOfOrders = r.Next(10) + 1; for (var j = 0; j < numberOfOrders; j++) { var order = new XElement("Order", new XAttribute("Number", j + 1), new XElement("ProductDescription", s_productNames[r.Next(s_productNames.Length)]), new XElement("Quantity", r.Next(10)), new XElement("OrderDate", "September 26, 2015")); orders.Add(order); } customers.Add(customer); } customers.Save(dataFi.FullName); return customers; } public static FileInfo ConvertToHtml(string file, string outputDirectory) { var fi = new FileInfo(file); var byteArray = File.ReadAllBytes(fi.FullName); using var memoryStream = new MemoryStream(); memoryStream.Write(byteArray, 0, byteArray.Length); using var wDoc = WordprocessingDocument.Open(memoryStream, true); var destFileName = new FileInfo(fi.Name.Replace(".docx", ".html")); if (outputDirectory != null && outputDirectory != string.Empty) { var di = new DirectoryInfo(outputDirectory); if (!di.Exists) { throw new OpenXmlPowerToolsException("Output directory does not exist"); } destFileName = new FileInfo(Path.Combine(di.FullName, destFileName.Name)); } var imageDirectoryName = destFileName.FullName.Substring(0, destFileName.FullName.Length - 5) + "_files"; var pageTitle = fi.FullName; var part = wDoc.CoreFilePropertiesPart; if (part != null) { pageTitle = (string)part.GetXDocument().Descendants(DC.title).FirstOrDefault() ?? fi.FullName; } // TODO: Determine max-width from size of content area. var settings = new WmlToHtmlConverterSettings(pageTitle); var htmlElement = WmlToHtmlConverter.ConvertToHtml(wDoc, settings); // Produce HTML document with <!DOCTYPE html > declaration to tell the browser // we are using HTML5. var html = new XDocument( new XDocumentType("html", null, null, null), htmlElement); // Note: the xhtml returned by ConvertToHtmlTransform contains objects of type // XEntity. PtOpenXmlUtil.cs define the XEntity class. See // http://blogs.msdn.com/ericwhite/archive/2010/01/21/writing-entity-references-using-linq-to-xml.aspx // for detailed explanation. // // If you further transform the XML tree returned by ConvertToHtmlTransform, you // must do it correctly, or entities will not be serialized properly. var htmlString = html.ToString(SaveOptions.DisableFormatting); File.WriteAllText(destFileName.FullName, htmlString, Encoding.UTF8); return destFileName; } private static void ConvertToDocx(string file, string destinationDir) { var sourceHtmlFi = new FileInfo(file); var sourceImageDi = new DirectoryInfo(destinationDir); var destDocxFi = new FileInfo(Path.Combine(destinationDir, sourceHtmlFi.Name.Replace(".html", "-ConvertedByHtmlToWml.docx"))); var html = HtmlToWmlReadAsXElement.ReadAsXElement(sourceHtmlFi); var usedAuthorCss = HtmlToWmlConverter.CleanUpCss((string)html.Descendants().FirstOrDefault(d => d.Name.LocalName.ToLower() == "style")); var settings = HtmlToWmlConverter.GetDefaultSettings(); // image references in HTML files contain the path to the subdir that contains the images, so base URI is the name of the directory // that contains the HTML files settings.BaseUriForImages = sourceHtmlFi.DirectoryName; var doc = HtmlToWmlConverter.ConvertHtmlToWml(defaultCss, usedAuthorCss, userCss, html, settings); doc.SaveAs(destDocxFi.FullName); } public class HtmlToWmlReadAsXElement { public static XElement ReadAsXElement(FileInfo sourceHtmlFi) { var htmlString = File.ReadAllText(sourceHtmlFi.FullName); XElement html = null; try { html = XElement.Parse(htmlString); } #if USE_HTMLAGILITYPACK catch (XmlException) { HtmlDocument hdoc = new HtmlDocument(); hdoc.Load(sourceHtmlFi.FullName, Encoding.Default); hdoc.OptionOutputAsXml = true; hdoc.Save(sourceHtmlFi.FullName, Encoding.Default); StringBuilder sb = new StringBuilder(File.ReadAllText(sourceHtmlFi.FullName, Encoding.Default)); sb.Replace("&amp;", "&"); sb.Replace("&nbsp;", "\xA0"); sb.Replace("&quot;", "\""); sb.Replace("&lt;", "~lt;"); sb.Replace("&gt;", "~gt;"); sb.Replace("&#", "~#"); sb.Replace("&", "&amp;"); sb.Replace("~lt;", "&lt;"); sb.Replace("~gt;", "&gt;"); sb.Replace("~#", "&#"); File.WriteAllText(sourceHtmlFi.FullName, sb.ToString(), Encoding.Default); html = XElement.Parse(sb.ToString()); } #else catch (XmlException) { throw; } #endif // HtmlToWmlConverter expects the HTML elements to be in no namespace, so convert all elements to no namespace. html = (XElement)ConvertToNoNamespace(html); return html; } private static object ConvertToNoNamespace(XNode node) { if (node is XElement element) { return new XElement(element.Name.LocalName, element.Attributes().Where(a => !a.IsNamespaceDeclaration), element.Nodes().Select(n => ConvertToNoNamespace(n))); } return node; } } private static readonly string defaultCss = @"html, address, blockquote, body, dd, div, dl, dt, fieldset, form, frame, frameset, h1, h2, h3, h4, h5, h6, noframes, ol, p, ul, center, dir, hr, menu, pre { display: block; unicode-bidi: embed } li { display: list-item } head { display: none } table { display: table } tr { display: table-row } thead { display: table-header-group } tbody { display: table-row-group } tfoot { display: table-footer-group } col { display: table-column } colgroup { display: table-column-group } td, th { display: table-cell } caption { display: table-caption } th { font-weight: bolder; text-align: center } caption { text-align: center } body { margin: auto; } h1 { font-size: 2em; margin: auto; } h2 { font-size: 1.5em; margin: auto; } h3 { font-size: 1.17em; margin: auto; } h4, p, blockquote, ul, fieldset, form, ol, dl, dir, menu { margin: auto } a { color: blue; } h5 { font-size: .83em; margin: auto } h6 { font-size: .75em; margin: auto } h1, h2, h3, h4, h5, h6, b, strong { font-weight: bolder } blockquote { margin-left: 40px; margin-right: 40px } i, cite, em, var, address { font-style: italic } pre, tt, code, kbd, samp { font-family: monospace } pre { white-space: pre } button, textarea, input, select { display: inline-block } big { font-size: 1.17em } small, sub, sup { font-size: .83em } sub { vertical-align: sub } sup { vertical-align: super } table { border-spacing: 2px; } thead, tbody, tfoot { vertical-align: middle } td, th, tr { vertical-align: inherit } s, strike, del { text-decoration: line-through } hr { border: 1px inset } ol, ul, dir, menu, dd { margin-left: 40px } ol { list-style-type: decimal } ol ul, ul ol, ul ul, ol ol { margin-top: 0; margin-bottom: 0 } u, ins { text-decoration: underline } br:before { content: ""\A""; white-space: pre-line } center { text-align: center } :link, :visited { text-decoration: underline } :focus { outline: thin dotted invert } /* Begin bidirectionality settings (do not change) */ BDO[DIR=""ltr""] { direction: ltr; unicode-bidi: bidi-override } BDO[DIR=""rtl""] { direction: rtl; unicode-bidi: bidi-override } *[DIR=""ltr""] { direction: ltr; unicode-bidi: embed } *[DIR=""rtl""] { direction: rtl; unicode-bidi: embed } "; private static readonly string userCss = @""; } }
41.170139
174
0.588513
[ "MIT" ]
stesee/Open-Xml-PowerTools
OpenXmlPowerToolsExamples/HtmlToWmlConverter02/HtmlToWmlConverter02.cs
11,859
C#
// <auto-generated /> using BlazorApp2.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using System; namespace BlazorApp2.Data.Migrations { [DbContext(typeof(ApplicationDbContext))] [Migration("00000000000000_CreateIdentitySchema")] partial class CreateIdentitySchema { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.0.0") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<string>("RoleId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<int>("AccessFailedCount") .HasColumnType("int"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<string>("Email") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<bool>("EmailConfirmed") .HasColumnType("bit"); b.Property<bool>("LockoutEnabled") .HasColumnType("bit"); b.Property<DateTimeOffset?>("LockoutEnd") .HasColumnType("datetimeoffset"); b.Property<string>("NormalizedEmail") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("PasswordHash") .HasColumnType("nvarchar(max)"); b.Property<string>("PhoneNumber") .HasColumnType("nvarchar(max)"); b.Property<bool>("PhoneNumberConfirmed") .HasColumnType("bit"); b.Property<string>("SecurityStamp") .HasColumnType("nvarchar(max)"); b.Property<bool>("TwoFactorEnabled") .HasColumnType("bit"); b.Property<string>("UserName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("ProviderKey") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("ProviderDisplayName") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.Property<string>("RoleId") .HasColumnType("nvarchar(450)"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.Property<string>("LoginProvider") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("Name") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("Value") .HasColumnType("nvarchar(max)"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); #pragma warning restore 612, 618 } } }
37.669065
125
0.47097
[ "MIT" ]
hebelmx/CQRSAndMediator-Scaffolding
BlazorApp2/Data/Migrations/00000000000000_CreateIdentitySchema.Designer.cs
10,472
C#
/* * Copyright 2010-2013 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. */ using System; using System.Net; using Amazon.DirectConnect.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; namespace Amazon.DirectConnect.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for AllocatePrivateVirtualInterface operation /// </summary> internal class AllocatePrivateVirtualInterfaceResponseUnmarshaller : JsonResponseUnmarshaller { public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { AllocatePrivateVirtualInterfaceResponse response = new AllocatePrivateVirtualInterfaceResponse(); context.Read(); response.AllocatePrivateVirtualInterfaceResult = AllocatePrivateVirtualInterfaceResultUnmarshaller.GetInstance().Unmarshall(context); return response; } public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { ErrorResponse errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); if (errorResponse.Code != null && errorResponse.Code.Equals("DirectConnectServerException")) { DirectConnectServerException ex = new DirectConnectServerException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); return ex; } if (errorResponse.Code != null && errorResponse.Code.Equals("DirectConnectClientException")) { DirectConnectClientException ex = new DirectConnectClientException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); return ex; } return new AmazonDirectConnectException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } private static AllocatePrivateVirtualInterfaceResponseUnmarshaller instance; public static AllocatePrivateVirtualInterfaceResponseUnmarshaller GetInstance() { if (instance == null) { instance = new AllocatePrivateVirtualInterfaceResponseUnmarshaller(); } return instance; } } }
41.824324
195
0.704039
[ "Apache-2.0" ]
jdluzen/aws-sdk-net-android
AWSSDK/Amazon.DirectConnect/Model/Internal/MarshallTransformations/AllocatePrivateVirtualInterfaceResponseUnmarshaller.cs
3,095
C#
using System.Threading.Tasks; using Couchbase.IntegrationTests.Fixtures; using Xunit; namespace Couchbase.IntegrationTests { public class SynchronousDurabilityTests : IClassFixture<ClusterFixture> { private readonly ClusterFixture _fixture; public SynchronousDurabilityTests(ClusterFixture fixture) { _fixture = fixture; } [Theory] [InlineData(DurabilityLevel.None)] [InlineData(DurabilityLevel.Majority)] [InlineData(DurabilityLevel.MajorityAndPersistActive)] [InlineData(DurabilityLevel.PersistToMajority)] public async Task Upsert_with_durability(DurabilityLevel durabilityLevel) { var collection = await _fixture.GetDefaultCollection(); // Upsert will throw exception if durability is not met await collection.Upsert( "id", new {name = "mike"}, durabilityLevel: durabilityLevel ); } } }
29.735294
81
0.648863
[ "Apache-2.0" ]
jeffrymorris/dotnet-couchbase-client
tests/Couchbase.IntegrationTests/SynchronousDurabilityTests.cs
1,011
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Buffers.Binary; using System.Device.I2c; using System.Threading; namespace Iot.Device.Ags01db { /// <summary> /// MEMS VOC Gas Sensor ASG01DB /// </summary> public class Ags01db : IDisposable { private I2cDevice _sensor; private int _lastMeasurment = 0; // CRC const private const byte CRC_POLYNOMIAL = 0x31; private const byte CRC_INIT = 0xFF; /// <summary> /// ASG01DB VOC (Volatile Organic Compounds) Gas Concentration (ppm) /// </summary> public double Concentration { get => GetConcentration(); } /// <summary> /// ASG01DB Version /// </summary> public byte Version { get => GetVersion(); } /// <summary> /// ASG01DB Default I2C Address /// </summary> public const byte DefaultI2cAddress = 0x11; /// <summary> /// Creates a new instance of the ASG01DB /// </summary> /// <param name="sensor">I2C Device, like UnixI2cDevice or Windows10I2cDevice</param> public Ags01db(I2cDevice sensor) { _sensor = sensor; } /// <summary> /// Cleanup /// </summary> public void Dispose() { _sensor?.Dispose(); _sensor = null; } /// <summary> /// Get ASG01DB VOC Gas Concentration /// </summary> /// <returns>Concentration (ppm)</returns> private double GetConcentration() { // The time of two measurements should be more than 2s. while (Environment.TickCount - _lastMeasurment < 2000) { Thread.Sleep(TimeSpan.FromMilliseconds(Environment.TickCount - _lastMeasurment)); } // Details in the Datasheet P5 // Write command MSB, LSB Span<byte> writeBuff = stackalloc byte[2] { (byte)Register.ASG_DATA_MSB, (byte)Register.ASG_DATA_LSB }; // Return data MSB, LSB, CRC checksum Span<byte> readBuff = stackalloc byte[3]; _sensor.Write(writeBuff); _sensor.Read(readBuff); _lastMeasurment = Environment.TickCount; // CRC check error if (!CheckCrc8(readBuff.Slice(0, 2), 2, readBuff[2])) { return -1; } ushort res = BinaryPrimitives.ReadUInt16BigEndian(readBuff.Slice(0, 2)); return res / 10.0; } /// <summary> /// Get ASG01DB Version /// </summary> /// <returns>Version</returns> private byte GetVersion() { // Details in the Datasheet P5 // Write command MSB, LSB Span<byte> writeBuff = stackalloc byte[2] { (byte)Register.ASG_VERSION_MSB, (byte)Register.ASG_VERSION_LSB }; // Return version, CRC checksum Span<byte> readBuff = stackalloc byte[2]; _sensor.Write(writeBuff); _sensor.Read(readBuff); // CRC check error if (!CheckCrc8(readBuff.Slice(0, 1), 1, readBuff[1])) { return unchecked((byte)-1); } return readBuff[0]; } /// <summary> /// 8-bit CRC Checksum Calculation /// </summary> /// <param name="data">Raw Data</param> /// <param name="length">Data Length</param> /// <param name="crc8">Raw CRC8</param> /// <returns>Checksum is true or false</returns> private bool CheckCrc8(ReadOnlySpan<byte> data, int length, byte crc8) { // Details in the Datasheet P6 byte crc = CRC_INIT; for (int i = 0; i < length; i++) { crc ^= data[i]; for (int j = 8; j > 0; j--) { if ((crc & 0x80) != 0) crc = (byte)((crc << 1) ^ CRC_POLYNOMIAL); else crc = (byte)(crc << 1); } } if (crc == crc8) return true; else return false; } } }
30.287671
121
0.516961
[ "MIT" ]
491134648/iot
src/devices/Ags01db/Ags01db.cs
4,424
C#
#if HAS_UNO #define STORYBOARD_RETARGET_ISSUE // https://github.com/unoplatform/uno/issues/6960 #define MANIPULATION_ABSOLUTE_COORD_ISSUE // https://github.com/unoplatform/uno/issues/6964 #endif using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Foundation; #if IS_WINUI using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; using Microsoft.UI.Xaml.Input; using Microsoft.UI.Xaml.Media; using Microsoft.UI.Xaml.Media.Animation; #else using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Animation; #endif namespace Uno.Toolkit.UI { /// <summary> /// Represents a container with two views; one view for the main content, /// and another view that can be revealed with swipe gesture. /// </summary> [TemplatePart(Name = TemplateParts.MainContentPresenterName, Type = typeof(ContentPresenter))] [TemplatePart(Name = TemplateParts.DrawerContentControlName, Type = typeof(ContentControl))] [TemplatePart(Name = TemplateParts.LightDismissOverlayName, Type = typeof(Border))] public partial class DrawerControl : ContentControl { public static class TemplateParts { public const string MainContentPresenterName = "MainContentPresenter"; public const string DrawerContentControlName = "DrawerContentControl"; public const string LightDismissOverlayName = "LightDismissOverlay"; } private const double DragToggleThresholdRatio = 1.0 / 3; private const double AnimateSnappingThresholdRatio = 0.95; private static readonly TimeSpan AnimationDuration = TimeSpan.FromMilliseconds(150); // template parts private ContentPresenter? _mainContentPresenter; private ContentControl? _drawerContentControl; private Border? _lightDismissOverlay; // references private TranslateTransform? _drawerContentPresenterTransform; private Storyboard _storyboard = new Storyboard(); private DoubleAnimation? _translateAnimation, _opacityAnimation; // states private bool _isReady = false; private bool _isGestureCaptured = false; private double _startingTranslateOffset = 0; private bool _suppressIsOpenHandler = false; public DrawerControl() { DefaultStyleKey = typeof(DrawerControl); } protected override void OnApplyTemplate() { StopRunningAnimation(); ResetPreviousTemplate(); base.OnApplyTemplate(); _mainContentPresenter = GetTemplateChild(TemplateParts.MainContentPresenterName) as ContentPresenter; _drawerContentControl = GetTemplateChild(TemplateParts.DrawerContentControlName) as ContentControl; _lightDismissOverlay = GetTemplateChild(TemplateParts.LightDismissOverlayName) as Border; if (_drawerContentControl != null) { UpdateSwipeContentPresenterSize(); UpdateSwipeContentPresenterLayout(); _drawerContentControl.RenderTransform = _drawerContentPresenterTransform = new TranslateTransform(); #if !STORYBOARD_RETARGET_ISSUE _translateAnimation = new DoubleAnimation { Duration = new Duration(AnimationDuration), }; Storyboard.SetTarget(_translateAnimation, _drawerContentPresenterTransform); UpdateTranslateAnimationTargetProperty(); _storyboard.Children.Add(_translateAnimation); #else RebuildTranslateAnimation(); #endif UpdateManipulationMode(); ManipulationStarted += OnManipulationStarted; ManipulationDelta += OnManipulationDelta; ManipulationCompleted += OnManipulationCompleted; SizeChanged += OnSizeChanged; } if (_lightDismissOverlay != null) { _opacityAnimation = new DoubleAnimation() { Duration = new Duration(AnimationDuration), }; Storyboard.SetTarget(_opacityAnimation, _lightDismissOverlay); Storyboard.SetTargetProperty(_opacityAnimation, nameof(_lightDismissOverlay.Opacity)); _storyboard.Children.Add(_opacityAnimation); _lightDismissOverlay.Tapped += OnLightDismissOverlayTapped; } if (DrawerDepth != 0) { UpdateIsOpen(IsOpen, animate: false); } _isReady = _drawerContentControl != null; void ResetPreviousTemplate() { _isReady = false; _storyboard.Children.Clear(); _storyboard = new Storyboard(); _drawerContentPresenterTransform = null; _translateAnimation = null; _opacityAnimation = null; _isGestureCaptured = false; _startingTranslateOffset = 0; _suppressIsOpenHandler = false; } } private void OnIsOpenChanged(DependencyPropertyChangedEventArgs e) { if (!_isReady) return; if (_suppressIsOpenHandler) return; StopRunningAnimation(); UpdateIsOpen((bool)e.NewValue, animate: IsLoaded); } private void OnDrawerDepthChanged(DependencyPropertyChangedEventArgs e) { if (!_isReady) return; UpdateSwipeContentPresenterSize(); UpdateIsOpen(IsOpen, animate: false); } private void OnOpenDirectionChanged(DependencyPropertyChangedEventArgs e) { if (!_isReady) return; StopRunningAnimation(); UpdateSwipeContentPresenterSize(); UpdateSwipeContentPresenterLayout(); UpdateManipulationMode(); #if !STORYBOARD_RETARGET_ISSUE UpdateTranslateAnimationTargetProperty(); #else RebuildTranslateAnimation(); #endif ResetOtherAxisTranslateOffset(); UpdateIsOpen(IsOpen, animate: false); } private void OnFitToDrawerContentChanged(DependencyPropertyChangedEventArgs e) { UpdateSwipeContentPresenterSize(); UpdateSwipeContentPresenterLayout(); _drawerContentControl?.UpdateLayout(); UpdateIsOpen(IsOpen, animate: false); } private void OnManipulationStarted(object sender, ManipulationStartedRoutedEventArgs e) { if (e.OriginalSource != this) return; if (!IsGestureEnabled) return; var position = #if MANIPULATION_ABSOLUTE_COORD_ISSUE this.TransformToVisual(null).Inverse.TransformPoint(e.Position); #else e.Position; #endif _isGestureCaptured = IsOpen ? true : IsInRangeForOpeningEdgeSwipe(position); if (_isGestureCaptured) { StopRunningAnimation(); _startingTranslateOffset = TranslateOffset; e.Handled = true; } else { e.Complete(); } } private void OnManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e) { if (!_isGestureCaptured || !IsGestureEnabled) return; e.Handled = true; var length = GetActualDrawerDepth(); var cumulative = IsOpenDirectionHorizontal() ? e.Cumulative.Translation.X : e.Cumulative.Translation.Y; var currentOffset = UseNegativeTranslation() ? Clamp(-length, _startingTranslateOffset + cumulative, 0) : Clamp(0, _startingTranslateOffset + cumulative, length); var ratio = Math.Abs(currentOffset) / length; UpdateOpenness(ratio); } private void OnManipulationCompleted(object sender, ManipulationCompletedRoutedEventArgs e) { if (!_isGestureCaptured || !IsGestureEnabled) return; _isGestureCaptured = false; e.Handled = true; StopRunningAnimation(); var length = GetActualDrawerDepth(); var cumulative = IsOpenDirectionHorizontal() ? e.Cumulative.Translation.X : e.Cumulative.Translation.Y; var isInCorrectDirection = Math.Sign(cumulative) == (IsOpen ^ UseNegativeTranslation() ? 1 : -1); var isPastThresholdRatio = Math.Abs(cumulative / length) >= DragToggleThresholdRatio; UpdateIsOpen(IsOpen ^ (isInCorrectDirection && isPastThresholdRatio)); } private void OnSizeChanged(object sender, SizeChangedEventArgs e) { UpdateSwipeContentPresenterSize(); UpdateIsOpen(IsOpen, animate: false); } private void OnLightDismissOverlayTapped(object sender, TappedRoutedEventArgs e) { StopRunningAnimation(); UpdateIsOpen(false); } private void UpdateIsOpen(bool willBeOpen, bool animate = true) { var length = GetActualDrawerDepth(); var currentOffset = TranslateOffset; var targetOffset = GetSnappingOffsetFor(willBeOpen); var relativeDistanceRatio = Math.Abs(Math.Abs(currentOffset) - Math.Abs(targetOffset)) / length; if (!animate || ((1 - relativeDistanceRatio) >= AnimateSnappingThresholdRatio)) { UpdateOpenness(willBeOpen ? 0 : 1); UpdateIsOpenWithSuppress(willBeOpen); } else { UpdateIsOpenWithSuppress(willBeOpen); PlayAnimation(currentOffset / GetVectoredLength(), willBeOpen); } void UpdateIsOpenWithSuppress(bool value) { try { _suppressIsOpenHandler = true; IsOpen = value; } finally { _suppressIsOpenHandler = false; } } } private void UpdateOpenness(double ratio) { TranslateOffset = ratio * GetVectoredLength(); if (_lightDismissOverlay != null) { _lightDismissOverlay.Opacity = 1 - ratio; _lightDismissOverlay.IsHitTestVisible = ratio != 1; } } private void PlayAnimation(double fromRatio, bool willBeOpen) { if (_storyboard == null) return; var toRatio = willBeOpen ? 0 : 1; if (_translateAnimation != null) { var vectoredLength = GetVectoredLength(); _translateAnimation.From = fromRatio * vectoredLength; _translateAnimation.To = toRatio * vectoredLength; } if (_opacityAnimation != null) { _opacityAnimation.From = 1 - fromRatio; _opacityAnimation.To = 1 - toRatio; } if (_lightDismissOverlay != null) { _lightDismissOverlay.IsHitTestVisible = willBeOpen; } _storyboard.Begin(); } private void StopRunningAnimation() { if (_storyboard != null && _storyboard.GetCurrentState() != ClockState.Stopped) { // we want to Pause() the animation midway to avoid the jarring feeling // but since paused state will still yield ClockState.Active // we have to actually use Stop() in order to differentiate // pause & snapshot the animated values in the middle of animation _storyboard.Pause(); var offset = TranslateOffset; var opacity = _lightDismissOverlay?.Opacity ?? default; // restore the values after stopping it _storyboard.Stop(); TranslateOffset = offset; if (_lightDismissOverlay != null) _lightDismissOverlay.Opacity = opacity; } } private void UpdateManipulationMode() { ManipulationMode = IsOpenDirectionHorizontal() ? ManipulationModes.TranslateX : ManipulationModes.TranslateY; } private void UpdateSwipeContentPresenterLayout() { if (_drawerContentControl == null) return; switch (OpenDirection) { case DrawerOpenDirection.Left: _drawerContentControl.HorizontalAlignment = HorizontalAlignment.Right; _drawerContentControl.VerticalAlignment = VerticalAlignment.Stretch; _drawerContentControl.HorizontalContentAlignment = FitToDrawerContent ? HorizontalAlignment.Right : HorizontalAlignment.Stretch; _drawerContentControl.VerticalContentAlignment = VerticalAlignment.Stretch; break; case DrawerOpenDirection.Down: _drawerContentControl.HorizontalAlignment = HorizontalAlignment.Stretch; _drawerContentControl.VerticalAlignment = VerticalAlignment.Top; _drawerContentControl.HorizontalContentAlignment = HorizontalAlignment.Stretch; _drawerContentControl.VerticalContentAlignment = FitToDrawerContent ? VerticalAlignment.Top : VerticalAlignment.Stretch; break; case DrawerOpenDirection.Up: _drawerContentControl.HorizontalAlignment = HorizontalAlignment.Stretch; _drawerContentControl.VerticalAlignment = VerticalAlignment.Bottom; _drawerContentControl.HorizontalContentAlignment = HorizontalAlignment.Stretch; _drawerContentControl.VerticalContentAlignment = FitToDrawerContent ? VerticalAlignment.Bottom : VerticalAlignment.Stretch; break; case DrawerOpenDirection.Right: default: _drawerContentControl.HorizontalAlignment = HorizontalAlignment.Left; _drawerContentControl.VerticalAlignment = VerticalAlignment.Stretch; _drawerContentControl.HorizontalContentAlignment = FitToDrawerContent ? HorizontalAlignment.Left : HorizontalAlignment.Stretch; _drawerContentControl.VerticalContentAlignment = VerticalAlignment.Stretch; break; } } private void UpdateSwipeContentPresenterSize() { if (_drawerContentControl == null) return; if (IsOpenDirectionHorizontal()) { _drawerContentControl.Height = double.NaN; _drawerContentControl.Width = DrawerDepth ?? (FitToDrawerContent ? double.NaN : ActualWidth); } else { _drawerContentControl.Height = DrawerDepth ?? (FitToDrawerContent ? double.NaN : ActualHeight); _drawerContentControl.Width = double.NaN; } } #if !STORYBOARD_RETARGET_ISSUE private void UpdateTranslateAnimationTargetProperty() { if (_translateAnimation == null) return; var property = IsOpenDirectionHorizontal() ? nameof(_drawerContentPresenterTransform.X) : nameof(_drawerContentPresenterTransform.Y); Storyboard.SetTargetProperty(_translateAnimation, property); } #else private void RebuildTranslateAnimation() { if (_translateAnimation != null) { _storyboard.Children.Remove(_translateAnimation); _translateAnimation = null; } _translateAnimation = new DoubleAnimation { Duration = new Duration(AnimationDuration), }; var property = IsOpenDirectionHorizontal() ? nameof(TranslateTransform.X) : nameof(TranslateTransform.Y); Storyboard.SetTarget(_translateAnimation, _drawerContentPresenterTransform); Storyboard.SetTargetProperty(_translateAnimation, property); _storyboard.Children.Add(_translateAnimation); } #endif private void ResetOtherAxisTranslateOffset() { if (IsOpenDirectionHorizontal()) { _drawerContentPresenterTransform.Y = 0; } else { _drawerContentPresenterTransform.X = 0; } } // helpers private double TranslateOffset { get => IsOpenDirectionHorizontal() ? _drawerContentPresenterTransform.X : _drawerContentPresenterTransform.Y; set { if (IsOpenDirectionHorizontal()) _drawerContentPresenterTransform.X = value; else _drawerContentPresenterTransform.Y = value; } } private bool IsInRangeForOpeningEdgeSwipe(Point p) { if (EdgeSwipeDetectionLength is double limit) { var position = IsOpenDirectionHorizontal() ? p.X : p.Y; var edgePosition = UseNegativeTranslation() ? 0 : IsOpenDirectionHorizontal() ? ActualWidth : ActualHeight; var distanceToEdge = Math.Abs(position - edgePosition); return distanceToEdge <= limit; } else // anywhere is fine if null { return true; } } private double GetSnappingOffsetFor(bool isOpen) { return isOpen ? 0 : GetVectoredLength(); } private bool IsOpenDirectionHorizontal() { return OpenDirection switch { DrawerOpenDirection.Down => false, DrawerOpenDirection.Up => false, _ => true, }; } private bool UseNegativeTranslation() { return OpenDirection switch { DrawerOpenDirection.Left => false, DrawerOpenDirection.Up => false, _ => true, }; } private double GetActualDrawerDepth() { if (_drawerContentControl == null) throw new InvalidOperationException($"{nameof(_drawerContentControl)} is null"); return DrawerDepth ?? (IsOpenDirectionHorizontal() ? GetDrawerContentSizeReferenceElement().ActualWidth : GetDrawerContentSizeReferenceElement().ActualHeight ); FrameworkElement GetDrawerContentSizeReferenceElement() => FitToDrawerContent ? (GetDrawerContentElement() ?? _drawerContentControl) : _drawerContentControl; FrameworkElement? GetDrawerContentElement() => _drawerContentControl.Content as FrameworkElement ?? (VisualTreeHelper.GetChildrenCount(_drawerContentControl) > 0 ? VisualTreeHelper.GetChild(_drawerContentControl, 0) as FrameworkElement : default); } private double GetVectoredLength() { return UseNegativeTranslation() ? -GetActualDrawerDepth() : GetActualDrawerDepth(); } private static double Clamp(double min, double value, double max) { return Math.Max(Math.Min(value, max), min); } } }
30.344762
136
0.751051
[ "MIT" ]
unoplatform/uno.toolkit.ui
src/Uno.Toolkit.UI/Controls/DrawerControl/DrawerControl.cs
15,933
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MyYouTubePlaylistsDemo.Identity.Models.HomeViewModels { public class IdentityServiceViewModel { public string Issuer { get; set; } public IEnumerable<ClientViewModel> Clients { get; set; } } }
23
66
0.704348
[ "MIT" ]
sg-dotnet/MyYouTubePlaylistsDemo
Areas/IdentityService/Models/HomeViewModels/IdentityServiceViewModel.cs
347
C#
/** /// ScrimpNet.Core Library /// Copyright © 2005-2011 /// /// This module is Copyright © 2005-2011 Steve Powell /// All rights reserved. /// /// This library is free software; you can redistribute it and/or /// modify it under the terms of the Microsoft Public License (Ms-PL) /// /// This library is distributed in the hope that it will be /// useful, but WITHOUT ANY WARRANTY; without even the implied /// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR /// PURPOSE. See theMicrosoft Public License (Ms-PL) License for more /// details. /// /// You should have received a copy of the Microsoft Public License (Ms-PL) /// License along with this library; if not you may /// find it here: http://www.opensource.org/licenses/ms-pl.html /// /// Steve Powell, spowell@scrimpnet.com **/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; namespace ScrimpNet { public static partial class Extensions { /// <summary> /// Extracts a value from a data record /// </summary> /// <typeparam name="T">Simple type to return</typeparam> /// <param name="dr">DataRow that contains the field</param> /// <param name="fieldName">Name of field to return</param> /// <returns>Converted type or default(T) if not able to convert</returns> public static T GetValue<T>(this IDataRecord dr, string fieldName) { return Transform.ConvertValue<T>(dr[fieldName]); } /// <summary> /// Extracts a value from a data record /// </summary> /// <typeparam name="T">Simple type to return</typeparam> /// <param name="dr">DataRow that contains the field</param> /// <param name="fieldName">Name of field to return</param> /// <param name="defaultValue">Value to return if value is null or an error occured</param> /// <returns>Converted type or default(T) if not able to convert</returns> public static T GetValue<T>(this IDataRecord dr, string fieldName, T defaultValue) { return Transform.ConvertValue<T>(dr[fieldName],defaultValue); } } }
37
99
0.655978
[ "MIT" ]
catcat0921/lindexi_gd
ScrimpNet.Library.Suite Solution/ScrimpNet.Core Project/Extensions.Data.cs
2,187
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace ASC.Web.Community.Modules.Forum.Core.Module { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class Patterns { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Patterns() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ASC.Web.Community.Modules.Forum.Core.Module.Patterns", typeof(Patterns).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to &lt;patterns&gt; /// &lt;formatter type=&quot;ASC.Notify.Patterns.NVelocityPatternFormatter, ASC.Common&quot; /&gt; /// /// &lt;!--New Post in Forum Topic--&gt; /// &lt;pattern id=&quot;new post in topic&quot; sender=&quot;email.sender&quot;&gt; /// &lt;subject resource=&quot;|subject_PostInTopicEmailPattern|ASC.Web.Community.Modules.Forum.Core.Module.ForumPatternResource,ASC.Web.Community&quot; /&gt; /// &lt;body styler=&quot;ASC.Notify.Textile.TextileStyler,ASC.Notify.Textile&quot; resource=&quot;|pattern_PostInTopicEmailPattern|ASC.Web.Community.Modules.Forum.Core.Module.ForumPatternResource,A [rest of string was truncated]&quot;;. /// </summary> public static string forum_patterns { get { return ResourceManager.GetString("forum_patterns", resourceCulture); } } } }
49.050633
249
0.610323
[ "Apache-2.0" ]
jeanluctritsch/CommunityServer
web/studio/ASC.Web.Studio/Products/Community/Modules/Forum/Core/Module/Patterns.Designer.cs
3,877
C#
using System.Management.Automation; using Microsoft.SharePoint.Client; using SharePointPnP.PowerShell.CmdletHelpAttributes; using OfficeDevPnP.Core.Utilities; namespace SharePointPnP.PowerShell.Commands { [Cmdlet(VerbsCommon.Set, "SPOMasterPage")] [CmdletHelp("Sets the default master page of the current web.", Category = CmdletHelpCategory.Branding)] [CmdletExample( Code = @"PS:> Set-SPOMasterPage -MasterPageServerRelativeUrl /sites/projects/_catalogs/masterpage/oslo.master", Remarks = "Sets the master page based on a server relative URL", SortOrder = 1)] [CmdletExample( Code = @"PS:> Set-SPOMasterPage -MasterPageServerRelativeUrl /sites/projects/_catalogs/masterpage/oslo.master -CustomMasterPageServerRelativeUrl /sites/projects/_catalogs/masterpage/oslo.master", Remarks = "Sets the master page and custom master page based on a server relative URL", SortOrder = 2)] [CmdletExample( Code = @"PS:> Set-SPOMasterPage -MasterPageSiteRelativeUrl _catalogs/masterpage/oslo.master", Remarks = "Sets the master page based on a site relative URL", SortOrder = 3)] [CmdletExample( Code = @"PS:> Set-SPOMasterPage -MasterPageSiteRelativeUrl _catalogs/masterpage/oslo.master -CustomMasterPageSiteRelativeUrl _catalogs/masterpage/oslo.master", Remarks = "Sets the master page and custom master page based on a site relative URL", SortOrder = 4)] public class SetMasterPage : SPOWebCmdlet { [Parameter(Mandatory = false, ParameterSetName = "SERVER", HelpMessage = "Specifies the Master page url based on the server relative URL")] [Alias("MasterPageUrl")] public string MasterPageServerRelativeUrl = null; [Parameter(Mandatory = false, ParameterSetName = "SERVER", HelpMessage = "Specifies the custom Master page url based on the server relative URL")] [Alias("CustomMasterPageUrl")] public string CustomMasterPageServerRelativeUrl = null; [Parameter(Mandatory = false, ParameterSetName = "SITE", HelpMessage = "Specifies the Master page url based on the site relative URL")] public string MasterPageSiteRelativeUrl = null; [Parameter(Mandatory = false, ParameterSetName = "SITE", HelpMessage = "Specifies the custom Master page url based on the site relative URL")] public string CustomMasterPageSiteRelativeUrl = null; protected override void ExecuteCmdlet() { if (ParameterSetName == "SERVER") { if (!string.IsNullOrEmpty(MasterPageServerRelativeUrl)) SelectedWeb.SetMasterPageByUrl(MasterPageServerRelativeUrl); if (!string.IsNullOrEmpty(CustomMasterPageServerRelativeUrl)) SelectedWeb.SetCustomMasterPageByUrl(CustomMasterPageServerRelativeUrl); } else { if (!string.IsNullOrEmpty(MasterPageSiteRelativeUrl)) { SelectedWeb.SetMasterPageByUrl(GetServerRelativeUrl(MasterPageSiteRelativeUrl)); } if (!string.IsNullOrEmpty(CustomMasterPageSiteRelativeUrl)) { SelectedWeb.SetCustomMasterPageByUrl(GetServerRelativeUrl(CustomMasterPageSiteRelativeUrl)); } } } private string GetServerRelativeUrl(string url) { var serverRelativeUrl = SelectedWeb.EnsureProperty(w => w.ServerRelativeUrl); return UrlUtility.Combine(serverRelativeUrl, url); } } }
49.643836
203
0.682947
[ "MIT" ]
andreashebeisen/PnP-PowerShell
Commands/Branding/SetMasterPage.cs
3,626
C#
using Prism.Commands; using Prism.Events; using Prism.Interactivity.InteractionRequest; using Prism.Regions; using QIQO.Business.Client.Contracts; using QIQO.Business.Client.Core; using QIQO.Business.Client.Core.Infrastructure; using QIQO.Business.Client.Core.UI; using QIQO.Business.Client.Entities; using QIQO.Business.Client.Wrappers; using QIQO.Business.Module.Orders.Services; using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Transactions; using Unity.Interception.Utilities; namespace QIQO.Business.Module.Orders.ViewModels { public class OrderViewModelX : ViewModelBase, IRegionMemberLifetime, IConfirmNavigationRequest //, IInteractionRequestAware { private readonly IEventAggregator _eventAggregator; private readonly IServiceFactory _serviceFactory; private readonly IProductListService _productService; private readonly IRegionManager _regionManager; private readonly IWorkingOrderService _workingOrderService; private readonly IReportService _reportService; private OrderWrapper _order; private Client.Entities.Account _currentAccount; private object _selectedOrderItem; private AddressWrapper _shipAddress; private AddressWrapper _billAddress; private ObservableCollection<Product> _productList; private ObservableCollection<Representative> _accountReps; private ObservableCollection<Representative> _salesReps; private ObservableCollection<FeeSchedule> _feeScheduleList; private ObservableCollection<AccountPerson> _accountContacts; private string _viewTitle = ApplicationStrings.TabTitleNewOrder; private bool _gridEnabled = true; public OrderViewModelX(IEventAggregator eventAggregator, IServiceFactory serviceFactory, IProductListService productService, IRegionManager regionManager, IReportService reportService, IWorkingOrderService workingOrderService) // { _eventAggregator = eventAggregator; _serviceFactory = serviceFactory; _productService = productService; _regionManager = regionManager; _reportService = reportService; _workingOrderService = workingOrderService; GetProductList(); BindCommands(); GetCompanyRepLists(); IsActive = true; IsActiveChanged += OrderViewModel_IsActiveChanged; _eventAggregator.GetEvent<OrderLoadedEvent>().Publish(string.Empty); } private void OrderViewModel_IsActiveChanged(object sender, EventArgs e) { IsActive = true; } public bool KeepAlive { get { if (Order.IsChanged && Order.Account.AccountCode != null) { return true; } return false; } } public void ConfirmNavigationRequest(NavigationContext navigationContext, Action<bool> continuationCallback) { //********** Do some sort fo confirmation with the end user here if (Order.IsChanged && !string.IsNullOrWhiteSpace(Order.Account.AccountCode)) { var confirm = new Confirmation(); confirm.Title = ApplicationStrings.SaveChangesTitle; confirm.Content = ApplicationStrings.SaveChangesPrompt; SaveChangesConfirmationRequest.Raise(confirm, r => { if (r != null && r.Confirmed) { if (Order.IsValid) { DoSave(); continuationCallback(false); } continuationCallback(true); } else { continuationCallback(true); } }); } else { continuationCallback(true); } } public OrderWrapper Order { get { return _order; } private set { SetProperty(ref _order, value); } } public AddressWrapper DefaultBillingAddress { get { return _billAddress; } private set { SetProperty(ref _billAddress, value); } } public AddressWrapper DefaultShippingAddress { get { return _shipAddress; } private set { SetProperty(ref _shipAddress, value); } } public ObservableCollection<AccountPerson> AccountContacts { get { return _accountContacts; } private set { SetProperty(ref _accountContacts, value); } } public ObservableCollection<Product> ProductList { get { return _productList; } private set { SetProperty(ref _productList, value); } } public ObservableCollection<Representative> AccountRepList { get { return _accountReps; } private set { SetProperty(ref _accountReps, value); } } public ObservableCollection<Representative> SalesRepList { get { return _salesReps; } private set { SetProperty(ref _salesReps, value); } } public ObservableCollection<FeeSchedule> FeeScheduleList { get { return _feeScheduleList; } private set { SetProperty(ref _feeScheduleList, value); } } public object SelectedOrderItem { get { return _selectedOrderItem; } set { SetProperty(ref _selectedOrderItem, value); InvalidateCommands(); } } public bool GridIsEnabled { get { return _gridEnabled; } private set { SetProperty(ref _gridEnabled, value); } } public override string ViewTitle { get { return _viewTitle; } protected set { SetProperty(ref _viewTitle, value); } } public override void OnNavigatedTo(NavigationContext navigationContext) { var paramAccountCode = navigationContext.Parameters.Where(item => item.Key == "AccountCode").FirstOrDefault(); var paramOrderKey = navigationContext.Parameters.Where(item => item.Key == "OrderKey").FirstOrDefault(); var paramOrderNumber = navigationContext.Parameters.Where(item => item.Key == "OrderNumber").FirstOrDefault(); if (paramAccountCode.Value != null) { Order.Account.AccountCode = (string)navigationContext.Parameters["AccountCode"]; GetAccount(Order.Account.AccountCode); return; } if (paramOrderKey.Value != null) { GetOrder((int)paramOrderKey.Value); return; } if (paramOrderNumber.Value != null) { Order = _workingOrderService.GetOrder((string)navigationContext.Parameters["OrderNumber"]); GetAccount(Order.Account.AccountCode); _eventAggregator.GetEvent<OrderLoadedEvent>().Publish(Order.OrderNumber); return; } InitNewOrder(); } public override bool IsNavigationTarget(NavigationContext navigationContext) { var paramAccountCode = navigationContext.Parameters.Where(item => item.Key == "AccountCode").FirstOrDefault(); var paramOrderNumber = navigationContext.Parameters.Where(item => item.Key == "OrderKey").FirstOrDefault(); return (paramAccountCode.Value != null || paramOrderNumber.Value != null) ? true : false; } public int SelectedOrderItemIndex { get; set; } public DelegateCommand CancelCommand { get; set; } public DelegateCommand CloseCommand { get; set; } public DelegateCommand SaveCommand { get; set; } public DelegateCommand DeleteCommand { get; set; } public DelegateCommand PrintCommand { get; set; } public DelegateCommand<string> GetAccountCommand { get; set; } public DelegateCommand<object> UpdateProdInfoCommand { get; set; } public DelegateCommand UpdateItemTotalCommand { get; set; } public DelegateCommand UpdateHeaderFromDetailCommand { get; set; } public DelegateCommand NewOrderItemCommand { get; set; } public DelegateCommand EditOrderItemCommand { get; set; } public DelegateCommand DeleteOrderItemCommand { get; set; } public DelegateCommand FindAccountCommand { get; set; } public DelegateCommand NewAccountCommand { get; set; } public InteractionRequest<ItemEditNotification> EditOrderItemRequest { get; set; } public InteractionRequest<ItemSelectionNotification> FindAccountRequest { get; set; } public InteractionRequest<IConfirmation> SaveChangesConfirmationRequest { get; set; } public InteractionRequest<IConfirmation> DeleteConfirmationRequest { get; set; } protected override void DisplayErrorMessage(Exception ex, [CallerMemberName] string methodName = "") { _eventAggregator.GetEvent<GeneralErrorEvent>().Publish(methodName + " - " + ex.Message); } protected void DisplayErrorMessage(string msg) { _eventAggregator.GetEvent<GeneralErrorEvent>().Publish(msg); } private void InitNewOrder() { var new_order = new Order() //*** GET this initializatoin stuff into the objects themselves!! (complete) { OrderEntryDate = DateTime.Now, OrderStatusDate = DateTime.Now, DeliverByDate = DateTime.Now.AddDays(7), // think about a defaul lead time for each account SalesRep = SalesRepList[0], AccountRep = AccountRepList[0] }; new_order.OrderItems.Add(InitNewOrderItem(1)); SelectedOrderItemIndex = 0; Order = new OrderWrapper(new_order); DefaultBillingAddress = new AddressWrapper(new Address()); DefaultShippingAddress = new AddressWrapper(new Address()); Order.PropertyChanged += Context_PropertyChanged; Order.AcceptChanges(); // Add order to the service here! _workingOrderService.OpenOrder(Order); GridIsEnabled = false; } private OrderItem InitNewOrderItem(int orderItemSeq) { return new OrderItem() { SalesRep = SalesRepList[0], AccountRep = AccountRepList[0] }; } private void GetOrder(int orderKey) { ExecuteFaultHandledOperation(() => { var orderService = _serviceFactory.CreateClient<IOrderService>(); using (orderService) { Order = new OrderWrapper(orderService.GetOrder(orderKey)); AccountContacts = new ObservableCollection<AccountPerson>(Order.Account.Model.Employees.Where(item => item.CompanyRoleType == QIQOPersonType.AccountContact).ToList()); Order.PropertyChanged += Context_PropertyChanged; Order.AcceptChanges(); _currentAccount = Order.Account.Model; } DefaultBillingAddress = Order.OrderItems[0].OrderItemBillToAddress; DefaultShippingAddress = Order.OrderItems[0].OrderItemShipToAddress; ViewTitle = Order.OrderNumber; GridIsEnabled = Order.OrderStatus != QIQOOrderStatus.Complete ? true : false; _eventAggregator.GetEvent<GeneralMessageEvent>().Publish($"Order {Order.OrderNumber} loaded successfully"); _eventAggregator.GetEvent<OrderLoadedEvent>().Publish(Order.OrderNumber); _eventAggregator.GetEvent<NavigationEvent>().Publish(ViewNames.OrderHomeView); }); } private void GetCompanyRepLists() { var employeeService = _serviceFactory.CreateClient<IEmployeeService>(); using (employeeService) { AccountRepList = new ObservableCollection<Representative>(employeeService.GetAccountRepsByCompany(CurrentCompanyKey)); SalesRepList = new ObservableCollection<Representative>(employeeService.GetSalesRepsByCompany(CurrentCompanyKey)); } } private void GetProductList() { ProductList = new ObservableCollection<Product>(_productService.ProductList); } private void BindCommands() { CancelCommand = new DelegateCommand(DoCancel, CanDoCancel); CancelCommand.IsActive = true; SaveCommand = new DelegateCommand(DoSave, CanDoSave); SaveCommand.IsActive = true; DeleteCommand = new DelegateCommand(DoDelete, CanDoDelete); DeleteCommand.IsActive = true; PrintCommand = new DelegateCommand(DoPrint, CanDoDelete); PrintCommand.IsActive = true; CloseCommand = new DelegateCommand(DoCancel); GetAccountCommand = new DelegateCommand<string>(GetAccount, CanGetAccount); UpdateProdInfoCommand = new DelegateCommand<object>(PopulateProductInfo); UpdateItemTotalCommand = new DelegateCommand(UpdateItemTotals); UpdateHeaderFromDetailCommand = new DelegateCommand(UpdateHeaderFromDetail); NewOrderItemCommand = new DelegateCommand(AddOrderItem, CanAddOrderItem); EditOrderItemCommand = new DelegateCommand(EditOrderItem, CanEditOrderItem); DeleteOrderItemCommand = new DelegateCommand(DeleteOrderItem, CanDeleteOrderItem); FindAccountCommand = new DelegateCommand(FindAccount); NewAccountCommand = new DelegateCommand(NewAccount); EditOrderItemRequest = new InteractionRequest<ItemEditNotification>(); FindAccountRequest = new InteractionRequest<ItemSelectionNotification>(); SaveChangesConfirmationRequest = new InteractionRequest<IConfirmation>(); DeleteConfirmationRequest = new InteractionRequest<IConfirmation>(); } private void DoPrint() { _reportService.ExecuteReport(Reports.Order, $"order_key={Order.OrderKey.ToString()}"); } private void NewAccount() { _regionManager.RequestNavigate(RegionNames.ContentRegion, ViewNames.AccountView); } private bool CanDoCancel() { return Order.IsChanged; } private void DoCancel() { _workingOrderService.CloseOrder(Order); _regionManager.RequestNavigate(RegionNames.ContentRegion, ViewNames.OrderHomeView); } private bool CanDoDelete() { return Order.OrderKey > 0; } private void DoDelete() { var confirm = new Confirmation(); confirm.Title = ApplicationStrings.DeleteOrderTitle; confirm.Content = $"Are you sure you want to delete order {Order.OrderNumber}?\n\nClick OK to delete. Click Cancel to return to the form."; DeleteConfirmationRequest.Raise(confirm, r => { if (r != null && r.Confirmed) { DeleteOrder(Order.OrderNumber); } }); } private void DeleteOrder(string orderNumber) { ExecuteFaultHandledOperation(() => { var orderService = _serviceFactory.CreateClient<IOrderService>(); using (var scope = new TransactionScope()) { using (orderService) { var ret_val = orderService.DeleteOrder(Order.Model); _eventAggregator.GetEvent<OrderDeletedEvent>().Publish($"Order {orderNumber} deleted successfully"); _regionManager.RequestNavigate(RegionNames.ContentRegion, ViewNames.OrderHomeView); } scope.Complete(); } }); } private void Context_PropertyChanged(object sender, PropertyChangedEventArgs e) { InvalidateCommands(); } private void InvalidateCommands() { SaveCommand.RaiseCanExecuteChanged(); DeleteCommand.RaiseCanExecuteChanged(); CancelCommand.RaiseCanExecuteChanged(); PrintCommand.RaiseCanExecuteChanged(); CloseCommand.RaiseCanExecuteChanged(); GetAccountCommand.RaiseCanExecuteChanged(); EditOrderItemCommand.RaiseCanExecuteChanged(); DeleteOrderItemCommand.RaiseCanExecuteChanged(); NewOrderItemCommand.RaiseCanExecuteChanged(); } private void FindAccount() { var notification = new ItemSelectionNotification(); notification.Title = ApplicationStrings.NotificationFindAccount; FindAccountRequest.Raise(notification, r => { if (r != null && r.Confirmed && r.SelectedItem != null) { if (r.SelectedItem is Client.Entities.Account found_account) { GetAccount(found_account.AccountCode); } } }); } private bool CanDeleteOrderItem() { return (SelectedOrderItem != null && ((OrderItemWrapper)SelectedOrderItem).ProductKey > 0); } private void DeleteOrderItem() { if (SelectedOrderItem is OrderItemWrapper itemToDel) { if (itemToDel.OrderItemKey == 0) { Order.OrderItems.Remove(itemToDel); } else { itemToDel.OrderItemStatus = QIQOOrderItemStatus.Canceled; itemToDel.OrderItemQuantity = 0; itemToDel.OrderItemLineSum = 0M; itemToDel.ItemPricePer = 0M; itemToDel.ProductDesc = itemToDel.ProductDesc + " (Deleted)"; itemToDel.OrderItemCompleteDate = DateTime.Now; } UpdateItemTotals(); } } private bool CanEditOrderItem() { return (SelectedOrderItem != null && ((OrderItemWrapper)SelectedOrderItem).ProductKey > 0); } private void EditOrderItem() { if (SelectedOrderItem is OrderItemWrapper itemToEdit) { ChangeOrderItem(itemToEdit.Model.Copy(), ApplicationStrings.NotificationEdit); } } private bool CanAddOrderItem() { return Order.Account.AccountKey != 0; } private void AddOrderItem() { var existingEmptyItem = Order.OrderItems.Where(i => i.ProductCode == null).FirstOrDefault().Model; if (existingEmptyItem != null) { existingEmptyItem.OrderItemQuantity = 1; existingEmptyItem.OrderKey = Order.OrderKey; existingEmptyItem.AccountRep = Order.AccountRep.Model; existingEmptyItem.SalesRep = Order.SalesRep.Model; existingEmptyItem.OrderItemBillToAddress = DefaultBillingAddress.Model; existingEmptyItem.OrderItemShipToAddress = DefaultShippingAddress.Model; ChangeOrderItem(existingEmptyItem, ApplicationStrings.NotificationEdit); } else { var newOrderItem = new OrderItem() { AccountRep = Order.AccountRep.Model, OrderItemBillToAddress = DefaultBillingAddress.Model, OrderItemQuantity = 1, OrderItemShipToAddress = DefaultShippingAddress.Model, OrderKey = Order.OrderKey, SalesRep = Order.SalesRep.Model }; ChangeOrderItem(newOrderItem, ApplicationStrings.NotificationAdd); } } private void ChangeOrderItem(OrderItem orderItem, string action) { if (orderItem != null) { GridIsEnabled = false; var bill_addresses = _currentAccount.Addresses.Where(item => item.AddressType == QIQOAddressType.Billing).ToList(); var ship_addresses = _currentAccount.Addresses.Where(item => item.AddressType == QIQOAddressType.Shipping).ToList(); var needed_objects = new Tuple<object, object, object>(orderItem, bill_addresses, ship_addresses); var notification = new ItemEditNotification(needed_objects); notification.Title = action + " Order Item"; //+ emp_to_edit.PersonCode + " - " + emp_to_edit.PersonFullNameFML; EditOrderItemRequest.Raise(notification, r => { if (r != null && r.Confirmed && r.EditibleObject != null) // { if (r.EditibleObject is OrderItem obj) { if (action == ApplicationStrings.NotificationEdit) { var changed_prod = ProductList.Where(item => item.ProductKey == obj.ProductKey).FirstOrDefault(); var item_to_update = SelectedOrderItem as OrderItemWrapper; item_to_update.ProductKey = obj.ProductKey; item_to_update.ProductCode = changed_prod.ProductCode; item_to_update.ProductName = obj.ProductName; item_to_update.ProductDesc = obj.ProductDesc; item_to_update.OrderItemQuantity = obj.OrderItemQuantity; item_to_update.ItemPricePer = obj.ItemPricePer; item_to_update.OrderItemLineSum = orderItem.OrderItemQuantity * orderItem.ItemPricePer; item_to_update.OrderItemStatus = obj.OrderItemStatus; item_to_update.OrderItemProduct.ProductKey = obj.ProductKey; item_to_update.OrderItemProduct.ProductCode = changed_prod.ProductCode; item_to_update.OrderItemProduct.ProductDesc = obj.ProductDesc; item_to_update.OrderItemProduct.ProductName = obj.ProductName; item_to_update.OrderItemBillToAddress.AddressKey = obj.OrderItemBillToAddress.AddressKey; item_to_update.OrderItemShipToAddress.AddressKey = obj.OrderItemShipToAddress.AddressKey; item_to_update.SalesRep.EntityPersonKey = obj.SalesRep.EntityPersonKey; item_to_update.AccountRep.EntityPersonKey = obj.AccountRep.EntityPersonKey; item_to_update.OrderItemShipDate = obj.OrderItemShipDate; item_to_update.OrderItemCompleteDate = obj.OrderItemCompleteDate; } else { Order.OrderItems.Add(new OrderItemWrapper(obj)); } UpdateItemTotals(); } } }); GridIsEnabled = true; } } private void PopulateProductInfo(object param) { var orderItem = Order.OrderItems[SelectedOrderItemIndex]; if (orderItem != null && orderItem.ProductKey > 0) { var sp = ProductList.Where(item => item.ProductKey == orderItem.ProductKey).FirstOrDefault(); //MessageToDisplay = order_item.ProductKey.ToString() + ": " + sp[0].ProductName; if (orderItem.ProductName == "" || orderItem.ProductName == null || orderItem.ProductName != sp.ProductName) { if (sp.ProductName != "") { var rp = sp.ProductAttributes.Where(item => item.AttributeType == QIQOAttributeType.Product_PRODBASE).FirstOrDefault(); var dq = sp.ProductAttributes.Where(item => item.AttributeType == QIQOAttributeType.Product_PRODDFQTY).FirstOrDefault(); //var.ProductKey = sp[0].ProductKey; // order_item.ProductKey = sp.ProductKey; orderItem.ProductCode = sp.ProductCode; orderItem.ProductName = sp.ProductName; orderItem.ProductDesc = sp.ProductDesc; orderItem.OrderItemQuantity = int.Parse(dq.AttributeValue); // Check for Fee Schedule here! var fsp = ApplyFeeSchedule(sp.ProductKey, decimal.Parse(rp.AttributeValue)); orderItem.ItemPricePer = (fsp != 0M) ? fsp : decimal.Parse(rp.AttributeValue); orderItem.OrderItemLineSum = orderItem.OrderItemQuantity * orderItem.ItemPricePer; //order_item.OrderItemProduct = new ProductWrapper(sp); orderItem.OrderItemProduct.ProductKey = sp.ProductKey; orderItem.OrderItemProduct.ProductCode = sp.ProductCode; orderItem.OrderItemProduct.ProductDesc = sp.ProductDesc; orderItem.OrderItemProduct.ProductName = sp.ProductName; orderItem.OrderItemProduct.ProductType = sp.ProductType; //order_item.OrderItemBillToAddress = DefaultBillingAddress; FillFromDefaultAddress(orderItem, QIQOAddressType.Billing); //order_item.OrderItemShipToAddress = DefaultShippingAddress; FillFromDefaultAddress(orderItem, QIQOAddressType.Shipping); orderItem.AccountRep.EntityPersonKey = _accountReps[0].EntityPersonKey; orderItem.SalesRep.EntityPersonKey = _salesReps[0].EntityPersonKey; orderItem.OrderItemSeq = SelectedOrderItemIndex + 1; } } } Order.OrderItemCount = Order.OrderItems.Sum(item => item.OrderItemQuantity); Order.OrderValueSum = Order.OrderItems.Sum(item => item.OrderItemLineSum); var seq = Order.OrderItems.Count; // Need to think about whether this is the best way to do this. What if they change an existing item? if (Order.OrderItems.Where(item => item.ProductKey == 0).FirstOrDefault() == null) { var new_item = new OrderItemWrapper(InitNewOrderItem(seq + 1)); FillFromDefaultAddress(new_item, QIQOAddressType.Billing); FillFromDefaultAddress(new_item, QIQOAddressType.Shipping); Order.OrderItems.Add(new_item); } } private void FillFromDefaultAddress(OrderItemWrapper orderItem, QIQOAddressType addressType) { if (addressType == QIQOAddressType.Billing) { if (DefaultBillingAddress != null) { orderItem.OrderItemBillToAddress.AddressKey = DefaultBillingAddress.AddressKey; orderItem.OrderItemBillToAddress.AddressType = QIQOAddressType.Billing; orderItem.OrderItemBillToAddress.AddressLine1 = DefaultBillingAddress.AddressLine1; orderItem.OrderItemBillToAddress.AddressLine2 = DefaultBillingAddress.AddressLine2; orderItem.OrderItemBillToAddress.AddressCity = DefaultBillingAddress.AddressCity; orderItem.OrderItemBillToAddress.AddressState = DefaultBillingAddress.AddressState; orderItem.OrderItemBillToAddress.AddressPostalCode = DefaultBillingAddress.AddressPostalCode; } } else { if (DefaultShippingAddress != null) { orderItem.OrderItemShipToAddress.AddressKey = DefaultShippingAddress.AddressKey; orderItem.OrderItemShipToAddress.AddressType = QIQOAddressType.Shipping; orderItem.OrderItemShipToAddress.AddressLine1 = DefaultShippingAddress.AddressLine1; orderItem.OrderItemShipToAddress.AddressLine2 = DefaultShippingAddress.AddressLine2; orderItem.OrderItemShipToAddress.AddressCity = DefaultShippingAddress.AddressCity; orderItem.OrderItemShipToAddress.AddressState = DefaultShippingAddress.AddressState; orderItem.OrderItemShipToAddress.AddressPostalCode = DefaultShippingAddress.AddressPostalCode; } } } private decimal ApplyFeeSchedule(int productKey, decimal defaultPrice) // think about if this needs to be in a service { var charge = 0M; string type; if (FeeScheduleList != null) { var fs = FeeScheduleList.Where(item => item.ProductKey == productKey).FirstOrDefault(); if (fs != null) { charge = fs.FeeScheduleValue; type = fs.FeeScheduleTypeCode; if (type == "P") { charge = defaultPrice * charge; } } } else { charge = defaultPrice; } return charge; } private void UpdateItemTotals() { if (SelectedOrderItemIndex != -1 && Order.OrderItems.Count > 0) { var orderItem = Order.OrderItems[SelectedOrderItemIndex]; if (orderItem != null & orderItem.OrderItemStatus != QIQOOrderItemStatus.Canceled) { if (orderItem.ItemPricePer <= 0) { if (orderItem.OrderItemProduct != null) { var rp = orderItem.OrderItemProduct.ProductAttributes.Where(item => item.AttributeType == QIQOAttributeType.Product_PRODBASE).FirstOrDefault(); if (rp != null) { orderItem.ItemPricePer = ApplyFeeSchedule(orderItem.ProductKey, decimal.Parse(rp.AttributeValue)); } } } if (orderItem.OrderItemQuantity <= 0) { if (orderItem.OrderItemProduct != null) { var dq = orderItem.OrderItemProduct.ProductAttributes.Where(item => item.AttributeType == QIQOAttributeType.Product_PRODDFQTY).FirstOrDefault(); if (dq != null) { orderItem.OrderItemQuantity = int.Parse(dq.AttributeValue); } } } orderItem.OrderItemLineSum = orderItem.OrderItemQuantity * orderItem.ItemPricePer; } } Order.OrderItemCount = Order.OrderItems.Sum(item => item.OrderItemQuantity); Order.OrderValueSum = Order.OrderItems.Sum(item => item.OrderItemLineSum); Order.OrderItems.ForEach(item => item.OrderItemSeq = Order.OrderItems.IndexOf(item) + 1); } private void UpdateHeaderFromDetail() { if (SelectedOrderItemIndex != -1 && Order.OrderItems.Count > 0) { var orderItem = Order.OrderItems[SelectedOrderItemIndex]; if (orderItem != null) { if (orderItem.OrderItemBillToAddress is AddressWrapper current_bill_address && current_bill_address.AddressKey != 0 && current_bill_address.AddressLine1 != null) { DefaultBillingAddress = current_bill_address; } if (orderItem.OrderItemShipToAddress is AddressWrapper current_ship_address && current_ship_address.AddressKey != 0 && current_ship_address.AddressLine1 != null) { DefaultShippingAddress = current_ship_address; } if (orderItem.SalesRep is RepresentativeWrapper current_sales_rep && current_sales_rep.EntityPersonKey != 0) { Order.SalesRep.EntityPersonKey = current_sales_rep.EntityPersonKey; } if (orderItem.AccountRep is RepresentativeWrapper current_account_rep && current_account_rep.EntityPersonKey != 0) { Order.AccountRep.EntityPersonKey = current_account_rep.EntityPersonKey; } } } } private bool CanGetAccount(string accountCode) { return accountCode.Length > 2; } private void GetAccount(string accountCode) { //throw new NotImplementedException(); ExecuteFaultHandledOperation(() => { var accountService = _serviceFactory.CreateClient<IAccountService>(); var comp = CurrentCompany as Company; using (accountService) { var account = accountService.GetAccountByCode(accountCode, comp.CompanyCode); if (account != null) { if (account.Employees != null) { AccountContacts = new ObservableCollection<AccountPerson>(account.Employees.Where(item => item.CompanyRoleType == QIQOPersonType.AccountContact).ToList()); } // Get the accounts main contact key var contact = account.Employees.Where(item => item.CompanyRoleType == QIQOPersonType.AccountContact).FirstOrDefault(); var cnt_key = contact != null ? contact.EntityPersonKey : 1; Order.Account.AccountKey = account.AccountKey; Order.Account.AccountName = account.AccountName; Order.Account.AccountCode = account.AccountCode; Order.Account.AccountDBA = account.AccountDBA; Order.Account.AccountDesc = account.AccountDesc; Order.AccountKey = account.AccountKey; Order.Account.AccountType = account.AccountType; Order.AccountContactKey = cnt_key; // account.Employees[0].EntityPersonKey; Order.OrderAccountContact.PersonFullNameFML = contact != null ? contact.PersonFullNameFML : "N/A"; Order.AccountRepKey = AccountRepList[0].EntityPersonKey; Order.SalesRepKey = SalesRepList[0].EntityPersonKey; DefaultBillingAddress = new AddressWrapper(account.Addresses.Where(item => item.AddressType == QIQOAddressType.Billing).FirstOrDefault()); DefaultShippingAddress = new AddressWrapper(account.Addresses.Where(item => item.AddressType == QIQOAddressType.Shipping).FirstOrDefault()); FeeScheduleList = new ObservableCollection<FeeSchedule>(account.FeeSchedules); _currentAccount = account; RaisePropertyChanged(nameof(Order)); GridIsEnabled = true; } else { DisplayErrorMessage($"Account with code '{accountCode}' not found"); } } }); _eventAggregator.GetEvent<NavigationEvent>().Publish(ViewNames.OrderHomeView); } private bool CanDoSave() { return Order.IsChanged && Order.IsValid; } private void DoSave() { _eventAggregator.GetEvent<GeneralMessageEvent>().Publish(ApplicationStrings.BeginningSave); ExecuteFaultHandledOperation(() => { var orderService = _serviceFactory.CreateClient<IOrderService>(); using (var scope = new TransactionScope()) { using (orderService) { if (Order.OrderKey == 0) { var accountService = _serviceFactory.CreateClient<IAccountService>(); Order.OrderNumber = accountService.GetAccountNextNumber(Order.Account.Model, QIQOEntityNumberType.OrderNumber); accountService.Dispose(); } //TODO: Do something to make sure the order items are in the object properly var new_order_line = Order.OrderItems.Where(item => item.ProductKey == 0).FirstOrDefault(); if (new_order_line != null) { Order.OrderItems.Remove(new_order_line); } // For some reason, these don't seem to get set properly when I add the account object to the Order object Order.Model.OrderItems.ForEach(item => item.OrderItemBillToAddress = DefaultBillingAddress.Model); Order.Model.OrderItems.ForEach(item => item.OrderItemShipToAddress = DefaultShippingAddress.Model); var order_key = orderService.CreateOrder(Order.Model); if (Order.OrderKey == 0) { Order.OrderKey = order_key; } Order.AcceptChanges(); ViewTitle = Order.OrderNumber; } scope.Complete(); } }); if (Order.OrderKey > 0) { _eventAggregator.GetEvent<OrderUpdatedEvent>().Publish($"Order {Order.OrderNumber} updated successfully"); _workingOrderService.CloseOrder(Order); _regionManager.RequestNavigate(RegionNames.ContentRegion, ViewNames.OrderHomeView); } } } }
46.292882
183
0.570716
[ "MIT" ]
rdrrichards/QIQO.Business.Client.Solution
QIQO.Business.Module.Orders/ViewModels/OrderViewModelX.cs
39,675
C#
using Blazor.Extensions.Storage; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace blazor.jwttest.Client.Classes { public class JwtDecode { // TODO: Figure out how to get the JWT Auth .net libs into blazor withoout totaly screwing things up // and replace all the JwtClaim names in this file with proper constants. private string _header { get; set; } private string _payload { get; set; } private string _token { get; set; } private LocalStorage _localStorage { get; } private string _authTokenName { get; set; } public JwtDecode(LocalStorage localStorage) { _localStorage = localStorage; } private void DecodeToken() { string[] parts = _token.Split('.'); _header = parts[0]; _payload = parts[1]; if (_header.Length % 4 != 0) // B64 strings must be a length that is a multiple of 4 to decode them { var lengthToBe = _header.Length.GetNextHighestMultiple(4); _header = _header.PadRight(lengthToBe, '='); } if (_payload.Length % 4 != 0) // B64 strings must be a length that is a multiple of 4 to decode them { var lengthToBe = _payload.Length.GetNextHighestMultiple(4); _payload = _payload.PadRight(lengthToBe, '='); } } public async Task<bool> LoadToken(string tokenName) { _authTokenName = tokenName; _token = await _localStorage.GetItem<string>(_authTokenName); return true; } public Dictionary<string, object> GetPayload() { DecodeToken(); var payload = Encoding.UTF8.GetString(Convert.FromBase64String(_payload)); var data = JsonConvert.DeserializeObject<Dictionary<string, object>>(payload); // Testing //foreach(var key in data) //{ // Console.WriteLine($"PAYLOAD: {key.Key} = {key.Value} (TYP: {key.Value.GetType().ToString()})"); //} return data; } public Dictionary<string, object> GetHeader() { DecodeToken(); var header = Encoding.UTF8.GetString(Convert.FromBase64String(_header)); var data = JsonConvert.DeserializeObject<Dictionary<string, object>>(header); // Testing //foreach (var key in data) //{ // Console.WriteLine($"HEADER: {key.Key} = {key.Value}"); //} return data; } public string GetName() { string result = "Not Set"; string nameClaim = "sub"; Dictionary<string, object> payload = GetPayload(); if (payload.ContainsKey(nameClaim)) { result = payload[nameClaim] as string; } return result; } public string GetFullName() { string result = "Not Set"; string givenNameClaim = "given_name"; Dictionary<string, object> payload = GetPayload(); if (payload.ContainsKey(givenNameClaim)) { result = payload[givenNameClaim] as string; } return result; } public string GetEmail() { string result = "Not Set"; string emailClaim = "email"; Dictionary<string, object> payload = GetPayload(); if (payload.ContainsKey(emailClaim)) { result = payload[emailClaim] as string; } return result; } public List<string> GetRoles() { // DO NOT Change this claim name, ASP.NET Core roles auth requires this exact role for roles on a controller to work const string roleType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role"; List<string> result = new List<string>(); Dictionary<string, object> payload = GetPayload(); if (payload.ContainsKey(roleType)) { // Role claims can either be a single string or a JArray (since where using Json.Net), we need to detect which if (payload[roleType] is JArray) { result.AddRange((payload[roleType] as JArray).ToObject<List<string>>()); } if (payload[roleType] is string) { result.Add(payload[roleType] as string); } } return result; } public bool HasTokenExpired() { bool result = false; // Always default to NO string expiryClaim = "exp"; Dictionary<string, object> payload = GetPayload(); if (payload.ContainsKey(expiryClaim)) { double timeStamp = Convert.ToDouble(payload[expiryClaim]); DateTime expiryTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); expiryTime = expiryTime.AddSeconds(timeStamp); if(expiryTime < DateTime.UtcNow) { result = true; } } return result; } public string GetIssuer() { string result = "NOT SET"; string issuerClaim = "iss"; Dictionary<string, object> payload = GetPayload(); if (payload.ContainsKey(issuerClaim)) { result = payload[issuerClaim] as string; } return result; } } }
26.489474
122
0.619909
[ "MIT" ]
BigHam/blazor.jwttest
blazor.jwttest.Client/Classes/JwtDecode.cs
5,035
C#
// CoreUtil using System; using System.Threading; using System.Data; using System.Data.Sql; using System.Data.SqlClient; using System.Data.SqlTypes; using System.Text; using System.Configuration; using System.Collections; using System.Collections.Generic; using System.Security.Cryptography; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.IO; using System.Drawing; using System.Drawing.Imaging; using System.Drawing.Drawing2D; using System.Diagnostics; using System.Web.Mail; using System.Net; using System.Net.Sockets; using System.Net.NetworkInformation; using System.Net.Mail; using System.Net.Mime; using CoreUtil; #pragma warning disable 0618 namespace CoreUtil { class WorkerQueuePrivate { object lockObj = new object(); List<ThreadObj> thread_list; ThreadProc thread_proc; int num_worker_threads; Queue<object> taskQueue = new Queue<object>(); Exception raised_exception = null; void worker_thread(object param) { while (true) { object task = null; lock (lockObj) { if (taskQueue.Count == 0) { return; } task = taskQueue.Dequeue(); } try { this.thread_proc(task); } catch (Exception ex) { if (raised_exception == null) { raised_exception = ex; } Console.WriteLine(ex.Message); } } } public WorkerQueuePrivate(ThreadProc thread_proc, int num_worker_threads, object[] tasks) { thread_list = new List<ThreadObj>(); int i; this.thread_proc = thread_proc; this.num_worker_threads = num_worker_threads; foreach (object task in tasks) { taskQueue.Enqueue(task); } raised_exception = null; for (i = 0; i < num_worker_threads; i++) { ThreadObj t = new ThreadObj(worker_thread); thread_list.Add(t); } foreach (ThreadObj t in thread_list) { t.WaitForEnd(); } if (raised_exception != null) { throw raised_exception; } } } public static class Tick64 { static object lock_obj = new object(); static uint last_value = 0; static bool is_first = true; static uint num_round = 0; public static long Value { get { unchecked { lock (lock_obj) { uint current_value = (uint)(System.Environment.TickCount + 3864700935); if (is_first) { last_value = current_value; is_first = false; } if (last_value > current_value) { num_round++; } last_value = current_value; ulong ret = 4294967296UL * (ulong)num_round + current_value; return (long)ret; } } } } public static uint ValueUInt32 { get { unchecked { return (uint)((ulong)Value); } } } } public class Event { EventWaitHandle h; public const int Infinite = Timeout.Infinite; public Event() { init(false); } public Event(bool manualReset) { init(manualReset); } void init(bool manualReset) { h = new EventWaitHandle(false, (manualReset ? EventResetMode.ManualReset : EventResetMode.AutoReset)); } public void Set() { h.Set(); } public bool Wait() { return Wait(Infinite); } public bool Wait(int millisecs) { return h.WaitOne(millisecs, false); } static EventWaitHandle[] toArray(Event[] events) { List<EventWaitHandle> list = new List<EventWaitHandle>(); foreach (Event e in events) { list.Add(e.h); } return list.ToArray(); } public static bool WaitAll(Event[] events) { return WaitAll(events, Infinite); } public static bool WaitAll(Event[] events, int millisecs) { if (events.Length <= 64) { return waitAllInner(events, millisecs); } else { return waitAllMulti(events, millisecs); } } static bool waitAllMulti(Event[] events, int millisecs) { int numBlocks = (events.Length + 63) / 64; List<Event>[] list = new List<Event>[numBlocks]; int i; for (i = 0; i < numBlocks; i++) { list[i] = new List<Event>(); } for (i = 0; i < events.Length; i++) { list[i / 64].Add(events[i]); } double start = Time.NowDouble; double giveup = start + (double)millisecs / 1000.0; foreach (List<Event> o in list) { double now = Time.NowDouble; if (now <= giveup || millisecs < 0) { int waitmsecs; if (millisecs >= 0) { waitmsecs = (int)((giveup - now) * 1000.0); } else { waitmsecs = Timeout.Infinite; } bool ret = waitAllInner(o.ToArray(), waitmsecs); if (ret == false) { return false; } } else { return false; } } return true; } static bool waitAllInner(Event[] events, int millisecs) { if (events.Length == 1) { return events[0].Wait(millisecs); } return EventWaitHandle.WaitAll(toArray(events), millisecs, false); } public static bool WaitAny(Event[] events) { return WaitAny(events, Infinite); } public static bool WaitAny(Event[] events, int millisecs) { if (events.Length == 1) { return events[0].Wait(millisecs); } return ((WaitHandle.WaitTimeout == EventWaitHandle.WaitAny(toArray(events), millisecs, false)) ? false : true); } public IntPtr Handle { get { return h.Handle; } } } public class ThreadData { static LocalDataStoreSlot slot = Thread.AllocateDataSlot(); public readonly SortedDictionary<string, object> DataList = new SortedDictionary<string, object>(); public static ThreadData CurrentThreadData { get { return GetCurrentThreadData(); } } public static ThreadData GetCurrentThreadData() { ThreadData t; try { t = (ThreadData)Thread.GetData(slot); } catch { t = null; } if (t == null) { t = new ThreadData(); Thread.SetData(slot, t); } return t; } } public delegate void ThreadProc(object userObject); public class ThreadObj { static int defaultStackSize = 100000; static LocalDataStoreSlot currentObjSlot = Thread.AllocateDataSlot(); public const int Infinite = Timeout.Infinite; ThreadProc proc; Thread thread; EventWaitHandle waitInit; EventWaitHandle waitEnd; EventWaitHandle waitInitForUser; public Thread Thread { get { return thread; } } object userObject; public ThreadObj(ThreadProc threadProc) { init(threadProc, null, 0); } public ThreadObj(ThreadProc threadProc, int stacksize) { init(threadProc, null, stacksize); } public ThreadObj(ThreadProc threadProc, object userObject) { init(threadProc, userObject, 0); } public ThreadObj(ThreadProc threadProc, object userObject, int stacksize) { init(threadProc, userObject, stacksize); } void init(ThreadProc threadProc, object userObject, int stacksize) { if (stacksize == 0) { stacksize = defaultStackSize; } this.proc = threadProc; this.userObject = userObject; waitInit = new EventWaitHandle(false, EventResetMode.AutoReset); waitEnd = new EventWaitHandle(false, EventResetMode.ManualReset); waitInitForUser = new EventWaitHandle(false, EventResetMode.ManualReset); this.thread = new Thread(new ParameterizedThreadStart(commonThreadProc), stacksize); this.thread.Start(this); waitInit.WaitOne(); } public static int DefaultStackSize { get { return defaultStackSize; } set { defaultStackSize = value; } } void commonThreadProc(object obj) { Thread.SetData(currentObjSlot, this); waitInit.Set(); try { this.proc(this.userObject); } finally { waitEnd.Set(); } } public static ThreadObj GetCurrentThreadObj() { return (ThreadObj)Thread.GetData(currentObjSlot); } public static void NoticeInited() { GetCurrentThreadObj().waitInitForUser.Set(); } public void WaitForInit() { waitInitForUser.WaitOne(); } public void WaitForEnd(int timeout) { waitEnd.WaitOne(timeout, false); } public void WaitForEnd() { waitEnd.WaitOne(); } public static void Sleep(int millisec) { if (millisec == 0x7fffffff) { millisec = ThreadObj.Infinite; } Thread.Sleep(millisec); } public static void Yield() { Thread.Sleep(0); } public static void ProcessWorkQueue(ThreadProc thread_proc, int num_worker_threads, object[] tasks) { WorkerQueuePrivate q = new WorkerQueuePrivate(thread_proc, num_worker_threads, tasks); } } }
18.180085
114
0.651789
[ "Apache-2.0" ]
ameerhassan/softethervpn-android
app/src/main/cpp/SoftEtherVPN/src/BuildUtil/CoreUtil/Thread.cs
8,583
C#
using OData_ClientSamplesConsole.Models; using Simple.OData.Client; using System; using System.Collections.Generic; namespace OData_ClientSamplesConsole { class Program { static void Main(string[] args) { ProductSamples(); Console.WriteLine("Done..."); Console.Read(); } public async static void ProductSamples() { var serviceUrl = "https://localhost:44358/service"; var client = new ODataClient(serviceUrl); // Basic API Console.WriteLine("Basic API"); var prouducts = await client.FindEntriesAsync("Products?$filter=Name eq 'Chai'"); foreach (var product in prouducts) { Console.WriteLine(product["Name"]); } // Fluent API Console.WriteLine("Fluent API"); var results = await client.For<Category>() .Expand(rr => rr.Products) //.Top(7).Skip(0) .FindEntriesAsync(); foreach(var result in results) { Console.WriteLine($"{result.Name}"); foreach(var product in result.Products) { Console.WriteLine($" {product.Name}"); } } // Fluent API (dynamic) Console.WriteLine("Fluent API (dynamic)"); var x = ODataDynamic.Expression; IEnumerable<dynamic> products = await client .For(x.Products) .Filter(x.Name == "Chai") .FindEntriesAsync(); foreach (var product in products) { Console.WriteLine(product.Name); } } } }
27.393939
93
0.497788
[ "Apache-2.0" ]
vincoss/NetCoreSamples
AspNetCore-2.0/src/OData_ClientSamplesConsole/Program.cs
1,810
C#
using System; using System.Collections.Generic; using System.Reflection; using System.Runtime.InteropServices; namespace EventsController { public static class WirecastAPI { private static object GetApplication() { try { object wirecast = Marshal.GetActiveObject("Wirecast.Application"); return wirecast; } catch (Exception e) { return null; } } public static void SetShotForLayer(int layer, int shot) { var wirecast = GetApplication(); var document = Late.Invoke(wirecast, "DocumentByIndex", 1); var layerObject = Late.Invoke(document, "LayerByIndex", layer); var shotId = Late.Invoke(layerObject, "ShotIDByIndex", shot); Late.Set(layerObject, "ActiveShotID", shotId); } public static void Take() { var wirecast = GetApplication(); var document = Late.Invoke(wirecast, "DocumentByIndex", 1); var layers = new[] {1, 2, 3, 4, 5}; foreach (var layerId in layers) { var layer = Late.Invoke(document, "LayerByIndex", layerId); Late.Invoke(layer, "Go"); } } public static void StartRecording() { var wirecast = GetApplication(); var document = Late.Invoke(wirecast, "DocumentByIndex", 1); Late.Invoke(document, "ArchiveToDisk", "start"); } public static void StopRecording() { var wirecast = GetApplication(); var document = Late.Invoke(wirecast, "DocumentByIndex", 1); Late.Invoke(document, "ArchiveToDisk", "stop"); } public static void StartBroadcasting() { var wirecast = GetApplication(); var document = Late.Invoke(wirecast, "DocumentByIndex", 1); Late.Invoke(document, "Broadcast", "start"); } public static void StopBroadcasting() { var wirecast = GetApplication(); var document = Late.Invoke(wirecast, "DocumentByIndex", 1); Late.Invoke(document, "Broadcast", "stop"); } } }
31.184211
82
0.53038
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
CVMEventi/EventsController
Windows/EventsController/WirecastAPI.cs
2,372
C#
namespace Xamarin.CommunityToolkit.Sample.Pages.Extensions { public partial class ExtensionsGalleryPage : BasePage { public ExtensionsGalleryPage() => InitializeComponent(); } }
23.25
59
0.784946
[ "MIT" ]
AbuMandour/XamarinCommunityToolkit
XamarinCommunityToolkitSample/Pages/Extensions/ExtensionsGalleryPage.xaml.cs
188
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 glue-2017-03-31.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.Glue.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Glue.Model.Internal.MarshallTransformations { /// <summary> /// DeleteWorkflow Request Marshaller /// </summary> public class DeleteWorkflowRequestMarshaller : IMarshaller<IRequest, DeleteWorkflowRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((DeleteWorkflowRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(DeleteWorkflowRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.Glue"); string target = "AWSGlue.DeleteWorkflow"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2017-03-31"; request.HttpMethod = "POST"; request.ResourcePath = "/"; request.MarshallerVersion = 2; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetName()) { context.Writer.WritePropertyName("Name"); context.Writer.Write(publicRequest.Name); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static DeleteWorkflowRequestMarshaller _instance = new DeleteWorkflowRequestMarshaller(); internal static DeleteWorkflowRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DeleteWorkflowRequestMarshaller Instance { get { return _instance; } } } }
35.580952
144
0.606799
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/Glue/Generated/Model/Internal/MarshallTransformations/DeleteWorkflowRequestMarshaller.cs
3,736
C#
// Copyright (c) 2021 Salim Mayaleh. All Rights Reserved // Licensed under the BSD-3-Clause License // Generated at 08.11.2021 21:25:55 by RaynetApiDocToDotnet.ApiDocParser, created by Salim Mayaleh. using System.Collections.Generic; using System.Threading.Tasks; using Maya.Raynet.Crm.Response.Get; namespace Maya.Raynet.Crm.Request.Get { public class ActivityCategories : GetRequest { protected override List<string> Actions { get; set; } = new List<string>(); public ActivityCategories() { Actions.Add("activityCategory"); } public new async Task<Model.DataResult<List<ActivityCategory>>> ExecuteAsync(ApiClient apiClient) { return await base.ExecuteAsync<List<ActivityCategory>>(apiClient); } } }
31.88
105
0.692597
[ "BSD-3-Clause" ]
mayaleh/Maya.Raynet.Crm
src/Maya.Raynet.Crm/Request/Get/ActivityCategories.cs
797
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Investigation.cs" company=""> // </copyright> // <summary> // Defines the Investigation type. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Holmes.Infrastructure.Services { using System; using System.Linq; using System.Text; using Holmes.Core.Interfaces; /// <summary> /// The investigation, effectively this is the logic of the investigation. /// </summary> public class Investigation { /// <summary> /// The investigation service. /// </summary> private readonly IInvestigationService investigationService; /// <summary> /// The world loading service. /// </summary> private readonly IWorldRepository worldLoadingService; /// <summary> /// Initializes a new instance of the <see cref="Investigation"/> class. /// </summary> /// <param name="worldLoadingService"> /// The world Loading Service. /// </param> /// <param name="investigationService">The investigation service</param> public Investigation(IWorldRepository worldLoadingService, IInvestigationService investigationService) { this.worldLoadingService = worldLoadingService; this.investigationService = investigationService; this.InvestigationTimeStep = TimeSpan.FromMinutes(5); } /// <summary> /// Gets or sets the investigation time step to use. Defaults to 5 minutes /// </summary> public TimeSpan InvestigationTimeStep { get; set; } /// <summary> /// Run the investigation scenario /// </summary> /// <returns> /// The <see cref="string"/> of the investigation. /// </returns> public string PerformInvestigation() { // We'll use a stringbuilder for performance reasons StringBuilder sb = new StringBuilder(); var world = this.worldLoadingService.GetWorld(); var startTime = world.CurrentTime; var investigationResult = InvestigationResult.Inconclusive; // We'll pull the number of suspects out using a Linq query under the assumption that // a room might be empty (even though in this example it won't be) var numberOfSuspects = world.InterrogationRooms.Select(x => x.Suspect != null).Count(); // Intro text sb.AppendLine( string.Format( "It was a dark and stormy night, the time was {0} and {1} suspects awaited their fate.", world.CurrentTime.ToString("t"), numberOfSuspects)); while (investigationResult == InvestigationResult.Inconclusive) { investigationResult = this.investigationService.Investigate(world, this.InvestigationTimeStep, ref sb); } var currentRoom = world.InterrogationRooms.Find(x => x.Investigators.Contains(world.Investigators[0])); sb.AppendLine( string.Format("It would appear that {0} is guilty of stealing the silver", currentRoom.Suspect.Name)); sb.AppendLine(string.Format("Investigation started at {0}", startTime)); sb.AppendLine(string.Format("Investigation finished at {0}", world.CurrentTime)); sb.AppendLine(string.Format("Total Investigation time: {0}", world.CurrentTime - startTime)); // return the investigation text return sb.ToString(); } } }
41.021739
120
0.573662
[ "MIT" ]
neoKushan/Holmes
src/Holmes/Holmes.Infrastructure/Services/Investigation.cs
3,776
C#