Custom web part deployment produces 'Cannot import this webpart' error - visual-studio-2010

I have built an empty SharePoint project in Visual Studio 2010 with some custom web parts in it. When I've tested these on my local development machine they can be added to a page without any trouble.
When I deploy the wsp via PowerShell to a remote SharePoint server, the web parts show in the web part gallery but adding one to a page gets me the error 'Cannot import this web part'. The logs have no further information in them. As per some answers I've found via Google, I've checked there is no code in Init. All initial processing is done within CreateChildControls (although I would have thought if this were the cause, I would get the same error on my local machine).
I originally asked this question at https://sharepoint.stackexchange.com/questions/11820/custom-web-part-deployment-produces-cannot-import-this-webpart-error. From the suggestions I received I decided to create a fresh project where I had done minimal coding.
The new project has just one simple label web part. The code for the web part is
using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
namespace TestWebParts.TestHelloWorld
{
[ToolboxItemAttribute(false)]
public class TestHelloWorld : WebPart
{
protected override void CreateChildControls()
{
Label lblThis = new Label();
lblThis.Text = "Testing web part";
Controls.Add(lblThis);
}
}
}
The .webpart file in the project is
<?xml version="1.0" encoding="utf-8"?>
<webParts>
<webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
<metaData>
<type name="TestWebParts.TestHelloWorld.TestHelloWorld, $SharePoint.Project.AssemblyFullName$" />
<importErrorMessage>$Resources:core,ImportErrorMessage;</importErrorMessage>
</metaData>
<data>
<properties>
<property name="Title" type="string">TestHelloWorld</property>
<property name="Description" type="string">My WebPart</property>
</properties>
</data>
</webPart>
</webParts>
I have checked that a safe control entry has been added. I have added CAS policies to the project (as these will be deployed to the bin rather than the GAC). The package manifest looks like this
<?xml version="1.0" encoding="utf-8"?>
<Solution xmlns="http://schemas.microsoft.com/sharepoint/">
<CodeAccessSecurity>
<PolicyItem>
<PermissionSet class="NamedPermissionSet" version="1" Description="Permission set for ECB">
<IPermission class="AspNetHostingPermission" version="1" Level="Minimal" />
<IPermission class="SecurityPermission" version="1" Flags="Execution,ControlPrincipal,ControlAppDomain,ControlDomainPolicy,ControlEvidence,ControlThread" />
<IPermission class="Microsoft.SharePoint.Security.SharePointPermission, Microsoft.SharePoint.Security, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"
version="1" ObjectModel="True" />
<IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Read="UserName" />
<IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" PathDiscovery="*AllFiles*" />
<IPermission class="System.Security.Permissions.ReflectionPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" PathDiscovery="*AllFiles*" />
</PermissionSet>
<Assemblies>
<Assembly Name="$SharePoint.Project.AssemblyName$" Vers7ion="$SharePoint.Project.AssemblyVersion$" PublicKeyBlob="$SharePoint.Project.AssemblyPublicKeyBlob$"/>
</Assemblies>
</PolicyItem>
</CodeAccessSecurity>
</Solution>
The .wsp installs fine on the dev machine I am trying to get this running on. When I try to view the web part in the Web Part Gallery I get the message "Cannot import this web part" as shown above. I have confirmed that the .dll is in the bin directory. The web.config file holds this entry
<SafeControl Assembly="TestWebParts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=8d63a878e7c304c2" Namespace="TestWebParts.TestHelloWorld" TypeName="*" Safe="True" SafeAgainstScript="True" />
When I view the webpart xml from the Web Part Gallery I see
<?xml version="1.0" encoding="utf-8"?>
<webParts>
<webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
<metaData>
<type name="TestWebParts.TestHelloWorld.TestHelloWorld, TestWebParts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=8d63a878e7c304c2" />
<importErrorMessage>Cannot import this Web Part.</importErrorMessage>
</metaData>
<data>
<properties>
<property name="Title" type="string">TestHelloWorld</property>
<property name="Description" type="string">My WebPart</property>
</properties>
</data>
</webPart>
</webParts>
Does anybody have any ideas as to what could be causing the issue when I deploy to the dev machine? The only other thing I can think of is that my local machine is Windows 7 and the dev machine is Windows Server 2008. Both are running SharePoint Foundation

It can not find the assembly referenced in the web part. The error you are seeing is actually the equivelant from this line of code.
Cannot import this Web Part.
What you need to do is verify the full class and assembly reference names in your .webpart definition file and update accordingly.
Unfortunately I can't tell you what it should be exactly because your project definition may be outputting the assembly with different info than your class defintion.

Related

Where can I find source code of Microsoft.AspNet.WebApi NuGet package?

I have a few question regarding Microsoft.AspNet.WebApi NuGet package source code:
Where is located repository with Microsoft.AspNet.WebApi Nuget package source code.
What commit id corresponds to version 5.2.3 of the NuGet package.
What *.nuspec file was used to create Microsoft.AspNet.WebApi package?
Thanks!
I was looking for the exact same thing and I finally found it. This page lists out the versions and where they correspond in the source. It is v.3.2.3 that maps to 5.2.3.
Repository Tags and Version Numbers
BY Scott Hanselman: http://www.hanselman.com/blog/CreatingANuGetPackageIn7EasyStepsPlusUsingNuGetToIntegrateASPNETMVC3IntoExistingWebFormsApplications.aspx
POSTED TO AVOID LINK ONLY ANSWER!
HOW I MADE MY OWN NUGET PACKAGE AND YOU SHOULD TOO BY Scott Hanselman:
Step 0 - Go get the NuGet.exe command line here. Put it in the Path or somewhere.
Step 1 - Make a folder for your new package, go there via the commmand line and run "nuget spec"
C:\Users\Scott\Desktop\AddMvc3ToWebForms>nuget spec
Created 'Package.nuspec' successfully.
C:\Users\Scott\Desktop\AddMvc3ToWebForms>dir Package.nuspec
Directory of C:\Users\Scott\Desktop\AddMvc3ToWebForms
02/15/2011 02:23 AM 813 Package.nuspec
1 File(s) 813 bytes
Now, I changed this file's name and edited it thusly.
<?xml version="1.0"?>
<package xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<metadata xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
<id>AddMvc3ToWebForms</id>
<version>0.4</version>
<authors>Scott Hanselman</authors>
<owners>Scott Hanselman</owners>
<iconUrl>http://www.hanselman.com/images/nugeticon.png</iconUrl>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>A totally unsupported way to quickly add ASP.NET MVC 3 support to your WebForms Application. Works on my machine.</description>
<tags>MVC MVC3 ASP.NET WebForms</tags>
</metadata>
</package>
Step 2 - Add stuff to your Content Folder
Since I want my NuGet package to add stuff to folders in my target Web Application, I put whatever I want in a folder called Content. Anything in that will show up in the root of my target project. This can be CSS, JS, CS or VB files, whatever. These files will all get dropped onto the project your package is applied to.
In my project I took the folders from an MVC application and put them in my NuGet folder structure. So, Content, Controllers, Models, Scripts, Views. Copied them right over from an existing blank ASP.NET MVC project.
My NuGet directory where I'm building the package
Step 3 - Decide what needs to be Pre-Processed
However, when my HomeController shows up in your project, Dear Reader, I don't want it to be in the namespace ScottMvcApplication! You want it in MvcApplication54 or whatever your project name is. I need pre-process the source a little to use your project's context, names, namespaces, etc.
For the files I want pre-processed automatically by NuGet, I add a .pp extension. In my example, HomeController.cs.pp.
Preprocessor files with a .pp extension
Then I add a few tokens I want replaced at install-time for that package. For example $rootnamespace$ or $assemblyname$. You can use any Visual Studio Project Property per the NuGet docs.
namespace $rootnamespace$.Controllers
{
public class HomeController : Controller
{
//snip
}
}
Step 4 - Decide what XML elements need to be merged (usually into web.config)
The next preprocessing that is common is adding elements to web.config. This is a nice little feature of NuGet because you just need to make a web.config.transform with the new elements and it will automatically and non-destructively add (and remove) them as needed. Here's my web.config.transform, for reference. Note this is not a full web.config. This is the one I added to my package in the control folder.
<configuration>
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages"/>
</namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
Step 5 - Add any PowerShell script you might need, especially for adding references
Almost done. Most package won't need much PowerShell, but some do. You can have an install.ps1 and an uninstall.ps1 and do lots of things. These go in a folder called Tools that's next to Content (not inside.)
Here's my install.ps1.
NOTE: Currently today there's no way to STOP the installation of a package while it's happening, so if you try to install mine on NuGet 1.0 I'll just warn you and ask you to uninstall. In the future there will likely be a pre-install or a dependency check. Hence the version check there.
param($installPath, $toolsPath, $package, $project)
if ($host.Version.Major -eq 1 -and $host.Version.Minor -lt 1)
{
"NOTICE: This package only works with NuGet 1.1 or above. Please update your NuGet install at http://nuget.codeplex.com. Sorry, but you're now in a weird state. Please 'uninstall-package AddMvc3ToWebForms' now."
}
else
{
$project.Object.References.Add("Microsoft.CSharp");
$project.Object.References.Add("System.Web.Mvc");
$project.Object.References.Add("Microsoft.Web.Infrastructure");
$project.Object.References.Add("System.Web.WebPages");
$project.Object.References.Add("System.Web.Razor");
$project.Object.References.Add("System.ComponentModel.DataAnnotations");
}
Note that in (the future) NuGet 1.2 I won't need this code, I'll just add the references in my NuSpec file directly.
Step 6 - Pack it up
Go back to the command line and run nuget pack
C:\Users\Scott\Desktop\AddMvc3ToWebForms>nuget pack
Attempting to build package from 'AddMvc3ToWebForms.nuspec'.
Successfully created package 'C:\Users\Scott\Desktop\AddMvc3ToWebForms\AddMvc3ToWebForms.0.4.nupkg'.
Step 7 - Submit your package
Next, login to the NuGet Gallery (beta) and Contribute Your Package. Just walk through the wizard and upload the nupkg. You can also get an API Key and use the command line tool to do this automatically, perhaps as part of a build process.
Submitting my app to the NuGet Gallery
That's it. If you've got an open source librar

How do you add a mime type when using ASP.NET vNext?

There's LOADS of information on how to add MIME types into a normal project.
These include configuring IIS, or modifying the web.config.
Both of these options are unavailable to me in vNext with IIS Express.
I had a look at the schema to the project.json file and couldn't find anything in there that would help either.
Can this be done yet? - I want to add a mime type for the .woff2 extension.
If you hosting it on IIS 7 or later then following step will do what you need. This answer I have used Visual Studio 2015 CTP5.
Publish your web application ( ASP.net vnext)
You can publish it to location like C:\MyPublish
Once it get successfully published you will find following location C:\MyPublish\wwwroot. Here You will find web.config.
Now host your site to in IIS ( Make sure that you have used C:\MyPublish\wwwroot as your path)
Now edit web.config over here just like you did for old version to add mime type. ( Following is my edit)
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="kpm-package-path" value="..\approot\packages" />
<add key="bootstrapper-version" value="1.0.0-beta2" />
<add key="kre-package-path" value="..\approot\packages" />
<add key="kre-version" value="1.0.0-beta2" />
<add key="kre-clr" value="CLR" />
<add key="kre-app-base" value="..\approot\src\WebApplication5" />
</appSettings>
<system.webServer>
<staticContent>
<remove fileExtension=".woff" />
<mimeMap fileExtension=".woff" mimeType="application/font-woff" />
</staticContent>
</system.webServer>
</configuration>
Note: As per my thinking In old version it is fix that it is always windows environment so we have direct web.config file in project and we edit that but now we have to follow different process to register as in future we can host completly on linux env as well.
Update : There is another way to do that as well. If you are using Microsoft.AspNet.StaticFiles package then you will have extension.
public void Configure(IApplicationBuilder app)
{
app.UseStaticFiles();
}
This will indirectly use https://github.com/aspnet/StaticFiles/blob/dev/src/Microsoft.AspNet.StaticFiles/FileExtensionContentTypeProvider.cs. Here you can see all mapping.
Update 2: (Add New Mime Type)
public void Configure(IApplicationBuilder app)
{
StaticFileOptions option = new StaticFileOptions();
FileExtensionContentTypeProvider contentTypeProvider = (FileExtensionContentTypeProvider)option.ContentTypeProvider;
contentTypeProvider.Mappings.Add("<<yourextention>>","<<mimetype>>");
app.UseStaticFiles(option);
}
Until this is released, you can also edit applicationhost.config which I found in D:\Documents\IISExpress\config (yours might be on your C drive [Documents]).
I added:
<mimeMap fileExtension=".woff2" mimeType="font/x-woff2" />
Inside <staticContent>.

VSTO Debug version fine, Installed version doesn't read app.config

I have a VSTO Excel 2007 add-in that should read connectionstrings from the app.config file, and then let the user decide which database to connect to. This works fine when I debug it, but when I run the deployed version (done with Windows Installer) the connectionstrings aren't read at all. I have added the primary outputs from all the projects to the setup project.
The app.config file is in the ExcelAddIn project, but not under the Excel heading. The class that manages the connectionstrings is in another project.
Here is my app.config file:
<?xml version="1.0"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
</configSections>
<connectionStrings>
<clear/>
<add name="MyEntities" connectionString="metadata=res://*/MyModel.csdl|res://*/MyModel.ssdl|res://*/SymModel.msl;provider=System.Data.SqlClient;provider connection string="data source=myServer;initial catalog=myDB;persist security info=True;user id=myUser;password=myPassword;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient"/>
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0"/>
</parameters>
</defaultConnectionFactory>
</entityFramework>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>
I use the following to get to the connectionstrings:
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConnectionStringsSection csSection = config.ConnectionStrings;
I have tried to add the ExcelAddin.dll.config file to the setup project's folder in which the Release folder and .proj file are. I have set the app.config file's 'Copy to Output Directory' property to 'Copy always' and the Build Action property to 'Content'.
Is there something worng with my app.config file, or why is it not picked up (the connectionstrings are not loaded into csSection) after I've run the installer?
Add file:/// to [TARGETDIR]ExcelAddIn.vsto|vstolocal (ex: file:///[TARGETDIR]ExcelAddIn.vsto|vstolocal) at the registry entries under "installer".
You need to add app.Config File to your Setup Project but not from the actual project do it from the Release\Debug folder of the ExcelAddIn project.
When you build you ExcelAddIn project it will leave App.config File to the Release\Debug Folder, piCk the file form there and include it into the dependicies folder of the Setup Project.
It seems that it is working with ClickOnce. So I still don't know what the problem was with the setup project and using Windows Installer, but at least I can deploy it.

Entity Framework version error in my small code first project

I'm writing a small test project in order to get my feet wet with EF code first. Unfortunately, when I try compiling, I get the following error:
Assembly 'Backend, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' uses
'EntityFramework, Version=4.3.1.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
which has a higher version than referenced assembly 'EntityFramework, Version=4.1.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089' c:\Users\Kevin\Documents\Visual
Studio 2010\Projects\CFTest\Backend\bin\Debug\Backend.dll CFTest
For some reason, there's a versioning conflict, but I dunno how to fix it.
EDIT: My App.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.3.1.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<parameter value="Data Source=.\SQLEXPRESS; Integrated Security=True; MultipleActiveResultSets=True" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>
My backend project had one version of EF while my MVC project came with another by default. Solved.
It is conflict with the version of the .NET framework your project is using, and the version of the .NET Framework that the EF dll was compiled in. If you go to the add reference window for the project, the listing should say what .NET Framework version each DLL uses. Change you project target to use that version as well.

Configuring Lightspeed for use in MVC3 Web project

I have a question regarding using LightSpeed in a MVC3 Web application. I am creating a REST Api project where I want to use LightSpeed, but the official configuration guidelines are quite vague. The official documentation says that the following lines need to be added to the file web.config:
<configSections>
<section name="lightSpeedContexts"
type="Mindscape.LightSpeed.Configuration.LightSpeedConfigurationSection, Mindscape.LightSpeed" />
</configSections>
<lightSpeedContexts>
<add name="Test" />
</lightSpeedContexts>
<lightSpeedContexts>
<add name="Test" dataProvider="SQLite3" />
</lightSpeedContexts>
I tried adding following lines to the web.config in the root:
<configSections>
<section name="lightSpeedContexts"
type="Mindscape.LightSpeed.Configuration.LightSpeedConfigurationSection, Mindscape.LightSpeed" />
</configSections>
<lightSpeedContexts>
<add name="Default" connectionStringName="Prod" dataProvider="MySQL5" />
</lightSpeedContexts>
<connectionStrings>
<add name="Prod" connectionString="server=localhost;User Id=production;password=xxx;Persist Security Info=True;database=CBS"/>
</connectionStrings>
This throws an exception when I start the Web application which tells me that configSections may not be specified more than once in the application. The root web.config file did not have any of these specified per default.
I am not sure where to put this configuration.
OK, I found out how to solve the problem.
I moved out the configSections that were in the two sub web.config files (in each Views folder) and put the contents in the main web.config file, then I added the lightSpeedContexts and connectionStrings in the main web.config file.

Resources