csharp 通用sql过程执行程序C#
通用sql过程执行程序C#
GenericSqlProvider.cs
public class GenericSqlProvider
{
private readonly string connectionString;
public GenericSqlProvider(string connectionString)
{
this.connectionString = connectionString;
}
public IResult<ProcedureResult> ExecuteCall(string procedureName, IDictionary<string, object> input)
{
using (var connection = new SqlConnection(connectionString))
{
var command = new SqlCommand(procedureName, connection) { CommandType = CommandType.StoredProcedure };
var parameters = input.Select(p =>
{
var param = command.CreateParameter();
param.ParameterName = p.Key;
param.Value = p.Value;
return param;
}).ToArray();
SqlParameter sampParm = command.Parameters.Add("RETURN_VALUE", SqlDbType.Int);
sampParm.Direction = ParameterDirection.ReturnValue;
command.Parameters.AddRange(parameters);
try
{
connection.Open();
var reader = command.ExecuteReader();
/*var tables = new List<DataTable>();
while (!reader.IsClosed)
{
DataTable schemaTable = reader.GetSchemaTable();
foreach (DataRow row in schemaTable.Rows)
{
foreach (DataColumn column in schemaTable.Columns)
{
Console.WriteLine("{0} = {1}", column.ColumnName, row[column]);
}
}
Console.WriteLine("\n");
var table = new DataTable();
table.Load(reader);
tables.Add(table);
foreach (DataRow row in table.Rows)
{
foreach (DataColumn column in table.Columns)
{
Console.WriteLine("{0} = {1}", column.ColumnName, row[column]);
}
}
Console.WriteLine("\n");
}*/
var results = new List<ICollection<DataRowObject>>();
if (reader.HasRows)
{
var dataObj = new List<DataRowObject>();
while (reader.Read())
{
var dataRow = new DataRowObject();
for (int i = 0; i < reader.FieldCount; i++)
{
dataRow.Add(reader.GetName(i), reader[i]);
}
dataObj.Add(dataRow);
}
results.Add(dataObj);
}
else
{
results.Add(null);
}
while (reader.NextResult())
{
if (reader.HasRows)
{
var dataObj = new List<DataRowObject>();
while (reader.Read())
{
var dataRow = new DataRowObject();
for (int i = 0; i < reader.FieldCount; i++)
{
dataRow.Add(reader.GetName(i), reader[i]);
}
dataObj.Add(dataRow);
}
results.Add(dataObj);
}
else
{
results.Add(null);
}
}
var returnValue = 0;
try
{
returnValue = (int)command.Parameters["RETURN_VALUE"].Value;
}
// ReSharper disable EmptyGeneralCatchClause
catch { }
// ReSharper restore EmptyGeneralCatchClause
return new Result<ProcedureResult>(new ProcedureResult(results.Count == 1 && results[0] == null ? null : results, returnValue));
}
catch (Exception ex)
{
return new Result<ProcedureResult>(null, (int)ExceptionType.DB_TIMEOUT, ex.Message);
}
finally
{
connection.Close();
}
}
}
}
public class ProcedureResult
{
public IEnumerable<IEnumerable<DataRowObject>> Results { get; private set; }
public int ReturnValue { get; private set; }
public ProcedureResult(IEnumerable<IEnumerable<DataRowObject>> results, int returnValue = 0)
{
Results = results == null ? null : results.Cast<List<DataRowObject>>().ToList();
ReturnValue = returnValue;
}
}
public class DataRowObject : NameObjectCollectionBase
{
public void Add(string key, object value)
{
BaseAdd(key, value);
}
public KeyValuePair<string, object> this[int index]
{
get { return new KeyValuePair<string, object>(BaseGetKey(index), BaseGet(index)); }
}
public object this[string key] { get { return BaseGet(key); } }
public override System.Collections.IEnumerator GetEnumerator()
{
for (int i = 0; i < Count; i++)
{
yield return this[i];
}
}
}
public interface IResult
{
bool Success { get; }
string ErrorMessage { get; }
int ErrorCode { get; }
}
public class Result : IResult
{
public bool Success { get; private set; }
public string ErrorMessage { get; private set; }
public int ErrorCode { get; private set; }
public Result(int errorCode = 0, string errorMessage = "")
{
ErrorCode = errorCode;
ErrorMessage = errorMessage;
Success = (errorCode == 0) && string.IsNullOrEmpty(errorMessage);
}
public static Result Successful = new Result();
public override string ToString()
{
return Success ? "Success" : string.Format("{0}({1})", ErrorCode, ErrorMessage);
}
}
public interface IResult<out T> : IResult
{
T Data { get; }
}
public class Result<TResult> : Result, IResult<TResult>
{
public TResult Data { get; private set; }
public Result(TResult data, int errorCode = 0, string errorMessage = "")
: base(errorCode, errorMessage)
{
Data = data;
}
}
csharp SortableBindingList C#
SortableBindingList C#
SortableBindingList.cs
public class SortableBindingList<T> : BindingList<T>
{
private readonly Dictionary<Type, PropertyComparer<T>> comparers;
private bool isSorted;
private ListSortDirection listSortDirection;
private PropertyDescriptor propertyDescriptor;
public SortableBindingList()
: base(new List<T>())
{
this.comparers = new Dictionary<Type, PropertyComparer<T>>();
}
public SortableBindingList(IEnumerable<T> enumeration)
: base(new List<T>(enumeration))
{
this.comparers = new Dictionary<Type, PropertyComparer<T>>();
}
protected override bool SupportsSortingCore
{
get { return true; }
}
protected override bool IsSortedCore
{
get { return this.isSorted; }
}
protected override PropertyDescriptor SortPropertyCore
{
get { return this.propertyDescriptor; }
}
protected override ListSortDirection SortDirectionCore
{
get { return this.listSortDirection; }
}
protected override bool SupportsSearchingCore
{
get { return true; }
}
protected override void ApplySortCore(PropertyDescriptor property, ListSortDirection direction)
{
List<T> itemsList = (List<T>)this.Items;
Type propertyType = property.PropertyType;
PropertyComparer<T> comparer;
if (!this.comparers.TryGetValue(propertyType, out comparer))
{
comparer = new PropertyComparer<T>(property, direction);
this.comparers.Add(propertyType, comparer);
}
comparer.SetPropertyAndDirection(property, direction);
itemsList.Sort(comparer);
this.propertyDescriptor = property;
this.listSortDirection = direction;
this.isSorted = true;
this.OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
}
protected override void RemoveSortCore()
{
this.isSorted = false;
this.propertyDescriptor = base.SortPropertyCore;
this.listSortDirection = base.SortDirectionCore;
this.OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
}
protected override int FindCore(PropertyDescriptor property, object key)
{
int count = this.Count;
for (int i = 0; i < count; ++i)
{
T element = this[i];
if (property.GetValue(element).Equals(key))
{
return i;
}
}
return -1;
}
}
public class PropertyComparer<T> : IComparer<T>
{
private readonly IComparer comparer;
private PropertyDescriptor propertyDescriptor;
private int reverse;
public PropertyComparer(PropertyDescriptor property, ListSortDirection direction)
{
this.propertyDescriptor = property;
Type comparerForPropertyType = typeof(Comparer<>).MakeGenericType(property.PropertyType);
this.comparer = (IComparer)comparerForPropertyType.InvokeMember("Default", BindingFlags.Static | BindingFlags.GetProperty | BindingFlags.Public, null, null, null);
this.SetListSortDirection(direction);
}
#region IComparer<T> Members
public int Compare(T x, T y)
{
return this.reverse * this.comparer.Compare(this.propertyDescriptor.GetValue(x), this.propertyDescriptor.GetValue(y));
}
#endregion
private void SetPropertyDescriptor(PropertyDescriptor descriptor)
{
this.propertyDescriptor = descriptor;
}
private void SetListSortDirection(ListSortDirection direction)
{
this.reverse = direction == ListSortDirection.Ascending ? 1 : -1;
}
public void SetPropertyAndDirection(PropertyDescriptor descriptor, ListSortDirection direction)
{
this.SetPropertyDescriptor(descriptor);
this.SetListSortDirection(direction);
}
}
csharp fail.cs
fail.cs
/*
* Sometimes the point of a specification is to show that a given scenario fails.
*
* A failing specification is similar to a SUT specification. It will return the SUT
* from its given method. The SUT will then be passed to the when() method where some
* action will happen. It is expected that this action will throw an exception.
*
* The exception is then passed to the expectations.
*
* note: if you are doing more complex operations other templates can be used with
* the TestContext pattern.
*/
public class FailingSpecification
{
public ISpecification it_will_fail = new FailingSpecification<FailingExample, SomethingFailedException>()
{
On = () => new FailingExample(),
When = (obj) => obj.CauseFailure(),
Expect =
{
exception => exception.Message == "Something failed!",
exception => exception.ErrorCode == 17
},
};
}
public class FailingExample
{
public void CauseFailure()
{
throw new SomethingFailedException("Something failed!", 17);
}
}
public class SomethingFailedException : Exception
{
public readonly int ErrorCode;
public SomethingFailedException(string msg, int errorCode) : base(msg)
{
ErrorCode = errorCode;
}
}
csharp Example.cs
Example.cs
public class AccountSpecifications
{
public Specification when_constructing_an_account = new
ConstructorSpecification<Account>()
{
When = () => new Account("Jane Smith", 17),
Expect =
{
account => account.AccountHolderName == "Jane Smith",
account => account.UniqueIdentifier == 17,
account => account.CurrentBalance == new Money(0m),
account => account.Transactions.Count() == 0
}
};
public Specification when_depositing_to_a_new_account = new ActionSpecification<Account>()
{
Before = () =>SystemTime.Set(new DateTime(2011,1,1)),
On = () => new Account("Joe User", 14),
When = account => account.Deposit(new Money(50)),
Expect =
{
account => account.CurrentBalance == new Money(50),
account => account.Transactions.Count() == 1,
account => account.Transactions.First().Amount ==
new Money(50),
account => account.Transactions.First().Type ==
TransactionType.Deposit,
account => account.Transactions.First().Timestamp
== new DateTime(2011,1,1),
},
Finally = SystemTime.Clear
};
public Specification when_withdrawing_to_overdraw_an_account = new FailingSpecification<Account, CannotOverdrawAccountException>()
{
On = () => new Account("Joe User", 14),
When = account => account.Withdraw(new Money(50)),
Expect =
{
exception => exception.Message == "The operation
would overdraw the account"
}
};
public Specification
when_witdrawing_from_account_with_sufficient_funds = new ActionSpecification<Account>()
{
Before = () => SystemTime.Set(new DateTime(2011, 1, 1)),
On = () => new Account("Joe User", 14, new Money(100)),
When = account => account.Withdraw(new Money(50)),
Expect =
{
account => account.CurrentBalance == new Money(50),
account => account.Transactions.Count() == 1,
account => account.Transactions.First().Amount ==
new Money(-50),
account => account.Transactions.First().Type ==
TransactionType.Deposit,
},
Finally = SystemTime.Clear
};
}
RESULTS in:
when constructing an account - Passed
On:
Results with:
Account: 17 owned by Jane Smith with a balance $0
With no previous transactions.
Expectations:
The Account's Account Holder Name must be equal to "Jane Smith" Passed
The Account's Unique Identifier must be equal to 17 Passed
The Account's Current Balance must be equal to $0 Passed
The Account's Transactions Count() must be equal to 0 Passed
--------------------------------------------------------------------------------
when depositing to a new account - Passed
On:
Account: 14 owned by Joe User with a balance $0
With no previous transactions.
Results with:
Account: 14 owned by Joe User with a balance $50
Deposit for $50 at 1/1/2011 12:00:00 AM
Expectations:
The Account's Current Balance must be equal to $50 Passed
The Account's Transactions Count() must be equal to 1 Passed
The Account's Transactions First() Amount must be equal to $50 Passed
(int)(The Account's Transactions First() Type) must be equal to 1 Passed
The Account's Transactions First() Timestamp must be equal to 1/1/2011 1
2:00:00 A M Passed
--------------------------------------------------------------------------------
when withdrawing to overdraw an account - Passed
On:
Account: 14 owned by Joe User with a balance $0
With no previous transactions.
Results with:
DocGeneratorExample.CannotOverdrawAccountException
The operation would overdraw the account
Expectations:
The Cannot Overdraw Account Exception's Message must be equal to "The o
peration would overdraw the account" Passed
--------------------------------------------------------------------------------
when witdrawing from account with sufficient funds - Passed
On:
Account: 14 owned by Joe User with a balance $100
With no previous transactions.
Results with:
Account: 14 owned by Joe User with a balance $50
Deposit for $-50 at 1/1/2011 12:00:00 AM
Expectations:
The Account's Current Balance must be equal to $50 Passed
The Account's Transactions Count() must be equal to 1 Passed
The Account's Transactions First() Amount must be equal to $-50 Passed
(int)(The Account's Transactions First() Type) must be equal to 1 Passed
--------------------------------------------------------------------------------
Press any key to continue . . .
csharp 示例SDL Tridion .Net模板,用于将JSON文件创建为包项,然后将其作为二进制变体发布
示例SDL Tridion .Net模板,用于将JSON文件创建为包项,然后将其作为二进制变体发布
PublishJsonFiles.cs
using System;
using Tridion.ContentManager;
using Tridion.ContentManager.CommunicationManagement;
using Tridion.ContentManager.Templating;
using Tridion.ContentManager.Templating.Assembly;
namespace Test.JsonTemplates
{
[TcmTemplateTitle("Publish JSON package items as Variants")]
public class PublishJsonFiles : ITemplate
{
public void Transform(Engine engine, Package package)
{
//Get all items of unknown type from the package
var items = package.GetAllByType(ContentType.Unknown);
//Remove all items that are NOT JSON files
foreach (var item in items)
{
if (!item.Properties[Item.ItemPropertyFileNameExtension].Equals("json", StringComparison.OrdinalIgnoreCase))
{
items.Remove(item);
}
}
//Check the package values for an optional structure group ID to publish to
var optionalStructureGroupId = package.GetValue("jsonStructureGroup");
StructureGroup jsonStructureGroup = null;
//Go get the structure group from Tridion if an Id has been specified
if (!String.IsNullOrWhiteSpace(optionalStructureGroupId))
{
var structureGroupTcmUri = new TcmUri(
Convert.ToInt32(optionalStructureGroupId),
ItemType.StructureGroup,
engine.PublishingContext.RenderedItem.ResolvedItem.Item.Id.PublicationId);
jsonStructureGroup = (StructureGroup)engine.GetObject(structureGroupTcmUri);
}
//Publish out the JSON files
foreach (var item in items)
{
var filename = item.Properties[Item.ItemPropertyFileName] + "." + item.Properties[Item.ItemPropertyFileNameExtension];
//If no structure group has been specified, publish to the default images directory configured for the publication
if (jsonStructureGroup == null)
{
engine.PublishingContext.RenderedItem.AddBinary(
item.GetAsStream(),
filename,
filename,
null,
"application/json");
}
else
{
engine.PublishingContext.RenderedItem.AddBinary(
item.GetAsStream(),
filename,
jsonStructureGroup,
filename,
null,
"application/json");
}
}
}
}
}
CreateTestData.cs
using Tridion.ContentManager.Templating;
using Tridion.ContentManager.Templating.Assembly;
namespace Test.JsonTemplates
{
class CreateTestData : ITemplate
{
public void Transform(Engine engine, Package package)
{
string JSON = "{\"h3title\":\"09/04/2013\"}";
var jsonItem = package.CreateStringItem(ContentType.Unknown, JSON);
jsonItem.Properties.Add(Item.ItemPropertyFileName, "test");
jsonItem.Properties.Add(Item.ItemPropertyFileNameExtension, "json");
package.PushItem("test.json", jsonItem);
}
}
}
csharp C#默认以管理员身份运行程序
C#默认以管理员身份运行程序
startAsAdministrator.cs
static void Main(string[] Args)
{
/**
* 当前用户是管理员的时候,直接启动应用程序
* 如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行
*/
//获得当前登录的Windows用户标示
System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
//创建Windows用户主题
Application.EnableVisualStyles();
System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
//判断当前登录用户是否为管理员
if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
{
//如果是管理员,则直接运行
Application.EnableVisualStyles();
Application.Run(new Form1());
}
else
{
//创建启动对象
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
//设置运行文件
startInfo.FileName = System.Windows.Forms.Application.ExecutablePath;
//设置启动参数
startInfo.Arguments = String.Join(" ", Args);
//设置启动动作,确保以管理员身份运行
startInfo.Verb = "runas";
//如果不是管理员,则启动UAC
System.Diagnostics.Process.Start(startInfo);
//退出
System.Windows.Forms.Application.Exit();
}
}
csharp LabMapSend_Safe类是一个单元类<br/>,它提供了将整数,实数和字符串值安全地发送到LabMap的函数。 <br/>所有这些发送 -
LabMapSend_Safe类是一个单元类<br/>,它提供了将整数,实数和字符串值安全地发送到LabMap的函数。 <br/>此类中的所有这些Send函数将在以下过程中发送值:<br/> <br/> 1.Call LabMap API LabMapSendXXX(..)将值发送到特定句柄。 <br/> 2.Call LabMap API LabMapWait()确保在操作完成后继续。 <br/> 3.Call LabMap API LabMapGetXXX(..)确保setValue与句柄中的returnValue相同。 <br/> <br/>当每次发送过程中tryCount大于tryCountLimit <br/>将抛出LabMapSendValueFailException。
LabMapSend_Safe.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Loop_Beleuchtung_Stadtpark_Norderstedt
{
/// <summary>
/// LabMapSend_Safe Class is a singlton class
/// which provides functions to send integer, real and string value to LabMap safely.
/// All these Send-functions in this class will send value in the folloing process:
///
/// 1.Call LabMap API LabMapSendXXX(..) to send the value to the specific handle.
/// 2.Call LabMap API LabMapWait() to make sure to continue after the operation finished.
/// 3.Call LabMap API LabMapGetXXX(..) to make sure the setValue is the same as the returnValue from the handle.
///
/// When the tryCount bigger than tryCountLimit in each sending process
/// A LabMapSendValueFailException will be thrown.
/// </summary>
public class LabMapSend_Safe
{
#region Singleton
private static volatile LabMapSend_Safe instance;
private static object syncRoot = new object();
private static object syncRoot_Int = new object();
private static object syncRoot_Real = new object();
private static object syncRoot_String = new object();
public static LabMapSend_Safe Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new LabMapSend_Safe();
}
}
return instance;
}
}
#endregion
LabMapDotNet.LabMap lab_map = LabMapDotNet.LabMap.Instance;
public void LabMapSendInt_Safe(uint handleNo, int setValue, int tryCountLimit)
{
int returnValue = int.MinValue;
int tryCount = 0;
lock (syncRoot_Int)
{
do
{
if (tryCount >= tryCountLimit)
{
Exception exp = new LabMapSendValueFailedException(handleNo, typeof(int), setValue);
LabMapSendLogger.Instance.LogLabMapSendException(exp);
throw exp;
}
try
{
lab_map.LabMapSendInt(handleNo, setValue);
lab_map.LabMapWait(handleNo);
int status = lab_map.LabMapGetStatus(handleNo, 0);
if ((status & LabMapDotNet.LabMapStatus.HandleReady) == LabMapDotNet.LabMapStatus.HandleReady)
{
}
returnValue = lab_map.LabMapGetInt(handleNo);
LabMapSendLogger.Instance.LabMapSendIntLog(handleNo, setValue, returnValue, tryCount);
}
finally
{
tryCount++;
}
if (returnValue == setValue) return;
} while (true);
}
}
public void LabMapSendInt_Safe_Ex(uint handleNo, int setValue, int tryCountLimit)
{
int returnValue = int.MinValue;
int tryCount = 0;
lock (syncRoot_Int)
{
do
{
if (tryCount >= tryCountLimit)
{
Exception exp = new LabMapSendValueFailedException(handleNo, typeof(int), setValue);
LabMapSendLogger.Instance.LogLabMapSendException(exp);
throw exp;
}
try
{
lab_map.LabMapSendInt(handleNo, setValue);
lab_map.LabMapWait(handleNo);
returnValue = lab_map.LabMapGetInt(handleNo);
LabMapSendLogger.Instance.LabMapSendIntLog(handleNo, setValue, returnValue, tryCount);
}
finally
{
tryCount++;
}
if (this.CheckIntReturnValueValid(setValue,returnValue)) return;
} while (true);
}
}
private bool CheckIntReturnValueValid(int setValue,int returnValue)
{
int off = 0; // -> 9
int start_ramp_up = 1; // -> 11 -> 10
int start_breathing = 2; // -> 21 -> 20
int restart_breathing = 21; //
int start_ramp_down = 3; // -> 31 -> 30
int start_lightplay = 4; // -> 41
int set_max_values = 5; // -> 50
if (setValue == off ) { return ((returnValue == setValue) || (returnValue == 9)) ; }
if (setValue == start_ramp_up ) { return ((returnValue == setValue) || (returnValue == 10) || (returnValue == 11));}
if (setValue == start_breathing ) { return ((returnValue == setValue) || (returnValue == 21) || (returnValue == 20));}
if (setValue == restart_breathing ) { return ( returnValue == setValue);}
if (setValue == start_ramp_down ) { return ((returnValue == setValue) || (returnValue == 31) || (returnValue == 30));}
if (setValue == start_lightplay ) { return ((returnValue == setValue) || (returnValue == 41));}
if (setValue == set_max_values ) { return ((returnValue == setValue) || (returnValue == 50));}
return (setValue == returnValue);
}
public void LabMapSendReal_Safe(uint handleNo, double setValue, int tryCountLimit)
{
float returnValue = float.NaN ;
int tryCount = 0;
lock (syncRoot_Real)
{
do
{
if (tryCount >= tryCountLimit)
{
Exception exp = new LabMapSendValueFailedException(handleNo, typeof(float), setValue);
LabMapSendLogger.Instance.LogLabMapSendException(exp);
throw exp;
}
try
{
lab_map.LabMapSendReal(handleNo, (float)setValue);
lab_map.LabMapWait(handleNo);
returnValue = lab_map.LabMapGetReal(handleNo);
LabMapSendLogger.Instance.LabMapSendRealLog(handleNo, (float)setValue, returnValue, tryCount);
}
finally
{
tryCount++;
}
if (Math.Abs(returnValue - setValue) < 0.001f) return;
} while (true);
}
}
public void LabMapSendString_Safe(uint handleNo, string setValue, int tryCountLimit)
{
string returnValue = string.Empty;
int tryCount = 0;
lock (syncRoot_String)
{
do
{
if (tryCount >= tryCountLimit)
{
Exception exp = new LabMapSendValueFailedException(handleNo, typeof(int), setValue);
LabMapSendLogger.Instance.LogLabMapSendException(exp);
throw exp;
}
try
{
lab_map.LabMapSendString(handleNo, setValue);
lab_map.LabMapWait(handleNo);
returnValue = lab_map.LabMapGetString(handleNo);
LabMapSendLogger.Instance.LabMapSendStringLog(handleNo, setValue, returnValue, tryCount);
}
finally
{
tryCount++;
}
if (returnValue == setValue) return;
} while (true);
}
}
}
public class LabMapSendValueFailedException : Exception
{
private uint _handleNo;
private Type _valueType;
private object _value;
public uint HandleNo
{
get { return _handleNo; }
set { _handleNo = value; }
}
public Type ValueType
{
get { return _valueType; }
set { _valueType = value; }
}
public object Value
{
get { return _value; }
set { _value = value; }
}
public LabMapSendValueFailedException(uint handleNo, Type valueType, object value)
{
this._handleNo = handleNo;
this._valueType = valueType;
this._value = value;
}
}
public class LabMapSendLogger
{
#region Singleton
private static volatile LabMapSendLogger instance;
private static object syncRoot = new object();
private static object syncRoot_Write = new object();
public static LabMapSendLogger Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new LabMapSendLogger();
}
}
return instance;
}
}
private LabMapSendLogger()
{
Initialize();
}
#endregion
private string logFileName = "LabMapSendLog.txt";
private bool isLogEnable = false;
private FileStream fs = null;
private void Initialize()
{
this.isLogEnable = (ini_settings.GetValue("DEBUG", "enable_labmap_send_log") == "True");
fs = new FileStream(logFileName, FileMode.Append);
}
public void LogLabMapSendException(Exception exp)
{
lock (syncRoot_Write)
{
if (!this.isLogEnable) return;
if (exp != null)
{
this.LogExceptiontoFile(exp);
}
}
}
public void LabMapSendIntLog(uint handleNo, int value, int returnValue, int tryCount)
{
lock (syncRoot_Write)
{
if (!this.isLogEnable) return;
string logText = string.Format("TryCount:{2} TimeStamp:{3} {4}<==LabMapSendInt({0},{1});", handleNo, value, tryCount, DateTime.Now.ToString("g"), returnValue);
this.LogTxtToFile(logText);
}
}
public void LabMapSendRealLog(uint handleNo, float value, float returnValue, int tryCount)
{
lock (syncRoot_Write)
{
if (!this.isLogEnable) return;
string logText = string.Format("TryCount:{2} TimeStamp:{3} {4}<==LabMapSendReal({0},{1});", handleNo, value, tryCount, DateTime.Now.ToString("g"), returnValue);
this.LogTxtToFile(logText);
}
}
public void LabMapSendStringLog(uint handleNo, string value, string returnValue, int tryCount)
{
lock (syncRoot_Write)
{
if (!this.isLogEnable) return;
string logText = string.Format("TryCount:{2} TimeStamp:{3} {4}<==LabMapSendString({0},\"{1}\");", handleNo, value, tryCount, DateTime.Now.ToString("g"), returnValue);
this.LogTxtToFile(logText);
}
}
private void LogTxtToFile(string txt)
{
try
{
byte[] data = new UTF8Encoding().GetBytes(txt + Environment.NewLine);
fs.Write(data, 0, data.Length);
fs.Flush();
}
catch { }
}
private void LogExceptiontoFile(Exception objException)
{
try
{
string content = Exception2TextString(objException);
byte[] data = new UTF8Encoding().GetBytes(content.ToString());
fs.Write(data, 0, data.Length);
fs.Flush();
}
catch { }
}
private string Exception2TextString(Exception objException)
{
StringBuilder content = new StringBuilder(1000);
content.AppendLine("");
content.AppendLine("=============================================");
content.AppendLine("+++++++++++LabMapSend Error++++++++++++++++++");
content.AppendLine("Date : " + DateTime.Now.ToLongTimeString());
content.AppendLine("Time : " + DateTime.Now.ToShortDateString());
content.AppendLine("Error : " + objException.Message.ToString().Trim());
content.AppendLine(objException.Message);
if (objException is LabMapSendValueFailedException)
{
LabMapSendValueFailedException exp = objException as LabMapSendValueFailedException;
content.AppendLine("HandleNo : " + exp.HandleNo);
content.AppendLine("Error : " + exp.Value.ToString());
}
content.AppendLine("+++++++++++++++++++++++++++++++++++++++++++++");
return content.ToString();
}
~LabMapSendLogger()
{
fs.Close();
}
}
/*
public class TestClass
{
public TestClass()
{
try
{
LabMapSend_Safe.Instance.LabMapSendInt_Safe(1, 1, 5);
}
catch(LabMapSendValueFailedException exp)
{
System.Windows.Forms.MessageBox.Show(
string.Format("HanedleNo:{0} ValueType:{1} Value:{2}",
exp.HandleNo,
exp.ValueType,
exp.Value));
}
}
}*/
}
csharp C#重命名复制文件
C#重命名复制文件
Rename.cs
Rename ==>System.IO.File.Move(@"K:\bin\vppclient.exe", @"K:\bin\vppclient" + DateTime.Now.Ticks.ToString() + ".tmp");
Copy==> File.Copy("file-a.txt", "file-new.txt", true);
csharp C#webbrowser
C#webbrowser
webbrowserOp.cs
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
//HtmlElement btnSubmit = webBrowser.Document.All["logonForm"];
HtmlElement tbUserid = webBrowser.Document.All["username"];
HtmlElement tbPasswd = webBrowser.Document.All["pwd"];
//if (tbUserid == null || tbPasswd == null )
// return;
tbUserid.SetAttribute("value", "123456789");
tbPasswd.SetAttribute("value", "123456789");
// HtmlElement formLogin = webBrowser.Document.Forms["logonForm"];
// formLogin.InvokeMember("submit");
SendKeys.Send("{TAB}");
SendKeys.Flush();
SendKeys.Send("{ENTER}");
SendKeys.Flush();
}
csharp 阻止在Visual Studio for Winforms Apps中的设计时执行代码
阻止在Visual Studio for Winforms Apps中的设计时执行代码
preventCodeExecutingAtDesignTime.cs
if(System.ComponentModel.LicenseManager.UsageMode == System.ComponentModel.LicenseUsageMode.Designtime)
//... Then Continue