Creating WebPart Page in feature activated event, sandbox solution
-
Sunday, August 05, 2012 7:04 PM
Hi All.
Im going to create new webpart page programmatically in feature activated event as sandbox solution. I have already created full trust proxy and some additional classes and methods. I've successfully deployed features(and they activated) and didnt get any errors, but no page was created as well. My code is next
1) This classes is included in FullTrustFeature wich is activated as farm solution.
namespace FullTrustProxy { [Serializable] public class FulltrustProxyServiceArgs : SPProxyOperationArgs { public static string StaticProxyOperationTypeName { get { return "FullTrustProxy.FullTrustProxyService"; } } public static string StaticProxyAssemblyName { get { return "FullTrustProxy, Version=1.0.0.0, Culture=neutral, PublicKeyToken=2dfe43bced7458f6"; } } public string ProxyOperationTypeName { get { return "FullTrustProxy.FullTrustProxyService"; } } public string ProxyAssemblyName { get { return "FullTrustProxy, Version=1.0.0.0, Culture=neutral, PublicKeyToken=2dfe43bced7458f6"; } } public SPFeatureReceiverProperties Properties { get; set; } /// <summary> /// Create Web Part Page /// </summary> /// <param name="web">SPWeb object</param> /// <param name="fileName">File name to create</param> public void CreateWebPartPage(SPWeb web, string fileName, string featureName) { string templateFilename = "spstd1.aspx"; string hive = SPUtility.GetGenericSetupPath("TEMPLATE\\" + SPContext.Current.Web.Language + "\\STS\\DOCTEMP\\SMARTPGS\\"); using (FileStream stream = new FileStream(hive + templateFilename, FileMode.Open)) { SPFolder libraryFolder = web.GetFolder("Site Pages"); SPFileCollection files = libraryFolder.Files; SPFile newFile = files.Add(fileName, stream); newFile.CheckIn(string.Format("File added by '{0}' feature", featureName), SPCheckinType.MajorCheckIn); newFile.Publish(string.Format("File published by '{0}' feature", featureName)); newFile.Approve(string.Format("File published by '{0}' feature", featureName)); } } } public static class Extensions { /// <summary> /// Gets the web. /// </summary> /// <param name="properties">The properties.</param> /// <returns></returns> public static SPWeb GetWeb(this SPFeatureReceiverProperties properties) { SPWeb site; if (properties.Feature.Parent is SPWeb) { site = (SPWeb)properties.Feature.Parent; } else if (properties.Feature.Parent is SPSite) { site = ((SPSite)properties.Feature.Parent).RootWeb; } else { throw new Exception("Unable to retrieve SPWeb - this feature is not Site or Web-scoped."); } return site; } } public class FullTrustProxyService : SPProxyOperation { // Uncomment the method below to handle the event raised after a feature has been activated. #region Public constant members /// <summary> /// define the name of file /// </summary> public const string PermissionManagementPage = "CustomWebPartPage1.aspx"; public const string PermissionManagementWebPartFileName = "CustomWebPart.webpart"; #endregion public override object Execute(SPProxyOperationArgs args) { var arguments = (FulltrustProxyServiceArgs)args; string featureName = "KinderGartenDefaultPageFeature"; SPWeb web = arguments.Properties.GetWeb(); try { arguments.CreateWebPartPage(web, PermissionManagementPage, featureName); } catch (Exception ex) { return ex.Message; } return "Success"; } } }2) Event receiver in Farm Solution wich will register Full trust proxy assembly
[Guid("550fdc91-38bd-4272-a6b7-8bdfef719476")] public class FullTrustProxyFeatureEventReceiver : SPFeatureReceiver { // Uncomment the method below to handle the event raised after a feature has been activated. public override void FeatureActivated(SPFeatureReceiverProperties properties) { SPUserCodeService userCodeService = SPUserCodeService.Local; var simpleOperation = new SPProxyOperationType( FulltrustProxyServiceArgs.StaticProxyAssemblyName, FulltrustProxyServiceArgs.StaticProxyOperationTypeName); userCodeService.ProxyOperationTypes.Add(simpleOperation); userCodeService.Update(); }
}
3) EventReceiver of sanbox solution which call proxy service and execute operation
Am I doing something wrong? Please advice me something dont know what to do else[Guid("6f0d5b5e-8b22-43df-9143-1fad29e9704c")] public class DefaultPageFeatureEventReceiver : SPFeatureReceiver { public override void FeatureActivated(SPFeatureReceiverProperties properties) { var proxyArgs = new FulltrustProxyServiceArgs(); proxyArgs.Properties = properties; var proxy = new FullTrustProxyService(); proxy.Execute(proxyArgs); // I've tried the code bellow but feature wasn't activated while deploing
//var result = SPUtility.ExecuteRegisteredProxyOperation( // proxyArgs.ProxyAssemblyName, // proxyArgs.ProxyOperationTypeName, // proxyArgs); }
- Edited by vitaliyalfa Sunday, August 05, 2012 7:46 PM
All Replies
-
Sunday, August 05, 2012 8:51 PM
Some additional info. If I use
var result = SPUtility.ExecuteRegisteredProxyOperation( proxyArgs.ProxyAssemblyName, proxyArgs.ProxyOperationTypeName, proxyArgs);to call proxy I get an error
Exception: Microsoft.SharePoint.UserCode.SPUserCodeSolutionExecutionFailedException: Unhandled exception was thrown by the sandboxed code wrapper's Execute method in the partial trust app domain: An unexpected error has occurred. ---> Microsoft.SharePoint.UserCode.SPUserCodeSolutionProxiedException: Type 'Microsoft.SharePoint.SPFeatureReceiverProperties' in Assembly 'Microsoft.SharePoint, Version=14.900.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' is not marked as serializable.
What do I need to serialize?
-
Monday, August 06, 2012 9:28 AM
Additional info
I commented some rows and previous error gone, but now when I use
var result = SPUtility.ExecuteRegisteredProxyOperation( proxyArgs.ProxyAssemblyName, proxyArgs.ProxyOperationTypeName, proxyArgs);to call execute method of full trust code. I get and error Microsoft.SharePoint.UserCode.SPUserCodeSolutionProxiedException: Could not load file or assembly 'FullTrustProxy, Version=1.0.0.0, Culture=neutral, PublicKeyToken=2dfe43bced7458f6' or one of its dependencies. The system cannot find the file specified.
Some logs
Solution Deployment : Installing to GAC - FullTrustProxy.dll
Leaving Monitored Scope (Feature Installation: Installing Feature 'FullTrustProxy_FullTrustProxyFeature' (ID: 'fb6c2293-f5ec-4d7c-b5ff-7e20aafde1ff') into the farm.). Execution Time=1.26074035293031
Entering monitored scope (Feature Installation: Installing Feature 'FullTrustProxy_FullTrustProxyFeature' (ID: 'fb6c2293-f5ec-4d7c-b5ff-7e20aafde1ff') into the farm.)
Leaving Monitored Scope (Feature Activation: Activating Feature 'FullTrustProxy_FullTrustProxyFeature' (ID: 'fb6c2293-f5ec-4d7c-b5ff-7e20aafde1ff').). Execution Time=231.179360044347
Leaving Monitored Scope (Feature Installation: Installing Feature 'KinderGartenDefaultPage_DefaultPageFeature' (ID: '76b75eef-01e4-4ed7-9c78-845ac1ae0a6c') into the farm.). Execution Time=269.934133534539
Leaving Monitored Scope (Feature Activation: Activating Feature 'KinderGartenDefaultPage_DefaultPageFeature' (ID: '76b75eef-01e4-4ed7-9c78-845ac1ae0a6c') at URL http://sharepoint:9090.). Execution Time=428.105078377629Feature Activation: Threw an exception, attempting to roll back. Feature 'KinderGartenDefaultPage_DefaultPageFeature' (ID: '76b75eef-01e4-4ed7-9c78-845ac1ae0a6c'). Exception: Microsoft.SharePoint.UserCode.SPUserCodeSolutionExecutionFailedException: Unhandled exception was thrown by the sandboxed code wrapper's Execute method in the partial trust app domain: File Not Found. ---> Microsoft.SharePoint.UserCode.SPUserCodeSolutionProxiedException: Could not load file or assembly 'FullTrustProxy, Version=1.0.0.0, Culture=neutral, PublicKeyToken=2dfe43bced7458f6' or one of its dependencies. The system cannot find the file specified. Server stack trace: at System.Reflection.Assembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection) at System.Reflection.Assembly.InternalLoad(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) at System.Reflection.Assembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) at System.Reflection.Assembly.Load(String assemblyString) at Microsoft.SharePoint.Utilities.SPUtility_SubsetProxy.ExecuteProxyOperation_Core(String assemblyName, String typeName, SPProxyOperationArgs args) at Microsoft.SharePoint.Utilities.SPUtility_SubsetProxy.ExecuteProxyOperation_Inner(String assemblyName, String typeName, SPProxyOperationArgs args) at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Int32 methodPtr, Boolean fExecuteInContext, Object[]& outArgs) at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg, Int32 methodPtr, Boolean fExecuteInContext) Exception rethrown at [0]: at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) at Microsoft.SharePoint.Utilities.SPUtility_SubsetProxy.s_ExecuteProxyOperation(String assemblyName, String typeName, SPProxyOperationArgs args) at Microsoft.SharePoint.Utilities.SPUtility.ExecuteRegisteredProxyOperation(String assemblyName, String typeName, SPProxyOperationArgs args) at KinderGartenDefaultPage.Features.DefaultPageFeature.DefaultPageFeatureEventReceiver.FeatureActivated(SPFeatureReceiverProperties properties) at Microsoft.SharePoint.UserCode.SPUserCodeFeatureCallOutWrapper.ExecuteInternal(Object userCodeObject, SPUserCodeRemoteExecutionContext context) at Microsoft.SharePoint.UserCode.SPUserCodeRemoteExecutionWrapper.Execute(SPUserCodeExecutionContext executionContext) at Microsoft.SharePoint.UserCode.SPUserCodeApplicationHostAppDomainRef.ExecuteWrapper(SPUserCodeWrapper wrapper, SPUserCodeExecutionContext executionContext) at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Int32 methodPtr, Boolean fExecuteInContext, Object[]& outArgs) at System.Runtime.Remoting.Messaging.StackBuilderSink.AsyncProcessMessage(IMessage msg, IMessageSink replySink) Exception rethrown at [1]: at System.Runtime.Remoting.Proxies.RealProxy.EndInvokeHelper(Message reqMsg, Boolean bProxyCase) at System.Runtime.Remoting.Proxies.RemotingProxy.Invoke(Object NotUsed, MessageData& msgData) at Microsoft.SharePoint.UserCode.SPUserCodeApplicationHostAppDomainRef.CodeToExecuteWrapper.EndInvoke(IAsyncResult result) at Microsoft.SharePoint.UserCode.SPUserCodeApplicationHostAppDomainRef.Execute(Type userCodeWrapperType, SPUserCodeCachedAssemblyGroup userAssemblyGroup, Guid siteCollectionId, Byte[] binaryUserCodeToken, Byte[] proxyOperationToken, SPUserCodeExecutionContext executionContext, Boolean shouldUsageLog, Int32 currentProcessId) --- End of inner exception stack trace --- Server stack trace: at Microsoft.SharePoint.UserCode.SPUserCodeApplicationHostAppDomainRef.Execute(Type userCodeWrapperType, SPUserCodeCachedAssemblyGroup userAssemblyGroup, Guid siteCollectionId, Byte[] binaryUserCodeToken, Byte[] proxyOperationToken, SPUserCodeExecutionContext executionContext, Boolean shouldUsageLog, Int32 currentProcessId) at Microsoft.SharePoint.UserCode.SPUserCodeApplicationHostAppDomainRef.Execute(Type userCodeWrapperType, SPUserCodeCachedAssemblyGroup userAssemblyGroup, Guid siteCollectionId, Byte[] binaryUserCodeToken, Byte[] proxyOperationToken, SPUserCodeExecutionContext executionContext, Boolean shouldUsageLog, Int32 currentProcessId) at Microsoft.SharePoint.UserCode.SPUserCodeAppDomain.Execute(Type userCodeWrapperType, SPUserCodeCachedAssemblyGroup userAssemblyGroup, Guid siteCollectionId, Byte[] binaryUserCodeToken, Byte[] proxyOperationToken, SPUserCodeExecutionContext executionContext, Boolean shouldUsageLog, Int32 currentProcessId) at Microsoft.SharePoint.UserCode.SPUserCodeWorkerProcessProxyForShim.ExecuteInternal(Type userCodeWrapperType, SPUserCodeCachedAssemblyGroup userAssemblyGroup, Guid siteCollectionId, Byte[] binaryUserCodeToken, Byte[] proxyOperationToken, SPUserCodeExecutionContext executionContext) at Microsoft.SharePoint.UserCode.SPUserCodeWorkerProcessProxy.Execute(Type userCodeWrapperType, SPUserCodeCachedAssemblyGroup userAssemblyGroup, Guid siteCollectionId, Byte[] binaryUserCodeToken, Byte[] proxyOperationToken, SPUserCodeExecutionContext executionContext) at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Int32 methodPtr, Boolean fExecuteInContext, Object[]& outArgs) at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg, Int32 methodPtr, Boolean fExecuteInContext) Exception rethrown at [0]: at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) at Microsoft.SharePoint.UserCode.SPUserCodeWorkerProcess.ExecuteDelegate.EndInvoke(IAsyncResult result) at Microsoft.SharePoint.UserCode.SPUserCodeWorkerProcess.Execute(Type userCodeWrapperType, SPUserCodeCachedAssemblyGroup userAssemblyGroup, Guid siteCollectionId, SPUserToken userToken, String currentAffinity, SPUserCodeExecutionContext executionContext) at Microsoft.SharePoint.UserCode.SPUserCodePoolableProcessConnection.Execute(Type userCodeWrapperType, SPUserCodeCachedAssemblyGroup userAssemblyGroup, Guid siteCollectionId, SPUserToken userToken, String affinity, SPUserCodeExecutionContext executionContext) at Microsoft.SharePoint.UserCode.SPUserCodeExecutionHost.Execute(Type userCodeWrapperType, Guid siteCollectionId, SPUserToken userToken, String affinity, SPUserCodeExecutionContext executionContext) at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Int32 methodPtr, Boolean fExecuteInContext, Object[]& outArgs) at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg, Int32 methodPtr, Boolean fExecuteInContext) Exception rethrown at [1]: at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) at Microsoft.SharePoint.Administration.ISPUserCodeExecutionHostProxy.Execute(Type userCodeWrapperType, Guid siteCollectionId, SPUserToken userToken, String affinityBucketName, SPUserCodeExecutionContext executionContext) at Microsoft.SharePoint.UserCode.SPUserCodeExecutionManager.Execute(Type userCodeWrapperType, SPSite site, SPUserCodeExecutionContext executionContext) at Microsoft.SharePoint.Administration.SPFeatureDefinition.<>c__DisplayClass1.<DoSPUserFeatureCallout>b__0() at Microsoft.SharePoint.Utilities.SecurityContext.RunAsProcess(CodeToRunElevated secureCode) at Microsoft.SharePoint.Administration.SPFeatureDefinition.DoSPUserFeatureCallout(SPSite site, SPWeb web, SPFeatureCallOutOperation operation, String solutionHash, String solutionValidatorHash, String solutionValidationErrorUrl, String solutionValidationErrorMessage, String customActionName, IDictionary`2 parameters) at Microsoft.SharePoint.SPFeature.DoActivationCallout(Boolean fActivate, Boolean fForce) at Microsoft.SharePoint.SPFeature.Activate(SPSite siteParent, SPWeb webParent, SPFeaturePropertyCollection props, Boolean fForce)
I dont know why, everything looks fine. Any Ideas?
- Edited by vitaliyalfa Monday, August 06, 2012 9:40 AM logs
-
Tuesday, August 07, 2012 2:08 PMI still need a sollution, can't solve myself
-
Tuesday, August 07, 2012 4:33 PM
In order to programmatically create a publishing page inside full-trust proxy of sandbox solution, you need spcontext to get to the right spsite and spweb etc. The spcontext is not available inside full-trust proxy operation class. Because sandbox proxies runs under spucworkerprocess.exe not the w3wp.exe.
http://msdn.microsoft.com/en-us/library/ff798433.aspx
You can pass a siteid to the proxy operation class and create spsite instance explicitly
Sundar Narasiman
- Edited by Sundar NarasimanMVP Tuesday, August 07, 2012 4:34 PM
-
Tuesday, August 07, 2012 10:08 PM
Thanks a lot for reply.
Ectually it was not spcontext problem. I went to GAC folder and found out that there is my asssebly, but with different Public Token Key. So I changed it and now get another error Microsoft.SharePoint.UserCode.SPUserCodeSolutionProxiedException: Object reference not set to an instance of an object. It can't run execute method on row
var result = SPUtility.ExecuteRegisteredProxyOperation( proxyArgs.ProxyAssemblyName, proxyArgs.ProxyOperationTypeName, proxyArgs);I comment all code on SPProxyOperation Execute method, does enyone know what the reason of it?
maybe tha assembly is not registered, how can I check?
-
Wednesday, August 08, 2012 6:58 AM
Ok. I checked if assembly is registered. It is. I write webpart wich shows me that
SPUserCodeService userCodeService = SPUserCodeService.Local; foreach (SPProxyOperationType item in userCodeService.ProxyOperationTypes) { Panel1.Controls.Add(new Label(){Text = "AssemblyName: " + item.AssemblyName + " TypeName: " + item.TypeName + " "}); }Some logs, maybe it helps
Microsoft.SharePoint.UserCode.SPUserCodeSolutionProxiedException: Object reference not set to an instance of an object. Server stack trace: at FullTrustCode.FullTrustCodeProxyService.Execute(SPProxyOperationArgs args) at Microsoft.SharePoint.Utilities.SPUtility_SubsetProxy.ExecuteProxyOperation_Core(String assemblyName, String typeName, SPProxyOperationArgs args) at Microsoft.SharePoint.Utilities.SPUtility_SubsetProxy.ExecuteProxyOperation_Inner(String assemblyName, String typeName, SPProxyOperationArgs args) at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Int32 methodPtr, Boolean fExecuteInContext, Object[]& outArgs) at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg, Int32 methodPtr, Boolean fExecuteInContext) Exception rethrown at [0]: at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) at Microsoft.SharePoint.Utilities.SPUtility_SubsetProxy.s_ExecuteProxyOperation(String assemblyName, String typeName, SPProxyOperationArgs args) at Microsoft.SharePoint.Utilities.SPUtility.ExecuteRegisteredProxyOperation(String assemblyName, String typeName, SPProxyOperationArgs args) at KinderGartenDefaultPage.Features.DefaultPageFeature.DefaultPageFeatureEventReceiver.FeatureActivated(SPFeatureReceiverProperties properties) at Microsoft.SharePoint.UserCode.SPUserCodeFeatureCallOutWrapper.ExecuteInternal(Object userCodeObject, SPUserCodeRemoteExecutionContext context) at Microsoft.SharePoint.UserCode.SPUserCodeRemoteExecutionWrapper.Execute(SPUserCodeExecutionContext executionContext) at Microsoft.SharePoint.UserCode.SPUserCodeApplicationHostAppDomainRef.ExecuteWrapper(SPUserCodeWrapper wrapper, SPUserCodeExecutionContext executionContext) at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Int32 methodPtr, Boolean fExecuteInContext, Object[]& outArgs) at System.Runtime.Remoting.Messaging.StackBuilderSink.AsyncProcessMessage(IMessage msg, IMessageSink replySink) Exception rethrown at [1]: at System.Runtime.Remoting.Proxies.RealProxy.EndInvokeHelper(Message reqMsg, Boolean bProxyCase) at System.Runtime.Remoting.Proxies.RemotingProxy.Invoke(Object NotUsed, MessageData& msgData) at Microsoft.SharePoint.UserCode.SPUserCodeApplicationHostAppDomainRef.CodeToExecuteWrapper.EndInvoke(IAsyncResult result) at Microsoft.SharePoint.UserCode.SPUserCodeApplicationHostAppDomainRef.Execute(Type userCodeWrapperType, SPUserCodeCachedAssemblyGroup userAssemblyGroup, Guid siteCollectionId, Byte[] binaryUserCodeToken, Byte[] proxyOperationToken, SPUserCodeExecutionContext executionContext, Boolean shouldUsageLog, Int32 currentProcessId)
-
Wednesday, August 08, 2012 3:07 PM
You can place breakpoint in the code-behind, attach the debugger to SPUCWorkerProcessProxy.exe and hit F5. This will help you to debug and figure out what's exactly going on
Sundar Narasiman
- Marked As Answer by Lhan HanModerator Thursday, August 16, 2012 3:14 AM

