2014年12月29日 星期一

ReportViewer 載入時間過長,加上Loading畫面

ReportViewer 載入時間過長,加上Loading畫面(使用ExtJS)

var myMask = new Ext.LoadMask(viewport, { msg: '處理中...' });
myMask.show();
var iframe = document.getElementById("mainContent");
iframe.onload = function () {
    myMask.hide();
  };
Ext.getDom('mainContent').src = "http://Site/Report.aspx"

2014年12月4日 星期四

刪除或修改暫存表格方法 (GLOBAL TEMPORARY TABLE)


新增欄位

TRUNCATE TABLE TPMPTABLE;
ALTER TABLE TPMPTABLE ADD (F1 VARCHAR2(6));

刪除表格TPMPTABLE

DROP TABLE TPMPTABLE;

刪除表格若出現以下錯誤

錯誤報告 - SQL 錯誤: ORA-14452: 嘗試建立, 更改或捨棄已在使用中之暫時表格的索引 14452. 00000 - "attempt to create, alter or drop an index on temporary table already in use" *Cause: An attempt was made to create, alter or drop an index on temporary table which is already in use. *Action: All the sessions using the session-specific temporary table have to truncate table and all the transactions using transaction specific temporary table have to end their transactions.


1.確定使用此表格的SID

SELECT SID, SERIAL# FROM V$SESSION V 
WHERE SID IN (SELECT SID FROM V$LOCK  L, DBA_OBJECTS O 
WHERE L.ID1 = O.OBJECT_ID AND O.OBJECT_NAME =UPPER('TPMPTABLE'));

2.刪除SESSION,成功後再做一次刪除表格動作(刪除SESSION的ORACLE帳號權限必須夠大)

ALTER SYSTEM KILL SESSION 'SID, SERIAL#';



2014年12月3日 星期三

Join至其他table並抓到最大的日期

取得table最大日期

SELECT K1,K2,D FROM T1
WHERE D = (SELECT MAX(D) FROM T1)

錯誤寫法:join至其他table並抓到最大的日期,此寫法會出現
ORA-01799: 資料欄不可以外部結合的方式與一個子查詢結合

SELECT K,D,D2 FROM T1 LEFT JOIN T2 ON T2.K2 = T1.K
AND T2.D2 = (SELECT MAX(D2) FROM T2)

成功寫法:join至其他table並抓到最大的日期

SELECT K,D,D2 FROM T1 LEFT JOIN 
(
  SELECT K2,D2 FROM T2 AA WHERE AA.D2 IN
   (
     SELECT MAX(D2) FROM T2
     WHERE T2.K2 = AA.K2
   )
)C ON C.K2 = T1.K

2014年11月28日 星期五

ORACLE 預存程序回傳錯誤

ORACLE 預存程序回傳錯誤

CREATE OR REPLACE PROCEDURE SPTEST(USERID IN VARCHAR2,RTN OUT VARCHAR2)
IS
  n NUMBER;
BEGIN
  n:=4/0;  
  RTN:= 'OK';
EXCEPTION
  WHEN OTHERS THEN
  RTN:= SQLERRM;
END SPTEST;

2014年10月24日 星期五

使用 FormsAuthentication.SetAuthCookie

使用FormsAuthentication.SetAuthCookie

var acct = "spring";
FormsAuthentication.SetAuthCookie(acct, false);

2014年10月22日 星期三

JavaScript Function (匿名函數)

this in C#

//直譯器載入js時,會先處理所有的宣告,包含變數與函數宣告,接下來才執行程式,因此尚未執行到匿名函數時,無法調用
//一般函數宣告方式,同一個scope的任何地方都可使用func1
func1();
function func1(){
  console.log('func1 => ' + 'type of func1 : ' + typeof func1);
}

//func2()必須在指定後才能調用,雖然是具名函數,但表示式的寫法,只會提升變數的宣告,並沒有函數的定義,所以func2()還是得像匿名函數一樣先指定才可調用   
var func2 = function func2 (){
  console.log('func2');
};
func2();

//匿名函數func3()必須在指定後才能調用 
var func3 = function(){
  console.log('func3');
};
func3();

//匿名函數,占用空間在執行完會馬上釋放
( function () { 
console.log('func4');
}()); //立即執行

//callback(回調函數)
$("#btn").click(function() {
  console.log('btn');
}); 

this在C#與JavaScript的不同

this in C#

class Program
    {
        static void Main(string[] args)
        {
            Lilo lilo = new Lilo();
            //lilo.strStitch 指向 類別Lilo的 public string strStitch;
            Console.WriteLine("{0} 是我的家人 !!", lilo.strStitch);
            Console.ReadLine();
        }
        class Lilo
        {
            public string strStitch;
            public Lilo()
            {
                string strStitch;
                strStitch = "STITCH";
                //this.strStitch 指向 public string strStitch;
                this.strStitch = strStitch;
            }
        }
    }

this in JavaScript

var lilo = {
  stitch : 'STITCH',
  f: function(){
    console.log(this.stitch + " 是我的家人 !!");
  }
};
//調用f函式後,f內的this指向點f()前面的lilo
lilo.f();

ASP.NET MVC Web API 資料庫處理 using

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Net.Http.Formatting;
using System.Data;
using MvcMusicStore.Models;
using System.Data.Entity;
using System.Configuration;
using System.Data.SqlClient;

namespace MvcMusicStore.Controllers
{
    public class ExtJSApiController : ApiController
    {     
        public dynamic ReviewDataGet(FormDataCollection form)
        {
            string conn = ConfigurationManager.ConnectionStrings["MvcMusicStoreContext"].ConnectionString;
            DataTable dt = new DataTable();
            string strCheck = form.Get("x");
            string strAlbumID = form.Get("AlbumID");
            string strTitle = form.Get("Title");
            using (SqlConnection sqlConnection = new SqlConnection(conn))
            {
                string strSql = "SELECT * FROM Albums WHERE AlbumID LIKE @AlbumID AND Title LIKE @Title";

                SqlCommand sqlCommand = new SqlCommand(strSql, sqlConnection);
                sqlCommand.Parameters.AddWithValue("@AlbumID", "%" + strAlbumID + "%");
                sqlCommand.Parameters.AddWithValue("@Title", "%" + strTitle + "%");
                sqlConnection.Open();
                dt.Load(sqlCommand.ExecuteReader());
            }
            DataSet ds = new DataSet();
            ds.Tables.Add(dt);
            return new ApiResponse()
            {
                success = true,
                msg = "",
                ds = ds
            };
        }
        public dynamic AlbumComboGet()
        {
            DataTable dt = new DataTable();
            using (SqlConnection sqlConnection = new SqlConnection(conn))
            {
                string strSql = "SELECT AlbumID AS 'TEXT',AlbumID AS 'VALUE' FROM Albums";
                SqlCommand sqlCommand = new SqlCommand(strSql, sqlConnection);
                sqlConnection.Open();
                dt.Load(sqlCommand.ExecuteReader());
            }
            return dt;
        }
    }
    public class ApiResponse
    {
        public DataSet ds { get; set; }
        public string msg { get; set; }
        public bool success { get; set; }
    }
}


2014年10月6日 星期一

ASP.NET MVC 使用 FullCalendar

好用的Calendar   FullCalendar


Model

public class CALENDAR
{
  public string title { get; set; }
  public string start { get; set; }
  public string end { get; set; }
  public string url { get; set; }
}

View

@{
    ViewBag.Title = "Calendar";
}

@section featured {

<link href="@Url.Content("~/Scripts/fullcalendar/lib/cupertino/jquery-ui.min.css")" rel="stylesheet" type="text/css" />
<link href="@Url.Content("~/Scripts/fullcalendar/fullcalendar.css")" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="@Url.Content("~/Scripts/fullcalendar/lib/moment.min.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/fullcalendar/lib/jquery.min.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/fullcalendar/fullcalendar.min.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/fullcalendar/lang-all.js")"></script>

<style>
    body {
        margin: 40px 10px;
        padding: 0;
        font-family: "Lucida Grande",Helvetica,Arial,Verdana,sans-serif;
        font-size: 14px;
        overflow:scroll !important;
    }

    #calendar {
        max-width: 900px;
        margin: 0 auto;
    }
</style>

   <div id='calendar'></div>
<script>

    $(document).ready(function () {
        $('#calendar').fullCalendar({
            theme: true,
            lang: 'zh-tw',
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'month,agendaWeek,agendaDay'
            },
            editable: false,
            eventLimit: true, // allow "more" link when too many events
            events: {
                type: 'POST',
                url: '../api/TP1025CalendarGet/CalendarData',
                error: function () {
                    alert('資料存取失敗!');
                },
                success: function (response) {
 
                }
            }
        });

    });

</script>
}

Controller

public class TP1025CalendarController : Controller
{
  //
  // GET: /TP1025Calendar/
  public ActionResult Index()
  {
      return View();
  }
}

Web API

public class TP1025CalendarGetController : ApiControllerWebBase
{
    public List CalendarData(FormDataCollection form)
    {
        List calendar = new List();

        foreach (DataRow dr in response.ds.Tables[0].Rows)
        {
            calendar.Add(new CALENDAR { title = dr["title"].ToString(), start = dr["start"].ToString(), url = "" });
        }
        return calendar;
    }
}

2014年9月24日 星期三

DataTable to List to Json

DataTable to List

var r = Shared.Process(this.ws, "TraBULLETINGet", form);

List<Bulletin> bulletin = new List<Bulletin>();

foreach (DataRow dr in r.ds.Tables["T1"].Rows)
 {
   bulletin.Add(new Bulletin { TITLE = dr["TITLE"].ToString(), DES = dr["DES"].ToString(), CREATE_DATE = dr["CREATE_DATE"].ToString() });
 }

var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(bulletin);

public class Bulletin
 {
     public string TITLE { get; set; }
     public string DES { get; set; }
     public string CREATE_DATE { get; set; }
 }

.NET讀取csv檔

錯誤:不是一個有效的路徑。請確定路徑名稱是拼對的,而且檔案位於您所連接的伺服器上。

string strConn = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\;Extended Properties='text'";
using (OleDbConnection conn = new OleDbConnection(strConn))
{
   DataTable dt = new DataTable();
   using (OleDbDataAdapter adapter = new OleDbDataAdapter(@"select  * from [aa.csv]", conn))
     {
       adapter.Fill(dt);
     }
}

2014年9月19日 星期五

Oracle 修改 SEQUENCE

修改INCREMENT(可以為負),再執行NEXTVAL

ALTER SEQUENCE seq INCREMENT BY 100;
SELECT seq.NEXTVAL FROM DUAL;

執行完記得改回1

ALTER SEQUENCE seq INCREMENT BY 1;

2014年9月15日 星期一

常用SQL,老是忘記...

SELECT SUM(A) AS A,SUM(B) AS B FROM (
SELECT 3 AS A,0 AS B
UNION ALL
SELECT 0 AS A,4 AS B
)A 

2014年9月14日 星期日

ASP.NET MVC Route Attribute


Route屬性

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace MvcMusicStore.Controllers
{
    public class DemoRouteController : ApiController
    {
        //GET: api/DemoRoute/5
        [Route("customers/{id}/orders")]
        [HttpGet]
        public string FindValue(int id)
        {
            return id.ToString();
        }
    }
}

SQL SERVER Loop

非必要,盡量少用Cursor

DECLARE @count INT
DECLARE @max INT
 SET @count = 0
 SET @max = 5
 WHILE (@count<@max)
 BEGIN
    SELECT @count
    Set @count=@count+1
 END

SQL SERVER 開啟 執行計畫 Execution plan



Visual Studio 修改專案檔 csproj



ASP.NET MVC (Model, View, Controller 簡單範例)

Model

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1.Models
{
    public class Album
    {
        public int AlbumID { get; set; }
        public string Title { get; set; }
    }
}

List Controller

public ActionResult Index()
        {
            List albums = new List();
            albums.Add(new Album { AlbumID = 1, Title = "Sting" });
            albums.Add(new Album { AlbumID = 2, Title = "Joan" });
            return View(albums);
        }

List View

@model IEnumerable<WebApplication1.Models.Album>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Title)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Title)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.AlbumID }) |
            @Html.ActionLink("Details", "Details", new { id=item.AlbumID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.AlbumID })
        </td>
    </tr>
}

</table>

Detail Controller

public ActionResult Details(int id)
        {
            var album = new Album { AlbumID = id, Title = "Hello" };
            return View(album);
        }

Detail View

@model WebApplication1.Models.Album

@{
    ViewBag.Title = "Details";
}

<h2>Details</h2>

<div>
    <h4>Album</h4>
 <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.Title)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Title)
        </dd>

    </dl>
</div>
<p>
    @Html.ActionLink("Edit", "Edit", new { id = Model.AlbumID }) |
    @Html.ActionLink("Back to List", "Index")
</p>

2014年9月4日 星期四

Visual Studio 2012 加入Web 參考

 



IE11 看不到列印按鈕 (ReportViewer)


  1. 確認目前安裝的ReportViewer版本
  2. 安裝最新版ReportViewer(11.0.3452.0)  http://www.microsoft.com/zh-tw/download/details.aspx?id=35747
  3. 安裝.NET Framework 4.5.1
  4. 重開機


2014年9月3日 星期三

C#執行EXE檔加參數

C#執行EXE檔加參數
string text = "";
string strUser = "894128";
string strPath = HttpContext.Current.Server.MapPath("~/OfficeUpload/");
System.IO.File.WriteAllText(strPath + strUser + ".txt", text);
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = Path.GetFileName(strPath + "/StockMergeRpt.exe");
psi.WorkingDirectory = Path.GetDirectoryName(strPath + "/StockMergeRpt.exe");
psi.Arguments = "-i " + strUser + ".txt -o " + strUser + ".doc";
Process.Start(psi);

2014年8月25日 星期一

DataSet 轉 XML (xml,xsd)

DataTable轉XML
DataTable dt = new DataTable("WPN");
dt.Columns.AddRange(new DataColumn[] {
   //new DataColumn("JCN",typeof(string),"",MappingType.Attribute),
   new DataColumn("ID1",typeof(string)),
   new DataColumn("ID2",typeof(string)),
   new DataColumn("NO",typeof(int)),
   new DataColumn("DT",typeof(DateTime))
  });

  dt.Columns["JCN"].MaxLength= 15;
  dt.Columns["MSNM"].MaxLength = 80;
           
  DateTime x = DateTime.Now;
  dt.PrimaryKey = new DataColumn[] { dt.Columns["ID1"], dt.Columns["ID2"]};

  dt.Rows.Add(new object[] { "WP001", "WP002", 3, Convert.ToDateTime("2014/06/25 10:16:08")});

  DataSet ds = new DataSet("WP");
  ds.Tables.Add(dt);

  ds.WriteXml("D:\\test.xml");
  ds.WriteXmlSchema("D:\\test.xsd");
驗證XSD
http://msdn.microsoft.com/en-us/library/3740e0b5(v=vs.110).aspx
string xmlFile = Server.MapPath("D:\\test.xml");
string xsdFile = Server.MapPath("D:\\test.xsd");

XmlTextReader textReader = new XmlTextReader(xmlFile);
XmlValidatingReader validatingReader = new XmlValidatingReader(textReader);
validatingReader.Schemas.Add(null, xsdFile);
validatingReader.ValidationType = ValidationType.Schema;
validatingReader.ValidationEventHandler += new ValidationEventHandler(validatingReader_ValidationEventHandler);

while (validatingReader.Read()){

}
validatingReader.Close();
public void validatingReader_ValidationEventHandler(object sender, ValidationEventArgs e)
{
   Response.Write("Error Message : " + e.Message);
}

2014年8月20日 星期三

JavaScript & ExtJS 全域變數

ExtJS內呼叫function時,將test789()指定為全域變數
renderer : function(){
        return "<input type='button' onclick=test789('12356789','00000000'); value='測試'></input>";
    }
test789 = function(param1,param2) {
        alert(param1 + param2);
    }


2014年7月11日 星期五

HTML 按下Enter預設按鈕

下方為簡單的HTML格式,包含3個button、1個text, 前兩個按鈕為隱藏樣式,若focus在text裡,按下Enter, 網頁預設會執行最接近的submit button(Button1不是subbmit button),所以是Button2。
<!DOCTYPE html>
<html>
<form>
<body>

  <input type='button' value='Button1' onclick='alert("Button1");' style='display:none'/>
  <input type='submit' value='Button2' onclick='alert("Button2");' style='display:none'/>
  <input type='text'/>
  <input type='submit' value='Button3' onclick='alert("Button3");'/>

</body>
</form>
</html>

Oracle 動態塞值到 IN Clause

解決下方情況

SELECT * FROM TableName
WHERE TUSER IN ('A','B','C')
--'A','B','C'為動態產生

1)新增類型

create or replace 
type ttype is table of varchar2(255)

2)新增函數

create or replace 
Function FindRLP RETURN ttype
 IS
   rtn ttype := ttype();
   idx integer := 0;
 BEGIN
  for r in (SELECT TUSER FROM UR_UIR WHERE RLNO='G05')
   loop
      rtn.extend;
      idx := idx+1;
      rtn(idx) := r.TUSER;
   end loop;
   return rtn;
 END;

使用方式

SELECT * FROM TableName
WHERE TUSER IN (SELECT * FROM TABLE(FindRLP))

2014年7月9日 星期三

Ajax使用Get method產生Cache問題

例如:利用Ajax呼叫.ashx時,使用Get method,若每次呼叫網址不變,則會有Cache問題

http://www.w3schools.com/tags/ref_httpmethods.asp

  • GET requests can be cached
  • POST requests are never cached

2014年7月5日 星期六

.NET存取Oracle資料庫相關Provider說明,ODBC、OleDb、OracleClient、ODAC

使用時確認各Provider支援的Oracle版本


1).NET Framework Data Provider for ODBC:

(Open Database Connectivity,開放資料庫互連)提供了標準的API方法來存取資料庫管理系統。尚未有ODBC之前,若要開發資料庫應用程式,必須使用資料庫廠商隨資料庫產品一同發行的一些工具集來存取資料庫。微軟於1992年發表了ODBC。
using System.Data;
using Microsoft.Data.Odbc;

     {
       OdbcConnection cn;
       OdbcCommand cmd;
       string MyString;

       MyString="Select * from Customers";

       cn= new OdbcConnection("Driver={Microsoft ODBC for Oracle};Server=myOracleServer;UID=spring;PWD=spring;");

       cmd=new OdbcCommand(MyString,cn);
       cn.Open();

       MessageBox.Show("Connected");

       cn.Close();
     }

2).NET Framework Data Provider for OLE DB:

是微軟為以統一方式存取不同型別的資料儲存設計的一種應用程式介面,是一組用元件物件模型(COM)實作的介面。OLE DB Provider for Oracle Client,呼叫 Oracle 資料庫的 OLE DB 資料提供者,通常由 Oracle 原廠提供。
using System.Data;
using System.Data.OleDb;

        {
            OleDbConnection cn;
            OleDbCommand cmd;
            string MyString;

            MyString = "Select * from Customers";

            cn = new OleDbConnection("Data Source=myOracleServer;Provider=OraOLEDB.Oracle.1;User Id=spring;Password=spring");

            cmd= new OleDbCommand(MyString,cn);
            cn.Open();

            MessageBox.Show("Connected");

            cn.Close();
        }

3).NET Framework Data Provider for Oracle:

支援Oracle用戶端軟體8.1.7(含)以後版本。Visual Studio 2010後建議使用ODP.NET。
(Microsoft:The types in System.Data.OracleClient are deprecated)
using System.Data;
using System.Data.OracleClient;

         {

            OracleConnection cn;
            OracleCommand cmd;
            string MyString;

            MyString = "Select * from Customers";

            cn = new OracleConnection("Data Source=myOracleServer;User Id=spring;Password=spring");

            cmd = new OracleCommand(MyString, cn);
            cn.Open();

            MessageBox.Show("Connected");

            cn.Close();

         }

4)ODAC:

(ODP.NET:Oracle Data Provider for .NET)不同版本 Visual Studio 須搭配不同ODAC(Oracle Data Access Components)

Web.config
<add name="Default" connectionString="Data Source=myOracleServer;User Id=spring;Password=spring;providerName="Oracle.DataAccess.Client"/>
using Oracle.DataAccess.Client;

         using (OracleConnection conn = new OracleConnection(ConfigurationManager.ConnectionStrings["Default"].ConnectionString))
         {
            OracleCommand cmd;
            try
            {
              conn.Open();
              cmd = new OracleCommand();
              cmd.Connection = conn;
              cmd.CommandText = "";

              cmd.ExecuteNonQuery();
             }
             catch (Exception ex)
             {}
             //使用using不需要close與dispose
             //finally
             //{
             //    cmd.Dispose();
             //    conn.Close();
             //    conn.Dispose();
             //}    
          }

2014年7月2日 星期三

SQL SERVER 編碼


SQL SERVER各種欄位型態編碼

select data_type, character_set_catalog, character_set_schema, character_set_name,collation_catalog, collation_schema, collation_name, count(*) count from information_schema.columns group by data_type, character_set_catalog, character_set_schema, character_set_name,collation_catalog, collation_schema, collation_name;


編碼說明(In SQL SERVER)

  • Big5(cp950) : 中文字占 2Byte 
  • Unicode(UTF-16) : 中文字占 2Byte
  • UTF-8 : 中文字占 3Byte 
例:
varchar(2) : 2Byte,可放1個中文字
nvarchar(2) : 4Byte,可放2個中文字

2014年6月30日 星期一

ASP.NET Submit (使用POST、GET)

PostDemo.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="PostDemo.aspx.cs" Inherits="PassValuesBetweenPages.PostDemo" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" method="post" action="PostDemo.aspx?p1=test456">
        <div>
            <input name="test" value="test123" type="text" />
            <input type="submit" value="送出" />    
        </div>
    </form>
</body>
</html>

PostDemo.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace PassValuesBetweenPages
{
    public partial class PostDemo : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Form["test"] != null)
            {
                string strTest = Request.Form["test"].ToString();
                string strP1 = Request.QueryString["p1"].ToString();
                Response.Write("test : " + strTest);
                Response.Write("p1 : " + strP1);
            }
        }
    }
}

ASP.NET Form Submit (使用POST)

FormSubmit.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FormSubmit.aspx.cs" Inherits="PassValuesBetweenPages.FormSubmit" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function submitform() {
            document.forms[0].submit();
        }
    </script>
</head>
<body>
    <form id="form1" method="post" action="FormSubmit.aspx">
        <div>
            <input name="test" value="test123" type="text" />
            <a href="javascript: submitform()">Submit</a>    
        </div>
    </form>
</body>
</html>

FormSubmit.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace PassValuesBetweenPages
{
    public partial class FormSubmit : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Form["test"] != null)
            {
                string strTest = Request.Form["test"].ToString();
                Response.Write("Form POST : " + strTest);
            }
        }
    }
}

2014年6月25日 星期三

ASP.NET MVC 整合 AD(Active Directory) 登入


先設定Web.config為Windows驗證

如果是Forms與Windows混合驗證,只需將登入畫面設定為Windows驗證,匿名登入可進入另一登入頁面


取得Client AD 帳號方法 HttpContext.Current.User.Identity.Name

若進去網站想要不彈出AD的驗證視窗
1. 安全性 => 近端內部網路 => 網站 => 加入網址
2. 網際網路選項 => 勾選「啟用整合式Windows驗證」

2014年6月20日 星期五

解決LDF檔不斷增大

若系統只靠"完整備份"進行還原,可以用此設定 自動壓縮 True (AUTO_SHRINK ON )

語法:


ALTER DATABASE 資料庫名稱 SET RECOVERY simple
use 資料庫名稱
go
dbcc shrinkfile('資料庫名稱_log',2)
ALTER DATABASE 資料庫名稱 SET RECOVERY FULL

2014年6月13日 星期五

ASP.NET 取得目前所有 Session 清單


HttpContext context = System.Web.HttpContext.Current;
for (int i = 0; i < context.Session.Contents.Count; i++)
  {
    Response.Write(Session.Contents[i].ToString() + "<br />");
  }

2014年6月11日 星期三

Visual Studio 2012 安裝錯誤 Microsoft Web Deploy 3.0 與目前的系統時鐘或簽署檔案的時間戳記核對時...

Visual Stuido 2012 安裝完成後出現如圖錯誤


此錯誤會造成新增 ASP.NET 專案時,發生下面錯誤


解決方式:

2014年5月28日 星期三

jQuery 取得 iframe 父層元素

//取最同一層元素
$('#flow')[0].innerHTML = "contents";
//取得上一層元素 (window通常可省略,e.g., window.parent.document)
$('#flow', parent.document)[0].innerHTML = "contents";
//取得最上層元素
$('#flow', top.document)[0].innerHTML = "contents";

IIS 根目錄網站與虛擬目錄網站 Web.config 影響

取消子網站繼承根目錄網站的設定即可
<location path="." inheritInChildApplications="false">
      <system.web>
         ...
      </system.web>
</location>

2014年5月22日 星期四

ASP.NET MVC 壓縮CSS與JavaScript

BundleConfig.cs
bundles.Add(new ScriptBundle("~/bundles/extjs").Include(
   "~/Scripts/extjs/ext-all-debug.js",
   "~/Scripts/default.js",
   "~/Scripts/jquery-1.7.1.js",
   "~/Scripts/extjs/ext-lang-zh_TW.js",
   "~/Scripts/TRAUtility.js"));
Web.config
<compilation debug="false" targetframework="4.5">
使用方式
@{
    Layout = null;
}
<html lang="zh-tw">
<head id="Head1" runat="server">
    <title></title> 
    @Scripts.Render("~/bundles/extjs")
</head>
<body>
</body>
</html>

修改前
 修改後

2014年5月20日 星期二

Visual Studio 2013 檔案屬性

不論是設計「RDLC報表」或「放在App_Code的程式」,
常常忘了修改檔案的屬性,
導致無法發佈RDLC報表至網站或放在App_Code的程式無法參照



2014年5月14日 星期三

設定本地端 IE 版本 X-UA-Compatible

本地端 IE 載入預設為IE7

查看回應標頭為 X-Powered-By: ASP.NET

設定IIS HTTP標頭為 X-UA-Compatible: IE=EmulateIE9

本地端 IE 版本則會依照 IIS 設定其瀏覽器相容性版本


2014年4月24日 星期四

jQuery.Gantt 設定假日屬性 holidays


參考 : http://taitems.github.io/jQuery.Gantt/

Handler.ashx

<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;
using System.Web.SessionState;
using System.Collections.Generic;

public class Handler : IHttpHandler,IReadOnlySessionState {
    
    public void ProcessRequest (HttpContext context) {
        
        List listHD = new List();
        listHD.Add("[\"/Date(1325433600000)/\"]");
        listHD.Add("[\"/Date(1325520000000)/\"]");
        listHD.Add("[\"/Date(1325692800000)/\"]");
        context.Response.ContentType = "application/json";
        context.Response.Charset = "utf-8";
        context.Response.Write(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(listHD));
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

getHD.js

$.ajax({
    type: 'post',
    async: false,
    url: "Handler.ashx",
    dataType: "json",
    contentType: 'application/json; charset=utf-8',
    success: function (result) {
        hd = result;
    },
    error: function () {
        hd = '';
        alert('讀取假日資料錯誤!');
    }
})

gantt.html

<script src="js/getHD.js" type="text/javascript"></script>
$(function() {
  $(".gantt").gantt({
  holidays: hd,
  ...   
}

2014年4月20日 星期日

ExtJS 物件導向


1.extends

Ext.onReady(function () {

    Ext.define('Family.Father', {
        //若太多屬性可使用config
        config:{
            Name: '',
            Money: 0
        },
        //alias: ['widget.Father'],//xtype:Father
        alias:'Father',
        MyMoney:function(){
            Ext.Msg.alert("Father's money : " + this.Money);
            console.log("Father's money : " + this.Money);
        },
        constructor: function (config) {
            //config初始化
            this.initConfig(config);
        }
    });

    Ext.define('Family.Son', {
        extend: 'Family.Father',
        alias: 'Son',
        SonMoney:function(){
            Ext.Msg.alert("Son's money : " + this.Money);
            console.log("Son's money : " + this.Money);
        },
        //若子類別有建構子,不會再調用父類別建構子
        //若只是單純調用父類別的建構子,可省略下方
        constructor: function () {
            //此方式可以使用子類別建構子外,並調用父類別建構子
            this.callParent(arguments);
        }
    });

    //alias: 'Son'
    var son = Ext.create('Son', {
        Name: 'summer',
        Money: 2000000
    });
    son.SonMoney();
    son.MyMoney();
});

2.apply/applyIf

Ext.apply(config1, config2);

3.override

//覆寫Ext.form.Field裡面的reset
//This method has been DEPRECATED since 4.1.0
//Use Ext.define instead

Ext.form.Field.override({
        reset: function () {
            var me = this;
            me.beforeReset();
            me.setValue('');//me.setValue(me.originalValue);
            me.clearInvalid();
            // delete here so we reset back to the original state
            delete me.wasValid;
        }
    });

    //新增clear method於Ext.form.Basic(用法 xxForm.getForm().clear();)
    Ext.define('TRA.form.Form', {
        override: 'Ext.form.Basic',
        clear: function () {
            Ext.suspendLayouts();
            var me = this,
                fields = me.getFields().items,
                f,
                fLen = fields.length;
            for (f = 0; f < fLen; f++) {
                fields[f].setValue('');//fields[f].reset();
                fields[f].clearInvalid();
            }
            Ext.resumeLayouts(true);

            //if (resetRecord === true) {
                delete me._record;
            //}
            return me;
        }
    });

    //grid預設鎖住排序與篩選
    Ext.define('TRA.form.Form', {
        override: 'Ext.grid.column.Column',
        sortable: false,
        menuDisabled: true
    });

2014年4月10日 星期四

System.Security.SecurityException 組件不允許部分信任的呼叫端

原本系統有一個使用NPOI元件下載Excel的功能,今天突然出現這個錯誤。
解決方法: http://support.microsoft.com/kb/320268/zh-tw


進入Frameowk目錄後,輸入指令
Drive:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\caspol.exe -m -ag 1 -url "file:////\\computername\sharename\*" FullTrust -exclusive on


✛修改成功後,IIS回收並重啟網頁

2014年4月9日 星期三

Visual Stuido 2013 自動關閉 IIS Express

Visual Studio 2013預設關閉瀏覽器會關掉 IIS Express


2014年4月3日 星期四

AngularJS + ASP.NET MVC drag and drop 拖拉

參考此網址修改為ASP.NET MVC連動資料庫 :
http://www.smartjava.org/content/drag-and-drop-angularjs-using-jquery-ui

ASP.NET MVC

結果