Thursday, April 19, 2018

Architecture and patterns

Architecture and patterns

Design patterns in .NET
Design principles in .NET
Domain Driven Design
Original skeleton project
DDD revisited
Externalising object dependencies
Service Oriented Architecture
Using a Windows service
Various
IIS

Wednesday, April 18, 2018

.NET Design Patterns

Design patterns are solutions to software design problems you find again and again in real-world application development. Patterns are about reusable designs and interactions of objects.
The 23 Gang of Four (GoF) patterns are generally considered the foundation for all other patterns. They are categorized in three groups: Creational, Structural, and Behavioral (for a complete list see below).
To give you a head start, the C# source code for each pattern is provided in 2 forms: structural and real-world. Structural code uses type names as defined in the pattern definition and UML diagrams. Real-world code provides real-world programming situations where you may use these patterns.
A third form, .NET optimized, demonstrates design patterns that fully exploit built-in .NET 4.5 features, such as, generics, attributes, delegates, reflection, and more. These and much more are available in our .NET Design Pattern Framework 4.5. You can see the Singletonpage for a .NET 4.5 Optimized example.


Creational Patterns
  Abstract FactoryCreates an instance of several families of classes
  BuilderSeparates object construction from its representation
  Factory MethodCreates an instance of several derived classes
  PrototypeA fully initialized instance to be copied or cloned
  SingletonA class of which only a single instance can exist

Structural Patterns
  AdapterMatch interfaces of different classes
  BridgeSeparates an object’s interface from its implementation
  CompositeA tree structure of simple and composite objects
  DecoratorAdd responsibilities to objects dynamically
  FacadeA single class that represents an entire subsystem
  FlyweightA fine-grained instance used for efficient sharing
  ProxyAn object representing another object

Behavioral Patterns
  Chain of Resp.A way of passing a request between a chain of objects
  CommandEncapsulate a command request as an object
  InterpreterA way to include language elements in a program
  IteratorSequentially access the elements of a collection
  MediatorDefines simplified communication between classes
  MementoCapture and restore an object's internal state
  ObserverA way of notifying change to a number of classes
  StateAlter an object's behavior when its state changes
  StrategyEncapsulates an algorithm inside a class
  Template MethodDefer the exact steps of an algorithm to a subclass
  VisitorDefines a new operation to a class without change

Learn C#


C# Sharp Programming Exercises, Practice, Solution

https://www.w3resource.com/csharp-exercises/


面向对象编程思想(OOP)

软件开发中疑难问题:
  • 软件复杂庞大
  • 很多软件进入维护阶段
  • 需求的不断变更
软件开发中存在很多其他的问题,上面只是从程序开发和设计的角度看到的部分问题。需求解决上面软件开发中的问题,就要求我们编写(设计)的软件具有很好的可读性、可维护性和可扩展性。我们需要保证代码具有高内聚低耦合。
下面将简单介绍面向对象的一些基本特性、设计原则,以及设计模式关系。
四大基本特性:
抽象:提取现实世界中某事物的关键特性,为该事物构建模型的过程。对同一事物在不同的需求下,需要提取的特性可能不一样。得到的抽象模型中一般包含:属性(数据)和操作(行为)。这个抽象模型我们称之为。对类进行实例化得到对象。
封装:封装可以使类具有独立性和隔离性;保证类的高内聚。只暴露给类外部或者子类必须的属性和操作。类封装的实现依赖类的修饰符(public、protected和private等)
继承:对现有类的一种复用机制。一个类如果继承现有的类,则这个类将拥有被继承类的所有非私有特性(属性和操作)。这里指的继承包含:类的继承和接口的实现。
多态:多态是在继承的基础上实现的。多态的三个要素:继承、重写和父类引用指向子类对象。父类引用指向不同的子类对象时,调用相同的方法,呈现出不同的行为;就是类多态特性。多态可以分成编译时多态和运行时多态。
抽象、封装、继承和多态是面向对象的基础。在面向对象四大基础特性之上,我们在做面向对象编程设计时还需要遵循有一些基本的设计原则。
七大设计原则:
  • SOLID原则(单一职责原则、开放关闭原则、里氏替换原则、接口隔离原则和依赖倒置原则)
  • 迪米特法则
  • 组合优于继承原则(合成复用原则)。
在遵循这些面向对象设计原则基础上,前辈们总结出一些解决不同问题场景的设计模式,以四人帮的gof23最为知名。
24种设计模式(gof23+1):
  • 创建型模式:
    1. 简单工厂模式(不包含在gof23中)
    2. 工厂模式
    3. 抽象工厂模式
    4. 单例模式
    5. 原型模式
    6. 创建者模式
  • 结构型模式:
    1. 组合模式
    2. 装饰者模式
    3. 外观模式
    4. 适配器模式
    5. 代理模式
    6. 享元模式
    7. 桥接模式
  • 行为型模式:
    1. 观察者模式
    2. 策略模式
    3. 状态模式
    4. 中介模式
    5. 模板方法
    6. 命令模式
    7. 备忘录模式
    8. 访问者模式
    9. 解释器模式
    10. 迭代器模式
    11. 职责链模式
在本文中只是为了梳理清楚面向对象的基本特性、设计原则和设计模式的关系;并没有涉及细节。在后续的文章中,我会一一详细讲述上面提及的关键概念。
下面用一张图来做个总结吧!



The Best Way To Import Data From Excel To SQL Server via ASP.NET

The Best Way To Import Data From Excel To SQL Server via ASP.NET

    
 4.62 (29 votes)
I've seen a lot of questions about the best way to import data from uploaded Excel files to a SQL Server database in an ASP.NET application. Most solutions involve the use of the JET or ACE OLEDB providers to read data from the saved Excel file, and some even show how to use Office Interop to obtain the data. However, all of these solutions rely on additional components being installed on the server, and they also require the uploaded file to be saved somewhere, even temporarily, which creates an additional maintenance task. The solution that follows makes use of a Nuget package that gets deployed with your application and can work with streams, so the uploaded file doesn't need to be saved. It is, in my submission, THE best way to import data from uploaded Excel files to SQL Server in an ASP.NET application.
The package name is EPPlus, and I have written about it before. It is available by searching for EPPlus in the Nuget Package Manager (VS 2015 onwards) or by typing
install-package epplus
in the Package Manager Console.
The following snippet shows a Web Form featuring just a FileUpload control and a Button:
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="SqlBulkInsertWithEPPlus.aspx.cs" Inherits="WebFormsTest.SqlBulkInsertWithEPPlus" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
    <asp:FileUpload ID="Upload" runat="server" />
    <asp:Button ID="Button1" runat="server" Text="Upload" />
</asp:Content>
The code for processing the uploaded Excel file makes use of an extension method called ToDataTable, which I have defined in a class called ExcelPackageExtenstions:
using OfficeOpenXml;
using System.Data;
using System.Linq;

public static class ExcelPackageExtensions
{
    public static DataTable ToDataTable(this ExcelPackage package)
    {
        ExcelWorksheet workSheet = package.Workbook.Worksheets.First();
        DataTable table = new DataTable();
        foreach (var firstRowCell in workSheet.Cells[1, 1, 1, workSheet.Dimension.End.Column])
        {
            table.Columns.Add(firstRowCell.Text);
        }
        for (var rowNumber = 2; rowNumber <= workSheet.Dimension.End.Row; rowNumber++)
        {
            var row = workSheet.Cells[rowNumber, 1, rowNumber, workSheet.Dimension.End.Column];
            var newRow = table.NewRow();
            foreach (var cell in row)
            {
                newRow[cell.Start.Column - 1] = cell.Text;
            }
            table.Rows.Add(newRow);
        }
        return table;
    }
}
This method is a simple utility method that takes the content of an Excel file and puts it into a DataTable. The code assumes two things: that only the first worksheet is of any interest; and that the first row of the worksheet contains headers. It uses those header values for ColumnName values in the DataTable. If you want to manage more than one worksheet in a workbook or your sheet doesn't contain a header row, you will need to modify the method accordingly.
The code behind that processes the file and performs the bulk insert looks like this:
using OfficeOpenXml;
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;

namespace WebFormsTest
{
    public partial class SqlBulkInsertWithEPPlus : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack && Upload.HasFile)
            {
                if(Path.GetExtension(Upload.FileName).Equals(".xlsx"))
                {
                    var excel = new ExcelPackage(Upload.FileContent);
                    var dt = excel.ToDataTable();
                    var table = "Contacts";
                    using (var conn = new SqlConnection("Server=.;Database=Test;Integrated Security=SSPI"))
                    {
                        var bulkCopy = new SqlBulkCopy(conn);
                        bulkCopy.DestinationTableName = table;
                        conn.Open();
                        var schema = conn.GetSchema("Columns", new[]{null, null, table, null} );
                        foreach (DataColumn sourceColumn in dt.Columns)
                        {
                            foreach (DataRow row in schema.Rows)
                            {
                                if (string.Equals(sourceColumn.ColumnName, (string)row["COLUMN_NAME"], StringComparison.OrdinalIgnoreCase))
                                {
                                    bulkCopy.ColumnMappings.Add(sourceColumn.ColumnName, (string)row["COLUMN_NAME"]);
                                    break;
                                }
                            }
                        }
                        bulkCopy.WriteToServer(dt);
                    }
                }
            }
        }
    }
}
This code checks to see if a file has been uploaded, and if one has, its extension is checked to ensure that it is an Excel file. Then the data is extracted into a DataTable using the ToDataTable extension method.The destination table is specified and then the schema of that table is obtained from the database. Each of the columns in the Excel worksheet is compared to the columns in the destination table, and if a match is found, an entry is added to the ColumnMappings collection, ensuring that any unmatched columns are ignored. Then the data is inserted into the destination table.
This is among the quickest ways to get data into a SQL Server database, and the code can be adapted easily to MVC, although the bulk of the code in the Page_Load event handler should go into a separate method that's called from the controller rather than in the controller itself. Even if you are using an ORM in your project like the Entity Framework, you are still advised to revert to ADO.NET and SqlBulkCopy for this type of operation purely for performance reasons.
You will notice that at no stage is the Excel file saved to the server, which removes any potential problems arising from permissions, file locking or file system checking. The EPPlus package is deployed to the server with the web application, so nothing needs to be installed on the server to get this to work, which means that you don't have to worry when moving the application from one host to another.

Summary

This article showed my preferred way to bulk import data from Excel into SQL Server from an uploaded file in an ASP.NET application. It uses EPPlus and SqlBulkCopy to accomplish that task quickly and efficiently.