顯示具有 C# 標籤的文章。 顯示所有文章
顯示具有 C# 標籤的文章。 顯示所有文章

2021年3月2日 星期二

Serial Log - Write to AWS Setting

            Log.Logger = new LoggerConfiguration()
                .Enrich.FromLogContext()
                .MinimumLevel.Debug()
                .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                .Enrich.WithFunction("SystemUserName", () => Environment.UserName)
                .Enrich.WithFunction("SystemName", () => sysetmName)
                .Enrich.WithFunction("OSVersion", () => Environment.OSVersion.VersionString)
                .Enrich.WithFunction("CurrentManagedThreadId", () => Environment.CurrentManagedThreadId.ToString())
                .Enrich.WithFunction("CurrentTimeZone", () => TimeZone.CurrentTimeZone.StandardName)
                // 時間戳
                .Enrich.WithFunction("TimeStamp", () => {
                    System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 當地時區
                    return ((long)(DateTime.Now - startTime).TotalSeconds).ToString(); // 相差秒數
                })
                .Enrich.WithFunction("LogGuid", () => Guid.NewGuid().ToString("N"))
                .WriteTo.AmazonS3(
                    new JsonFormatter(),
                    "log.log",
                    "logforservice",
                    Amazon.RegionEndpoint.APNortheast1,
                    "KeyId",
                    "Key",
                    fileSizeLimitBytes: 10,
                    autoUploadEvents: true,
                    rollingInterval: Serilog.Sinks.AmazonS3.RollingInterval.Minute,
                    bucketPath: $"{sysetmName}/{DateTime.Now.Year}/{DateTime.Now.Month}/{DateTime.Now.Day}/{DateTime.Now.Hour}"
                )
                .CreateLogger();

2021年3月1日 星期一

NLOG Setting - write to Sql,File

 <?xml version="1.0" encoding="utf-8" ?>

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"

      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"

      autoReload="true"

      throwExceptions="false"

      internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">


  <variable name="myvar" value="myvalue"/>


  <targets>

    <target name="MessageLogFile" xsi:type="File" fileName="C://logs/CampaignFlow/SendMessageLog_${shortdate}.log" 

            layout="${longdate} | ${level:uppercase=true} |  ${message} ${newline}" />


    <target name="coloredConsole" xsi:type="ColoredConsole" useDefaultRowHighlightingRules="false"

            layout="${longdate}|${pad:padding=5:inner=${level:uppercase=true}}|${message}" >

    <highlight-row condition="level == LogLevel.Debug" foregroundColor="DarkGray" />

    <highlight-row condition="level == LogLevel.Info" foregroundColor="Gray" />

    <highlight-row condition="level == LogLevel.Warn" foregroundColor="Yellow" />

    <highlight-row condition="level == LogLevel.Error" foregroundColor="Red" />

    <highlight-row condition="level == LogLevel.Fatal" foregroundColor="Red" backgroundColor="White" />

    </target>

    <target name="tracelogguid" xsi:type="database" connectionstring="${dbconnectionstring}" commandtext="insert into [dbo].[tracelog] &#xd;&#xa;     ([controller] ,[action] ,[request] ,[response] ,[createtime] ,[issuccess] ,[requestid] ,[exceptionresult],[errorcode],[stringkeyword],[intkeyword],[guidkeyword]) &#xd;&#xa;     values (@controller, @action, @request, @response, @createtime, @issuccess, @requestid, @exceptionresult,@errorcode,@stringkeyword,@intkeyword,@guidkeyword);">

<parameter name="@controller" layout="${event-properties:item=controller}" />

<parameter name="@action" layout="${event-properties:item=action}" />

     <parameter name="@request" layout="${event-properties:item=request}" />

<parameter name="@response" layout="${event-properties:item=response}" />

<parameter name="@createtime" layout="${event-properties:item=createtime}" />

<parameter name="@issuccess" layout="${event-properties:item=issuccess}" />

<parameter name="@requestid" layout="${event-properties:item=requestid}" />

<parameter name="@request" layout="${event-properties:item=request}" />

<parameter name="@errorcode" layout="${event-properties:item=errorcode}" />

<parameter name="@exceptionresult" layout="${exception:tostring}" />

<parameter name="@stringkeyword" layout="${event-properties:item=stringkeyword}" />

<parameter name="@intkeyword" layout="${event-properties:item=intkeyword}" />

<parameter name="@guidkeyword" layout="${event-properties:item=guidkeyword}" />

</target>


  </targets>


  <rules>

   <logger name="*" minlevel="Trace" writeTo="tracelogguid" />

    <logger name="*" levels="Trace,Debug,Warn" writeTo="MessageLogFile,coloredConsole" />

  </rules>

</nlog>


2020年5月27日 星期三

[ODA.NET] C# Connect Oracle 9i

C# 要連接Oracle 有幾種方法
目前最推薦的就是利用 Oracle.ManagedDataAccess
但是此套件不支援舊版

所以要連接較舊版本的Oracle可以利用 
Oracle.DataAccess.dll


開發工具: Microsoft Visual Studio 2019
資料庫: Oracle9i

1.到Oracle 官網安裝 (以下有傳送門)

ODAC 11.2 Release 5 and Oracle Developer Tools for Visual Studio (11.2.0.3.20)

要注意版本,如果下載到新版(12.X)會不能用

照著精靈一步一步安裝

安裝完成到安裝的資料夾下
~\product\11.2.0\client_1\odp.net\bin\4 取出
Oracle.DataAccess.dll

再加入專案就完成了





























static void Main(string[] args)
   {
            string connstring =
  "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=xxxx)(PORT=xxxx))" +
  "(CONNECT_DATA=(SERVICE_NAME=xxxx)));User Id=xxxx;Password=xxxx;";

            using (OracleConnection conn = new OracleConnection(connstring))
            {
                conn.Open();
                string sql = "select * from xxxx where ROWNUM = 1";
                using (OracleCommand comm = new OracleCommand(sql, conn))
                {
                    using (OracleDataReader rdr = comm.ExecuteReader())
                    {
                        while (rdr.Read())
                        {
                            Console.WriteLine(rdr.GetString(0));
                        }
                    }
                }
            }
    }


參考:


C#連Oracle連線字串


Oracle 
ODAC with Oracle Developer Tools for Visual Studio

2019年11月29日 星期五

[C#] Lambda All() check ListA all in ListB

public static bool ContainsAll<T>(IEnumerable<T> source, IEnumerable<T> values)
{
    return values.All(value => source.Contains(value));
}

2019年11月26日 星期二

新增 net core project


$ dotnet new web -o <專案名稱>
dotnet help 可以查看專案型態的參數
安裝npm $ npm install 檢查npm安裝版本
$ npm -v

init npm
$npm init
如果沒有要設定專案資訊 直接Enter到底
結束之後 會再package.json寫入設定

npm安裝套件 ex jquery
$ npm install jquery

安裝LibMan
$ dotnet tool install -g Microsoft.Web.LibraryManager.Cli

Run
$ dotnet run


Ref microsoft microsoft-SingleR install

2019年11月24日 星期日

.Net Core Console使用依賴注入

public static async Task Main(string[] args)
{

     // 取得設定檔
      IConfiguration config = new ConfigurationBuilder()
                             .AddJsonFile("appsettings.json", true, true)
                             .Build();
    // 建立容器
    var serviceCollection = new ServiceCollection();

    // 註冊服務
    serviceCollection.AddTransient();
    serviceCollection.AddTransient();

    // 加入SqlServer 連線字串
    serviceCollection.AddDbContext(options => options.UseSqlServer(config["ConnectionStrings:DefaultConnection"]));

    // 建立依賴服務提供者
    var serviceProvider = serviceCollection.BuildServiceProvider();

    // 執行
    await serviceProvider.GetRequiredService().Run();
}

C# 比較字串不分大小寫

除了把字串ToUpper() 或 ToLower() 以外

還可以用 String.Compare()
//最後一個參數改成true 就可以忽略大小寫
String.Compare(strSource, strTarget, true) 
回傳為0 即相等


而另外一種我最常用來做搜尋的方法是Contains()

sourceString.Contains("Search-Word", StringComparison.InvariantCultureIgnoreCase, 
new System.Globalization.CultureInfo("en-US")));

2019年3月4日 星期一

移除警告



當出現很多警告

如果要讓警告消失,用NotePad++ 開啟專案檔編輯,
加入 <DependsOnNETStandard>true</DependsOnNETStandard>






這樣一來 警告就不會再出現了

2016年6月7日 星期二

[C#] [Html AgilityPack] 解析HTML 抓取台灣銀行外匯資料

MVC 架構 當練習 隨便寫寫 有點亂...

功能:
1.抓取外匯資料
2.預設顯示 美金 英鎊 日圓 RMB
3.可供選顯示/隱藏 其他外幣資料


2016年6月2日 星期四

[asp.net]一些日期應用

//取得 上個月月底的天數 
string lastMonth = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.AddMonths(-1).Month).ToString()

//取得現在時間的日期
int nowDate = DateTime.Now.Day

2016年5月11日 星期三

[MVC] 簡易分頁 PagedList

1. 先安裝 NuGet套件 - PagedList.Mvc



























2. Controller

      using PagedList;
      using PageList.Models;

        public ActionResult Index(int page =1)
        {
            //page用來記憶目前是哪一頁
            int currentPage = page < 1 ? 1 : page;

           //資料必須先經過排序
            var product = db.Product.Where(x => x.Status == 1).OrderBy(x => x.ID);

            //分頁資料使用 ToPagedList()
            //參數分別是傳入所要分頁的頁碼以及分頁資料量
            //此範例就是每一頁會有10筆資料
            var PageResult = product.ToPagedList(currentPage, 10);
            

            return View(PageResult);
        }

3. View
















需要using PagedList.Mvc PagedList

取得分頁:

@Html.PagedListPager((IPagedList)Model, page => Url.Action("Index", new { page = page}))


































//設定PagedListRenderOptions 可更改樣式
@Html.PagedListPager((IPagedList)Model, page => Url.Action("Index", new  { page = page})
,PagedListRenderOptions.MinimalWithPageCountText)



//也可以自由設定顯示物件
@Html.PagedListPager((IPagedList)Model, page => Url.Action("Index", new  { page = page}),
    new PagedListRenderOptions {
        DisplayLinkToIndividualPages=false,
        DisplayLinkToFirstPage =PagedListDisplayMode.IfNeeded,
        DisplayLinkToLastPage= PagedListDisplayMode.IfNeeded,
        DisplayLinkToNextPage = PagedListDisplayMode.IfNeeded,
        DisplayLinkToPreviousPage = PagedListDisplayMode.IfNeeded,
        DisplayPageCountAndCurrentLocation = true,
        PageCountAndCurrentLocationFormat ="第{0}頁 / 共{1}頁"
    })









https://github.com/TroyGoode/PagedList

2016年5月3日 星期二

[C#][EXIFextractor] Mobile Web 上傳圖片,照片翻轉90度 rotateImage


遇到這種問題 有點傻眼

不知道怎麼解決,測了也沒發現什麼規律性的原因(偏偏我就是拿偏偏我就是用iphone safari)

頓時有了希望全世界都生活在智障型手機的時代是多麼美好,多麼幸福,多麼......方便 ORZ

不過感嘆歸感嘆,希望歸希望,身為21世紀現代人類,還是要追求一下科技進步、社會發展



不用你們提醒我,我知道我現在很難得的正在囉嗦.............

[問題原因] 貌似是瀏覽器吃不到照片的一些tag

這裡有針對IOS詳細介紹照片方向的問題

解決之前 還要加入參考

點我連結下載頁面  進去之後點 Donload Source files

code在這

方便大家 也為了防止頁面被404狙擊 我還是備份一下



HttpPostedFile file = HttpContext.Current.Request.Files["file"];
 
//Create bitmap image from posted file
System.Drawing.Bitmap bmpImg = new System.Drawing.Bitmap(file.InputStream);
 
//rotate if needed
bmpImg = rotateImage(bmpImg);
 
//save image
targetFilePath = "somewhere...";
bmpImg.Save(targetFilePath, ImageFormat.Jpeg);
public Bitmap rotateImage(System.Drawing.Bitmap img)
    {
        try
            {
                RotateFlipType rft = RotateFlipType.RotateNoneFlipNone;
                System.Drawing.Imaging.PropertyItem[] properties = img.PropertyItems;
                
                foreach (System.Drawing.Imaging.PropertyItem p in properties)
                {
                    if (p.Id == 274 || p.Id == 5029)
                    {
                        short orientation = BitConverter.ToInt16(p.Value, 0);
                        switch (orientation)
                        {
                            case 1:
                                rft = RotateFlipType.RotateNoneFlipNone;
                                break;
                            case 3:
                                rft = RotateFlipType.Rotate180FlipNone;
                                break;
                            case 6:
                                rft = RotateFlipType.Rotate90FlipNone;
                                break;
                            case 8:
                                rft = RotateFlipType.Rotate270FlipNone;
                                break;
                        }
                    }
                }
                if (rft != RotateFlipType.RotateNoneFlipNone)
                {
                    img.RotateFlip(rft);
                }
            }
            catch
            {

            }
            return img;
    }
 

2016年4月12日 星期二

[C#]string[] convert to int[]

字串陣列 轉換成 數字陣列的寫法
   string[] tempRGB = str.Replace("rgb(", "").Replace(")", "").Split(',');

   int[] RGB = Array.ConvertAll(tempRGB, x => int.Parse(x));

2016年2月16日 星期二

在ActionResult中呼叫ActionResult的Function,並接到Json


就是吧! 當我要新增資料 發現 資料庫已經有這筆資料存在時,就改作Update的動作

Update這個Function 已經存在了,所以就想著直接CALL....


喔!!! 這件事就這麼發生了

介紹一下兩個Funtion

新增 --> ActionResult AddNewProduct ,傳回 bool success, String ErroMsg

Update --> ActionResult ProductUpdate 傳回 bool iResult , String Msg

傳回的東西都是 JsonResult , 我想要抓到 ProductUpdate 的Json 回到 AddNewProduct 傳出去


具體怎麼做剛開始還覺得有可能嗎?真的能成嗎?

一方面又覺得若不行 那真的太笨了 =__=

然後我就問了...行呀! 真的能~~


看看片段的實作 CODE

[HttpPost]
public ActionResult AddNewProduct(string ID)
{
   bool iResult = true;
   string msg="";
   bool update = true;
   if (update)
   {
     //把要呼叫的Function ActionResult 轉型成 JsonResult
     JsonResult r = (JsonResult)ProductUpdate(ID,true);

     //因為拿到的r是object 所以再轉一次
     dynamic resultData = r.Data;
     
     //要用的時候,也要給他型別才行
     iResult = (bool)resultData.success;
     if(iResult)
     {
        msg = (String)resultData.FinishMsg;
        msg = msg.Replace("更新", "匯入");   
     }else
     {
       msg = (String)resultData.ErrorMsg;
       msg = msg.Replace("更新", "匯入") + "請重新新增商品";
     }
  }
   else
   {
     //新增資料
    }
 return new JsonResult()
 {
    Data = new { success = iResult , Msg = msg }
 };

}

附上 stackoverflow
還是GOOGLE的高亮程式碼漂亮阿!
其實每次要把CODE放上來我都會腦抽忘了怎麼弄ORZ

2016年2月4日 星期四

[Lambda]Contains 一次搜尋多筆資料

Lambda 語句中,進行類似 SQL in 的搜尋方法


string[] ArrayNo = {"A111", "B222" , "C333" };

var tmp = db.Product.Where(x => x.Status == 1 && ArrayNo.Contains(x.No)).ToList();


2016年1月6日 星期三

[MVC]CheckBox複選、全選、取消

我忘了有沒有寫過類似的東西 剛好今天有空,索性整理一下吧
JQUERY
         // Tab名稱的全選和取消
         $("#AllTab").change(function () {
             if ($(this).is(":checked")) {
                 $("[id*=chkTab] input").prop("checked", true);
             } else {
                 $("[id*=chkTab] input").removeAttr("checked");
             }
         });
         $("[id*=chkTab] input").on("change", function () {

             //全部都選到了,"全部"這個選項打勾,反之,則取消
             if ($("[id*=chkTab] input").length == $("[id*=chkTab] input:checked").length) {
                 $("#AllTab").prop("checked", true);
             }
             else {
                 $("#AllTab").removeAttr("checked");
             }
         });
View 順便講一下好了,checkList 這個是用來記錄CheckBox選取的狀態 MVC 才可以這樣用......
//這段程式碼可以不用理他,是POSTBACK 回來時
//想讓畫面保留勾選的項目
@{ 
    string[] checkList = new string[7];//最後一個存放 全部 的狀態
    if (splitFilter[1] != null)
    {
      string[] splitck = splitFilter[1].TrimEnd(',').Split(',');
      if (splitck[0] != "-1")
      {
         foreach (string i in splitck)
         {
           checkList[int.Parse(i) - 1] = "checked";
          }
      }
                                 
    }
 }

Checkbox是長這樣的

<input type="checkbox" value="1" @checkList[1]><label>AA</label>




 Controller

接到勾選的Tab後,去DB搜尋
之前寫的不太簡潔,順帶記錄一下新寫法

if (Tag != "-1") 
{
  List TagCondition = new List();
  foreach (var t in Tag.Substring(0, Tag.Length - 1).Split(','))
  {
     TagCondition.Add(Convert.ToInt32(t));
   }
   product = product.Where(x =>TagCondition.Contains(x.TabName));
}

2015年10月27日 星期二

[C#] DataTable 實現SQL Distinct


DataTable BoardbyMenu = MyDataTable.DefaultView.ToTable(true, "Menu_ID");


來看一下 ToTable的參數:

ToTable ( bool distinct , params string[] columnNames ) ;

第一個true 過濾重複資料

第二個是欄位名稱,可放多個欄位 寫法:

new string[] { "Menu_ID , name" }




2015年10月12日 星期一

[C#][MVC] 資料寫進DB時,檢查是否有Null

create 是要準被塞進DB裡的物件 當create裡面屬性有 null 時 , 就給空值 , 防止DBNull 錯誤發生
IList properties = typeof(ProductSize).GetProperties().ToList();
  foreach (var p in properties)
  {
     if (p.GetValue(create) == null && p.PropertyType == typeof(string))
     {
         p.SetValue(create, "");
      }
  }

2015年10月5日 星期一

[C#]MVC 關於刪除資料RemoveRange Remove

var PTryReport = db.ProductTryReport.Where(x => x.ProductSize_ID == Check.ID);
  if (PTryReport.Any())
  {
    //原本這樣寫 會出錯交易失敗錯誤
    //因為刪除del就會改變PTryReport的值
    foreach (var del in PTryReport)
    {
      db.ProductTryReport.Remove(del);
      db.SaveChanges();
    }
  }
//理想的寫法 用 RemoveRange 一次刪除全部資料
 if (PTryReport.Any())
 {
     db.ProductTryReport.RemoveRange(PTryReport);
     db.SaveChanges();
                                   
  }

2015年9月17日 星期四

[C#] Split 分割字串

用法一 :最普通的字串分割

split() 括號記得用單引號包起來


            string tmp = "AA#BB#CC";
            string[] strSplit = tmp.Split('#');
            string GetValue = strSplit[0]; // 拿到 AA
            GetValue = tmp.Split('#')[1]; //直接拿到字串 BB
            //多字元分割
            string tmp2 = "AA#|BB$$CC#|";
            string[] strSplit2 = tmp2.Split(new string[] { "#|","$$" }, StringSplitOptions.RemoveEmptyEntries);
            string GetValue2 = "";
            foreach(string s in strSplit2)
            {
                GetValue2 += s + " "; //拿到 AA BB CC
            }

             //20160311 新增 分割換行的寫法
             string[] NewLine = tmp.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
             
             //textarea 會把換行符號轉成\n 所以也可以這樣寫
             string[] NewLine2 = tmp.products.Replace("\n","|").Split('|');