C# (CSharp) this Code Examples

C# (CSharp) this - 30 примеров найдено. Это лучшие примеры C# (CSharp) кода для this, полученные из open source проектов. Вы можете ставить оценку каждому примеру, чтобы помочь нам улучшить качество примеров.
Пример #1
0
        public static Type GetEntityType(this Type type)
        {
            if (!type.IsCrudController()) return null;

            var @interface = type.FindInterfaceThatCloses(typeof(CrudController<,>));
            return @interface.GetGenericArguments()[0];
        }
Пример #2
0
        public static string Decrypt(this string stringToDecrypt, string key)
        {
            if (string.IsNullOrEmpty(stringToDecrypt))
            {
                throw new ArgumentException("An empty string value cannot be encrypted.");
            }

            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentException("Cannot decrypt using an empty key. Please supply a decryption key.");
            }

            //var cspp = new CspParameters { KeyContainerName = key };
            var cspp = new CspParameters { KeyContainerName = key, Flags = CspProviderFlags.UseMachineKeyStore };

            var rsa = new RSACryptoServiceProvider(cspp) { PersistKeyInCsp = true };

            var decryptArray = stringToDecrypt.Split(new[] { "-" }, StringSplitOptions.None);
            var decryptByteArray = Array.ConvertAll(decryptArray, (s => Convert.ToByte(byte.Parse(s, System.Globalization.NumberStyles.HexNumber))));


            byte[] bytes = rsa.Decrypt(decryptByteArray, true);

            string result = System.Text.Encoding.UTF8.GetString(bytes);

            return result;
        }
Пример #3
0
        public static void Dump(this IMix mix, string name = null)
        {
            Console.WriteLine("-------------------------------------------------------");

            if (name != null)
            {
                Console.WriteLine(name);
                Console.WriteLine("-------------------------------------------------------");
            }

            for (int i = 0; i < mix.Count; i++)
            {
                IMixItem item = mix[i];

                Transition transition = item.Transition;

                string strategy = transition.Strategy == null
                                   ? "<null strategy>"
                                   : transition.Strategy.Description;

                Console.WriteLine(">>> {0} --> {1} using {2}", transition.FromKey, transition.ToKey, strategy);
                Console.WriteLine("{0}. {1}/{2:0.#}bpm {3}", i, item.ActualKey, item.ActualBpm, item.Track);
            }

            Console.WriteLine("{0} tracks total.", mix.Count);
            Console.WriteLine("-------------------------------------------------------");
        }
Пример #4
0
        public static bool IsLegalSize(this int size, KeySizes[] legalSizes, out bool validatedByZeroSkipSizeKeySizes)
        {
            validatedByZeroSkipSizeKeySizes = false;
            for (int i = 0; i < legalSizes.Length; i++)
            {
                KeySizes currentSizes = legalSizes[i];
                
                // If a cipher has only one valid key size, MinSize == MaxSize and SkipSize will be 0
                if (currentSizes.SkipSize == 0)
                {
                    if (currentSizes.MinSize == size)
                    {
                        // Signal that we were validated by a 0-skipsize KeySizes entry. Needed to preserve a very obscure
                        // piece of back-compat behavior.
                        validatedByZeroSkipSizeKeySizes = true;
                        return true;
                    }
                }
                else if (size >= currentSizes.MinSize && size <= currentSizes.MaxSize)
                {
                    // If the number is in range, check to see if it's a legal increment above MinSize
                    int delta = size - currentSizes.MinSize;

                    // While it would be unusual to see KeySizes { 10, 20, 5 } and { 11, 14, 1 }, it could happen.
                    // So don't return false just because this one doesn't match.
                    if (delta % currentSizes.SkipSize == 0)
                    {
                        return true;
                    }
                }
            }
            return false;
        }
Пример #5
0
		/// <summary>
		/// Return the substring up to but not including the first instance of 'c'.
		/// If 'c' is not found, the entire string is returned.
		/// </summary>
		public static string SubstringBefore (this String src, char c) {
			if (String.IsNullOrEmpty(src)) return "";
 
			int idx = Math.Min(src.Length, src.IndexOf(c));
			if (idx < 0) return src;
			return src.Substring(0, idx);
		}
        /// <summary>
        /// Appends key=value to the string.
        /// Does not append ? or &amp; before key=value.
        /// </summary>
        public static StringBuilder AppendQueryParam(this StringBuilder sb, string key, string value)
        {
            Debug.Assert(!string.IsNullOrWhiteSpace(key));
            Debug.Assert(value != null);

            return sb.Append(key).Append('=').Append(value);
        }
Пример #7
0
 /// <summary>
 /// 	Sets the time on the specified DateTime value using the specified time zone.
 /// </summary>
 /// <param name = "datetimeOff">The base date.</param>
 /// <param name = "timespan">The TimeSpan to be applied.</param>
 /// <param name = "localTimeZone">The local time zone.</param>
 /// <returns>/// The DateTimeOffset including the new time value/// </returns>
 public static DateTimeOffset SetTime(this DateTimeOffset datetimeOff, TimeSpan timespan,
                                      TimeZoneInfo localTimeZone)
 {
     var localDate = datetimeOff.ToLocalDateTime(localTimeZone);
     localDate.SetTime(timespan);
     return localDate.ToDateTimeOffset(localTimeZone);
 }
	public static MouseButton ToOpenTKSingle(this MouseButtons buttons)
	{
		if ((buttons & MouseButtons.Left) != MouseButtons.None) return MouseButton.Left;
		else if ((buttons & MouseButtons.Right) != MouseButtons.None) return MouseButton.Right;
		else if ((buttons & MouseButtons.Middle) != MouseButtons.None) return MouseButton.Middle;
		else return MouseButton.LastButton;
	}
        public static SmtpClient GenerateSmtpClient(this SmtpConfigurationEntity config)
        {
            if (config.DeliveryMethod != SmtpDeliveryMethod.Network)
            {
                return new SmtpClient
                {
                    DeliveryFormat = config.DeliveryFormat,
                    DeliveryMethod = config.DeliveryMethod,
                    PickupDirectoryLocation = config.PickupDirectoryLocation,
                };
            }
            else
            {
                SmtpClient client = EmailLogic.SafeSmtpClient(config.Network.Host, config.Network.Port);
                client.DeliveryFormat = config.DeliveryFormat;
                client.UseDefaultCredentials = config.Network.UseDefaultCredentials;
                client.Credentials = config.Network.Username.HasText() ? new NetworkCredential(config.Network.Username, config.Network.Password) : null;
                client.EnableSsl = config.Network.EnableSSL;

                foreach (var cc in config.Network.ClientCertificationFiles)
                {
                    client.ClientCertificates.Add(cc.CertFileType == CertFileType.CertFile ?
                        X509Certificate.CreateFromCertFile(cc.FullFilePath)
                        : X509Certificate.CreateFromSignedFile(cc.FullFilePath));
                }

                return client;
            }
        }
 public static void DeserializeObject(this Stream stream, object obj, List<string> nameTable)
 {
     while (stream.Position < stream.Length)
     {
         stream.ReadAndMapProperty(obj, nameTable);
     }
 }
Пример #11
0
 public static LEAP_VECTOR ToCVector(this Vector3 vector) {
   LEAP_VECTOR cVector = new LEAP_VECTOR();
   cVector.x = vector.x;
   cVector.y = vector.y;
   cVector.z = vector.z;
   return cVector;
 }
Пример #12
0
 public static void DisposeIfNotNull(this IDisposable disposable)
 {
     if (disposable != null)
     {
         disposable.Dispose();
     }
 }
        public static IIntermediarySocket AsIntermediary(this EasyZMqConfigurer configurer, string backendAddress)
        {
            var frontendAddressBinder = configurer.AddressBinder;
            var backendAddressBinder = new BindAddressBinder(new Uri(backendAddress));

            return CreateIntermediarySocket(frontendAddressBinder, backendAddressBinder);
        }
Пример #14
0
 public static AttributeGroup FixedDates(this AttributeGroup group)
 {
     group.UtcCreated = FixedSystemDate;
     group.UtcModified = FixedSystemDate;
     group.UtcStatusChanged = FixedSystemDate;
     return group;
 }
        public static string FQN(this XElement element)
        {
            if (element == null)
                return string.Empty;

            var ns = element.Name.NamespaceName;
            var prefix = element.Document.Root.GetPrefixOfNamespace(ns);

            if (string.IsNullOrWhiteSpace(prefix))
            {
                var nsRoot = element.Document.Root.GetDefaultNamespace().NamespaceName;
                if (!string.IsNullOrWhiteSpace(nsRoot))
                {
                    if (string.IsNullOrWhiteSpace(prefix) && nsRoot.Equals(ns))
                    {
                        prefix = Common.DefaultNamespace;
                    }
                }
            }

            if (!string.IsNullOrWhiteSpace(prefix))
                prefix = prefix + ":";

            return prefix + element.Name.LocalName;
        }
 private static void TraceMessage(this Message message)
 {
     Console.WriteLine("\tTime:       {0}", DateTime.Now.ToString("HH:mm:ss.ffffff"));
     Console.WriteLine("\tMessage ID: {0}", message.Id);
     Console.WriteLine("\tCorrel. ID: {0}", message.CorrelationId);
     Console.WriteLine("\tContents:   {0}", message.Body);
 }
        public static UITextureAtlas GetInfoTooltip(this AssetManager assetManager, string infoTooltipName, string infoTooltipPath)
        {
            var infoTooltipAtlas = ScriptableObject.CreateInstance<UITextureAtlas>();
            infoTooltipAtlas.padding = 0;
            infoTooltipAtlas.name = infoTooltipName;

            var shader = Shader.Find("UI/Default UI Shader");
            if (shader != null) infoTooltipAtlas.material = new Material(shader);

            var texture = assetManager.GetTexture(infoTooltipPath);

            infoTooltipAtlas.material.mainTexture = texture;

            const int ittW = 535;
            const int ittH = 150;

            var sprite = new UITextureAtlas.SpriteInfo
            {
                name = string.Format(infoTooltipName.ToUpper()),
                region = new Rect(0f, 0f, 1f, 1f),
                texture = new Texture2D(ittW, ittH, TextureFormat.ARGB32, false)
            };

            infoTooltipAtlas.AddSprite(sprite);

            return infoTooltipAtlas;
        }
        public static IServiceCollection AddFromAssembly(this IServiceCollection serviceCollection, Assembly assembly)
        {
            var builder = new ServiceDescriptorsBuilder().AddSourceAssembly(assembly);
            BuildAndFill(serviceCollection, builder);

            return serviceCollection;
        }
Пример #19
0
 public static StringBuilder AppendEscapedXml(this StringBuilder builder, string value)
 {
   if (value == null) return builder;
   builder.EnsureCapacity(builder.Length + value.Length + 10);
   for (var i = 0; i < value.Length; i++)
   {
     switch (value[i])
     {
       case '&':
         builder.Append("&amp;");
         break;
       case '<':
         builder.Append("&lt;");
         break;
       case '>':
         builder.Append("&gt;");
         break;
       case '"':
         builder.Append("&quot;");
         break;
       case '\'':
         builder.Append("&apos;");
         break;
       default:
         builder.Append(value[i]);
         break;
     }
   }
   return builder;
 }
Пример #20
0
 public static string Series(this UrlHelper helper, int seriesId, string seriesSlug)
 {
     return helper.Action(
            MVC.Posts.ActionNames.Series,
         MVC.Posts.Name,
         new { seriesId, seriesSlug });
 }
Пример #21
0
        /*public static float NextFloat(this Random rand, float maxValue = 1.0f, float minValue=0.0f)
        {
            return (float)rand.NextDouble() * (maxValue - minValue) + minValue;
        }*/
        public static Vector2 NextVector2(this Random rand, float maxLength = 1.0f, float minLength = 1.0f)
        {
            double theta = rand.NextDouble() * 2 * Math.PI;
            float length = rand.NextFloat(minLength, maxLength);

            return new Vector2(length * (float)Math.Cos(theta), length * (float)Math.Sin(theta));
        }
Пример #22
0
	public static Field.Index GetIndex(this IndexDefinition self, string name, Field.Index? defaultIndex)
	{
		if (self.Indexes == null)
			return defaultIndex ?? Field.Index.ANALYZED_NO_NORMS;
		FieldIndexing value;
		if (self.Indexes.TryGetValue(name, out value) == false)
		{
			if (self.Indexes.TryGetValue(Constants.AllFields, out value) == false)
			{
				string ignored;
				if (self.Analyzers.TryGetValue(name, out ignored) ||
					self.Analyzers.TryGetValue(Constants.AllFields, out ignored))
				{
					return Field.Index.ANALYZED; // if there is a custom analyzer, the value should be analyzed
				}
				return defaultIndex ?? Field.Index.ANALYZED_NO_NORMS;
			}
		}
		switch (value)
		{
			case FieldIndexing.No:
				return Field.Index.NO;
			case FieldIndexing.Analyzed:
				return Field.Index.ANALYZED_NO_NORMS;
			case FieldIndexing.NotAnalyzed:
				return Field.Index.NOT_ANALYZED_NO_NORMS;
			case FieldIndexing.Default:
				return defaultIndex ?? Field.Index.ANALYZED_NO_NORMS;
			default:
				throw new ArgumentOutOfRangeException();
		}
	}
Пример #23
0
		/// <summary>
		/// Return the substring after to but not including the last instance of 'c'.
		/// If 'c' is not found, the entire string is returned.
		/// </summary>
		public static string SubstringAfterLast (this String src, char c) {
			if (String.IsNullOrEmpty(src)) return "";
 
			int idx = Math.Min(src.Length - 1, src.LastIndexOf(c) + 1);
			if (idx < 0) return src;
			return src.Substring(idx);
		}
Пример #24
0
 /// <summary>
 ///  Returns maximum spell range based on hitbox of unit. 
 /// </summary>
 /// <param name="spell"></param>
 /// <param name="unit"></param>
 /// <returns>Maximum spell range</returns>
 public static float ActualMaxRange(this WoWSpell spell, WoWUnit unit)
 {
     if (spell.MaxRange == 0)
         return 0;
     // 0.3 margin for error
     return unit != null ? spell.MaxRange + unit.CombatReach + 1f : spell.MaxRange;
 }
Пример #25
0
        public static string CreateAutoCompleteDictionaryEntryHash(this string entry, bool log = true)
        {
            if (!string.IsNullOrWhiteSpace(entry))
            {
                //Trim white space
                string hash = entry.Trim();
                
                //Hashes are stored without diacritics (accents etc)
                hash = hash.RemoveDiacritics();

                //Hashes are stored as uppercase
                hash = hash.ToUpper();
                
                if (!string.IsNullOrWhiteSpace(hash))
                {
                    if (log)
                    {
                        Log.DebugFormat("Entry of '{0}' hashed to '{1}'", entry, hash);
                    }

                    return hash;
                }
            }

            return null;
        }
Пример #26
0
        // Create an md5 sum string of this string
        public static string GetMd5Sum(this string str)
        {
            // First we need to convert the string into bytes, which
            // means using a text encoder.
            Encoder enc = System.Text.Encoding.Unicode.GetEncoder();

            // Create a buffer large enough to hold the string
            byte[] unicodeText = new byte[str.Length * 2];
            enc.GetBytes(str.ToCharArray(), 0, str.Length, unicodeText, 0, true);

            // Now that we have a byte array we can ask the CSP to hash it
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] result = md5.ComputeHash(unicodeText);

            // Build the final string by converting each byte
            // into hex and appending it to a StringBuilder
            var sb = new StringBuilder();
            for (int i = 0; i < result.Length; i++)
            {
                sb.Append(result[i].ToString("X2"));
            }

            // And return it
            return sb.ToString();
        }
Пример #27
0
 public static void AssertNotNullOrEmpty(this string source, string message = null)
 {
     if (string.IsNullOrEmpty(source))
     {
         throw new Exception("Assertion failed: " + (message ?? "expected to not be null or empty"));
     }
 }
        public static string FQN(this XAttribute element)
        {
            if (element == null)
                return string.Empty;

            return "@" + element.Name.LocalName;
        }
 /// <summary>
 /// Repeats the specified <see cref="Action"/> the number of times.
 /// </summary>
 /// <param name="input">The number of times to repeat the <see cref="Action"/>.</param>
 /// <param name="action">The <see cref="Action"/> to repeat.</param>
 public static void Times(this int input, Action action)
 {
     while (input-- > 0)
     {
         action();
     }
 }
Пример #30
0
 public static Obj_AI_Hero GetTarget(this Spell spell,
     bool ignoreShields = true,
     Vector3 from = default(Vector3),
     IEnumerable<Obj_AI_Hero> ignoredChampions = null)
 {
     return TargetSelector.GetTarget(spell, ignoreShields, from, ignoredChampions);
 }