今天终于把Clone Entity的代码写完了。可能还有一些问题。主要是不能一些栏位的值后续的栏位可能用不上.
技术关键点:
1.__doPostBack('<%this.Button1.ClientID%>','')实现开启页面以后自动点击按钮的功能。
2.MS Crm是用SQL2005对.net framework 3.5的功能有一些并不好.UpdatePanel没有用上。所以没有动画效果.
3.终于知道怎么只编译单一的网页,还有就是发布时会删除发布目录内的内容。要小心一些.
4.javascript执行时机会慢于Page_Load,不知道window.onload是在什么时机调用的.会先于Page_Load还是后于window.onload.
5.我是在Page_Load时注册一段script来实现我在window.onload要执行的代码。才实现自动点击按钮的功能.
6.问个问题就是MS如何实现动态加载网页的。尤其是他的变量和javascript那部分还是不太理解。可能还是要看一下.本来我还想模仿一个MS的办法,但最终还是放弃了.
7.取父窗口内容的代码还是比较有用的应该要记下来,留备下次使用.
8.Callback还没有试出来,要试试Callback Events的网页的用法.
附一部分代码.
Code
<script language='javascript' type="text/javascript">
var IS_PATHBASEDURLS = false;
</script>
<script type="text/javascript" src="/_static/_common/scripts/global.js"></script>
<script language='javascript' type="text/javascript">
var _isInitialLoad = true;
function getParentDocument()
{
if (
(window.opener != null) &&
(window.opener.parent != null) &&
(window.opener.parent.document != null)
) {
//This is the parent form
var parentDoc = window.opener.document;
return parentDoc ;
}
}
function getSelectedOpportunityId()
{
var parentForm=getParentDocument ();
if (parentForm ==null)
return null;
// get array of selected records
var a = parentForm.all['crmGrid'].InnerGrid.SelectedRecords;
var selectedItems = new Array(a.length);
for (var i=0; i < a.length; i++)
{
selectedItems = a[0];
}
var oId = selectedItems[0];
return oId ;
}
function pageLoad(sender, args)
{
if(_isInitialLoad)
{
_isInitialLoad = false;
var oId=getSelectedOpportunityId();
if (oId ==null)
oId ="{2ED292E9-2DB2-DD11-9109-002215572EEF}";
var buton=document.getElementById ("txtFormId");
buton.value=oId ;
// simulate a button click by forcing the postback
// causing the updatepanel to update
__doPostBack('<%= this.Button1.ClientID %>','');
}
function LookUpStock()
{
var oId=getSelectedOpportunityId();
if (oId ==null)
oId ="{2ED292E9-2DB2-DD11-9109-002215572EEF}";
var buton=document.getElementById ("txtFormId");
buton.value=oId ;
CallServer(oId,null);
//__doPostBack('<%= this.Button1.ClientID %>','');
}
function ReceiveServerData(rValue)
{
//document.getElementById("ResultsSpan").innerHTML = rValue;
}
}
</script>
<script language='javascript' type="text/javascript">
var IS_PATHBASEDURLS = false;
</script>
<script type="text/javascript" src="/_static/_common/scripts/global.js"></script>
<script language='javascript' type="text/javascript">
var _isInitialLoad = true;
function getParentDocument()
{
if (
(window.opener != null) &&
(window.opener.parent != null) &&
(window.opener.parent.document != null)
) {
//This is the parent form
var parentDoc = window.opener.document;
return parentDoc ;
}
}
function getSelectedOpportunityId()
{
var parentForm=getParentDocument ();
if (parentForm ==null)
return null;
// get array of selected records
var a = parentForm.all['crmGrid'].InnerGrid.SelectedRecords;
var selectedItems = new Array(a.length);
for (var i=0; i < a.length; i++)
{
selectedItems = a[0];
}
var oId = selectedItems[0];
return oId ;
}
function pageLoad(sender, args)
{
if(_isInitialLoad)
{
_isInitialLoad = false;
var oId=getSelectedOpportunityId();
if (oId ==null)
oId ="{2ED292E9-2DB2-DD11-9109-002215572EEF}";
var buton=document.getElementById ("txtFormId");
buton.value=oId ;
// simulate a button click by forcing the postback
// causing the updatepanel to update
__doPostBack('<%= this.Button1.ClientID %>','');
}
function LookUpStock()
{
var oId=getSelectedOpportunityId();
if (oId ==null)
oId ="{2ED292E9-2DB2-DD11-9109-002215572EEF}";
var buton=document.getElementById ("txtFormId");
buton.value=oId ;
CallServer(oId,null);
//__doPostBack('<%= this.Button1.ClientID %>','');
}
function ReceiveServerData(rValue)
{
//document.getElementById("ResultsSpan").innerHTML = rValue;
}
}
</script>
刚才代码贴错了。修改一下
Code
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.Sdk.Query;
using Microsoft.Crm.SdkTypeProxy;
using Microsoft.Win32;
public partial class CloneOpportunityProduct : System.Web.UI.Page,ICallbackEventHandler
{
private CrmService _service = null;
private bool offline = false;
private Guid callerId = Guid.Empty;
private bool bIsIFD = false;
public string orgname;
public string crmurl;
public string metaurl;
private string strNewId="";
protected void WriteJs(string jsContent)
{
this.Page.RegisterStartupScript("writejs", "<script type='text/javascript'>" + jsContent + "</script>");
}
protected void Page_Load(object sender, EventArgs e)
{
//Trigger Postback On Hidden Button To Show Progress Box
if(!Page.IsPostBack)
{
String cbReference =
Page.ClientScript.GetCallbackEventReference(this,
"arg", "ReceiveServerData", "context");
String callbackScript;
callbackScript = "function CallServer(arg, context)" +
"{ " + cbReference + ";}";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
"CallServer", callbackScript, true);
WriteJs("window.attachEvent('onload', pageLoad);");
}
}
public void RaiseCallbackEvent(String eventArgument)
{
string strId = "";
//String sEventArguments = this.Request.Params["__EVENTARGUMENT"];
strId = eventArgument;
//if (sEventArguments != null)
//{
// Int32 iDelimiter = sEventArguments.IndexOf('$');
// String sArgument = sEventArguments.Substring(iDelimiter + 1);
//}
//Parse Query String Variables
if (strId.Length > 0)
{
//Guid _entityid = new Guid(Request["id"].ToString());
strNewId=CloneOpportunity(strId);
}
}
public String GetCallbackResult()
{
return strNewId;
}
protected void Button1_Click(object sender, EventArgs e)
{
string strId="" ;
//String sEventArguments = this.Request.Params["__EVENTARGUMENT"];
strId = this.txtFormId.Value;
//if (sEventArguments != null)
//{
// Int32 iDelimiter = sEventArguments.IndexOf('$');
// String sArgument = sEventArguments.Substring(iDelimiter + 1);
//}
//Parse Query String Variables
if(strId.Length > 0)
{
//Guid _entityid = new Guid(Request["id"].ToString());
strNewId=CloneOpportunity(strId);
WriteJs(@"window.open('/"+(bIsIFD ? "": orgname +"/") +"sfa/opps/edit.aspx?id=" + strNewId + "','','menubar=0, status=1, width=1000, height=600'); close();");
}
}
public string CloneOpportunity(string strId)
{
if (strId == "")
return "Old opportunity is nothing";
InitOrgAndUrl();
using (new CrmImpersonator())
{
CrmAuthenticationToken token;
if (offline == true)
{
token = new CrmAuthenticationToken();
}
else
{
token = CrmAuthenticationToken.ExtractCrmAuthenticationToken(Context, orgname);
callerId = token.CallerId;
}
token = new CrmAuthenticationToken();
token.OrganizationName = orgname ;
token.AuthenticationType = 0;
//Create the Service
//CrmService service = new CrmService();
_service = new CrmService();
_service.Credentials = System.Net.CredentialCache.DefaultCredentials;
_service.CrmAuthenticationTokenValue = token;
_service.Url = crmurl;
Guid Guid_opportunityId = CreateOpportunity(strId);
CreateOpportunityProduct(strId, Guid_opportunityId.ToString());
// This code shows how to create the metadata service.
// It is not used in this sample.
// MetadataService meta = new MetadataService();
// meta.CrmAuthenticationTokenValue = token;
// meta.Credentials = CredentialCache.DefaultCredentials;
// meta.Url = "http://localhost/mscrmservices/2007/MetadataService.asmx";
//account account = new account();
//account.name = "Offline Impersonator: " + DateTime.Now.TimeOfDay.ToString();
//if (offline == false)
// // Explicitly set the owner ID for the record if not offline.
// account.ownerid = new Owner("systemuser", token.CallerId);
//service.Create(account);
return Guid_opportunityId.ToString();
}
}
public Guid CreateOpportunity(string strId)
{
DynamicEntity dy = RetriveDynamic(EntityName.opportunity.ToString(), null, new Guid(strId));
if (dy == null)
throw new Exception("Not found opportunity:" + strId);
dy.Properties.Remove("opportunityid");
if (offline == false)
{
//dy.Properties["ownerid"] = new Owner("systemuser", callerId);
// dy["createdby"] = new Owner("systemuser", callerId);
}
return _service.Create(dy);
}
private void CreateOpportunityProduct(string strOldOpportunityId, string strNewOpportunityId)
{
QueryByAttribute query = new QueryByAttribute();
RetrieveMultipleRequest rmr = new RetrieveMultipleRequest();
query.EntityName = EntityName.opportunityproduct.ToString();
query.ColumnSet = new AllColumns();
query.Attributes = new string[] { "opportunityid" };
query.Values = new string[] { strOldOpportunityId };
rmr.Query = query;
rmr.ReturnDynamicEntities = true;
RetrieveMultipleResponse response = (RetrieveMultipleResponse)_service.Execute(rmr);
if (response.BusinessEntityCollection.BusinessEntities.Count > 0)
{
foreach (DynamicEntity dy in response.BusinessEntityCollection.BusinessEntities)
{
dy.Properties.Remove("opportunityproductid");
if (offline == false)
{
//dy.Properties["ownerid"] = new Owner("systemuser", callerId);
//dy["createdby"] = new Owner("systemuser", callerId);
}
Lookup lookupOpportunity = new Lookup(EntityName.opportunity.ToString(), new Guid(strNewOpportunityId));
dy["opportunityid"] = lookupOpportunity;
_service.Create(dy);
}
}
}
private DynamicEntity RetriveDynamic(string entityName, string stringFields, Guid entityId)
{
TargetRetrieveDynamic trd = new TargetRetrieveDynamic();
RetrieveRequest rr = new RetrieveRequest();
trd.EntityId = entityId;
trd.EntityName = entityName.ToLower();
if (stringFields == null)
{
AllColumns ac = new AllColumns();
rr.ColumnSet = ac;
}
else
{
ColumnSet cs = new ColumnSet();
cs.AddColumns(stringFields.Split(','));
rr.ColumnSet = cs;
}
rr.Target = trd;
rr.ReturnDynamicEntities = true;
RetrieveResponse dy = (RetrieveResponse)_service.Execute(rr);
return (DynamicEntity)dy.BusinessEntity;
}
private void InitOrgAndUrl()
{
//Page.RegisterStartupScript("startup", "<script type='text/javascript'>initFormValues();</script>");
#region CRM URLs and Organization Name
if (Request.Url.Host.ToString() == "127.0.0.1")
{
offline = true;
//Retrieve the Port and OrgName from the Registry
RegistryKey regkey = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\MSCRMClient");
orgname = regkey.GetValue("ClientAuthOrganizationName").ToString();
string portnumber = regkey.GetValue("CassiniPort").ToString();
//Construct the URLs
string baseurl = "http://localhost:" + portnumber + "/mscrmservices/2007/";
crmurl = baseurl + "crmservice.asmx";
metaurl = baseurl + "metadataservice.asmx";
}
else
{
offline = false;
//Retrieve the URLs from the Registry
RegistryKey regkey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\MSCRM");
string ServerUrl = regkey.GetValue("ServerUrl").ToString();
crmurl = ServerUrl + "/2007/crmservice.asmx";
metaurl = ServerUrl + "/2007/metadataservice.asmx";
//Retrieve the Query String from the current URL
if (Request.QueryString["orgname"] == null)
{
orgname = string.Empty;
}
else
{
//Query String
string orgquerystring = Request.QueryString["orgname"].ToString();
if (string.IsNullOrEmpty(orgquerystring))
{
orgname = string.Empty;
}
else
{
orgname = orgquerystring;
}
}
string preUrl = Request.UrlReferrer.Host.ToLower();
int preUrlstart = preUrl.IndexOf("://") + 3;
int preOrgNameLen=preUrl.IndexOf(".") - preUrlstart;
if (preOrgNameLen<=0)
{
bIsIFD=false ;
}
else
{
string preUrlorgname = preUrl.Substring(preUrlstart, preOrgNameLen);
if (string.IsNullOrEmpty(preUrlorgname))
{
bIsIFD = false;
}else
{
bIsIFD =true;
}
}
if (string.IsNullOrEmpty(orgname))
{
//Windows Auth URL
if (Request.Url.Segments[2].TrimEnd('/').ToLower() == "isv")
{
orgname = Request.Url.Segments[1].TrimEnd('/').ToLower();
}
//IFD URL
if (string.IsNullOrEmpty(orgname))
{
string url = Request.Url.ToString().ToLower();
int start = url.IndexOf("://") + 3;
orgname = url.Substring(start, url.IndexOf(".") - start);
}
}
}
#endregion
}
private string SetLinkButtonProperties(string id,string name,string org)
{
string path = "http://www.cnblogs.com/../";
switch(name)
{
case "account":
path += org + "/sfa/accts/edit.aspx?id=" + id;
break;
case "contact":
path += "/sfa/conts/edit.aspx?id=" + id;
break;
case "opportunity":
path += "/sfa/conts/edit.aspx?id=" +id;
break;
case "lead":
path += "/sfa/lead/edit.aspx?id=" + id;
break;
case "incident":
path += "/cs/cases/edit.aspx?id=" + id;
break;
default:
path += "/userdefined/edit.aspx?id=" + id + "&etn=" + name;
break;
}
return path;
}
}
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.Sdk.Query;
using Microsoft.Crm.SdkTypeProxy;
using Microsoft.Win32;
public partial class CloneOpportunityProduct : System.Web.UI.Page,ICallbackEventHandler
{
private CrmService _service = null;
private bool offline = false;
private Guid callerId = Guid.Empty;
private bool bIsIFD = false;
public string orgname;
public string crmurl;
public string metaurl;
private string strNewId="";
protected void WriteJs(string jsContent)
{
this.Page.RegisterStartupScript("writejs", "<script type='text/javascript'>" + jsContent + "</script>");
}
protected void Page_Load(object sender, EventArgs e)
{
//Trigger Postback On Hidden Button To Show Progress Box
if(!Page.IsPostBack)
{
String cbReference =
Page.ClientScript.GetCallbackEventReference(this,
"arg", "ReceiveServerData", "context");
String callbackScript;
callbackScript = "function CallServer(arg, context)" +
"{ " + cbReference + ";}";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
"CallServer", callbackScript, true);
WriteJs("window.attachEvent('onload', pageLoad);");
}
}
public void RaiseCallbackEvent(String eventArgument)
{
string strId = "";
//String sEventArguments = this.Request.Params["__EVENTARGUMENT"];
strId = eventArgument;
//if (sEventArguments != null)
//{
// Int32 iDelimiter = sEventArguments.IndexOf('$');
// String sArgument = sEventArguments.Substring(iDelimiter + 1);
//}
//Parse Query String Variables
if (strId.Length > 0)
{
//Guid _entityid = new Guid(Request["id"].ToString());
strNewId=CloneOpportunity(strId);
}
}
public String GetCallbackResult()
{
return strNewId;
}
protected void Button1_Click(object sender, EventArgs e)
{
string strId="" ;
//String sEventArguments = this.Request.Params["__EVENTARGUMENT"];
strId = this.txtFormId.Value;
//if (sEventArguments != null)
//{
// Int32 iDelimiter = sEventArguments.IndexOf('$');
// String sArgument = sEventArguments.Substring(iDelimiter + 1);
//}
//Parse Query String Variables
if(strId.Length > 0)
{
//Guid _entityid = new Guid(Request["id"].ToString());
strNewId=CloneOpportunity(strId);
WriteJs(@"window.open('/"+(bIsIFD ? "": orgname +"/") +"sfa/opps/edit.aspx?id=" + strNewId + "','','menubar=0, status=1, width=1000, height=600'); close();");
}
}
public string CloneOpportunity(string strId)
{
if (strId == "")
return "Old opportunity is nothing";
InitOrgAndUrl();
using (new CrmImpersonator())
{
CrmAuthenticationToken token;
if (offline == true)
{
token = new CrmAuthenticationToken();
}
else
{
token = CrmAuthenticationToken.ExtractCrmAuthenticationToken(Context, orgname);
callerId = token.CallerId;
}
token = new CrmAuthenticationToken();
token.OrganizationName = orgname ;
token.AuthenticationType = 0;
//Create the Service
//CrmService service = new CrmService();
_service = new CrmService();
_service.Credentials = System.Net.CredentialCache.DefaultCredentials;
_service.CrmAuthenticationTokenValue = token;
_service.Url = crmurl;
Guid Guid_opportunityId = CreateOpportunity(strId);
CreateOpportunityProduct(strId, Guid_opportunityId.ToString());
// This code shows how to create the metadata service.
// It is not used in this sample.
// MetadataService meta = new MetadataService();
// meta.CrmAuthenticationTokenValue = token;
// meta.Credentials = CredentialCache.DefaultCredentials;
// meta.Url = "http://localhost/mscrmservices/2007/MetadataService.asmx";
//account account = new account();
//account.name = "Offline Impersonator: " + DateTime.Now.TimeOfDay.ToString();
//if (offline == false)
// // Explicitly set the owner ID for the record if not offline.
// account.ownerid = new Owner("systemuser", token.CallerId);
//service.Create(account);
return Guid_opportunityId.ToString();
}
}
public Guid CreateOpportunity(string strId)
{
DynamicEntity dy = RetriveDynamic(EntityName.opportunity.ToString(), null, new Guid(strId));
if (dy == null)
throw new Exception("Not found opportunity:" + strId);
dy.Properties.Remove("opportunityid");
if (offline == false)
{
//dy.Properties["ownerid"] = new Owner("systemuser", callerId);
// dy["createdby"] = new Owner("systemuser", callerId);
}
return _service.Create(dy);
}
private void CreateOpportunityProduct(string strOldOpportunityId, string strNewOpportunityId)
{
QueryByAttribute query = new QueryByAttribute();
RetrieveMultipleRequest rmr = new RetrieveMultipleRequest();
query.EntityName = EntityName.opportunityproduct.ToString();
query.ColumnSet = new AllColumns();
query.Attributes = new string[] { "opportunityid" };
query.Values = new string[] { strOldOpportunityId };
rmr.Query = query;
rmr.ReturnDynamicEntities = true;
RetrieveMultipleResponse response = (RetrieveMultipleResponse)_service.Execute(rmr);
if (response.BusinessEntityCollection.BusinessEntities.Count > 0)
{
foreach (DynamicEntity dy in response.BusinessEntityCollection.BusinessEntities)
{
dy.Properties.Remove("opportunityproductid");
if (offline == false)
{
//dy.Properties["ownerid"] = new Owner("systemuser", callerId);
//dy["createdby"] = new Owner("systemuser", callerId);
}
Lookup lookupOpportunity = new Lookup(EntityName.opportunity.ToString(), new Guid(strNewOpportunityId));
dy["opportunityid"] = lookupOpportunity;
_service.Create(dy);
}
}
}
private DynamicEntity RetriveDynamic(string entityName, string stringFields, Guid entityId)
{
TargetRetrieveDynamic trd = new TargetRetrieveDynamic();
RetrieveRequest rr = new RetrieveRequest();
trd.EntityId = entityId;
trd.EntityName = entityName.ToLower();
if (stringFields == null)
{
AllColumns ac = new AllColumns();
rr.ColumnSet = ac;
}
else
{
ColumnSet cs = new ColumnSet();
cs.AddColumns(stringFields.Split(','));
rr.ColumnSet = cs;
}
rr.Target = trd;
rr.ReturnDynamicEntities = true;
RetrieveResponse dy = (RetrieveResponse)_service.Execute(rr);
return (DynamicEntity)dy.BusinessEntity;
}
private void InitOrgAndUrl()
{
//Page.RegisterStartupScript("startup", "<script type='text/javascript'>initFormValues();</script>");
#region CRM URLs and Organization Name
if (Request.Url.Host.ToString() == "127.0.0.1")
{
offline = true;
//Retrieve the Port and OrgName from the Registry
RegistryKey regkey = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\MSCRMClient");
orgname = regkey.GetValue("ClientAuthOrganizationName").ToString();
string portnumber = regkey.GetValue("CassiniPort").ToString();
//Construct the URLs
string baseurl = "http://localhost:" + portnumber + "/mscrmservices/2007/";
crmurl = baseurl + "crmservice.asmx";
metaurl = baseurl + "metadataservice.asmx";
}
else
{
offline = false;
//Retrieve the URLs from the Registry
RegistryKey regkey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\MSCRM");
string ServerUrl = regkey.GetValue("ServerUrl").ToString();
crmurl = ServerUrl + "/2007/crmservice.asmx";
metaurl = ServerUrl + "/2007/metadataservice.asmx";
//Retrieve the Query String from the current URL
if (Request.QueryString["orgname"] == null)
{
orgname = string.Empty;
}
else
{
//Query String
string orgquerystring = Request.QueryString["orgname"].ToString();
if (string.IsNullOrEmpty(orgquerystring))
{
orgname = string.Empty;
}
else
{
orgname = orgquerystring;
}
}
string preUrl = Request.UrlReferrer.Host.ToLower();
int preUrlstart = preUrl.IndexOf("://") + 3;
int preOrgNameLen=preUrl.IndexOf(".") - preUrlstart;
if (preOrgNameLen<=0)
{
bIsIFD=false ;
}
else
{
string preUrlorgname = preUrl.Substring(preUrlstart, preOrgNameLen);
if (string.IsNullOrEmpty(preUrlorgname))
{
bIsIFD = false;
}else
{
bIsIFD =true;
}
}
if (string.IsNullOrEmpty(orgname))
{
//Windows Auth URL
if (Request.Url.Segments[2].TrimEnd('/').ToLower() == "isv")
{
orgname = Request.Url.Segments[1].TrimEnd('/').ToLower();
}
//IFD URL
if (string.IsNullOrEmpty(orgname))
{
string url = Request.Url.ToString().ToLower();
int start = url.IndexOf("://") + 3;
orgname = url.Substring(start, url.IndexOf(".") - start);
}
}
}
#endregion
}
private string SetLinkButtonProperties(string id,string name,string org)
{
string path = "http://www.cnblogs.com/../";
switch(name)
{
case "account":
path += org + "/sfa/accts/edit.aspx?id=" + id;
break;
case "contact":
path += "/sfa/conts/edit.aspx?id=" + id;
break;
case "opportunity":
path += "/sfa/conts/edit.aspx?id=" +id;
break;
case "lead":
path += "/sfa/lead/edit.aspx?id=" + id;
break;
case "incident":
path += "/cs/cases/edit.aspx?id=" + id;
break;
default:
path += "/userdefined/edit.aspx?id=" + id + "&etn=" + name;
break;
}
return path;
}
}