Show ErrorList Windows in Visual Studio 2010 Addin - visual-studio-2010

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");
}
}

Related

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.

Unable to load DLL 'e_sqlite3': The specified module could not be found

I have a Xamarin Forms solution. I added sqlite-net-pcl as reference to all projects. It works fine on Android but crashes on Windows 8.1 and Windows Phone 8.1. I have an IOS project but I don't have OSX at the moment to try it.
I use this in the Windows projects to access the database:
using System.IO;
using SQLite;
using Xamarin.Forms;
using HelloXamarin.Windows;
using Windows.Storage;
[assembly: Dependency(typeof(SQLiteDb))]
namespace HelloXamarin.Windows
{
public class SQLiteDb : ISQLiteDb
{
public SQLiteAsyncConnection GetConnection(string databaseName)
{
var documentsPath = ApplicationData.Current.LocalFolder.Path;
var path = Path.Combine(documentsPath, databaseName);
return new SQLiteAsyncConnection(path);
}
}
}
Here are my references:
I get this exception when trying to access the database:
The type initializer for 'SQLite.SQLiteConnection' threw an exception.
Unable to load DLL 'e_sqlite3': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
at SQLitePCL.SQLite3Provider_e_sqlite3.NativeMethods.sqlite3_win32_set_directory(UInt32 directoryType, String directoryPath)
at SQLitePCL.SQLite3Provider_e_sqlite3..ctor()
at SQLitePCL.Batteries_V2.Init() at SQLite.SQLiteConnection..cctor()
I have no idea how to solve this, please help me!
The whole solution is available on GitHub:
https://github.com/apspot/HelloXamarin
For me, it worked by adding the e_sqlite3 bundle to the executable project
By this time the issue is still open. So before they come with some solid fix, you can use this work around, to solve the issue for now.
Add one helper class
using System;
using System.Diagnostics;
using System.IO;
namespace SQLitePCL
{
public class NativeLibraryHack
{
public static bool Hacked { get; private set; }
public static bool DoHack()
{
if (Hacked) return true;
try
{
const string runtimeFolderName = "/runtimes";
var destinationPath = typeof(SQLitePCL.raw).Assembly.Location
.Replace("\\", "/");
var destinationLength = destinationPath.LastIndexOf("/", StringComparison.OrdinalIgnoreCase);
var destinationDirectory = destinationPath.Substring(0, destinationLength) + runtimeFolderName;
var sourcePath = new Uri(typeof(SQLitePCL.raw).Assembly.CodeBase)
.AbsolutePath;
var sourceLength = sourcePath.LastIndexOf("/", StringComparison.OrdinalIgnoreCase);
var sourceDirectory = sourcePath.Substring(0, sourceLength) + runtimeFolderName;
if (Directory.Exists(sourceDirectory))
CopyFilesRecursively(new DirectoryInfo(sourceDirectory), new DirectoryInfo(destinationDirectory));
}
catch (Exception ex)
{
//Ignore Exception
Debug.WriteLine(ex.Message);
return false;
}
return (Hacked = true);
}
private static void CopyFilesRecursively(
DirectoryInfo source,
DirectoryInfo target
)
{
foreach (var dir in source.GetDirectories())
CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name));
foreach (var file in source.GetFiles())
{
try
{
var destinationFile = Path.Combine(target.FullName, file.Name);
if (!File.Exists(destinationFile))
file.CopyTo(destinationFile);
}
catch (Exception ex)
{
//Ignore Exception
Debug.WriteLine(ex.Message);
}
}
}
}
}
And add the hack before your db migration script, I am using web api 2
so i did on RouteConfig.RegisterRoutes
NativeLibraryHack.DoHack();
using (KSDBContext db = new KSDBContext())
{
db.Database.Migrate();
}
You need to add the SQLite Extensions.
Go to Tools > Extensions and Updates
Go to Online, then search for SQLite.
Download SQLite for Windows Runtime
In your Windows Project, Add Reference and ensure you add the extension.
Also remove Microsoft.VCLibs from your references.
Try referencing Visual C++ 2015 Runtime for Universal Windows Platform Apps. That sorted it out for me.
Go to References
Add Reference
Extensions.
Check"Visual C++ 2015 Runtime for Universal Windows Platform Apps"
OK

Programmatically access TFS annotations to determine owner

I'm working on a project team and our application is in TFS. I'm attempting to determine how many lines of code each team member is responsible. In TFS, I'm aware of the Annotate feature in the Visual Studio interface which allows you to see who last modified each line of code so I know TFS has this information.
I've written a small console app which accesses my TFS project and all its files, but I now need to programmatically access annotations so I can see who the owner of each line is. Here is my existing code:
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
public class Program
{
static void Main(string[] args)
{
var credentials = new NetworkCredential(username, password, domain);
var server = new TfsTeamProjectCollection(new Uri(serverUrl), credentials);
var version = server.GetService(typeof(VersionControlServer)) as VersionControlServer;
var items = version.GetItems(projectPath, RecursionType.Full);
var fileItems = items.Items.Where(x => x.ItemType == ItemType.File);
foreach (var fileItem in fileItems)
{
var serverItem = fileItem.ServerItem;
//TODO: retrieve and parse annotations
}
}
}
I can't seem to figure out how to retrieve annotations once I have the TFS item. This link explains how to do it by calling TFPT, but after implementing it (tfpt annotate /noprompt <filename>), you are only give the last changeset and code per line, not the owner.
I also found a Microsoft.TeamFoundation.VersionControl.Server namespace that has an Annotation class. I installed TFS on my machine to have access to that DLL, but it doesn't seem like it is of any help to this problem.
How can you programmatically access TFS annotations to determine the owner of a line of code for a file?
You may have to query the branch when a Item's change type is Branch.
For a simple example, there is a scenario
$/Project
/Main`
/a.txt
/Develop
/a.txt (branched from main)
When you query the history of $/project/Develop/a.txt, you can also get the history of $/project/Main/a.txt using following code
void GetAllHistory(string serverItem)
{
var changesets=vcs.QueryHistory(serverItem,
Microsoft.TeamFoundation.VersionControl.Client.VersionSpec.Latest,
0,
Microsoft.TeamFoundation.VersionControl.Client.RecursionType.None,
null,
new Microsoft.TeamFoundation.VersionControl.Client.ChangesetVersionSpec(1),
Microsoft.TeamFoundation.VersionControl.Client.VersionSpec.Latest,
int.MaxValue,
true,
false);
foreach (var obj in changesets)
{
Microsoft.TeamFoundation.VersionControl.Client.Changeset cs = obj as Microsoft.TeamFoundation.VersionControl.Client.Changeset;
if (cs == null)
{
return;
}
foreach (var change in cs.Changes)
{
if (change.Item.ServerItem != serverItem)
{
return;
}
Console.WriteLine(string.Format("ChangeSetID:{0}\tFile:{1}\tChangeType:{2}", cs.ChangesetId,change.Item.ServerItem, change.ChangeType));
if ((change.ChangeType & Microsoft.TeamFoundation.VersionControl.Client.ChangeType.Branch) == Microsoft.TeamFoundation.VersionControl.Client.ChangeType.Branch)
{
var items=vcs.GetBranchHistory(new Microsoft.TeamFoundation.VersionControl.Client.ItemSpec[]{new Microsoft.TeamFoundation.VersionControl.Client.ItemSpec(serverItem, Microsoft.TeamFoundation.VersionControl.Client.RecursionType.None)},
Microsoft.TeamFoundation.VersionControl.Client.VersionSpec.Latest);
GetAllHistory(items[0][0].Relative.BranchToItem.ServerItem);
}
}
}
}

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.

Installing a .net 2008 windows service

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.

Resources