C#に投稿されたコード一覧

C# サロゲートペアを考慮してSubstringできるやつ

using System;
using System.Collections.Generic;
using System.Text;

namespace Liberfy
{
	public sealed unsafe class TwStringInfo : IDisposable
	{
		#region fields

		private int* surrogateIndices;
		private int surrogateIndicesLength;

		#endregion

		#region properties

		public string String { get; private set; }

		public int Length { get; private set; }

		#endregion

		public TwStringInfo(string text)
		{
			if (text == null) return;

			var surrogateIndicesList = new LinkedList<int>();

			String = text.Normalize(NormalizationForm.FormC);

			char c;
			int Length = String.Length;

			int surrogateIndex;
			for (surrogateIndex = 0; surrogateIndex < Length; surrogateIndex++)
			{
				if ('\uD800' <= (c = String[surrogateIndex]) && c <= '\uDBFF')
				{
					surrogateIndicesList.AddLast(surrogateIndex);
					surrogateIndex++;
				}
			}

			surrogateIndicesLength = surrogateIndicesList.Count;

			if (surrogateIndicesLength > 0)
			{
				int* indices = stackalloc int[surrogateIndicesLength];

				LinkedListNode<int> node = surrogateIndicesList.First;

				for (int i = 0; i < surrogateIndicesLength; i++)
				{
					indices[i] = node.Value;
					node = node.Next;
				}

				surrogateIndices = indices;
				indices = null;

				surrogateIndicesList.Clear();
			}

			surrogateIndicesList = null;
		}

		public string Substring(int startIndex)
		{
			int substringStartIndex = startIndex;

			for (int i = 0; i < surrogateIndicesLength; i++)
			{
				if (surrogateIndices[i] < startIndex)
				{
					substringStartIndex++;
				}
				else
				{
					break;
				}
			}

			return String.Substring(substringStartIndex);
		}

		public string Substring(int startIndex, int length)
		{
			int i = 0;
			int substringStartIndex = startIndex;
			int substringLength = length;
			int totalLength = startIndex + length;

			for (; i < surrogateIndicesLength; i++)
			{
				if (surrogateIndices[i] < startIndex)
				{
					substringStartIndex++;
				}
				else
				{
					break;
				}
			}

			for (; i < surrogateIndicesLength; i++)
			{
				if (surrogateIndices[i] < totalLength)
				{
					substringLength++;
				}
				else
				{
					break;
				}
			}

			return String.Substring(substringStartIndex, substringLength);
		}

		#region IDisposable Support
		private bool disposedValue = false;

		private void Dispose(bool disposing)
		{
			if (!disposedValue)
			{
				if (disposing)
				{
					Length = 0;
					String = null;
				}
				else
				{
					surrogateIndices = null;
					surrogateIndicesLength = 0;
				}

				disposedValue = true;
			}
		}

		~TwStringInfo()
		{
			Dispose(false);
		}

		public void Dispose()
		{
			Dispose(true);
			GC.SuppressFinalize(this);
		}
		#endregion
	}
}

C# [WPF]TreeViewのItemにアイコン追加

TreeView TV = new TreeView();
//icon add
StackPanel sp = new StackPanel();
sp.Orientation = Orientation.Horizontal;
BitmapImage bmi = new BitmapImage();
bmi = new BitmapImage(new Uri("ITEM.png", UriKind.RelativeOrAbsolute));
Image img = new Image();
img.Source = bmi;
img.Height = 15;
img.Width = 15;
sp.Children.Add(img);
TextBlock tb = new TextBlock();
tb.Text = "TreeItem";
sp.Children.Add(tb);
 
//Add Parent's Node
TreeViewItem item = new TreeViewItem();
item.Header = sp;
TV.Items.Add(item);

C# Cryptographyでの暗号化

using System;
using System.Text;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
 
namespace Encryption
{
    [ComVisible(true)]
    public class Crypt : IDisposable
    {
        public string Encrypt(string arg)
        {
            byte[] bytes = Encoding.Unicode.GetBytes(arg);
            byte[] cryptData = ProtectedData.Protect(bytes, null, DataProtectionScope.CurrentUser);
            return ByteArrayToString(protectedData);
        }
        private string ByteArrayToString(byte[] ba)
        {
            string hexStr = BitConverter.ToString(ba);
            return hexStr.Replace("-", "");
        }
        public void Dispose(){}
    }
}

C# [添付]タイムラインの文字列表示処理

		/// <summary>
		/// 同じ型の配列を結合します。
		/// </summary>
		/// <typeparam name="T">配列の型</typeparam>
		/// <param name="args">結合する配列</param>
		/// <returns></returns>
		public static IList<T> ConcatArray<T>(params IEnumerable<T>[] args)
		{
			var ie = new List<T>();
			if (args != null)
				args.ForEach(arg =>
					{
						if (arg != null)
							ie.AddRange(arg);
					});
			return ie;
		}

	/// <summary>
	/// 拡張メソッド
	/// </summary>
	public static class Extensions
	{
		public static void ForEach<T>(this T[] root, Action<T> loop)
		{
			if (loop != null) foreach (var item in root) loop(item);

		}

		public static void ForEach<T>(this IEnumerable<T> root, Action<T, int> loop)
		{
			if (loop != null)
				foreach (var item in root.Select((v, i) => new { v, i }))
					loop(item.v, item.i);
		}
	}

C# タイムラインの文字列表示処理

		public static void TwitterObectToInline(InlineCollection inlines, CoreTweet.Core.CoreBase obj, bool clearInlines = false)
		{
			if (obj == null || obj == null) return;

			// 内容の消去
			if (clearInlines) inlines.Clear();

			string text = null;
			IList<Entity> dic = null;

			// エンティティのリスト作成
			if (obj is Status)
			{
				var status = (Status)obj;
				text = status.Text;
				dic = ConcatArray<Entity>( // エンティティの結合
					status.Entities.UserMentions,
					status.Entities.Urls,
					status.Entities.Symbols,
					status.Entities.Media,
					status.Entities.HashTags);
			}
			else if (obj is DirectMessage)
			{
				var message = (DirectMessage)obj;
				text = message.Text;
				dic = ConcatArray<Entity>(
					message.Entities.UserMentions,
					message.Entities.Urls,
					message.Entities.Symbols,
					message.Entities.Media,
					message.Entities.HashTags);
			}

			if (dic == null) return;

			if (dic.Count > 0)
			{
				// エンティティが含まれている場合

				// エンティティの出現番号順に並び替え
				dic = dic.OrderBy(entity => entity.Indices[0]).ToList();

				// エンティティの開始が0文字目で無い場合に文字列を挿入
				if (dic[0].Indices[0] != 0)
					inlines.Add(HttpUtility.HtmlDecode(text.Substring(0, dic[0].Indices[0])));

				// エンティティの追加
				dic.ForEach((entity, index) =>
				{
					// *** リンクの生成 ***
					var link = new Hyperlink()
					{
						Cursor = Cursors.Hand,
					};

					if (entity is UserMentionEntity)
					{
						var user = (UserMentionEntity)entity;
						link.Inlines.Add(string.Format("@{0}", user.ScreenName));
					}
					else if (entity is UrlEntity)
					{
						var url = (UrlEntity)entity;
						link.Inlines.Add(url.DisplayUrl);
					}
					else if (entity is SymbolEntity)
					{
						var symbol = (SymbolEntity)entity;
						link.Inlines.Add(string.Format("{0}{1}",
							text[symbol.Indices[0]] == '$' ? '$' : '#',
							symbol.Text));
					}
					else if (entity is MediaEntity)
					{
						var media = (MediaEntity)obj;
						link.Inlines.Add(media.MediaUrl.AbsoluteUri);
					}

					inlines.Add(link);

					// *** エンティティ間/前後の文字列の挿入 ***

					var len = entity.Indices[1]; // エンティティの文字列の最終
					if (len != text.Length)
					{
						if (dic.Count > index + 1)
							inlines.Add(HttpUtility.HtmlDecode(
								text.Substring(len, dic[index + 1].Indices[0] - len)));

						else
							inlines.Add(HttpUtility.HtmlDecode(
								text.Substring(len, text.Length - len)));
					}
				});
			}
			else inlines.Add(HttpUtility.HtmlDecode(text));

			dic.Clear();
			dic = null;
		}

C# クラスの複製(MemberwiseClone)

/// <summary>
/// UserControl1.xaml の相互作用ロジック
/// </summary>
public partial class UserControl1 : UserControl, ICloneable
{
	public UserControl1()
	{
		InitializeComponent();
	}

	public object Clone()
	{
		return MemberwiseClone();

		// 複製
		// var uc1 = new UserControl1();
		// var uc2 = (UserControl1)userControl1.Clone();
	}
}

C# クラスの複製(MemberwiseClone)

/// <summary>
/// UserControl1.xaml の相互作用ロジック
/// </summary>
public partial class UserControl1 : UserControl, ICloneable
{
	public UserControl1()
	{
		InitializeComponent();
	}

	public object Clone()
	{
		return MemberwiseClone();
			// 複製
		// var uc1 = ne UserControl1();
		// var uc2 = (UserControl1)userControl1.Clone();
	}
}

C# Cryptographyでの暗号化

using System;
using System.Text;
using System.Security.Cryptography;
using System.Runtime.InteropServices;

namespace Encryption
{
    [ComVisible(true)]
    public class Crypt : IDisposable
    {
        public string Encrypt(string arg)
        {
            byte[] bytes = Encoding.Unicode.GetBytes(arg);
            byte[] cryptData = ProtectedData.Protect(bytes, null, DataProtectionScope.CurrentUser);
            return ByteArrayToString(protectedData);
        }
        private string ByteArrayToString(byte[] ba)
        {
            string hexStr = BitConverter.ToString(ba);
            return hexStr.Replace("-", "");
        }
        public void Dispose(){}
    }
}

C# [WPF]TreeViewのItemにアイコン追加

TreeView TV = new TreeView();
//icon add
StackPanel sp = new StackPanel();
sp.Orientation = Orientation.Horizontal;
BitmapImage bmi = new BitmapImage();
bmi = new BitmapImage(new Uri("ITEM.png", UriKind.RelativeOrAbsolute));
Image img = new Image();
img.Source = bmi;
img.Height = 15;
img.Width = 15;
sp.Children.Add(img);
TextBlock tb = new TextBlock();
tb.Text = "TreeItem";
sp.Children.Add(tb);

//Add Parent's Node
TreeViewItem item = new TreeViewItem();
item.Header = sp;
TV.Items.Add(item);

C# [WPF]TreeViewのItemにアイコン追加

TreeView TV = new TreeView();
//icon add
StackPanel sp = new StackPanel();
sp.Orientation = Orientation.Horizontal;
BitmapImage bmi = new BitmapImage();
bmi = new BitmapImage(new Uri("ITEM.png", UriKind.RelativeOrAbsolute));
Image img = new Image();
img.Source = bmi;
img.Height = 15;
img.Width = 15;
sp.Children.Add(img);
TextBlock tb = new TextBlock();
tb.Text = "TreeItem";
sp.Children.Add(tb);

//Add Parent's Node
TreeViewItem item = new TreeViewItem();
item.Header = sp;
TV.Items.Add(item);
Total Pages: 1 / 3123

よく投稿されているコード

タグ

最近投稿されたコード