Installing a .net 2008 windows service - windows

I just created a simple test Windows Service and am having trouble. I'm new to Windows Services so I don't know if I'm even doing this right.
namespace testWindowsService
{
public partial class Service1 : ServiceBase
{
public Service1()
{InitializeComponent();}
protected override void OnStart(string[] args)
{
FileStream fs = new FileStream(#"c:\temp\started.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter m_streamWriter = new StreamWriter(fs);
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.WriteLine("Service Started on \n" + DateTime.Now.ToShortDateString() + " at " + DateTime.Now.ToShortTimeString());
m_streamWriter.Flush();
m_streamWriter.Close();
}
protected override void OnStop()
{
FileStream fs = new FileStream(#"c:\temp\stopped.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter m_streamWriter = new StreamWriter(fs);
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.WriteLine("Service Stopped \n" + DateTime.Now.ToShortDateString() + " at " + DateTime.Now.ToShortTimeString());
m_streamWriter.Flush();
m_streamWriter.Close();
}
}
}
Then I built the project and opened Command Prompt from Start -> All Programs -> Microsoft Visual Studio 2008 -> Visual Studio Tools -> Visual Studio 2008 Command Prompt. From the prompt I ran:
installutil C:\Users\myUser\Documents\MyServices\testWindowsService\testWindowsService\bin\Debug\testWindowsService.exe
But I get the error:
No public installers with the RunInstallerAttribute.Yes attribute could be found in the C:\Users\myUser\Documents\MyServices\testWindowsService\testWindowsService\bin\Debug\testWindowsService.exe assembly.
I've tried googling it but found a lot of dead ends and half answers.
Thank you

You need a create an installer. Have a read through these articles to see an example. In particular:
[RunInstallerAttribute(true)]
public class ProjectInstaller : Installer{
private ServiceInstaller serviceInstaller1;
private ServiceProcessInstaller processInstaller;
public MyProjectInstaller(){
// Instantiate installers for process and services.
processInstaller = new ServiceProcessInstaller();
serviceInstaller1 = new ServiceInstaller();
// The services run under the system account.
processInstaller.Account = ServiceAccount.LocalSystem;
// The services are started manually.
serviceInstaller1.StartType = ServiceStartMode.Manual;
serviceInstaller2.StartType = ServiceStartMode.Manual;
// ServiceName must equal those on ServiceBase derived classes.
serviceInstaller1.ServiceName = "Hello-World Service 1";
// Add installers to collection. Order is not important.
Installers.Add(serviceInstaller1);
Installers.Add(processInstaller);
}
}
You can quite easily add an installer class to your project in VS2008, it appears as an item type when adding a new item.

Related

How to unit test Azure Functions in Visual Studio

I am using Visual Studio to create Azure Functions. I can create, publish and run functions manually. If I set my Function project to Start Up and run, I host starts. How do I get the Host to start when using MSTest ?
I want to write a test using RestSharp and invoke the functions during the tests - the way the actual applicaion will work. It seems I need a way to get MSTest to start the Azure Function Host.
I was hoping to find an approach similar to debugging Asp.Net/SOAP in older versions of VS where the MSTest engine would start the IISExpress and attach VS to the Asp.Net projects. Edit and continue was supported.
I have worked out the following approaches, so far:
RestSharp Code:
var url = $"http://localhost:7071/api";
var functionKey = "this value is ignored by 'Azure Functions Core Tools' ";
var client = new RestSharp.RestClient(url);
var request = new RestSharp.RestRequest("GetConnectionString", RestSharp.Method.POST);
request.AddHeader("x-functions-key", functionKey);
var response = client.Execute<string>(request);
Option 1:
Run 2nd instance of VS and run the Functions.
Update code to reflect url paths displayed by Azure Functions Core Tools.
Edit and continue works.
Option 2:
Add this class to UnitTest project:
Attach to func.exe process to debug functions
Edit and continue do not work.
[TestClass]
public class Initializer
{
static System.Diagnostics.Process process { get; set; }
[AssemblyInitialize]
public static void Initialize(TestContext context)
{
//process does not use the WorkingDirectory properly with %userprofile%
var userprofile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
var path = $#"{userprofile}\source\repos\mypro\...\myproj.Functions\bin\Debug\netcoreapp3.1";
var startInfo = new ProcessStartInfo
{
FileName = #"cmd.exe",
Arguments = #"/C ""%localappdata%\AzureFunctionsTools\Releases\3.2.0\cli_x64\func.exe host start --port 7071 --pause-on-error""",
//RedirectStandardInput = true,
//RedirectStandardOutput = true,
//RedirectStandardError = true,
//UseShellExecute = false,
UseShellExecute = true,
WorkingDirectory = path
};
process = new System.Diagnostics.Process()
{
StartInfo = startInfo
};
process.Start();
// Thread.Sleep(3000);
}
[AssemblyCleanup]
public static void Cleanup()
{
process.CloseMainWindow();
}
}
Option 3:
Start func.exe process
Working Folder: ...\source\repos\xxx\xxx\xxx.Functions\bin\Debug\netcoreapp3.1\
Command Line:
"C:\Users\username\AppData\Local\AzureFunctionsTools\Releases\3.2.0\cli_x64\func.exe" host start --port 7071 --pause-on-error
Attach to func.exe process.
Edit and continue does not work.

Xamarin Forms - calling rest service from viewmodel of pcl

I created a class that connected to the API to retrieve the required data using httpclient. That file was called in the code behind file of the view and worked perfectly. Than I decided to implement the MVVM approach. As a result, I moved the code that initialized the rest service class to the view-model.
After doing that, i stopped getting the data. To investigate, I stated the the debugging session with the breakpoint placed at the line where i initialize the rest service class. Than i executed that line. By doing that, I found out that a huge android mono exception is thrown and the debugging session if stopped. The app exits the debugging session.
This has happened for the first time since i stated developing my app in Xamarin Forms. I have no idea about why it is breaking like that. Your help will be greatly appreciated.
This is the code that was working properly.
In the view code behind file
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class SubtaskPage : ContentPage
{
protected override void OnAppearing()
{
base.OnAppearing();
PopulateSubtaskData();
}
private async void PopulateSubtaskData()
{
lstSubtasks.IsRefreshing = true;
try
{
RestService rs = new RestService();
SResponse = await rs.GetSubtasksAsync(Convert.ToInt32(Application.Current.Properties["UserId"]));
if (SResponse.Status == 1)
{
lstSubtasks.ItemsSource = SResponse.Subtasks;
}
else
{
await DisplayAlert("Error", SResponse.Message, "Ok");
}
}
catch (Exception E)
{
Debug.WriteLine(#"GetSubtasksAsync -> ERROR {0}", E.Message);
}
lstSubtasks.IsRefreshing = false;
}
}
The rest service class is as follows
This class is in a separate folder named "Services". ip and url have been changed for security reason.
class RestService
{
HttpClient client;
public List<Ticket> Tickets { get; private set; }
string Server1 = "server ip";
string Server2 = "server ip";
public RestService()
{
client = new HttpClient();
client.MaxResponseContentBufferSize = 256000;
}
public async Task<SubtasksResponse> GetSubtasksAsync(int UserId)
{
SubtasksResponse SubtaskResponse = new SubtasksResponse();
string ApiUrl = "URL";
string Url = "";
HttpResponseMessage response;
if (CrossConnectivity.Current.IsConnected)
{
Url = await GetActiveServerAsync();
if (Url != "")
{
var uri = string.Format(Url + ApiUrl, UserId);
try
{
response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
SubtaskResponse.Subtasks = JsonConvert.DeserializeObject<List<Ticket>>(content);
SubtaskResponse.Status = 1;
}
else
{
SubtaskResponse.Subtasks = null;
SubtaskResponse.Status = 0;
SubtaskResponse.Message = "Attempt to fetch data from server was unsuccessful. Please try again";
}
}
catch (Exception E)
{
SubtaskResponse.Subtasks = null;
SubtaskResponse.Status = 0;
SubtaskResponse.Message = "Error occured while fetching data from the server. Please try again";
}
}
else
{
SubtaskResponse.Subtasks = null;
SubtaskResponse.Status = 0;
SubtaskResponse.Message = "Remote Server Not Responding! Please try again later";
}
}
else
{
SubtaskResponse.Subtasks = null;
SubtaskResponse.Status = 0;
SubtaskResponse.Message = "No Network Connection Found! Please connect to a network and try again";
}
return SubtaskResponse;
}
}
}
This was working fine until I added the view model into the mix.
This is how I am calling the function in the view model.
async Task<SubtasksResponse> PopulateSubtaskList()
{
RestService rs = new RestService();
IsBusy = true;
_subtaskList = await rs.GetSubtasksAsync(Convert.ToInt32(Application.Current.Properties["UserId"]));
IsBusy = false;
return _subtaskList;
}
"RestService rs = new RestService();" this is the line where the code breaks.
Here is the image of the exception that occurs when the code breaks.
Hope you get the clear picture of the situation. Please let me know if additional information is required.
Thanks
Don't do this. If you want to call rest from a mvvm Xamarin Forms app I can advice Refit. All the difficult work is already done for you and abstracted away. With a few lines of code you are up and running.
BTW the error message you are showing probably has nothing to do with your code but is a bug in a recent Xamarin version. See here: https://bugzilla.xamarin.com/show_bug.cgi?id=56787
Found the answer on this page (https://releases.xamarin.com/common-issues-in-the-xamarin-15-2-2-release-being-tracked-by-the-xamarin-team/).
The solution is as follows
Download the missing Mono.Posix file and unzip the archive.
Right-click the Mono.Posix.dll file in Explorer and select Properties.
Check the Digital Signatures tab to ensure the file shows a valid Xamarin Inc. signature.
At the bottom of the General tab, if an Unblock checkbox appears, enable it and select OK. (This checkbox appears depending on how the file was downloaded.)
For Visual Studio 2017, copy the Mono.Posix.dll file into the “Xamarin.VisualStudio” extension directory. For example, for a default installation of the Enterprise edition, copy the file into:
C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\Extensions\Xamarin.VisualStudio
For Visual Studio 2015, copy the file into the “Xamarin\Xamarin” extension directory:
C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Xamarin\Xamarin\
Quit and restart Visual Studio.
For more detail, visit the link given above.

Get latest from Visual Studio Team Services using Command Line passing /login credentials with TF.exe

Has anyone had success getting latest source code from the Visual Studio Team Services (formerly Visual Studio Online, Team Foundation Service) Version Control Server using the command line and passing in credentials programmatically?
-I have discovered that you can't use the Windows ID credentials that you use to login to Team Explorer or the VSO website in the command line. You need to create Alternate Credentials for the user profile in Team Services.
-I have found out that if you omit the /login in tf.exe, the Team Services login dialog appears and asks you to type in your Windows ID credentials (unless they are already cached in your Team Explorer or Visual Studio (or even possibly Browser and Windows Credential Caches)
-I have found out that the alternate credential work Using the Java version of tf.exe - Team Explorer Everywhere Command Line Client (TEE CLC). TEE CLC actually uses the /login credentials that you pass in and lets you connect. The same thing does NOT seem to be possible with the TF.EXE in C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\ BUT INSTALLING JAVA ON THIS BUILD ENVIRONMENT IS AGAINST POLICY. So the TEE CLC is NOT a viable option.
tf get $/MyProj /collection:https://myaccount.visualstudio.com/DefaultCollection /login:user:pass
the above command simply ignores the /login credentials if you have the Windows ID credentials cached or it returns the error message TF30063: You are not authorized to access myaccount.visualstudio.com (which is not true, because the credentials DO work with the Java client)
Are there any other alternatives that do not require installing Java?
I got an answer from Microsoft Support: AA Creds for VSO do not work with TF.EXE at this time. TEE CLC or using object model code are the only alternatives currently. We are looking at doing this in the future.
Object Model Code refers to the Microsoft.TeamFoundation.VersionControl.Client Namespace in the dll by the same name. I ended up writing a quick C# console app to download the latest code without installing Java. An added benefit of this approach is that it does not require creating a throwaway Workspace.
if you use the code below to create an executable called tfsget.exe it can be called from the command line like this:
tfsget https://myvso.visualstudio.com/DefaultCollection $/MyProj/Folder c:\Projects login password
and I added a silent switch to suppress listing each file that can be used like:
tfsget https://myvso.visualstudio.com/DefaultCollection $/MyProj/Folder c:\Projects login password silent
here's the code, hope this helps until MS updates TF.exe
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
namespace TfsGet
{
class Program
{
static void Main(string[] args)
{
var tfsParams = TfsDownloadParams.Create(args);
var tpc = new TfsTeamProjectCollection(new Uri(tfsParams.ServerUrl), tfsParams.Credentials);
CheckAccess(tpc, tfsParams);
Download(tpc, tfsParams);
}
private static void CheckAccess(TfsTeamProjectCollection tpc, TfsDownloadParams tfsParams)
{
try
{
tpc.Authenticate();
}
catch
{
Console.WriteLine("TFS Authentication Failed");
Console.WriteLine("Server Url:{0}", tfsParams.ServerUrl);
Console.WriteLine("Project Path:{0}", tfsParams.ServerProjectPath);
Console.WriteLine("Target Path:{0}", tfsParams.TargetPath);
Environment.Exit(1);
}
}
static void Download(TfsTeamProjectCollection tpc, TfsDownloadParams tfsParams)
{
var versionControl = tpc.GetService<VersionControlServer>();
// Listen for the Source Control events.
versionControl.NonFatalError += Program.OnNonFatalError;
var files = versionControl.GetItems(tfsParams.ServerProjectPath, VersionSpec.Latest, RecursionType.Full);
foreach (Item item in files.Items)
{
var localFilePath = GetLocalFilePath(tfsParams, item);
switch (item.ItemType)
{
case ItemType.Any:
throw new ArgumentOutOfRangeException("ItemType.Any - not sure what to do with this");
case ItemType.File:
if (!tfsParams.Silent) Console.WriteLine("Getting: '{0}'", localFilePath);
item.DownloadFile(localFilePath);
break;
case ItemType.Folder:
if (!tfsParams.Silent) Console.WriteLine("Creating Directory: {0}", localFilePath);
Directory.CreateDirectory(localFilePath);
break;
}
}
}
private static string GetLocalFilePath(TfsDownloadParams tfsParams, Item item)
{
var projectPath = tfsParams.ServerProjectPath;
var pathExcludingLastFolder = projectPath.Substring(0, projectPath.LastIndexOf('/')+1);
string relativePath = item.ServerItem.Replace(pathExcludingLastFolder, "");
var localFilePath = Path.Combine(tfsParams.TargetPath, relativePath);
return localFilePath;
}
internal static void OnNonFatalError(Object sender, ExceptionEventArgs e)
{
var message = e.Exception != null ? e.Exception.Message : e.Failure.Message;
Console.Error.WriteLine("Exception: " + message);
}
}
public class TfsDownloadParams
{
public string ServerUrl { get; set; }
public string ServerProjectPath { get; set; }
public string TargetPath { get; set; }
public TfsClientCredentials Credentials { get; set; }
public bool Silent { get; set; }
public static TfsDownloadParams Create(IList<string> args)
{
if (args.Count < 5)
{
Console.WriteLine("Please supply 5 or 6 parameters: tfsServerUrl serverProjectPath targetPath userName password [silent]");
Console.WriteLine("The optional 6th 'silent' parameter will suppress listing each file downloaded");
Console.WriteLine(#"Ex: tfsget ""https://myvso.visualstudio.com/DefaultCollection"" ""$/MyProject/ProjectSubfolder"" ""c:\Projects Folder"", user, password ");
Environment.Exit(1);
}
var tfsServerUrl = args[0]; //"https://myvso.visualstudio.com/DefaultCollection";
var serverProjectPath = args[1]; // "$/MyProject/Folder Path";
var targetPath = args[2]; // #"c:\Projects\";
var userName = args[3]; //"login";
var password = args[4]; //"passsword";
var silentFlag = args.Count >= 6 && (args[5].ToLower() == "silent"); //"silent";
var tfsCredentials = GetTfsCredentials(userName, password);
var tfsParams = new TfsDownloadParams
{
ServerUrl = tfsServerUrl,
ServerProjectPath = serverProjectPath,
TargetPath = targetPath,
Credentials = tfsCredentials,
Silent = silentFlag,
};
return tfsParams;
}
private static TfsClientCredentials GetTfsCredentials(string userName, string password)
{
var networkCreds= new NetworkCredential(userName, password);
var basicCreds = new BasicAuthCredential(networkCreds);
var tfsCreds = new TfsClientCredentials(basicCreds)
{
AllowInteractive = false
};
return tfsCreds;
}
}
}
Here is a snippet using .NET TFS libraries & Powershell integration that worked for us - tf.exe does not play well with VSO authorization. Curious if anyone else has success using this route. We are using ADFS, so the powershell process is run as the user we want to authenticate with.
TF Get Latest Workspace.ps1
$path = "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\ReferenceAssemblies\v2.0"
Add-Type -Path "$path\Microsoft.TeamFoundation.Client.dll"
Add-Type -Path "$path\Microsoft.TeamFoundation.VersionControl.Client.dll"
Add-Type -Path "$path\Microsoft.TeamFoundation.VersionControl.Common.dll"
$collection = "https://mycorp.visualstudio.com/defaultcollection"
$tpc = [Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection($collection)
$vc = $tpc.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
# retrieve workspace by path
$projectPath = "$/MyApp/MyBranch"
$workspacePath = "C:\Projects\MyApp\MyBranch"
$workspace = $vc.GetWorkspace($workspacePath)
# get full download every time (tf get /force /recursive)
function DownloadAllFiles([Microsoft.TeamFoundation.VersionControl.Client.Workspace] $workspace, [string] $projectPath) {
$recursionType = [Microsoft.TeamFoundation.VersionControl.Client.RecursionType]::Full
$versionSpec = [Microsoft.TeamFoundation.VersionControl.Client.LatestVersionSpec]::Instance
$itemSpec = new-object Microsoft.TeamFoundation.VersionControl.Client.ItemSpec($projectPath,$recursionType)
$getRequest = New-Object Microsoft.TeamFoundation.VersionControl.Client.GetRequest($projectPath,$recursionType,$versionSpec)
$getOptions = [Microsoft.TeamFoundation.VersionControl.Client.GetOptions]::GetAll -bor [Microsoft.TeamFoundation.VersionControl.Client.GetOptions]::Overwrite
$workpaceStatus = $workspace.Get($getRequest, $getOptions)
write-output $workpaceStatus
}
# get delta download - changes only (retrieves all mapped items)
function DownloadWorkspaceUpdates([Microsoft.TeamFoundation.VersionControl.Client.Workspace] $workspace) {
$workpaceStatus = $workspace.Get()
write-output $workpaceStatus
}
# get delta download - changes only (retrieves specific mapped items)
function DownloadWorkspaceUpdates([Microsoft.TeamFoundation.VersionControl.Client.Workspace] $workspace, [string] $projectPath) {
$recursionType = [Microsoft.TeamFoundation.VersionControl.Client.RecursionType]::Full
$versionSpec = [Microsoft.TeamFoundation.VersionControl.Client.LatestVersionSpec]::Instance
$itemSpec = new-object Microsoft.TeamFoundation.VersionControl.Client.ItemSpec($projectPath,$recursionType)
$getRequest = New-Object Microsoft.TeamFoundation.VersionControl.Client.GetRequest($projectPath,$recursionType,$versionSpec)
$getOptions = [Microsoft.TeamFoundation.VersionControl.Client.GetOptions]::Overwrite
$workpaceStatus = $workspace.Get($getRequest, $getOptions)
write-output $workpaceStatus
}
# force latest download (slower)
DownloadAllFiles -workspace $workspace -projectPath $projectPath
# download deltas (fast), all mappings
DownloadWorkspaceUpdates -workspace $workspace
# download deltas (fast), specific mapping
DownloadWorkspaceUpdates -workspace $workspace -projectPath $projectPath
This could easily be extended to support TfsClientCredentials (i.e. Alternate Access credentials). I prefer the powershell approach as it doesn't require compilation or an extra EXE to copy around.

Show ErrorList Windows in Visual Studio 2010 Addin

I have Win7 64 bits, Visual Studio 2010, and I have developed an Addin for Vs2010.
I try show messages in Error List Windows VS.
I use ErrorListProvider in OnBuildProjConfigDone build event for Addin
this._buildEvents.OnBuildProjConfigDone += new _dispBuildEvents_OnBuildProjConfigDoneEventHandler(_buildEvents_OnBuildProjConfigDone);
I get this error InvalidOperationException
The service 'Microsoft.VisualStudio.Shell.Interop.IVsTaskList' must be
installed for this feature to work. Ensure that this service is
available.
Connect
public partial class Connect : IDTExtensibility2, IDTCommandTarget, System.Windows.Forms.IWin32Window, IOleCommandTarget
OnBuildProjConfigDone
void _buildEvents_OnBuildProjConfigDone(string project, string projectConfig, string platform, string solutionConfig, bool success)
{
// Omitted
if (!resul)
{
project.DTE.ExecuteCommand("Build.Cancel");
var errorListHelper = new ErrorListHelper();
ErrorListProvider errorProvider = errorListHelper.GetErrorListProvider();
var newError = new ErrorTask();
newError.ErrorCategory = TaskErrorCategory.Message;
newError.Category = TaskCategory.BuildCompile;
newError.Text = "Cualquier mensaje de error aqui";
errorProvider.Tasks.Add(newError);
}
}
ErrorListHelper
public class ErrorListHelper : System.IServiceProvider
{
public ErrorListProvider GetErrorListProvider()
{
ErrorListProvider provider = new ErrorListProvider(this);
provider.ProviderName = "Provider";
provider.ProviderGuid = System.Guid.NewGuid();
return provider;
}
public object GetService(Type serviceType)
{
return Package.GetGlobalService(serviceType);
}
}
Suggestion by #JohnL: I put a breakpoint in my GetService method and Package.GetGlobalService is returning null.
Any suggestions?
Ryan Molden (MSFT) says:
Package.GetGlobalService is relying on at least one MPF package (from
the specific version of MPF you are referencing) having been loaded.
Since you yourself are an AddIn not a Package you can't guarantee that
in any way.
You should pass something like new
ServiceProvider((Microsoft.VisualStudio.OLE.Interop.IServiceProvider))) as the argument to ErrorListProvide
Package.GetGlobalService is returning null.
I use this code in my Addin. I test it and I get not error, and I can show errors and warnings in ErrorList Windows VS. I'll testing more for safely.
public partial class Connect
{
ErrorListProvider _errorListProvider = null;
void CreateErrorListProvider()
{
if (_errorListProvider == null)
{
System.IServiceProvider serviceProvider = new ServiceProvider(_applicationObject as Microsoft.VisualStudio.OLE.Interop.IServiceProvider);
_errorListProvider = new ErrorListProvider(serviceProvider);
_errorListProvider.ProviderName = "custom Errors";
_errorListProvider.ProviderGuid = new Guid("xxxxxxxxxxxxxx");
}
}

Testing SharePoint List Workflow from Visual Studio 2010

I am trying to create a custom workflow in Visual Studio 2010 for SharePoint 2010 and have run into a problem. I have figured out how to deploy the workflow to the SharePoint site, but executing it results in an error. However, the error message is completely non-descriptive, so I want to find out if there is a way to execute it from Visual Studio so I can see where it fails, and possibly why.
I'm trying to simply create a new subsite based on a given ListItem.Title information.
How is it you go about debugging?
For reference, here is my code
class CreateSubsite : System.Workflow.ComponentModel.Activity
{
protected override System.Workflow.ComponentModel.ActivityExecutionStatus
Execute(System.Workflow.ComponentModel.ActivityExecutionContext executionContext)
{
createSite();
return System.Workflow.ComponentModel.ActivityExecutionStatus.Closed;
}
public void createSite()
{
using (SPSite currentSite = SPContext.Current.Site)
{
using (SPWeb currentWeb = SPContext.Current.Web)
{
SPList currentList = SPContext.Current.List;
SPListItem currentListItem = SPContext.Current.ListItem;
WorkflowContext workflow = new WorkflowContext();
SPSite parentSite = new SPSite(workflow.CurrentWebUrl);
SPWeb newSite = currentSite.AllWebs.Add(
currentListItem.Title.Replace(" ", "_"),
currentListItem.Title,
String.Empty, currentWeb.Language, "CI Template", false, false
);
}
}
}
}
Try to remove Using keyword from your code .You should not dispose your SPSite and SPWeb when you use SPContext because disposing of that object might actually break the workflow as it may still need a reference to that object for later use.
just rewrite your code without use using
public void createSite() {
SPSite currentSite = SPContext.Current.Site
SPWeb currentWeb = SPContext.Current.Web
//.... Rest of your code
Hope that help
Regards.

Resources