หมวดหมู่: C#

C#: ConfigurationsC#: Configurations

C# จะเก็บ configurations อย่าง connection strings ไว้ในไฟล์ app.config หรือ web.config เวลา compiled โปรแกรมไปไว้ที่เครื่อง user แล้วเหมือนมันจะเปิดเผยไปหน่อย แถมเวลาเปลี่ยน environment จาก dev ไป uat อะไรแบบนี้ทีก็มาแก้กันที ถ้าแค่ database ตัวเดียวยังไม่เท่าไหร่ แต่ถ้าต้องติดต่อหลายก้อน แล้วต้องสลับไปมา ตอนที่แก้บัคพร้อม uat นี่พลาดได้ง่าย ๆ
วิธีที่นิยมกันก็คือสร้าง class ขึ้นมาใหม่ แล้วใช้ config เอาจาก class แทน เช่น ไฟล์ Configurations.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PrototypesCSharp
{
 class Configurations
 {
  public static string environment = "DEV"; // DEV, UAT, PRODUCTION

  public static Dictionary<string, string> DSNs()
  {

   var dsns = new Dictionary<string, string>();

   switch (Configurations.environment)
   {

    case "DEV":
     {
      dsns["dns1"] = "Server=127.0.0.1;Database=prototype_DEV;User Id=pitt;Password=phunsanit";
      dsns["dns1_replicate"] = "Server=127.0.0.1;Database=prototype_DEV;User Id=pitt;Password=phunsanit";
      dsns["dns2"] = "Server=127.0.0.1;Database=prototype_DEV;User Id=pitt;Password=phunsanit";
      dsns["dns2_replicate"] = "Server=127.0.0.1;Database=prototype_DEV;User Id=pitt;Password=phunsanit";
     }
     break;

    case "PRODUCTION":
     {
      dsns["dns1"] = "Server=127.0.0.1;Database=prototype;User Id=pitt;Password=phunsanit;";
      dsns["dns1_replicate"] = "Server=127.0.0.1;Database=prototype;User Id=pitt;Password=phunsanit;";
      dsns["dns2"] = "Server=127.0.0.1;Database=prototype;User Id=pitt;Password=phunsanit;";
      dsns["dns2_replicate"] = "Server=127.0.0.1;Database=prototype;User Id=pitt;Password=phunsanit;";
     }
     break;

    case "UAT":
     {
      dsns["dns1"] = "Server=127.0.0.1;Database=prototype_UAT;User Id=pitt;Password=phunsanit";
      dsns["dns1_replicate"] = "Server=127.0.0.1;Database=prototype_UAT;User Id=pitt;Password=phunsanit";
      dsns["dns2"] = "Server=127.0.0.1;Database=prototype_UAT;User Id=pitt;Password=phunsanit";
      dsns["dns2_replicate"] = "Server=127.0.0.1;Database=prototype_UAT;User Id=pitt;Password=phunsanit";
     }
     break;

   }

   return dsns;
  }

 }
}

เวลาจะใช้ในฟอร์มอื่นก็แค่เรียกใช้อย่าง

  string dns1 = Configurations.DSNs()["dns1"].ToString();
  SqlConnection objConn = new SqlConnection(dns1);

แบบนี้ถ้าอยากจะเปลี่ยน environment จาก DEV, UAT หรือ PRODUCTION ก็เปลี่ยนแค่ public static string environment = “DEV”; // DEV, UAT, PRODUCTION บรรทัดเดียว ก็ได้แล้ว ถ้ามี database อื่นหรือคอนฟิกอื่น ๆ ก็แค่เพิ่มรายการเข้าไป ตามที่ใช้

เพื่อให้ง่ายในการดูว่าโปรแกรมเรากำลังใช้ environment ตัวไหนอยู่อาจจะใช้วิธีอย่าง C#: แสดง program version