I am now updating an integration program written for Dynamics 2015 in order to support Dynamics 365. At the moment it uses the Microsoft.Xrm.Client dll methods to create an organization service context. Is there an equivalent to Microsoft.Xrm.Tooling as Microsoft.Xrm.Client seems unsupported.
var getCRMOrgService = CreateCRMOrgService(logger);
var client = CreatePosPerfectConnection(logger);
if (getCRMOrgService != null)
{
using (var ctx = new DataContext(new CrmOrganizationServiceContext(getCRMOrgService)))
{
ctx.TryAccessCache(cache => cache.Mode = OrganizationServiceCacheMode.Disabled);
/******Rest of the code******/
Here I require to change the CreateCRMOrgService and CrmOrganizationServiceContext Methods to the ones supported by Microsoft.Xrm.Tooling alone
It looks like you'll want to switch to CrmServiceClient, which is in the Microsoft.Xrm.Tooling.Connector namespace.
To get the NuGet package:
In your project, right click on the References node and select Manage NuGet Packages. Under Browse search for "xrm tooling". Install Microsoft.CrmSdk.XrmTooling.CoreAssembly and you should be good to go.
Then create a CrmServiceClient via a connection string
var svc = new CrmServiceClient(connectionString);
Then for the context (query provider) do something like this (please note this is untested code):
private List<Entity> getRecords()
{
using (var context = new Microsoft.Xrm.Sdk.Client.OrganizationServiceContext(svc))
{
var result = from e in organizationServiceContext.CreateQuery("new_entity")
where e.GetAttributeValue<string>("new_field") == "my value"
select e;
return result.Take(100).ToList();
}
}
Related
I am totally new to proxmox VE and i want to create a Vitual Machine inside proxmox using C# console application.
I have search a lot and i only found an API program which has all the functionality but i don't know how to use it. https://github.com/EnterpriseVE/eve2pve-api-dotnet
Can someone help me how to create and delete a vm in proxmox using this API in detail or anyone have any different approach to do this
Usage:
var client = new Client("10.92.90.91");
if (client.Login("root", "password"))
{
var vm = client.Nodes["pve1"].Qemu[100];
//config vm
var config = vm.Config.VmConfig();
Console.WriteLine(Client.ObjectToJson(config.Response));
//create snapshot
var response = vm.Snapshot.Snapshot("pippo2311");
//update snapshot description
vm.Snapshot["pippo2311"].Config.UpdateSnapshotConfig("descr");
//delete snapshot
vm.Snapshot["pippo2311"].Delsnapshot();
//list of snapshot
foreach (var snapshot in vm.Snapshot.SnapshotList().Response.data)
{
Console.WriteLine(Client.ObjectToJson(snapshot));
Console.WriteLine(snapshot.name);
}
client.ResponseType = "png";
var dataImg = client.Nodes["pve1"].Rrd.Rrd("cpu", "day").Response;
Console.WriteLine("<img src=\"{dataImg}\" \>");
}
Get the project from github
Compile the project
Add reference to the project's dll
Use it just like the example above
Using NotificationHubClient I can get all registered devices using GetAllRegistrationsAsync(). But if I do not use the registration model but the installation model instead, how can I get all installations? There are methods to retrieve a specific installation but none to get everything.
You're correct, as of July 2016 there's no way to get all installations for a hub. In the future, the product team is planning to add this feature to the installations model, but it will work in a different way. Instead of making it a runtime operation, you'll provide your storage connection string and you'll get a blob with everything associated with the hub.
Sorry for visiting an old thread... but in theory you could use the GetAllRegistrationsAsyc to get all the installations. I guess this will return everything without an installation id as well, but you could just ignore those if you choose.
Could look something like this
var allRegistrations = await _hub.GetAllRegistrationsAsync(0);
var continuationToken = allRegistrations.ContinuationToken;
var registrationDescriptionsList = new List<RegistrationDescription>(allRegistrations);
while (!string.IsNullOrWhiteSpace(continuationToken))
{
var otherRegistrations = await _hub.GetAllRegistrationsAsync(continuationToken, 0);
registrationDescriptionsList.AddRange(otherRegistrations);
continuationToken = otherRegistrations.ContinuationToken;
}
// Put into DeviceInstallation object
var deviceInstallationList = new List<DeviceInstallation>();
foreach (var registration in registrationDescriptionsList)
{
var deviceInstallation = new DeviceInstallation();
var tags = registration.Tags;
foreach(var tag in tags)
{
if (tag.Contains("InstallationId:"))
{
deviceInstallation.InstallationId = new Guid(tag.Substring(tag.IndexOf(":")+1));
}
}
deviceInstallation.PushHandle = registration.PnsHandle;
deviceInstallation.Tags = new List<string>(registration.Tags);
deviceInstallationList.Add(deviceInstallation);
}
I am not suggesting this to be the cleanest chunk of code written, but it does the trick for us. We only use this for debugging type purposes anyways
Here I am using IIdentityManagementService to retrieve a specified user by name. Now I want to retrieve only those team projects which they are a member of and can create tasks/workitems for in TFS. My program allows a user to create a task in TFS and I only want them to be able to see a list of the projects which they have access to for creating tasks/work items.
var tfsTpc = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri("http://dotnettfs:8080/tfs/"));
identityService = tfsTpc.GetService<IIdentityManagementService>();
userId = identityService.ReadIdentity(
IdentitySearchFactor.DisplayName,
strOutlookUser,
MembershipQuery.Direct,
ReadIdentityOptions.None
);
userTpc = new TfsTeamProjectCollection(tfsTpc.Uri, userId.Descriptor);
cssService = (ICommonStructureService4)userTpc.GetService(typeof(ICommonStructureService4));
wis = userTpc.GetService<WorkItemStore>();
lstAllProjects.AddRange(cssService.ListAllProjects().ToList());
List<string> lstViewProjectNames = lstAllProjects.Select(a => a.Name).ToList();
Right now, the list shows all projects within that software collection when I want it to show only those projects which the retrieved user has access to.
then they are able to create a task and specify the iteration and area for one of those projects.
var store = wis.Projects[0]; //should be a specified project, not the first element.
WorkItem pbi = new WorkItem(store.WorkItemTypes["Product Backlog Item"]);
pbi.IterationPath = lstIterations.Where(a => a.Name == selectedIteration.ToString())
.Select(a => a.Path).First().ToString();
pbi.AreaPath = lstAreas.Where(a => a.Name == selectedArea.ToString())
.Select(a => a.Path).First().ToString();
I only want them to be able to see a list of the projects which they
have access to for creating tasks/work items.
Work items are tied to areas and areas are tied to team projects.
The basic steps are:
1) Connect to TFS as the user in question
2) Retrieve the team project in question
3) Get the areas for the team project in question
4) Check each one for the ability to create work items (you can probably get away with doing the recursive check on just the root area node)
The usings you will need (might not need all):
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Framework.Client;
using Microsoft.TeamFoundation.Framework.Common;
using Microsoft.TeamFoundation.Server;
using Microsoft.TeamFoundation.VersionControl.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
IIdentityManagementService identityManagementService = tpc.GetService<IIdentityManagementService>();
TfsTeamProjectCollection tpc = GetTfsCollection();
TeamFoundationIdentity identity = identityManagementService.ReadIdentity(IdentitySearchFactor.AccountName, #"Domain\username", MembershipQuery.None, ReadIdentityOptions.None);
TfsTeamProjectCollection impersonatedTPC = new TfsTeamProjectCollection(new Uri(this._tfsUri, this._tfsCollectionName), identity.Descriptor);
WorkItemStore impersonatedWIS = impersonatedTPC.GetService<WorkItemStore>();
ProjectCollection impersonatedProjects = impersonatedWIS.Projects;
foreach (Project p in impersonatedProjects)
{
if (p.Name == "My Team Project")
{
NodeCollection areas = p.AreaRootNodes;
foreach (Node area in areas)
{
if (area.HasWorkItemWriteRightsRecursive)
{
//They do have rights
}
}
}
}
Note that I call GetTfsCollection() which my own user defined function (this is just the class that I constructed with, passing in the root tfs uri and the collection name as string). I also didn't put in any exception handling, just showing the basics:
private TfsTeamProjectCollection GetTfsCollection()
{
return TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(this._tfsUri, this._tfsCollectionName));
}
In new version of TeamFoundation 2013 default build templates, the Workspace variable is missing. It is needed as intput parameter for few key activities like ConvertWorkspaceItem. How do I get current workspace for TfvcTemplate.12.xaml templates? I've tried to use this msdn thread but it's not working for me (returns null workspace name). Any suggestions?
There's a new activity in 2013 called GetLocalPath that replaces ConvertWorkspaceItem.
The activity is under the Microsoft.TeamFoundation.Build.Activities.Core namespace in the Microsoft.TeamFoundation.Build.Activities assembly.
It uses the LocalPathProvider class that aggregates all workspaces used in the build and exposes path translation for all of them in one place. This basically removes the dependency of knowing the workspace in order to translate server paths to local paths and allows you to use as many workspaces as you want without worrying about breaking something down the line.
When MS takes something away, it's usually for a good reason. "hacking" is really not necessary.
I went with a hack using internal classes from Microsoft.TeamFoundation.Build.Activities.dll (used by microsoft to create workspace name). You need to create custom activity with following code:
public sealed class GetDefaultWorkspace : BaseActivity<Workspace>
{
public override Activity CreateBody()
{
var type = typeof(TfGetSources).Assembly.GetType("Microsoft.TeamFoundation.Build.Activities.TeamFoundation.TfGetSources+GetDefaultWorkspaceName");
var activity = (CodeActivity<string>)Activator.CreateInstance(type);
var sequence = new Sequence();
var workspaceName = new Variable<string>();
sequence.Variables.Add(workspaceName);
sequence.Activities.Add(activity);
activity.Result = (OutArgument<string>) workspaceName;
sequence.Activities.Add(new GetWorkspace
{
Name = workspaceName,
Result = new LambdaReference<Workspace>(ctx => Result.Get(ctx))
});
return sequence;
}
}
This answer might work better for some people. ghord's answer works well, and passes the Workspace back where it can be used in the XAML. However, for my purposes I only want the workspace in my custom TFS activities, so I ended up with this alternative...
public sealed class CustomActivity : CodeActivity
{
protected override void Execute(CodeActivityContext context)
{
// get workspace
var buildDetail = context.GetExtension<IBuildDetail>();
var buildAgent = context.GetExtension<IBuildAgent>();
var buildDirectory = buildAgent.GetExpandedBuildDirectory(buildDetail.BuildDefinition);
var workspacePath = Path.Combine(buildDirectory, "src");
var wsInfo = Workstation.Current.GetLocalWorkspaceInfo(workspacePath);
var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(wsInfo.ServerUri);
tfs.Connect(ConnectOptions.None);
var vcs = tfs.GetService<VersionControlServer>();
// finally can get to the workspace here
var workspace = vcs.GetWorkspace(workspacePath);
}
}
Using this method, I don't have to have an activity that just returns the workspace, and then have to pass the workspace into other TFS activities. I just get the workspace from within my own activity while it runs.
I believe the method employed here will use the already downloaded workspace. Keep in mind, that this approach will only work within the scope of "Run on agent" sequence after "Initialize Environment" and before ResetEnvironment within the finally statement of Try Compile, Test, Publish. Else, the workflow will have no knowledge of a sources directory.
http://social.msdn.microsoft.com/Forums/vstudio/en-US/420ba073-bdf5-4ab4-88da-c84561d1a1ba/creating-dynamic-working-folder-in-tfs2013-defaulttemplate?forum=tfsbuild
I'm using fluent migrator to manage my database migrations, but what I'd like to do is have the migrations run at app start. The closest I have managed is this:
public static void MigrateToLatest(string connectionString)
{
using (var announcer = new TextWriterAnnouncer(Console.Out)
{
ShowElapsedTime = true,
ShowSql = true
})
{
var assembly = typeof(Runner).Assembly.GetName().Name;
var migrationContext = new RunnerContext(announcer)
{
Connection = connectionString,
Database = "SqlServer2008",
Target = assembly
};
var executor = new TaskExecutor(migrationContext);
executor.Execute();
}
}
I'm sure I had this working, but I've not looked at it for sometime (hobby project) and it's now throwing null reference exceptions when it gets to the Execute line. Sadly there are no docs for this and I've been banging my head on it for ages.
Has anyone managed to get this kind of thing working with FluentMigrator?
PM> Install-Package FluentMigrator.Tools
Manually add a reference to:
packages\FluentMigrator.Tools.1.6.1\tools\AnyCPU\40\FluentMigrator.Runner.dll
Note that the folder name will vary on version number, this illustration uses the current 1.6.1 release. If you need the .NET 3.5 runner use the \35\ directory.
public static class Runner
{
public class MigrationOptions : IMigrationProcessorOptions
{
public bool PreviewOnly { get; set; }
public string ProviderSwitches { get; set; }
public int Timeout { get; set; }
}
public static void MigrateToLatest(string connectionString)
{
// var announcer = new NullAnnouncer();
var announcer = new TextWriterAnnouncer(s => System.Diagnostics.Debug.WriteLine(s));
var assembly = Assembly.GetExecutingAssembly();
var migrationContext = new RunnerContext(announcer)
{
Namespace = "MyApp.Sql.Migrations"
};
var options = new MigrationOptions { PreviewOnly=false, Timeout=60 };
var factory =
new FluentMigrator.Runner.Processors.SqlServer.SqlServer2008ProcessorFactory();
using (var processor = factory.Create(connectionString, announcer, options))
{
var runner = new MigrationRunner(assembly, migrationContext, processor);
runner.MigrateUp(true);
}
}
}
Note the SqlServer2008ProcessorFactory this is configurable dependent upon your database, there is support for: 2000, 2005, 2008, 2012, and 2014.
I have actually accomplished running migrations in the application_start however it is hard to tell from that code what could be wrong... Since it is open source I would just grab the code and pull it into your solution and build it to find out what the Execute method is complaining about. I found that the source code for Fluent Migrator is organized pretty well.
One thing that you might have to be concerned about if this is a web app is making sure that no one uses the database while you are migrating. I used a strategy of establishing a connection, setting the database to single user mode, running the migrations, setting the database to multi user mode, then closing the connection. This also handles the scenario of a load balanced web application on multiple servers so 2 servers don't try to run migrations against the same database.