随手记录下可能有用的代码

随手记录下可能有用的代码

记录一下:
FrameworkElement FrameworkElement = new FrameworkElement();
return (Style)FrameworkElement.TryFindResource(“样式名”);

日志
[assembly: log4net.Config.XmlConfigurator(ConfigFile = “log4net.config”, ConfigFileExtension = “config”, Watch = true)]

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="System.Configuration.IgnoreSectionHandler"/>
  </configSections>
  <log4net>
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="Log\" />
      <param name="AppendToFile" value="true" />
      <param name="rollingStyle" value="Date" />
      <param name="datePattern" value="yyyy-MM-dd.'log.txt'" />
      <param name="staticLogFileName" value="false"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"/>
      </layout>
    </appender>
    <root>
      <level value="All"/>
      <appender-ref ref="RollingLogFileAppender"/>
    </root>
  </log4net>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
  </startup>
</configuration>

exp
1.导出用户库
exp user/pwd@orcl file=‘xx.dmp’
2.导出表
exp user/pwd@orcl file=‘xx.dmp’ tables=(table1,table2,…)
3.导出表结构不导出数据
exp user/pwd@orcl file=‘xx.dmp’ rows=n
imp
1.导入用户库
imp user/pwd@orcl file=‘xx.dmp’ full=y ignore=y
2.导入表
imp user/pwd@orcl file=‘xx.dmp’ tables=(table1,table2,…) ignore=y

//因为C#和Java的byte字节的高位和地位是完全相反的,所以在接收字节数据需要翻转

private string ReadString(byte[] stringBytes, int index, int count)
{
 	string msg = Encoding.UTF8.GetString(stringBytes, index, count);            //只用这种方式直接得到的字节数组直接就是大端序
	msg.Trim();                                                                 //在从服务器接收的时候去掉"\r"
	return msg;
}
private byte[] WriteString(string msg)
{
	byte[] temp = Encoding.UTF8.GetBytes(msg + "\r\n");                           //因为java的字符串在后面会自动加上“\r”,在发送到服务器上时需要加上"\r"
	return temp;
}

Bitmap To BitmapFrame

//Bitmap bitmap
using (System.IO.MemoryStream imageStream= new System.IO.MemoryStream())
 {
     bitmap.Save(imageStream, System.Drawing.Imaging.ImageFormat.Png);
     return BitmapFrame.Create(imageStream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
 }

BitmapImage 裁剪

private System.Windows.Media.Imaging.BitmapSource Get16X9BitmapSource(System.Windows.Media.Imaging.BitmapImage img)
        {
            ImageHelper.Get16X9WidthAndHeight(img, out int x, out int y, out int width, out int height);
            return new System.Windows.Media.Imaging.CroppedBitmap(img, new Int32Rect(x, y, width, height));
        }

public static void Get16X9WidthAndHeight(BitmapImage bitmapImage, out int x, out int y, out int width, out int height)
        {
            x = 0;
            y = 0;
            width = (int)bitmapImage.Width;
            height = (int)bitmapImage.Height;
            if (width * 9 > height * 16)
            {
                width = height * 16 / 9;
                x = ((int)bitmapImage.Width - width) / 2;
            }
            if (width * 9 < height * 16)
            {
                height = width * 9 / 16;
                y = ((int)bitmapImage.Height - height) / 2;
            }
        }

Sql server
select * from master.sys.sysprocesses where dbid = db_id(‘表名’)
断开某个连接
kill spid号
断开所以连接
declare @d varchar(8000)
set @d= ’ ’
select @d=@d+ ’ kill '+cast(spid as varchar)+char(13)
from master.sys.sysprocesses where dbid=db_id(‘表名’)
exec(@d)

自定义用户控件

{Binding RelativeSource={RelativeSource Mode= FindAncestor, AncestorType={x:Type local:UserTile}}, Path=UserImageSource}"

注册表

public static bool IsExistKey(string keyName)
        {
            try
            {
                bool _exist = false;
                RegistryKey local = Registry.LocalMachine;
                RegistryKey runs = local.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
                if (runs == null)
                {
                    RegistryKey key2 = local.CreateSubKey("SOFTWARE");
                    RegistryKey key3 = key2.CreateSubKey("Microsoft");
                    RegistryKey key4 = key3.CreateSubKey("Windows");
                    RegistryKey key5 = key4.CreateSubKey("CurrentVersion");
                    RegistryKey key6 = key5.CreateSubKey("Run");
                    runs = key6;
                }
                string[] runsName = runs.GetValueNames();
                foreach (string strName in runsName)
                {
                    if (strName.ToUpper() == keyName.ToUpper())
                    {
                        _exist = true;
                        return _exist;
                    }
                }
                return _exist;
            }
            catch
            {
                return false;
            }
        }
        public static bool SelfRunning(bool isStart, string exeName, string path)
        {
            try
            {
                RegistryKey local = Registry.LocalMachine;
                RegistryKey key = local.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
                if (key == null)
                {
                    local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
                    key = local.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
                }
                if (isStart)//若开机自启动则添加键值对
                {
                    key.SetValue(exeName, path);
                    key.Close();
                }
                else//否则删除键值对
                {
                    string[] keyNames = key.GetValueNames();
                    foreach (string keyName in keyNames)
                    {
                        if (keyName.ToUpper() == exeName.ToUpper())
                        {
                            key.DeleteValue(exeName);
                            key.Close();
                        }
                    }
                }
            }
            catch (Exception)
            {
                return false;
                //throw;
            }

            return true;
        }

并发集合:
System.Collections.Concurrent

ConcurrentQueue
ConcurrentStack
ConcurrentBag
ConcurrentDictionary
ConcurrentXXX
BlockingCollection
BlockingCollection

	/// <summary>
    /// 树工具类
    /// </summary>
    public static class ListTreeExtension
    {
        /// <summary>
        /// 将列表转换为树形结构
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="list">数据</param>
        /// <param name="rootwhere">根条件</param>
        /// <param name="childswhere">节点条件</param>
        /// <param name="addchilds">添加子节点</param>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static List<T> ToTree<T>(this List<T> list, Func<T, T, bool> rootwhere, Func<T, T, bool> childswhere, Action<T, IEnumerable<T>> addchilds, T entity = default(T))
        {
            var treelist = new List<T>();
            //空树
            if (list == null || list.Count == 0)
            {
                return treelist;
            }
            if (!list.Any<T>(e => rootwhere(entity, e)))
            {
                return treelist;
            }

            //树根
            if (list.Any<T>(e => rootwhere(entity, e)))
            {
                treelist.AddRange(list.Where(e => rootwhere(entity, e)));
            }

            //树叶
            foreach (var item in treelist)
            {
                if (list.Any(e => childswhere(item, e)))
                {
                    var nodedata = list.Where(e => childswhere(item, e)).ToList();
                    foreach (var child in nodedata)
                    {
                        //添加子集
                        var data = list.ToTree(childswhere, childswhere, addchilds, child);
                        addchilds(child, data);
                    }
                    addchilds(item, nodedata);
                }
            }

            return treelist;
        }
    }
public static T Create<T>(string assemblyName, AttributeBase attr)
        {
            var tps = GetAssembly(assemblyName);
            if (tps != null)
            {
                foreach (var tp in tps)
                {
                    var a = tp.GetCustomAttribute<AttributeBase>();
                    var intr = tp.GetInterface(typeof(T).Name);
                    if (intr != null && a != null && a.Name == attr.Name)
                    {
                        if (intr.ContainsGenericParameters)
                        {
                            var genericType = tp.MakeGenericType(typeof(T).GetGenericArguments());
                            return (T)Activator.CreateInstance(genericType);
                        }
                        return (T)Activator.CreateInstance(tp);
                    }
                }
            }

            return default;
        }

深拷贝

public static class TransExp<TIn, TOut>
{
    private static readonly Func<TIn, TOut> cache = GetFunc();
    private static Func<TIn, TOut> GetFunc()
    {
        ParameterExpression parameterExpression = Expression.Parameter(typeof(TIn), "p");
        List<MemberBinding> memberBindingList = new List<MemberBinding>();

        foreach (var item in typeof(TOut).GetProperties())
        {
            if (!item.CanWrite) continue;
            MemberExpression property = Expression.Property(parameterExpression, typeof(TIn).GetProperty(item.Name));
            MemberBinding memberBinding = Expression.Bind(item, property);
            memberBindingList.Add(memberBinding);
        }

        MemberInitExpression memberInitExpression = Expression.MemberInit(Expression.New(typeof(TOut)), memberBindingList.ToArray());
        Expression<Func<TIn, TOut>> lambda = Expression.Lambda<Func<TIn, TOut>>(memberInitExpression, new ParameterExpression[] { parameterExpression });

        return lambda.Compile();
    }

    public static TOut Trans(TIn tIn)
    {
        return cache(tIn);
    }
}

输入法设置焦点

// 使用
var source = (HwndSource)PresentationSource.FromVisual(tb);
if (source != null){ SetFocus(source.Handle); }

//引入
[DllImport("User32.dll")]
private static extern IntPtr SetFocus(IntPtr hWnd);

List2Tree

public static IEnumerable<TreeItem<T>> GenerateTree<T, k>(this IEnumerable<T> collection, Func<T, K> id_ selector, Func<T , K>parent_ id_ selector, K root_ id) 
{
	foreach(var c in collection.Where (c=>EqualityComparer<K>.Default.Equals(parent_ id_ selector(c), root_ id)))
	{
		yield return new TreeItem<T>
		{
			Item = c
			Children = collection.GenerateTree(id_ selector, parent_ id_ selector, id_ selector(c) )
		}
	}
}

不生成多余语言

<PropertyGroup>
   <SatelliteResourceLanguages>en</SatelliteResourceLanguages>
</PropertyGroup>

窗口圆角

    // The enum flag for DwmSetWindowAttribute's second parameter, which tells the function what attribute to set.
    public enum DWMWINDOWATTRIBUTE
    {
        DWMWA_WINDOW_CORNER_PREFERENCE = 33
    }

    // The DWM_WINDOW_CORNER_PREFERENCE enum for DwmSetWindowAttribute's third parameter, which tells the function
    // what value of the enum to set.
    public enum DWM_WINDOW_CORNER_PREFERENCE
    {
        DWMWCP_DEFAULT = 0,
        DWMWCP_DONOTROUND = 1,
        DWMWCP_ROUND = 2,
        DWMWCP_ROUNDSMALL = 3
    }

public class WindowsUtils
{
  public static void SetWindowDonotRound(Window window)
        {
            var preference = DWM_WINDOW_CORNER_PREFERENCE.DWMWCP_DONOTROUND;
            DwmSetWindowAttribute(new WindowInteropHelper(System.Windows.Window.GetWindow(window)).EnsureHandle(), DWMWINDOWATTRIBUTE.DWMWA_WINDOW_CORNER_PREFERENCE, ref preference, sizeof(uint));
        }

        [DllImport("dwmapi.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        private static extern long DwmSetWindowAttribute(IntPtr hwnd,
                                                     DWMWINDOWATTRIBUTE attribute,
                                                     ref DWM_WINDOW_CORNER_PREFERENCE pvAttribute,
                                                     uint cbAttribute);
}
以下是一个使用媒体API的随手拍小程序代码的示例: ```html <!-- index.wxml --> <view class="container"> <camera bindtakephoto="takePhoto" /> <image src="{{photo}}" class="photo" /> </view> ``` ```javascript // index.js Page({ data: { photo: '' }, takePhoto: function (e) { const ctx = wx.createCameraContext(); ctx.takePhoto({ quality: 'high', success: (res) => { this.setData({ photo: res.tempImagePath }) } }) } }) ``` ```css /* index.wxss */ .container { display: flex; flex-direction: column; justify-content: center; align-items: center; height: 100vh; } .photo { width: 300px; height: 300px; margin-top: 20px; border-radius: 50%; } ``` 这个小程序包含一个 `camera` 组件和一个 `image` 组件。当用户点击拍照按钮时,`takePhoto` 方法被调用。在 `takePhoto` 方法中,我们创建了一个 `camera` 上下文并调用了 `takePhoto` 方法。当照片拍摄成功后,我们将照片的临时路径设置为 `photo` 数据,这样就可以在 `image` 组件中显示照片了。 需要注意的是,使用摄像头 API 需要在 `app.json` 文件中声明相应的权限,例如: ```json { "permission": { "scope.userLocation": { "desc": "你的位置信息将用于小程序定位" }, "scope.camera": { "desc": "你的相机将用于拍摄照片" } } } ``` 此外,还需要在 `project.config.json` 文件中添加以下配置: ```json { "miniprogramRoot": "./", "appid": "你的小程序 AppID", "projectname": "随手拍小程序", "description": "一个使用媒体 API 的随手拍小程序", "setting": { "urlCheck": true, "es6": true, "postcss": true, "minified": true, "newFeature": true } } ``` 以上就是一个简单的使用媒体 API 的随手拍小程序代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值