I've to admit I'm a little bit confused with how ASP.NET vNext handles dependencies. The thing is that I'd like to use Microsoft Sync Framework with an API I'm implementing in ASP.NET 5. Back in the past I used to install the SDK and then just reference appropriate dlls. It seems that it's not the case with vNext as it's all package driven when it comes to dependencies. Thus I've found Microsoft.SyncFramework package on NuGet and added it as a dependency in my ASP.NET vNext project:
"dependencies": {
"Microsoft.AspNet.Server.IIS": "1.0.0-beta1",
"Microsoft.AspNet.Diagnostics": "1.0.0-beta1",
"Microsoft.AspNet.Mvc": "6.0.0-beta1"
},
"frameworks": {
"aspnet50": {
"dependencies": {
"Microsoft.SyncFramework": "2.1.0.2"
}
},
"aspnetcore50": { }
}
And when VS tries to restore the package, it gets this error:
System.NullReferenceException: Object reference not set to an instance of an object.
at Microsoft.Framework.Runtime.LibraryInformation..ctor(LibraryDescription description)
at Microsoft.Framework.Runtime.LibraryManager.<>c__DisplayClass2.<GetLibraryInfoThunk>b__7(LibraryDescription library)
at System.Linq.Enumerable.WhereSelectListIterator`2.MoveNext()
at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer)
at Microsoft.Framework.Runtime.LibraryManager.EnsureInitialized()
at Microsoft.Framework.Runtime.LibraryManager.GetLibraryInformation(String name, String aspect)
at Microsoft.Framework.Runtime.ProjectExportProviderHelper.GetExportsRecursive(ICache cache, ILibraryManager manager, ILibraryExportProvider libraryExportProvider, ILibraryKey target, Boolean dependenciesOnly)
at Microsoft.Framework.Runtime.LibraryManager.<>c__DisplayClass0.<GetAllExports>b__1(CacheContext ctx)
at Microsoft.Framework.Runtime.CacheExtensions.<>c__DisplayClass0`1.<Get>b__1(CacheContext ctx)
at Microsoft.Framework.Runtime.Cache.CreateEntry(Object k, Func`2 acquire)
at Microsoft.Framework.Runtime.Cache.<>c__DisplayClass3.<AddEntry>b__4()
at System.Lazy`1.CreateValue()
at System.Lazy`1.LazyInitValue()
at System.Lazy`1.get_Value()
at Microsoft.Framework.Runtime.Cache.Get(Object key, Func`2 factory)
at Microsoft.Framework.Runtime.CacheExtensions.Get[T](ICache cache, Object key, Func`2 factory)
at Microsoft.Framework.Runtime.LibraryManager.GetAllExports(String name, String aspect)
at Microsoft.Framework.Runtime.LibraryManager.GetAllExports(String name)
at Microsoft.Framework.Runtime.ProjectMetadataProvider.GetProjectMetadata(String name)
at Microsoft.Framework.DesignTimeHost.ApplicationContext.Initialize(String appPath, String configuration, Boolean triggerBuildOutputs)
at Microsoft.Framework.DesignTimeHost.ApplicationContext.Calculate()
at Microsoft.Framework.DesignTimeHost.ApplicationContext.DoProcessLoop()
at Microsoft.Framework.DesignTimeHost.ApplicationContext.ProcessLoop(Object state)
And as a result I don't have the package included.
Any ideas on how to tackle this?
Apparently ASP.NET vNext dropped support for running *.ps1 scripts in NuGet packages http://forums.asp.net/p/2027698/5842272.aspx
Related
Is there a way to get the release/published dates of nuget packages? I've searched the nuget commands and VS powershell scripts but am coming up empty. I can't even find it on nuget.org, which gives abstractions like 'one month ago' instead.
I would prefer a programmatic way to retrieve this info. But I'll settle for any way at all.
Use the NuGet SDK. I've modified the code to display the Published property.
ILogger logger = NullLogger.Instance;
CancellationToken cancellationToken = CancellationToken.None;
SourceCacheContext cache = new SourceCacheContext();
SourceRepository repository = Repository.Factory.GetCoreV3("https://api.nuget.org/v3/index.json");
PackageMetadataResource resource = await repository.GetResourceAsync<PackageMetadataResource>();
IEnumerable<IPackageSearchMetadata> packages = await resource.GetMetadataAsync(
"Newtonsoft.Json", // replace with the required package id
includePrerelease: true,
includeUnlisted: false,
cache,
logger,
cancellationToken);
foreach (IPackageSearchMetadata package in packages)
{
Console.WriteLine($"Version: {package.Identity.Version}");
Console.WriteLine($"Publish date: {package.Published}");
}
I'm changing a project from using an EDMX file to Code First. The project is one of a few projects in a solution, and it only contains the entities and the DbContext class.
This is what I've done so far:
Removed the old project from the solution (but not deleted it just yet, just renamed the folder).
Added a new class library project to the solution, and given it the same name as the old one.
Used NuGet to add Entity Framework to the new project.
Copied all the entity classes that were generated by the old EDMX file to the new project and included them all.
Copied the DbContext class as well.
Modified the app.config file to change the connection string to a standard connection string without the metadata stuff.
Added a reference to all the other projects that uses to use the old project.
Everything looks good and it compiles with no errors, but when I try to enable-migrations it throws this error:
PM> enable-migrations
Checking if the context targets an existing database...
System.Data.Entity.Core.MetadataException: Unable to load the specified metadata resource.
at System.Data.Entity.Core.Metadata.Edm.MetadataArtifactLoaderCompositeResource.LoadResources(String assemblyName, String resourceName, ICollection`1 uriRegistry, MetadataArtifactAssemblyResolver resolver)
at System.Data.Entity.Core.Metadata.Edm.MetadataArtifactLoaderCompositeResource.CreateResourceLoader(String path, ExtensionCheck extensionCheck, String validExtension, ICollection`1 uriRegistry, MetadataArtifactAssemblyResolver resolver)
at System.Data.Entity.Core.Metadata.Edm.MetadataArtifactLoader.Create(String path, ExtensionCheck extensionCheck, String validExtension, ICollection`1 uriRegistry, MetadataArtifactAssemblyResolver resolver)
at System.Data.Entity.Core.Metadata.Edm.MetadataCache.SplitPaths(String paths)
at System.Data.Entity.Core.Common.Utils.Memoizer`2.<>c__DisplayClass2.<Evaluate>b__0()
at System.Data.Entity.Core.Common.Utils.Memoizer`2.Result.GetValue()
at System.Data.Entity.Core.Common.Utils.Memoizer`2.Evaluate(TArg arg)
at System.Data.Entity.Core.Metadata.Edm.MetadataCache.GetArtifactLoader(DbConnectionOptions effectiveConnectionOptions)
at System.Data.Entity.Core.Metadata.Edm.MetadataCache.GetMetadataWorkspace(DbConnectionOptions effectiveConnectionOptions)
at System.Data.Entity.Core.EntityClient.EntityConnection.GetMetadataWorkspace()
at System.Data.Entity.Core.Objects.ObjectContext.RetrieveMetadataWorkspaceFromConnection()
at System.Data.Entity.Core.Objects.ObjectContext..ctor(EntityConnection connection, Boolean isConnectionConstructor, ObjectQueryExecutionPlanFactory objectQueryExecutionPlanFactory, Translator translator, ColumnMapFactory columnMapFactory)
at System.Data.Entity.Internal.InternalConnection.CreateObjectContextFromConnectionModel()
at System.Data.Entity.Internal.LazyInternalConnection.CreateObjectContextFromConnectionModel()
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.LazyInternalContext.get_ModelBeingInitialized()
at System.Data.Entity.Infrastructure.EdmxWriter.WriteEdmx(DbContext context, XmlWriter writer)
at System.Data.Entity.Utilities.DbContextExtensions.<>c__DisplayClass1.<GetModel>b__0(XmlWriter w)
at System.Data.Entity.Utilities.DbContextExtensions.GetModel(Action`1 writeXml)
at System.Data.Entity.Utilities.DbContextExtensions.GetModel(DbContext context)
at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration, DbContext usersContext, DatabaseExistenceState existenceState, Boolean calledByCreateDatabase)
at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration)
at System.Data.Entity.Migrations.Design.MigrationScaffolder..ctor(DbMigrationsConfiguration migrationsConfiguration)
at System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldRunner.Run()
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
at System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldInitialCreate(String language, String rootNamespace)
at System.Data.Entity.Migrations.EnableMigrationsCommand.<>c__DisplayClass2.<.ctor>b__0()
at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
Unable to load the specified metadata resource.
It looks like it still thinks I'm using an EDMX. I also get this error when I try to run the application.
What am I missing?
You have to change the connection string of the starter project (asp.net or winforms project).
When using EF 4.3.1 migrations every time i need to add a migration or update database i have to use the StartUpProject parameter. Can I set this somewhere so I don't have to keep doing this? I don't want to set my data project as the start up project. My context and migrations are in different projects if that makes a difference.
Exception thrown when not using StartpProject parameter:
update-database -verbose
Using NuGet project 'Data.Deployment'.
Using StartUp project ''.
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ArgumentException: The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG))
--- End of inner exception stack trace ---
at System.RuntimeType.InvokeDispMethod(String name, BindingFlags invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers, Int32 culture, String[] namedParameters)
at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
at System.Management.Automation.ComMethod.InvokeMethod(PSMethod method, Object[] arguments)
Exception has been thrown by the target of an invocation.
At least with Entity Framework 6, to specify the Startup Project use the -StartUpProjectName parameter with update-database:
update-database -StartUpProjectName <String>
You can use the get-help command within Package Manager Console to view possible parameters for commands:
get-help update-database -detailed
Use the StartupProject parameter: Update-database -StartupProject "PROJECTNAME"
I'm not sure if this is what you're talking about, but you can set the default project in the Package Manager Console to the project where your Migrations config resides in; it's the rightmost dropdown list.
This way I've never had to provide the startup project as an argument.
A clean way around this is to attach a Test Project to the solution.
Even if you don't want to write lots of unit tests, it's an appropriate start-up project for a data layer namespace or similar.
That makes your start up issue cleaner, the package manager applies to the whole solution IIRC - so make sure the default project is the one with the migrations folder in it.
When I try to use nunit-console.exe to run all the tests in a solution file as such:
nunit-console.exe MyProject.sln
I get the following exception (shown below). However when run the console runner on ANY of the projects in my folder structure, the runner works just fine and never gives me the following exception. I also am pretty certain that the version of the nunit library that I am linking to is the same as the runner that I am using. Also, my solution doesn't reference any projects that are outside the directory structure containing my .sln file.
Does anyone have any clue what I can do!? :(
Thanks!
Phil
NUnit version 2.5.10.11092
Copyright (C) 2002-2009 Charlie Poole.
Copyright (C) 2002-2004 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov.
Copyright (C) 2000-2002 Philip Craig.
All Rights Reserved.
Runtime Environment -
OS Version: Microsoft Windows NT 6.1.7601 Service Pack 1
CLR Version: 4.0.30319.1 ( Net 4.0 )
ProcessModel: Default DomainUsage: Default
Execution Runtime: net-4.0
Unhandled Exception:
System.IO.FileLoadException: Could not load file or assembly 'nunit.framework, Version=2.5.10.11092, Culture=neutral, Pu
blicKeyToken=96d09a1eb7f44a77' or one of its dependencies. The located assembly's manifest definition does not match the
assembly reference. (Exception from HRESULT: 0x80131040)
File name: 'nunit.framework, Version=2.5.10.11092, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77'
Server stack trace:
at System.ModuleHandle.ResolveType(RuntimeModule module, Int32 typeToken, IntPtr* typeInstArgs, Int32 typeInstCount,
IntPtr* methodInstArgs, Int32 methodInstCount, ObjectHandleOnStack type)
at System.ModuleHandle.ResolveTypeHandleInternal(RuntimeModule module, Int32 typeToken, RuntimeTypeHandle[] typeInsta
ntiationContext, RuntimeTypeHandle[] methodInstantiationContext)
at System.ModuleHandle.ResolveTypeHandle(Int32 typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHa
ndle[] methodInstantiationContext)
at System.Reflection.RuntimeModule.ResolveType(Int32 metadataToken, Type[] genericTypeArguments, Type[] genericMethod
Arguments)
at System.Reflection.CustomAttribute.FilterCustomAttributeRecord(CustomAttributeRecord caRecord, MetadataImport scope
, Assembly& lastAptcaOkAssembly, RuntimeModule decoratedModule, MetadataToken decoratedToken, RuntimeType attributeFilte
rType, Boolean mustBeInheritable, Object[] attributes, IList derivedAttributes, RuntimeType& attributeType, IRuntimeMeth
odInfo& ctor, Boolean& ctorHasParameters, Boolean& isVarArg)
at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeModule decoratedModule, Int32 decoratedMetadataToken,
Int32 pcaCount, RuntimeType attributeFilterType, Boolean mustBeInheritable, IList derivedAttributes, Boolean isDecorate
dTargetSecurityTransparent)
at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeType type, RuntimeType caType, Boolean inherit)
at NUnit.Core.CoreExtensions.InstallAdhocExtensions(Assembly assembly)
at NUnit.Core.Builders.TestAssemblyBuilder.Load(String path)
at NUnit.Core.Builders.TestAssemblyBuilder.Build(String assemblyName, Boolean autoSuites)
at NUnit.Core.Builders.TestAssemblyBuilder.Build(String assemblyName, String testName, Boolean autoSuites)
at NUnit.Core.TestSuiteBuilder.Build(TestPackage package)
at NUnit.Core.SimpleTestRunner.Load(TestPackage package)
at NUnit.Core.ProxyTestRunner.Load(TestPackage package)
at NUnit.Core.ProxyTestRunner.Load(TestPackage package)
at NUnit.Core.RemoteTestRunner.Load(TestPackage package)
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 fExec
uteInContext)
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 NUnit.Core.TestRunner.Load(TestPackage package)
at NUnit.Util.TestDomain.Load(TestPackage package)
at NUnit.ConsoleRunner.ConsoleUi.Execute(ConsoleOptions options)
at NUnit.ConsoleRunner.Runner.Main(String[] args)
WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].
Try using the Fusion Log Viewer to see what assembly is failing to load. It should tell you not only what file it is failing on, but where it tried looking for that file.
In my case nunit-console.exe did not respect the assembly redirection from web|app.config. unless you provide /domain=multiple
My Problem:
EntityFrameworkTesting.Moq -> requests Moq, Version=4.2.1409.1722
I had already a newer assembly referenced.
The solution for me was to add /domain=multiple parameter. see the NUnit docs
So I run:
D:\tools\NUnit-2.6.4\bin\nunit-console.exe %SOLUTION_PATH%\Project.sln /config:Release /framework:net-4.0 /domain=multiple /xml=nunit-result.xml
Summary
I currently have a NAnt build script that performs a vssget on either the latest source code, or a specific branch (using a ${branch} parameter).
Whenever we do a production build/deployment the code-tree that was built has a branch created, (so that we can continue development and still know what codebase is on production, pretty standard stuff...)
Problem
The process of creation of that branch is still a manual one, performed by someone going into Visual Source Safe Explorer and performing the branching procedure. I was wondering if there is any way in NAnt of creating a VSS branch.
Current Plan
I already know about using <exec program="ss"> and am trying to avoid that, but in the absence of any better solutions, that is the most probable route I will take.
Does anyone know if there is a NAnt or NAntContrib target for this, or if anyone has a script task that they have used to do this in the past and could provide the code for that, that would be very much appreciated.
Disclaimer
I know about cvs, svn, git and all the other Source Control solutions, and to change the tool is not an option at present
We actually need this where I work. I whipped together a small task called 'vssbranch' (not particularly creative but here is the code...an example build file and the output of its execution:
CODE:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using SourceSafeTypeLib;
using NAnt.Core;
using NAnt.Core.Attributes;
namespace NAnt.Contrib.Tasks.SourceSafe
{
[TaskName("vssbranch")]
public sealed class BranchTask : BaseTask
{
/// <summary>
/// The label comment.
/// </summary>
[TaskAttribute("comment")]
public String Comment { get; set; }
/// <summary>
/// Determines whether to perform the branch recursively.
/// The default is <see langword="true"/>
/// </summary>
[TaskAttribute("recursive"),
BooleanValidator()]
public Boolean Recursive { get; set; }
[TaskAttribute("branchname", Required = true)]
public String BranchName { get; set; }
protected override void ExecuteTask()
{
this.Open();
try
{
if (VSSItemType.VSSITEM_PROJECT != (VSSItemType)this.Item.Type)
throw new BuildException("Only vss projects can be branched", this.Location);
IVSSItem newShare = null;
this.Comment = String.IsNullOrEmpty(this.Comment) ? String.Empty : this.Comment;
if (null != this.Item.Parent)
newShare = this.Item.Parent.NewSubproject(this.BranchName, this.Comment);
if (null != newShare)
{
newShare.Share(this.Item as VSSItem, this.Comment,
(this.Recursive) ?
(int)VSSFlags.VSSFLAG_RECURSYES : 0);
foreach (IVSSItem item in newShare.get_Items(false))
this.BranchItem(item, this.Recursive);
}
}
catch (Exception ex)
{
throw new BuildException(String.Format("Failed to branch '{0}' to '{1}'", this.Item.Name, this.BranchName), this.Location, ex);
}
}
private void BranchItem(IVSSItem itemToBranch, Boolean recursive)
{
if (null == itemToBranch) return;
if (this.Verbose)
this.Log(Level.Info, String.Format("Branching {0} path: {1}", itemToBranch.Name, itemToBranch.Spec));
if (VSSItemType.VSSITEM_FILE == (VSSItemType)itemToBranch.Type)
itemToBranch.Branch(this.Comment, 0);
else if (recursive)
{
foreach (IVSSItem item in itemToBranch.get_Items(false))
this.BranchItem(item, recursive);
}
}
}
}
BUILD FILE:
<echo message="About to execute: VSS Branch" />
<echo message="Source Safe Path: ${SourceSafeRootPath}/${CURRENT_FILE}" />
<vssbranch
username="my_user_name"
password="my_password"
recursive="true"
comment="attempt to make a branch"
branchname="test-branch"
dbpath="${SourceSafeDBPath}"
path="${SourceSafeRootPath}/${CURRENT_FILE}"
verbose="true"
/>
</foreach>
</target>
OUTPUT:
NAnt 0.85 (Build 0.85.2478.0; release; 10/14/2006)
Copyright (C) 2001-2006 Gerry Shaw
http://nant.sourceforge.net
Buildfile: file:///C:/scm/custom/src/VssBranch/bin/Debug/test.build
Target framework: Microsoft .NET Framework 2.0
Target(s) specified: run
run:
[loadtasks] Scanning assembly "NAnt.Contrib.Tasks" for extensions.
[loadtasks] Scanning assembly "VssBranch" for extensions.
[echo] About to execute: VSS Branch
....
[vssbranch] Branching SecurityProto path: $/VSS/Endur's Source/C#/DailyLive/proto/test-branch/SecurityProto
....
BUILD SUCCEEDED
Total time: 12.9 seconds.
Obviously the output would vary, I was pulling in the items to branch from a text file named 'params.txt'. This task performs what is known in the VSS world as 'Share and Branch' (Branching immediately after Sharing)...other source control systems do not need to share before branching, eh...that's for another day
The vss tasks live in the NAntContrib project and no, currently there is no task that supports branching. Though, following the model of the existing vss tasks (add, checkout, checkin, etc) in NAntContrib, you could grab the source and extend it yourself. That is, if the VSS API supports branching.