.net 如何修改config文件

by kevin 25. 十月 2018 11:31 >
string appConfigFile = Assembly.GetEntryAssembly().Location; Configuration appConfig = ConfigurationManager.OpenExeConfiguration(appConfigFile); AppSettingsSection appSettings = (AppSettingsSection)appConfig.GetSection("appSettings"); var config = UploadConfig; appSettings.Settings["KEY"].Value = "VALUE"; appConfig.Save(); ConfigurationManager.RefreshSection("appSettings"); 留一份代码,只是为了以后使用ctrl+C、ctrl+V大法。

FluentData入门(四)--Mapping

by kevin 13. 九月 2013 17:55 >
映射 自动映射 – 在数据库对象和.Net object自动进行1:1匹配 1: List<Product> products = Context.Sql(@"select * 2: from Product") 3: .QueryMany<Product>(); 自动映射到一个自定义的Collection: 1: ProductionCollection products = Context.Sql("select * from Product").QueryMany<Product, ProductionCollection>(); 如果数据库字段和POCO类属性名不一致,使用SQL别名语法AS: 1: List<Product> products = Context.Sql(@"select p.*, 2: c.CategoryId as Category_CategoryId, 3: c.Name as Category_Name 4: from Product p 5: inner join Category c on p.CategoryId = c.CategoryId") 6: .QueryMany<Product>(); 在这里p.*中的ProductId和ProductName会自动映射到Prodoct.ProductId和Product.ProductName,而Category_CategoryId和Category_Name 将映射到 Product.Category.CategoryId 和 Product.Category.Name. 使用dynamic自定义映射规则 1: List<Product> products = Context.Sql(@"select * from Product") 2: .QueryMany<Product>(Custom_mapper_using_dynamic); 3:  4: public void Custom_mapper_using_dynamic(Product product, dynamic row) 5: { 6: product.ProductId = row.ProductId; 7: product.Name = row.Name; 8: } 使用datareader进行自定义映射: 1: List<Product> products = Context.Sql(@"select * from Product") 2: .QueryMany<Product>(Custom_mapper_using_datareader); 3:  4: public void Custom_mapper_using_datareader(Product product, IDataReader row) 5: { 6: product.ProductId = row.GetInt32("ProductId"); 7: product.Name = row.GetString("Name"); 8: } 或者,当你需要映射到一个复合类型时,可以使用QueryComplexMany或者QueryComplexSingle。 1: var products = new List<Product>(); 2: Context.Sql("select * from Product").QueryComplexMany<Product>(products, MapComplexProduct); 3:  4: private void MapComplexProduct(IList<Product> products, IDataReader reader) 5: { 6: var product = new Product(); 7: product.ProductId = reader.GetInt32("ProductId"); 8: product.Name = reader.GetString("Name"); 9: products.Add(product); 10: } 多结果集 FluentData支持多结果集。也就是说,可以在一次数据库查询中返回多个查询结果。使用该特性的时候,记得使用类似下面的语句对查询语句进行包装。需要在查询结束后把连接关闭。 1: using (var command = Context.MultiResultSql) 2: { 3: List<Category> categories = command.Sql( 4: @"select * from Category; 5: select * from Product;").QueryMany<Category>(); 6:  7: List<Product> products = command.QueryMany<Product>(); 8: } 执行第一个查询时,会从数据库取回数据,执行第二个查询的时候,FluentData可以判断出这是一个多结果集查询,所以会直接从第一个查询里获取需要的数据。 分页 1: List<Product> products = Context.Select<Product>("p.*, c.Name as Category_Name") 2: .From(@"Product p 3: inner join Category c on c.CategoryId = p.CategoryId") 4: .Where("p.ProductId > 0 and p.Name is not null") 5: .OrderBy("p.Name") 6: .Paging(1, 10).QueryMany(); 调用 Paging(1, 10),会返回最先检索到的10个Product。   Mapping Automapping - 1:1 match between the database and the .NET object: List<Product> products = Context.Sql(@"select *             from Product")             .QueryMany<Product>(); Automap to a custom collection: ProductionCollection products = Context.Sql("select * from Product").QueryMany<Product, ProductionCollection>(); Automapping - Mismatch between the database and the .NET object, use the alias keyword in SQL: Weakly typed: List<Product> products = Context.Sql(@"select p.*,             c.CategoryId as Category_CategoryId,             c.Name as Category_Name             from Product p             inner join Category c on p.CategoryId = c.CategoryId")                 .QueryMany<Product>(); Here the p.* which is ProductId and Name would be automapped to the properties Product.Name and Product.ProductId, and Category_CategoryId and Category_Name would be automapped to Product.Category.CategoryId and Product.Category.Name. Custom mapping using dynamic: List<Product> products = Context.Sql(@"select * from Product")             .QueryMany<Product>(Custom_mapper_using_dynamic); public void Custom_mapper_using_dynamic(Product product, dynamic row) {     product.ProductId = row.ProductId;     product.Name = row.Name; } Custom mapping using a datareader: List<Product> products = Context.Sql(@"select * from Product")             .QueryMany<Product>(Custom_mapper_using_datareader); public void Custom_mapper_using_datareader(Product product, IDataReader row) {     product.ProductId = row.GetInt32("ProductId");     product.Name = row.GetString("Name"); } Or if you have a complex entity type where you need to control how it is created then the QueryComplexMany/QueryComplexSingle can be used: var products = new List<Product>(); Context.Sql("select * from Product").QueryComplexMany<Product>(products, MapComplexProduct); private void MapComplexProduct(IList<Product> products, IDataReader reader) {     var product = new Product();     product.ProductId = reader.GetInt32("ProductId");     product.Name = reader.GetString("Name");     products.Add(product); } Multiple result sets FluentData supports multiple resultsets. This allows you to do multiple queries in a single database call. When this feature is used it's important to wrap the code inside a using statement as shown below in order to make sure that the database connection is closed. using (var command = Context.MultiResultSql) {     List<Category> categories = command.Sql(             @"select * from Category;             select * from Product;").QueryMany<Category>();     List<Product> products = command.QueryMany<Product>(); } The first time the Query method is called it does a single query against the database. The second time the Query is called, FluentData already knows that it's running in a multiple result set mode, so it reuses the data retrieved from the first query. Select data and Paging A select builder exists to make selecting data and paging easy: List<Product> products = Context.Select<Product>("p.*, c.Name as Category_Name")                    .From(@"Product p                     inner join Category c on c.CategoryId = p.CategoryId")                    .Where("p.ProductId > 0 and p.Name is not null")                    .OrderBy("p.Name")                    .Paging(1, 10).QueryMany(); By calling Paging(1, 10) then the first 10 products will be returned.

FluentData入门(三)--Query

by kevin 13. 九月 2013 16:08 >
查询一组数据 返回一组dynamic对象(new in .NET 4.0) 1: List<dynamic> products = Context.Sql("select * from Product").QueryMany<dynamic>(); 返回一组强类型对象 1: List<Product> products = Context.Sql("select * from Product").QueryMany<Product>(); 返回一个自定义的Collection 1: ProductionCollection products = Context.Sql("select * from Product").QueryMany<Product, ProductionCollection>(); 返回单个对象 返回一个dynamic对象 1: dynamic product = Context.Sql(@"select * from Product where ProductId = 1").QuerySingle<dynamic>(); 返回一个强类型对象: 1: Product product = Context.Sql(@"select * from Product where ProductId = 1").QuerySingle<Product>(); 返回一个DataTable: 1: DataTable products = Context.Sql("select * from Product").QuerySingle<DataTable>(); 其实QueryMany<DataTable>和QuerySingle<DataTable>都可以用来返回DataTable,但考虑到QueryMany<DataTable>返回的是List<DataTable>,所以使用QuerySingle<DataTable>来返回DataTable更方便。 查询一个标量值 1: int numberOfProducts = Context.Sql(@"select count(*) from Product").QuerySingle<int>(); 返回一组标量值 1: List<int> productIds = Context.Sql(@"select ProductId from Product").QueryMany<int>(); 设置查询参数: 索引顺序形式的参数 1: dynamic products = Context.Sql(@"select * from Product where ProductId = @0 or ProductId = @1", 1, 2).QueryMany<dynamic>(); 或者 1: dynamic products = Context.Sql(@"select * from Product where ProductId = @0 or ProductId = @1").Parameters(1, 2).QueryMany<dynamic>(); 名字形式的参数: 1: var command = Context.Sql(@"select @ProductName = Name from Product 2: where ProductId=1") 3: .ParameterOut("ProductName", DataTypes.String, 100); 4: command.Execute(); 5:  6: string productName = command.ParameterValue<string>("ProductName"); 7:  8: List of parameters - in operator: 9: List<int> ids = new List<int>() { 1, 2, 3, 4 }; 10:  11: dynamic products = Context.Sql(@"select * from Product 12: where ProductId in(@0)", ids).QueryMany<dynamic>(); Output 参数: 1: dynamic products = Context.Sql(@"select * from Product 2: where ProductId = @ProductId1 or ProductId = @ProductId2") 3: .Parameter("ProductId1", 1) 4: .Parameter("ProductId2", 2) 5: .QueryMany<dynamic>(); Query for a list of items Return a list of dynamic objects (new in .NET 4.0): List<dynamic> products = Context.Sql("select * from Product").QueryMany<dynamic>(); Return a list of strongly typed objects: List<Product> products = Context.Sql("select * from Product").QueryMany<Product>(); Return a list of strongly typed objects in a custom collection: ProductionCollection products = Context.Sql("select * from Product").QueryMany<Product, ProductionCollection>(); Return a DataTable: See Query for a single item. Query for a single item Return as a dynamic object: dynamic product = Context.Sql(@"select * from Product                 where ProductId = 1").QuerySingle<dynamic>(); Return as a strongly typed object: Product product = Context.Sql(@"select * from Product             where ProductId = 1").QuerySingle<Product>(); Return as a DataTable: DataTable products = Context.Sql("select * from Product").QuerySingle<DataTable>(); Both QueryMany<DataTable> and QuerySingle<DataTable> can be called to return a DataTable, but since QueryMany returns a List<DataTable> then it's more convenient to call QuerySingle which returns just DataTable. Eventhough the method is called QuerySingle then multiple rows will still be returned as part of the DataTable. Query for a scalar value int numberOfProducts = Context.Sql(@"select count(*)             from Product").QuerySingle<int>(); Query for a list of scalar values List<int> productIds = Context.Sql(@"select ProductId                 from Product").QueryMany<int>(); Parameters Indexed parameters: dynamic products = Context.Sql(@"select * from Product             where ProductId = @0 or ProductId = @1", 1, 2).QueryMany<dynamic>(); or: dynamic products = Context.Sql(@"select * from Product             where ProductId = @0 or ProductId = @1")             .Parameters(1, 2).QueryMany<dynamic>(); Named parameters: dynamic products = Context.Sql(@"select * from Product             where ProductId = @ProductId1 or ProductId = @ProductId2")             .Parameter("ProductId1", 1)             .Parameter("ProductId2", 2)             .QueryMany<dynamic>(); Output parameter: var command = Context.Sql(@"select @ProductName = Name from Product             where ProductId=1")             .ParameterOut("ProductName", DataTypes.String, 100); command.Execute(); string productName = command.ParameterValue<string>("ProductName"); List of parameters - in operator: List<int> ids = new List<int>() { 1, 2, 3, 4 }; dynamic products = Context.Sql(@"select * from Product             where ProductId in(@0)", ids).QueryMany<dynamic>();

FluentData入门(二)--创建DbContext

by kevin 7. 九月 2013 13:58 >
如何创建和初始化一个DbContext 可以在*.config文件中配置connection string,将connection string name或者将整个connection string 作为参数传递给DbContext来创建DbContext。 重要配置 IgnoreIfAutoMapFails – IDbContext.IgnoreIfAutoMapFails返回一个IDbContext,该实例中,如果自动映射失败时是否抛出异常 通过*.config中配置的ConnectionStringName创建一个DbContext 1: public IDbContext Context() 2: { 3: return new DbContext().ConnectionStringName("MyDatabase", 4: new SqlServerProvider()); 5: }   调用DbContext的ConnectionString方法显示设置connection string来创建   1: public IDbContext Context() 2: { 3: return new DbContext().ConnectionString( 4: "Server=MyServerAddress;Database=MyDatabase;Trusted_Connection=True;", new SqlServerProvider()); 5: } 其他可以使用的Provider 只有通过使用不同的Provider,就可以切换到不同类型的数据库服务器上,比如 AccessProvider, DB2Provider, OracleProvider, MySqlProvider, PostgreSqlProvider, SqliteProvider, SqlServerCompact, SqlAzureProvider, SqlServerProvider.   Create and initialize a DbContext The connection string on the DbContext class can be initialized either by giving the connection string name in the *.config file or by sending in the entire connection string. Important configurations IgnoreIfAutoMapFails - Calling this prevents automapper from throwing an exception if a column cannot be mapped to a corresponding property due to a name mismatch. Create and initialize a DbContext The DbContext can be initialized by either calling ConnectionStringName which will read the connection string from the *.config file: public IDbContext Context() {     return new DbContext().ConnectionStringName("MyDatabase",             new SqlServerProvider()); } or by calling the ConnectionString method to set the connection string explicitly: public IDbContext Context() {     return new DbContext().ConnectionString(     "Server=MyServerAddress;Database=MyDatabase;Trusted_Connection=True;", new SqlServerProvider()); } Providers If you want to work against another database than SqlServer then simply replace the new SqlServerProvider() in the sample code above with any of the following: AccessProvider, DB2Provider, OracleProvider, MySqlProvider, PostgreSqlProvider, SqliteProvider, SqlServerCompact, SqlAzureProvider, SqlServerProvider.

FluentData入门(一)--核心概念

by kevin 7. 九月 2013 13:17 >
DbContext类 这是FluentData的核心类,可以通过配置ConnectionString来定义这个类,如何连接数据库和对具体的哪个数据库进行数据查询操作。 DbCommand类 这个类负责在相对应的数据库执行具体的每一个数据操作。 Events DbContext类定义了以下这些事件: OnConnectionClosed OnConnectionOpened OnConnectionOpening OnError OnExecuted OnExecuting 可以在事件中,记录每个SQL查询错误或者SQL查询执行的 时间等信息。 Builders Builder用来创建Insert, Update, Delete等相关的DbCommand实例。  Mapping FluentData可以将SQL查询结果自动映射成一个POCO(POCO - Plain Old CLR Object)实体类,也可以转换成一个dynamic类型。 自动转成实体类: 如果字段名中不包含下划线("_"),将映射到具有相同名字的属性上,例如:字段名 "Name" 将映射到属性名 "Name"。 如果字段名中不包含下划线("_"),将映射到内嵌的属性上,例如:字段名 "CategoryName" 将映射到属性名 "Category.Name"。 如果数据库字段名和属性名不一致,可以使用SQL的as让他们一致。 自动转换成dynamic类型: 对应dynamic类型,会为每个字段生成一个同名的属性,例如:字段名 "Name" 将映射到属性名 "Name"。 什么时候应该主动释放资源? 如果使用UseTransaction或者UseSharedConnection,那么DbContext需要主动释放。 如果使用UseMultiResult或者MultiResultSql,那么DbCommand需要主动释放。 如果使用UseMultiResult,那么StoredProcedureBuilder需要主动释放。 其他所有的类都会自动释放,也就是说,一个数据库连接只在查询开始前才进行,查询结束后会马上关闭。   DbContext This class is the starting point for working with FluentData. It has properties for defining configurations such as the connection string to the database, and operations for querying the database. DbCommand This is the class that is responsible for performing the actual query against the database. Events The DbContext class has support for the following events: OnConnectionClosed OnConnectionOpened OnConnectionOpening OnError OnExecuted OnExecuting By using any of these then you can for instance write to the log if an error has occurred or when a query has been executed. Builders A builder provides a nice fluent API for generating SQL for insert, update and delete queries. Mapping FluentData can automap the result from a SQL query to either a dynamic type (new in .NET 4.0) or to your own .NET entity type (POCO - Plain Old CLR Object) by using the following convention: Automap to an entity type: If the field name does not contain an underscore ("_") then it will try to try to automap to a property with the same name. For instance a field named "Name" would be automapped to a property also named "Name". If a field name does contain an underscore ("") then it will try to map to a nested property. For instance a field named "CategoryName" would be automapped to the property "Category.Name". If there is a mismatch between the fields in the database and in the entity type then the alias keyword in SQL can be used or you can create your own mapping method. Check the mapping section below for code samples. Automap to a dynamic type: For dynamic types every field will be automapped to a property with the same name. For instance the field name Name would be automapped to the Name property. When should you dispose? DbContext must be disposed if you have enabled UseTransaction or UseSharedConnection. DbCommand must be disposed if you have enabled UseMultiResult (or MultiResultSql). StoredProcedureBuilder must be disposed if you have enabled UseMultiResult. In all the other cases dispose will be handled automatically by FluentData. This means that a database connection is opened just before a query is executed and closed just after the execution has been completed.

开发杂记:RequestValidationMode

by kevin 30. 八月 2013 13:56 >
碰到一个管理后台项目,使用的是Asp.net 2.0时候的WebForm,但项目已经升级到Asp.net 4.0了。 今天碰到一个小意外,测试那边报了一个HttpRequestValidationException,在.net 2.0时代,将页面的ValidateRequest设置为false,或者在Web.Config里面设置<pages validateRequest="false" />,升级到.net 4.0后,验证模式也已经升级了。所以如果采用默认的设置,就会报HttpRequestValidationException,解决的办法是,将RequestValidationMode设置为2.0,代码如下: 1: <system.web> 2: <compilation debug="true" targetFramework="4.0"/> 3: <httpRuntime requestValidationMode="2.0" /> 4: <pages validateRequest="false"></pages> 5: </system.web> 关于RequestValidationMode,有两个值,默认是4.0 4.0 (the default). The HttpRequest object internally sets a flag that indicates that request validation should be triggered whenever any HTTP request data is accessed. This guarantees that the request validation is triggered before data such as cookies and URLs are accessed during the request. The request validation settings of the pages element (if any) in the configuration file or of the @ Page directive in an individual page are ignored. 2.0. Request validation is enabled only for pages, not for all HTTP requests. In addition, the request validation settings of the pages element (if any) in the configuration file or of the @ Page directive in an individual page are used to determine which page requests to validate.

C#小技巧-持续更新

by kevin 29. 八月 2013 22:19 >
字符串转换为日期 1: DateTime.ParseExact(MYCulturDate, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture); 获取某个文件夹下的所有文件 1: Directory.GetFiles("Path", "*.*", SearchOption.AllDirectories)

开发杂记:C#压缩JPG文件

by kevin 20. 八月 2013 21:44 >
最近在开发65emall的时候,发现产品的缩略图每个都有几十KB,检查了下,发现,在生成缩略图的时候,代码里只是设置了InterpolationMode,如下 1: g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Low; 其实这样的压缩,非常有限,所以文件还是非常大。 其实,要真正压缩jpg文件,还是要降低图片的质量,这里我们设置了50%,结果图片大小缩小了80-90%。 具体的代码如下 1: private static ImageCodecInfo GetEncoder(ImageFormat format) 2: { 3: ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders(); 4: foreach (ImageCodecInfo codec in codecs) 5: { 6: if (codec.FormatID == format.Guid) 7: { 8: return codec; 9: } 10: } 11: return null; 12: } 13:  14: private static void CreateImage(int oldWidth, int oldHeight, int limitWidth, int limitHeight, 15: System.Drawing.Image oldImage, string path, string fileName) 16: { 17: if (!System.IO.Directory.Exists(path)) 18: { 19: System.IO.Directory.CreateDirectory(path); 20: } 21: int createWidth, createHeight; 22: ImageSize(oldWidth, oldHeight, limitWidth, limitHeight, out createWidth, out createHeight); 23:  24: System.Drawing.Bitmap createImage = new System.Drawing.Bitmap(createWidth, createHeight); 25: System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(createImage); 26: g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Low; 27: g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; 28: g.Clear(System.Drawing.Color.Transparent); 29: g.DrawImage(oldImage, new System.Drawing.Rectangle(0, 0, createWidth, createHeight), 30: new System.Drawing.Rectangle(0, 0, oldImage.Width, oldImage.Height), 31: System.Drawing.GraphicsUnit.Pixel); 32: ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg); 33: System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality; 34: EncoderParameters myEncoderParameters = new EncoderParameters(1); 35: EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 50L); 36: myEncoderParameters.Param[0] = myEncoderParameter; 37: createImage.Save(path + fileName, jgpEncoder, myEncoderParameters); 38: g.Dispose(); 39: createImage.Dispose(); 40: } 参考资料: How to: Set JPEG Compression Level How to: Use Interpolation Mode to Control Image Quality During Scaling

开发杂技:double和decimal

by kevin 26. 四月 2013 13:53 >
(1)double是双精度浮点型,精确计算中使用浮点数是非常危险的。 (2)decimal类型并不是C#中的基础类型,所以使用的时候会对计算时的性能有影响。 还有两个非常危险的错误认识!!   1、decimal不是浮点型、decimal不存在精度损失。 decimal是一个不折不扣的浮点型,不论它精度有多高,精度损失依然存在! 2、decimal所能储存的数比double大,从double到decimal的类型转换不会出现任何问题。 只有从整形到decimal的转换才是扩大转换,decimal的精度比double大,但所能储存的最大数却比double要小。

打赏请我喝果汁咯

支付宝 微信

关于我

80后,单身,平庸的程序员。

喜欢看书,乐于交友,向往旅游。

遇建Kevin

FluentData交流群:477926269

Fluentdata