最近為了要用到log等機制及把entity 從web project 獨立成為函數庫的專業以供日後他案應用
索興把EF從4升到EF6,不過在執行測試時,出現以下的訊息:
===========================================================
The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information.
===========================================================
那會安爾生~~~!?
anyway,先找solution吧,
參考以下的連結,照他吩咐去做就是了:
1.把app.config (是caller project的app.config,不是entity 所在的project的app.confiig)的
<entityFramework>區塊拿掉
2.DbContext子類別--EntityContext類別提供一個public static getDbContext的函數,取代其建構元
(能不能把建構元設為 inner或是private的層次?沒試,要試才知)
ex:
==============================
public static ERPEntities getDbContext() {
if (!isEF6Inited) {
// EF 6.0.1 throws an exception, unless we first probe the provider types.
var type1 = typeof(System.Data.Entity.SqlServer.SqlProviderServices);
//var type2 = typeof(System.Data.Entity.SqlServerCompact.SqlCeProviderServices);
}
return new ERPEntities();
}
==============================
2.在repository(也就是呼叫/操作Entity Context的商業邏輯Facade類別)中,
把原本呼叫new xxxEntity()的方式改由從 getDbContext()的方式取得DbContext
以上,大功告成,祝大家開發愉快了
2014年7月24日 星期四
EF4->EF6,執行時出現 「The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information.」訊息
2014年6月12日 星期四
for asp.net 2.0 "__doPostBack" 沒有無定義!?
錯誤訊息:"__doPostBack"找不到定義
不想討論成因
直接說solution好了
找個地方放個asp.net的TextBox,其AutoPostBack要設定為true
試看看就可以了.
..
什麼? 要把這TextBox隱藏起來啊,當然不能用asp:TextBox中的visible屬性,否則就白做了
直接用control.Style["visibility"]="hidden" 把它藏起來....而且還不會影響到功能
大家加油了
2014年6月7日 星期六
MSSQL 2000之連結及分頁 (for .net 2.0)
別看銀行系統億來億去的,他們很多內部系統到現在還在用classic asp & vb6的
而且SQL還是用2000的
案子接下來了就是要找solution的
1.MSSQL之於ASP.NET2.0的連接例句:
"server=10.10.10.20;uid=sa;pwd=s123A;database=Northwind"
就這樣簡單
2.分頁機制:
注意!! 只有MSSQL2005以上才支援ROW_NUMBER函數!!
所以要用別的方式來自己造出rownum
select * from
(SELECT productId,supplierid,
(SELECT COUNT(*)
FROM products AS em2
WHERE em2.productID < em1.productID and supplierId<>5) as temprownum
FROM products AS em1 where supplierId<>5) as subtable
order by temprownum
條件兩個都要有....別忘了.
而且SQL還是用2000的
案子接下來了就是要找solution的
1.MSSQL之於ASP.NET2.0的連接例句:
"server=10.10.10.20;uid=sa;pwd=s123A;database=Northwind"
就這樣簡單
2.分頁機制:
注意!! 只有MSSQL2005以上才支援ROW_NUMBER函數!!
所以要用別的方式來自己造出rownum
select * from
(SELECT productId,supplierid,
(SELECT COUNT(*)
FROM products AS em2
WHERE em2.productID < em1.productID and supplierId<>5) as temprownum
FROM products AS em1 where supplierId<>5) as subtable
order by temprownum
條件兩個都要有....別忘了.
(參考: http://www.dotblogs.com.tw/hatelove/archive/2009/07/14/9482.aspx)
不過我覺的最好用的方式是用temp Table的方式來做:
==============================================
select
testRowNum=IDENTITY(INT,1,1),
orders.shipName,
orders.ShipAddress,
orders.CustomerId
into #tempViewTest1974
from orders;
select * from #tempViewTest1974 where testRowNum between 10 and 20;
drop table #tempViewTest1974;
===============temp table 的流水號請自己產生比較妥當================
其他,有遇到再行補充.
2014年2月14日 星期五
oracle 11g create db後,遇到「監聽器未啟動或資料庫服務未在監聽器註冊」的error !?
環境:
server 2012 (64bit)+11g 64
在create一個「TOC64」的db時,結果出現以下錯誤畫面:
如何解決?
server 2012 (64bit)+11g 64
在create一個「TOC64」的db時,結果出現以下錯誤畫面:
![]() |
| 第一次看到這樣的錯誤,真的會很不知所措 |
請打開Net Manager:
1. 看一下「服務命名」是否有沒有把db加入(如果沒有,那就真的無救了,正常是會有的)
2.切換到Listener,IP形態的位址要指定(日後外部連入會用的到)
3.重點來了!!,請切換到listener的「其他服務」
請新增一個「服務」,指定其「程式名稱」、「SID」及「ORACLE本位目錄」
Oracle本位目錄不知道的話,直接copy第一個服務的那個欄位來用就可以了
設定完後,儲存網路組態,再去服務中把Oracle Listener 的服務重新啟動(其相對的「OracleService你的DB」也重啟服務吧)
用toad在本機連看看吧
----後記--------------------------
事實上最快的方式是直到修改listener.ora & tnsnames.ora,修改完後,用tns name(在toad中手動輸入)直接去連就可以了
----後記--------------------------
事實上最快的方式是直到修改listener.ora & tnsnames.ora,修改完後,用tns name(在toad中手動輸入)直接去連就可以了
---listener.ora--參考內容
# listener.ora Network Configuration File: D:\app\Administrator\product\11.2.0\dbhome_2\NETWORK\ADMIN\listener.ora
# Generated by Oracle configuration tools.
SID_LIST_LISTENER =
(SID_LIST =
(SID_DESC =
(PROGRAM = extproc)
(SID_NAME = CLRExtProc)
(ORACLE_HOME = D:\app\Administrator\product\11.2.0\dbhome_2)
)
(SID_DESC =
(PROGRAM = ttcs64)
(SID_NAME = ttcs64)
(ORACLE_HOME = D:\app\Administrator\product\11.2.0\dbhome_2)
)
)
LISTENER =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
)
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
)
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = 10.10.10.11)(PORT = 1521))
)
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = WIN-A2HVFKEQJ1M)(PORT = 1521))
)
)
ADR_BASE_LISTENER = D:\app\Administrator
# listener.ora Network Configuration File: D:\app\Administrator\product\11.2.0\dbhome_2\NETWORK\ADMIN\listener.ora
# Generated by Oracle configuration tools.
SID_LIST_LISTENER =
(SID_LIST =
(SID_DESC =
(PROGRAM = extproc)
(SID_NAME = CLRExtProc)
(ORACLE_HOME = D:\app\Administrator\product\11.2.0\dbhome_2)
)
(SID_DESC =
(PROGRAM = ttcs64)
(SID_NAME = ttcs64)
(ORACLE_HOME = D:\app\Administrator\product\11.2.0\dbhome_2)
)
)
LISTENER =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
)
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
)
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = 10.10.10.11)(PORT = 1521))
)
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = WIN-A2HVFKEQJ1M)(PORT = 1521))
)
)
ADR_BASE_LISTENER = D:\app\Administrator
=========================================
------------tnsnames.ora參考內容-----------------
# tnsnames.ora Network Configuration File: D:\app\Administrator\product\11.2.0\dbhome_2\network\admin\tnsnames.ora
# Generated by Oracle configuration tools.
TOC64 =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = WIN-A2HVFKEQJ1M)(PORT = 1521))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = TOC64)
)
)
ORACLR_CONNECTION_DATA =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
)
(CONNECT_DATA =
(SID = CLRExtProc)
(PRESENTATION = RO)
)
)
LISTENER_ORCL =
(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
TTCS64 =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
)
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = TTCS64)
)
)
LISTENER_TTCS64 =
(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
ORCL =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
)
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = orcl)
)
)
===============================================
以上,大家加油吧
2014年1月6日 星期一
for MSSQL-- 「in 」語法後面要用字串變數去做,行嗎?
舉例:
==================================
declare @id as varchar(100)
set @id='1,150,45,33'
select rows from table where table.id in (@id)
============================
行嗎?
以上面這寫法是不行的,不過只要變巧一下
在這之前,先準備好一個叫做SplitWords函數,放心,人家已經寫好了
為了怕連結失效,我也在此Ctl-C / Ctl-V一下
================================================
==================================
declare @id as varchar(100)
set @id='1,150,45,33'
select rows from table where table.id in (@id)
============================
行嗎?
以上面這寫法是不行的,不過只要變巧一下
在這之前,先準備好一個叫做SplitWords函數,放心,人家已經寫好了
為了怕連結失效,我也在此Ctl-C / Ctl-V一下
================================================
CREATE FUNCTION SplitWords(@text varchar(8000)) RETURNS @words TABLE ( pos smallint primary key, value varchar(8000) ) AS BEGIN DECLARE @pos smallint, @i smallint, @j smallint, @s varchar(8000) SET @pos = 1 WHILE @pos <= LEN(@text) BEGIN SET @i = CHARINDEX(' ', @text, @pos) SET @j = CHARINDEX(',', @text, @pos) IF @i > 0 OR @j > 0 BEGIN IF @i = 0 OR (@j > 0 AND @j < @i) SET @i = @j IF @i > @pos BEGIN -- @i now holds the earliest delimiter in the string SET @s = SUBSTRING(@text, @pos, @i - @pos) INSERT INTO @words VALUES (@pos, @s) END SET @pos = @i + 1 WHILE @pos < LEN(@text) AND SUBSTRING(@text, @pos, 1) IN (' ', ',') SET @pos = @pos + 1 END ELSE BEGIN INSERT INTO @words VALUES (@pos, SUBSTRING(@text, @pos, LEN(@text) - @pos + 1)) SET @pos = LEN(@text) + 1 END END RETURN END
================================================
有這個好用的函數後,之前的
----------------------------------------------------
declare @id as varchar(100)set @id='1,150,45,33'select * from table1 where table1.id in (@id)----------------------------------------------------改成:----------------------------------------------------declare @id as varchar(100)set @id='1,150,45,33'select * from table1 t1where t1.id in (select value from dbo.SplitWords(@id) )----------------------------------------------------怎樣,好用吧?
2013年11月12日 星期二
team foundation server 2010 初次見面(設定)
因為這次是有用不同的MSQQL instance,所以不是用預設的方式
開啟tfs configuration center,選用「Advanced」
開啟tfs configuration center,選用「Advanced」
第二步驟,選擇server instance,別忘了加入我們手動設定的instance
Account方面,用預設的 Local Service就可以了
Analysis service單元,老樣子,別忘了 sql server instance 全名要加上去,按"test"試過才可以哦
Report service方面,別忘了指定帳號,也要test一下卡保險:
Sharepoint service,請用內建的吧:
先看一下設定有沒有漏勾去:
好,最重要的一點,先verify(驗證看看再說,有錯誤一定要修正)
恭喜,都過了,那就Configue吧
如何create team project 呢?
裝好了,來到vs2012的開發介面,找一下小組->連接到Team foundation server
右邊就會出現 Team explorer功能區,點一下「連結」
這時,要加入我們剛才設定好的tfs2010 server
連上去,並選擇Team project collection.
目前只是連接到Team project collection,現在重點來了,要create team project
一樣是在Team Explorer功能表區,點一下插頭icon(連接到Team 專案),
看到下面的「新增Team 專案」了吧?點一下就可以定義team project了
沒意外的話,專案就新建完成了:
這時,再回到tfs server的Administration Console介面中,看一下「Team Project Collections」
看一下Team Proeject Collection下面的「Team Proejcts」就可以看到我們所create的Team Project了
以上,大家加油了
2013年10月31日 星期四
老生常談--MVC action result 如何輸出檔案?
基本上asp.net web form 方式的檔案下載大家應該很熟了
======例,在某列中找出下載的檔案資料===============
protected void DownloadDoc_Click(object sender, EventArgs e) {
ImageButton imageButton = (ImageButton)sender;
TableCell tableCell = (TableCell)imageButton.Parent;
GridViewRow row = (GridViewRow)tableCell.Parent;
;
//GridView1.SelectedIndex = row.RowIndex;
//doc path is found by the datakey attribute of grid and corresponding field/column
string docPath = GridView1.DataKeys[row.RowIndex]["DOC_PATH"].ToString();
//trigger the download process.
string filename = Path.GetFileName(docPath);
System.IO.Stream stream = null;
try
{
// Open the file into a stream.
stream = new FileStream(docPath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
// Total bytes to read:
long bytesToRead = stream.Length;
Response.ContentType = "application/octet-stream";
string fileExt = Path.GetExtension(docPath);
Response.AddHeader("Content-Disposition", "attachment; filename=" +
util.MisFunc.ConvertDateTimeToJavaMilliSecond(System.DateTime.Now) + fileExt);
// Read the bytes from the stream in small portions.
while (bytesToRead > 0)
{
// Make sure the client is still connected.
if (Response.IsClientConnected)
{
// Read the data into the buffer and write into the
// output stream.
byte[] buffer = new Byte[10000];
int length = stream.Read(buffer, 0, 10000);
Response.OutputStream.Write(buffer, 0, length);
Response.Flush();
// We have already read some bytes.. need to read
// only the remaining.
bytesToRead = bytesToRead - length;
}
else
{
// Get out of the loop, if user is not connected anymore..
bytesToRead = -1;
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
// An error occurred..
}
finally
{
if (stream != null)
{
stream.Close();
}
}
}
====================================================
那ASP.net MVC4呢?
==============MVC4的寫法更簡潔======================
using System.Net.Mime;
using System.IO;
string path = (string)recFile["DOC_PATH"];
var contentDisposition = new ContentDisposition
{
FileName = "doc.pdf",
Inline = true
};
Response.AppendHeader("Content-Disposition", contentDisposition.ToString());
byte[] bytes = System.IO.File.ReadAllBytes(path); //ReportStore.GetProfileInByte(path);
MemoryStream ms = new MemoryStream(bytes);
return new FileStreamResult(ms, MediaTypeNames.Application.Pdf);
}
================================================
======例,在某列中找出下載的檔案資料===============
protected void DownloadDoc_Click(object sender, EventArgs e) {
ImageButton imageButton = (ImageButton)sender;
TableCell tableCell = (TableCell)imageButton.Parent;
GridViewRow row = (GridViewRow)tableCell.Parent;
;
//GridView1.SelectedIndex = row.RowIndex;
//doc path is found by the datakey attribute of grid and corresponding field/column
string docPath = GridView1.DataKeys[row.RowIndex]["DOC_PATH"].ToString();
//trigger the download process.
string filename = Path.GetFileName(docPath);
System.IO.Stream stream = null;
try
{
// Open the file into a stream.
stream = new FileStream(docPath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
// Total bytes to read:
long bytesToRead = stream.Length;
Response.ContentType = "application/octet-stream";
string fileExt = Path.GetExtension(docPath);
Response.AddHeader("Content-Disposition", "attachment; filename=" +
util.MisFunc.ConvertDateTimeToJavaMilliSecond(System.DateTime.Now) + fileExt);
// Read the bytes from the stream in small portions.
while (bytesToRead > 0)
{
// Make sure the client is still connected.
if (Response.IsClientConnected)
{
// Read the data into the buffer and write into the
// output stream.
byte[] buffer = new Byte[10000];
int length = stream.Read(buffer, 0, 10000);
Response.OutputStream.Write(buffer, 0, length);
Response.Flush();
// We have already read some bytes.. need to read
// only the remaining.
bytesToRead = bytesToRead - length;
}
else
{
// Get out of the loop, if user is not connected anymore..
bytesToRead = -1;
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
// An error occurred..
}
finally
{
if (stream != null)
{
stream.Close();
}
}
}
====================================================
那ASP.net MVC4呢?
==============MVC4的寫法更簡潔======================
using System.Net.Mime;
using System.IO;
...
...
public FileStreamResult getPdfFile(string path) {string path = (string)recFile["DOC_PATH"];
var contentDisposition = new ContentDisposition
{
FileName = "doc.pdf",
Inline = true
};
Response.AppendHeader("Content-Disposition", contentDisposition.ToString());
byte[] bytes = System.IO.File.ReadAllBytes(path); //ReportStore.GetProfileInByte(path);
MemoryStream ms = new MemoryStream(bytes);
return new FileStreamResult(ms, MediaTypeNames.Application.Pdf);
}
================================================
2013年10月27日 星期日
for sencha-touch store 載入一堆空白的資料列!! 那會安爾!?
今天在實作下拉載入分頁的List時
(好吧,先分享一下最短的實作好了,也不過是從書上抄來的)
====sample as below=======================
Ext.Viewport.setMasked({xtype:'loadmask',message:'Loading Data....'});
var storeFiles=Ext.create('Ext.data.Store', {
autoDestroy:true,
model: 'TocMobile.model.FileMdl',
pageSize:4,
//storeId: 'Store4Files',
autoLoad:false,
proxy: {
type: 'ajax',
actionMethods: {
create: 'POST',
read: 'POST',
update: 'POST',
destroy: 'POST'
},
extraParams: {
icNo: icNo,
password: password
},
url: 'http://'+SERVER_IP+'/TocMobile/.....',
reader: {
type: 'json',
rootProperty: 'rows'
}
}
});
storeFiles.load(
function(){
Ext.Viewport.setMasked(false);
var fileTemplate=new Ext.XTemplate(
'<tpl for=".">',
'<div class="File2Download" >',
' <span class="icondownlaod" >',
' <img src="./Adobe_PDF_Icon.svg.png" width="40" height="40" />',
' </span>',
' <span class="UploadDate">{uploadDate}</span>',
' <br>',
' <span class="UploadDetail">{uploadRemark}</span>',
'</div>',
'</tpl>'
);
var list=Ext.create('Ext.List',{
store:storeFiles,
height:'100%',
itemTpl:fileTemplate,
plugins:[
{
xclass:'Ext.plugin.ListPaging',
autoPaging:true,
loadMoreText:'Next...'
}
],
emptyText:'No Data!!'
});
var pnlFileList= Ext.getCmp('PnlMain4FileListUnit');
pnlFileList.getComponent('lblFileListStatus').setHtml(" File Listing");
pnlFileList.getComponent('pnlListFiles').removeAll();
pnlFileList.getComponent('pnlListFiles').add(list);
}
);
(好吧,先分享一下最短的實作好了,也不過是從書上抄來的)
====sample as below=======================
Ext.Viewport.setMasked({xtype:'loadmask',message:'Loading Data....'});
var storeFiles=Ext.create('Ext.data.Store', {
autoDestroy:true,
model: 'TocMobile.model.FileMdl',
pageSize:4,
//storeId: 'Store4Files',
autoLoad:false,
proxy: {
type: 'ajax',
actionMethods: {
create: 'POST',
read: 'POST',
update: 'POST',
destroy: 'POST'
},
extraParams: {
icNo: icNo,
password: password
},
url: 'http://'+SERVER_IP+'/TocMobile/.....',
reader: {
type: 'json',
rootProperty: 'rows'
}
}
});
storeFiles.load(
function(){
Ext.Viewport.setMasked(false);
var fileTemplate=new Ext.XTemplate(
'<tpl for=".">',
'<div class="File2Download" >',
' <span class="icondownlaod" >',
' <img src="./Adobe_PDF_Icon.svg.png" width="40" height="40" />',
' </span>',
' <span class="UploadDate">{uploadDate}</span>',
' <br>',
' <span class="UploadDetail">{uploadRemark}</span>',
'</div>',
'</tpl>'
);
var list=Ext.create('Ext.List',{
store:storeFiles,
height:'100%',
itemTpl:fileTemplate,
plugins:[
{
xclass:'Ext.plugin.ListPaging',
autoPaging:true,
loadMoreText:'Next...'
}
],
emptyText:'No Data!!'
});
var pnlFileList= Ext.getCmp('PnlMain4FileListUnit');
pnlFileList.getComponent('lblFileListStatus').setHtml(" File Listing");
pnlFileList.getComponent('pnlListFiles').removeAll();
pnlFileList.getComponent('pnlListFiles').add(list);
}
);
============end of sample code============================
在測試時,卻一直發生load時來了5百多筆的空白資料!!!
明明別人的程式都正常的啊
John組長眉頭一皺,案情並不單純是client的問題
原來.....是出在server side沒事把資料列用「new JavaScriptSerializer().Serialize(...)」
變成「json內的字串格式」
==============以下是錯誤的,小心!!=================
List<File2Download> listfile=new List<File2Download>();
...
...
var result = new
{
success = true,
total=toalRowCount,
rows =new JavaScriptSerializer().Serialize(listfile)
};
JsonResult jResult = new JsonResult();
jResult.Data = result;
jResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return jResult;
==============================================
吐出來的字串就成了
"{"success":true,"total":30,"rows":[{\"uploadDate\":\"2013-08-29\",\"docPath\":\"test path\",\"uploadRemark\":\"test remark\"},...]}";
哎,既然是用「JsonResult」,就給他放心去轉換成字串就是了嘛
=======以下才是正確的==========================
List<File2Download> listfile=new List<File2Download>();
...
...
var result = new
{
success = true,
total=toalRowCount,
rows =listfile //--->就這樣,別手賤!!
};
JsonResult jResult = new JsonResult();
jResult.Data = result;
jResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return jResult;
=========================================
吐出來的就成了:
{"success":true,"total":30,"rows":[{"uploadDate":"2012-10-15","docPath":"test path","uploadRemark":"test remark"},...]}
神奇的是Sencha Touch 的store物件會解開那堆字變成文字的成為一堆空白資料列而且還不會給你出現exception/error才叫麻煩吧
Anyway,總之,別隨便用「JavaScriptSerializer().Serialize(...)」方法就是了
2013年10月20日 星期日
Android包html5網頁,用到定位權限時的設定
最近先用動態網頁寫好再用android / ios去包成app的開發方式頗為流行
所以順勢把之前的掌上商城andriod版一點一點地改成mobile web來包看看
不過光是在定位時發生問題.
WebView要如何使用Goelocation的權限呢?
步驟1,在 AndroidManifest.xml 指定以下權限:
======================================
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_ASSISTED_GPS" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
所以順勢把之前的掌上商城andriod版一點一點地改成mobile web來包看看
不過光是在定位時發生問題.
WebView要如何使用Goelocation的權限呢?
步驟1,在 AndroidManifest.xml 指定以下權限:
======================================
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_ASSISTED_GPS" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
=============================================
步驟二,在WebView的setting中設定以下權限:
(假設Activity中有個「mWebView.」WebView型態的變數)
=============================================
mWebView.getSettings().setGeolocationEnabled(true);
mWebView.getSettings().setAppCacheEnabled(true);
mWebView.getSettings().setDatabaseEnabled(true);
mWebView.getSettings().setDomStorageEnabled(true);
=============================================
步驟三,在遇到請求權限時,包裝的app如何應對?
===========================================
mWebView.setWebChromeClient(new WebChromeClient() {
public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
callback.invoke(origin, true, false);
}
});
=====================================
以上,其他的就照大家最常看到的webview應用來做了
2013年10月18日 星期五
好文轉貼使用ASP.NET SimpleMembership 提供者
最近有遇到asp.net MVC4.5的 權限整合問題:
原來的前後台版本是用WebMatrix/WebSecurity,
而如今前台要改版成為行動版,而VS2012的mobile的範本的membership機制是用「Universal Provider」,這下子麻煩大了
所幸,前人已經踢過鐵板了,參考這篇連結吧
使用ASP.NET SimpleMembership 提供者
以及
To call this method, the “Membership.Provider” property must be an instance of “ExtendedMembershipProvider”
另外,以下摘錄實作程序(真的是我實過也試過可以run)
步驟一,修改web.config,加入原本auth的db connection
=====================
<connectionStrings>
<add name="memberConnection" ........ providerName="System.Data.SqlClient" />
</connectionStrings>
步驟三,,安裝套件「WebMatrix.WebData」
步驟四,到Gloabal.aspx.cs的 Application_Start函數,加上webSecurity的起始設定
(當然這是基於你已經把role/user_profile...等其他資料表都開好的假設)
==========================
protected void Application_Start()
{
//memberConnection是我們在web.config中設定的connection string.
WebSecurity.InitializeDatabaseConnection("memberConnection", "StoreManager", "UserId", "UserName", autoCreateTables: true);
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
==========================
步驟五,修改model中,RegisterModel等其他model的欄位,有的非必要的就把他的[Required]拿掉
步驟六.修改Account Controller--基本上都不必改,唯一要改的是「新建用戶帳號」那段
因為實作是委託給WebSecurity,所以小改一下才會成功:
=======原本========================
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// 嘗試註冊使用者
MembershipCreateStatus createStatus;
Membership.CreateUser(model.UserName, model.Password, model.Email, passwordQuestion: null, passwordAnswer: null, isApproved: true, providerUserKey: null, status: out createStatus);
if (createStatus == MembershipCreateStatus.Success)
{
FormsAuthentication.SetAuthCookie(model.UserName, createPersistentCookie: false);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", ErrorCodeToString(createStatus));
}
}
// 如果執行到這裡,發生某項失敗,則重新顯示表單
return View(model);
}
==============改為==================================
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
try {
WebMatrix.WebData.WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
//自己再加入user & Role mapping table--「webpages_UsersInRoles」的inser動作吧...
FormsAuthentication.SetAuthCookie(model.UserName, createPersistentCookie: false);
return RedirectToAction("Index", "Home");
}catch(Exception exp)
{
ModelState.AddModelError("", exp.Message);
}
}
// 如果執行到這裡,發生某項失敗,則重新顯示表單
return View(model);
}
======================================================
其他登入/改變密碼都沒問題.這樣算是大功告成了!!
以上,誌於 2013.10.19
原來的前後台版本是用WebMatrix/WebSecurity,
而如今前台要改版成為行動版,而VS2012的mobile的範本的membership機制是用「Universal Provider」,這下子麻煩大了
所幸,前人已經踢過鐵板了,參考這篇連結吧
使用ASP.NET SimpleMembership 提供者
以及
To call this method, the “Membership.Provider” property must be an instance of “ExtendedMembershipProvider”
另外,以下摘錄實作程序(真的是我實過也試過可以run)
步驟一,修改web.config,加入原本auth的db connection
=====================
<connectionStrings>
<add name="memberConnection" ........ providerName="System.Data.SqlClient" />
</connectionStrings>
=====================
步驟二.在web.config中,把原本的
==========================
<profile defaultProvider="DefaultProfileProvider">
...
...
</roleManager>
==============================
改成以下的設定:
==============================================
<profile defaultProvider="SimpleProfileProvider">
<providers>
<add name="SimpleProfileProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" connectionStringName="DefaultConnection" applicationName="/" />
</providers>
</profile>
<membership defaultProvider="SimpleMembershipProvider">
<providers>
<add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
</providers>
</membership>
<roleManager defaultProvider="SimpleRoleProvider">
<providers>
<add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData" />
</providers>
</roleManager>
==============================================
步驟四,到Gloabal.aspx.cs的 Application_Start函數,加上webSecurity的起始設定
(當然這是基於你已經把role/user_profile...等其他資料表都開好的假設)
==========================
protected void Application_Start()
{
//memberConnection是我們在web.config中設定的connection string.
WebSecurity.InitializeDatabaseConnection("memberConnection", "StoreManager", "UserId", "UserName", autoCreateTables: true);
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
==========================
步驟五,修改model中,RegisterModel等其他model的欄位,有的非必要的就把他的[Required]拿掉
步驟六.修改Account Controller--基本上都不必改,唯一要改的是「新建用戶帳號」那段
因為實作是委託給WebSecurity,所以小改一下才會成功:
=======原本========================
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// 嘗試註冊使用者
MembershipCreateStatus createStatus;
Membership.CreateUser(model.UserName, model.Password, model.Email, passwordQuestion: null, passwordAnswer: null, isApproved: true, providerUserKey: null, status: out createStatus);
if (createStatus == MembershipCreateStatus.Success)
{
FormsAuthentication.SetAuthCookie(model.UserName, createPersistentCookie: false);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", ErrorCodeToString(createStatus));
}
}
// 如果執行到這裡,發生某項失敗,則重新顯示表單
return View(model);
}
==============改為==================================
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
try {
WebMatrix.WebData.WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
//自己再加入user & Role mapping table--「webpages_UsersInRoles」的inser動作吧...
FormsAuthentication.SetAuthCookie(model.UserName, createPersistentCookie: false);
return RedirectToAction("Index", "Home");
}catch(Exception exp)
{
ModelState.AddModelError("", exp.Message);
}
}
// 如果執行到這裡,發生某項失敗,則重新顯示表單
return View(model);
}
======================================================
其他登入/改變密碼都沒問題.這樣算是大功告成了!!
以上,誌於 2013.10.19
訂閱:
文章 (Atom)




















