案例转自https://www.cnblogs.com/stonefeng/p/5679638.html
//主体基类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DecoratorModeDemo
{
abstract class PanCake
{
public string desc = "";
public abstract string getDesc();
public abstract double price();
}
}
//主体:肉夹馍
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DecoratorModeDemo
{
class Roujiamo:PanCake
{
public Roujiamo()
{ this.desc = "肉夹馍"; }
public override string getDesc()
{
return desc;
}
public override double price()
{
return 6;
}
}
}
//主体手抓饼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DecoratorModeDemo
{
class TornCake:PanCake
{
public TornCake()
{
this.desc = "手抓饼";
}
public override string getDesc()
{
return desc;
}
public override double price()
{
return 4;
}
}
}
//装饰者基类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DecoratorModeDemo
{
abstract class Condiment:PanCake
{
public PanCake panCake;
public Condiment(PanCake p)
{
panCake = p;
}
}
}
//装饰者煎蛋
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DecoratorModeDemo
{
class FiredEgg:Condiment
{
public FiredEgg(PanCake pancake):base(pancake)
{
}
public override string getDesc()
{
return panCake.getDesc()+",煎蛋";
}
public override double price()
{
return this.panCake.price() + 2;
}
}
}
//主函数
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DecoratorModeDemo
{
class Program
{
static void Main(string[] args)
{
TornCake torncake = new TornCake();
Console.WriteLine(torncake.getDesc() + " ¥" +torncake.price().ToString());
PanCake roujiamo = new Roujiamo();
roujiamo = new FiredEgg(roujiamo);
roujiamo = new FiredEgg(roujiamo);
Console.WriteLine(roujiamo.getDesc()+" ¥"+roujiamo.price());
Console.ReadLine();
}
}
}
运行结果
心得:装饰者派生自主体基类,继承了主体需要操作的对象。同时装饰者的成员对象中有主体,用以耦合主体。通过创建不同的装饰者派生类,重写主体类方法来实现对主体类的不同操作。
roujiamo = new FiredEgg(roujiamo)实际上roujiamo已经变成了煎蛋,只不过这个煎蛋的成员包含肉夹馍,返回的方法经重写已经用原肉夹馍处理过了。
EF SaveChanges() 报错(转载)
最佳答案
报这个错是因为,提交了主键重复的数据,虽然未提交到数据库中
但是现在的EF上下文中已经包含了我提交的数据,下次在提交正确数据时,
原来添加到上下文中的数据依然还在。。如何处理这个问题呢?
using(var db = new .......())
{
db.save...........();
}
1、dbcontext 每次使用时重新new一个,不要使用单例模式,可以考虑单元模式。
2、EF 上下文被我设置成了静态的了
3、我也是Commit时SaveChanges() 方法报更新条目出错,
别人说是数据的id 重复,但我调试看了Add 的三个id 都没重复,
后来发现是Add对象的DateTime 类型的属性没有赋值。赋值之后就能保存到数据库了。
4、一次插入多行时,其中有一个重复(我创建了唯一复合索引),导致所有都插入失败,而且重新运行插入依然失败。这说明了公用一个上下文的坏处,
后来改用Using和cry catch。不出错就一次插入,出错就循环赋值中using多个上下文,保证不重复部分插入成功。
来源:https://q.cnblogs.com/q/44768/
C# 四舍五入 保留两位小数(转载)
一、C#默认四舍五入
1 Math.Round(45.367,2) //Returns 45.37
2 Math.Round(45.365,2) //Returns 45.36
二、C#中的Round()不是我们中国人理解的四舍五入,是老外的四舍五入,是符合IEEE标准的四舍五入,
具体是四舍六入,下面的才是符合中国人理解的四舍五入。
1 Math.Round(45.367,2,MidpointRounding.AwayFromZero); //Returns 45.37
2 Math.Round(45.365,2,MidpointRounding.AwayFromZero); //Returns 45.37
来源:https://www.cnblogs.com/xuliangxing/p/6585865.html
DataGridView样式生成器使用说明
啥都不说先看图
一、 功能介绍
1. winform DataGridView样式代码可视化即时生成,所见即所得
2. 预置DataGridView样式代码方案
预置三种样式方案可在此基础上复制生成新的样式方案,
3. 样式方案删除自动备份
样式方案删除后自动改名为 样式方案文件名_bak_20151007-084328.dgvs 文件备份到程序启动目录下的backup文件夹内,需要恢复时移动到程序启动目录即可
4. 预览导入已生成样式方案
导入本软件生成的样式方案可以预览代码 样式,及属性设置
二、 使用方法:
1. 样式代码的使用方法
选择并复制要应用的样式代码
新建一个窗体拖入一个DataGridView控件
按F7转到代码视图
应用样式
注意:DataGridView要设置数据源,如没有数据则不会显示样式出来 以下是最终效果
2. 新建自定义样式代码
点击新建方案按钮
在右侧样式设置面板设置各种属性
注意:文本框直接输入格式如#ff0000格式的十六进制颜色值或者双击选择颜色值
3. 复制现有样式代码
可以在已有的样式方案基础上再做修改然后保存为新样式方案
MSSQL如何将查询结果拼接成字符串
在博问上看到一个提问“MSSQL如何将查询结果拼接成字符串” ,想了一下应该怎么实现呢,在c#等语言下好实现,但在sql里实现、还真没做过。
目标:想要在SQL中将查询的结果拼接为 '1','2','3','4','5'
分析:要进行拼接就要取得每行的值,想到了游标可以做到。于是有了下面的方法
select name from area
查询结果如下
办公楼
车间
宿舍
未知
宜家厂
综合楼
解决方法:
declare @name varchar(50)
declare @result varchar(500)
set @result=''
--定义一个游标
declare user_cur cursor for select name from area
--打开游标
open user_cur
while @@fetch_status=0
begin
--读取游标
fetch next from user_cur into @name
--print @name
set @result=@result+','''+@name+''''
--print @Login
end
close user_cur
--摧毁游标
deallocate user_cur
print @result
查询结果如下:
,'宜家厂','宿舍','车间','未知','办公楼','综合楼','综合楼'
快递查询 C#
//电商ID
private string EBusinessID = "1257164";
//电商加密私钥,快递鸟提供,注意保管,不要泄漏
private string AppKey = "63a33b7c-464c-4de6-b4a3-6e1fc19da51c";
//请求url
private string ReqURL = "http://api.kdniao.cc/Ebusiness/EbusinessOrderHandle.aspx";
/// <summary>
/// Json方式 查询订单物流轨迹
/// </summary>
/// <returns></returns>
public string postkuaidi(string com, string nu)
{
Dictionary<string, string> list = new Dictionary<string, string>();
#region 快递
list.Add("邮政平邮", "YZPY");
list.Add("邮政国内", "YZPY");
list.Add("中国邮政", "YZPY");
list.Add("申通快递", "STO");
#endregion
string typeCom = "";
foreach (var dc in list)
{
if (com == dc.Key)
{
typeCom = dc.Value;
}
}
string requestData = "{OrderCode:'',ShipperCode:'" + typeCom + "','LogisticCode':'" + nu + "'}";
Dictionary<string, string> param = new Dictionary<string, string>();
param.Add("RequestData", HttpUtility.UrlEncode(requestData, Encoding.UTF8));
param.Add("EBusinessID", EBusinessID);
param.Add("RequestType", "1002");
string dataSign = encrypt(requestData, AppKey, "UTF-8");
param.Add("DataSign", HttpUtility.UrlEncode(dataSign, Encoding.UTF8));
param.Add("DataType", "2");
string result = sendPost(ReqURL, param);
//根据公司业务处理返回的信息......
JObject jo = JObject.Parse(result);
return jo.ToString();
}
/// <summary>
/// Post方式提交数据,返回网页的源代码
/// </summary>
/// <param name="url">发送请求的 URL</param>
/// <param name="param">请求的参数集合</param>
/// <returns>远程资源的响应结果</returns>
private string sendPost(string url, Dictionary<string, string> param)
{
string result = "";
StringBuilder postData = new StringBuilder();
if (param != null && param.Count > 0)
{
foreach (var p in param)
{
if (postData.Length > 0)
{
postData.Append("&");
}
postData.Append(p.Key);
postData.Append("=");
postData.Append(p.Value);
}
}
byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(postData.ToString());
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded";
request.Referer = url;
request.Accept = "*/*";
request.Timeout = 30 * 1000;
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
request.Method = "POST";
request.ContentLength = byteData.Length;
Stream stream = request.GetRequestStream();
stream.Write(byteData, 0, byteData.Length);
stream.Flush();
stream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream backStream = response.GetResponseStream();
StreamReader sr = new StreamReader(backStream, Encoding.GetEncoding("UTF-8"));
result = sr.ReadToEnd();
sr.Close();
backStream.Close();
response.Close();
request.Abort();
}
catch (Exception ex)
{
result = ex.Message;
}
return result;
}
///<summary>
///电商Sign签名
///</summary>
///<param name="content">内容</param>
///<param name="keyValue">Appkey</param>
///<param name="charset">URL编码 </param>
///<returns>DataSign签名</returns>
private string encrypt(String content, String keyValue, String charset)
{
if (keyValue != null)
{
return base64(MD5(content + keyValue, charset), charset);
}
return base64(MD5(content, charset), charset);
}
///<summary>
/// 字符串MD5加密
///</summary>
///<param name="str">要加密的字符串</param>
///<param name="charset">编码方式</param>
///<returns>密文</returns>
private string MD5(string str, string charset)
{
byte[] buffer = System.Text.Encoding.GetEncoding(charset).GetBytes(str);
try
{
System.Security.Cryptography.MD5CryptoServiceProvider check;
check = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] somme = check.ComputeHash(buffer);
string ret = "";
foreach (byte a in somme)
{
if (a < 16)
ret += "0" + a.ToString("X");
else
ret += a.ToString("X");
}
return ret.ToLower();
}
catch
{
throw;
}
}
/// <summary>
/// base64编码
/// </summary>
/// <param name="str">内容</param>
/// <param name="charset">编码方式</param>
/// <returns></returns>
private string base64(String str, String charset)
{
return Convert.ToBase64String(System.Text.Encoding.GetEncoding(charset).GetBytes(str));
}
通过smtp直接发送邮件
/// <summary>
/// SMTP发送邮件
/// </summary>
/// <param name="fromEmail">发送邮件地址</param>
/// <param name="toEmail">收件箱</param>
/// <param name="subject">邮箱主题</param>
/// <param name="contentAttachment"></param>
/// <param name="fromEmailPwd">发送邮件密码</param>
/// <returns></returns>
public static bool SendMailBySMTP(string fromEmail, string toEmail, string subject, Attachment contentAttachment,
string fromEmailPwd)
{
bool rr = true;
if (ConfigurationManager.AppSettings["CreditoEmailSwitch"].ToString() == "true")
{
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage(fromEmail, toEmail);
mail.SubjectEncoding = Encoding.UTF8;
mail.Subject = subject;
mail.IsBodyHtml = true; //是否允许内容为 HTML 格式
mail.BodyEncoding = Encoding.UTF8;
string emailContent = "邮件内容";
mail.Body = emailContent;
mail.Attachments.Add(contentAttachment); //添加一个附件
int defaltFlag = 0;
SmtpClient smtp = new SmtpClient("fastsmtp.qiye.163.com");//serviceFlag > 14 ? "smtp.qiye.163.com" :
smtp.Port = 25;
smtp.EnableSsl = true;
smtp.Credentials = new NetworkCredential(fromEmail, fromEmailPwd); //SMTP 验证
//smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
try
{
smtp.Send(mail);
}
catch (Exception ex)
{
rr = false;
SysLog.Write("发送邮件异常", ex.Message + "时间:" + DateTime.Now.ToString());
}
finally
{
mail.Attachments.Dispose(); //邮件发送完毕,释放对附件的锁定
}
}
else
{
rr = false;
}
return rr;
}
C# 带参访问接口,WebClient方式
public static string GetPostString(string urladdress, string @params)
{
string returnValue = null;
using (WebClient client = new WebClient())
{
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
client.Encoding = Encoding.UTF8;
returnValue = client.UploadString(urladdress, "POST", @params);
}
return returnValue;
}
-------------------------以上 为 与同事之间的接口查询-------------------------------------
C# 发送手机短信
由于使用 收费 第三方 屏蔽 可能有 免费 第三方。
private const string Cdkey = "8S*********************";密钥id
private const string Password = "151515******";密钥密码
private const string BaseUrl = "http://hprpt******地址*";
/// <summary>
/// 发送及时短信
/// </summary>
/// <param name="phone"></param>
/// <param name="content"></param>
/// <returns></returns>
public string SendSms(string phone, string content)
{
//UTF-8
string Content = HttpUtility.UrlEncode(content.Trim(), System.Text.Encoding.GetEncoding("UTF-8"));
phone = phone.Replace("\r\n", "").Trim();
string sendurl = BaseUrl + "/sdkproxy/sendsms.action?cdkey=" + Cdkey + "&password=" + Password + "&phone=" + phone + "&message=" + Content;
var resultstr = string.Empty;
try
{
var rst = (HttpWebRequest)WebRequest.Create(sendurl); //主要第一步
using (var stream = rst.GetResponse().GetResponseStream())//第二步
{
if (stream != null)
{
using (var reader = new StreamReader(stream, Encoding.GetEncoding("UTF-8")))//3
{
resultstr = reader.ReadToEnd();//4
}
}
}
}
catch (Exception ex)
{
throw;
}
return resultstr;
}
文件 日志 写入 与读取
private static string logPath = @"D:\LogS\Logs\";
public static string FloderPath
{
get
{
return logPath;
}
set
{
logPath = value;
}
}
private static object lockHelper = new object();
//简单的写了一个页面
public ActionResult Logtext()
{
return View();
}
//简单的写了一个页面入口提交文字
public ActionResult Add(string Text)
{
string textlog = Text;
//写入
Write("测试:", textlog);
string fileName = "测试:" + "-" + DateTime.Now.ToString("yyyy_MM_dd") + ".log";
//读取
var str = Read(fileName, "utf-8");
var Temp = new
{
nsuccess = false,
message = "写入读取成功"
};
return Json(Temp);
}
/// <summary>
/// 写日志
/// </summary>
/// <param name="LogType">日志类型</param>
/// <param name="Strings">消息</param>
public static bool Write(string LogType, string str)
{
try
{
//string fileName = LogType + "-" + DateTime.Now.ToString("yyyy_MM_dd") + ".log";
if (!System.IO.Directory.Exists(FloderPath))
{
System.IO.Directory.CreateDirectory(FloderPath);
}
return Write(LogType, str, "utf-8");
}
catch
{
return false;
}
}
/// <summary>
/// 写日志gb2312 UTF-8
/// </summary>
/// <param name="LogType">日志类型</param>
/// <param name="str">消息</param>
/// <param name="encoding">编码gb2312 UTF-8</param>
public static bool Write(string LogType, string str, string encoding)
{
if (!System.IO.Directory.Exists(FloderPath))
{
System.IO.Directory.CreateDirectory(FloderPath);
}
string fileName = LogType + "-" + DateTime.Now.ToString("yyyy_MM_dd") + ".log";
bool _isTrue = false;
lock (lockHelper)
{
System.IO.FileStream f = null;
System.IO.StreamWriter f2 = null;
try
{
if (!System.IO.File.Exists(logPath + fileName)) { f = System.IO.File.Create(logPath + fileName); f.Close(); f.Dispose(); f = null; }
f2 = new System.IO.StreamWriter(logPath + fileName, true, System.Text.Encoding.GetEncoding(encoding));
f2.WriteLine("----------------------------------------header-------------------------------------");
f2.WriteLine(str);
f2.WriteLine("----------------------------------------footer-------------------------------------");
_isTrue = true;
}
catch { }
finally
{
if (f != null) { f.Close(); f.Dispose(); f = null; }
if (f2 != null) { f2.Close(); f2.Dispose(); f2 = null; }
}
}
return _isTrue;
}
/// <summary>
/// 读取文件中的内容
/// </summary>
/// <param name="fileName">文件</param>
/// <param name="encoding">编码gb2312 UTF-8</param>
/// <returns>ArrayList</returns>
public static ArrayList Read(string fileName, string encoding)
{
string lineText = null; ArrayList txtTextArr = new ArrayList();
if (!System.IO.File.Exists(FloderPath + fileName)) { txtTextArr = null; return txtTextArr; }
lock (lockHelper)
{
StreamReader reader = encoding.Equals("") ? new StreamReader(FloderPath + fileName) : new StreamReader(FloderPath + fileName, System.Text.Encoding.GetEncoding(encoding));
while ((lineText = reader.ReadLine()) != null)
{
txtTextArr.Add(lineText);
}
reader.Close();
reader.Dispose();
}
return txtTextArr;
}