I'm working from the docs on trying to create a sheet with a view on it using the Revit API in C#
here is the docs URL link. You can find the code at the bottom in the first C# block.
I get a red squiggly under the view3D.Id:
Viewport.Create(doc, viewSheet.Id, view3D.Id, new XYZ(location.U, location.V, 0));
I can't find that it was deprecated nor can I figure out how to resolve it. I'm a bit confused about why it's trying to grab its own elementID. Also, just getting into the revit-API. it seems like "views" in Revit are called "viewports" in the API. i need to read more on this.
here is the entire code block:
private void CreateSheetView(Autodesk.Revit.DB.Document document, View3D view3D)
{
// Get an available title block from document
FilteredElementCollector collector = new FilteredElementCollector(document);
collector.OfClass(typeof(FamilySymbol));
collector.OfCategory(BuiltInCategory.OST_TitleBlocks);
FamilySymbol fs = collector.FirstElement() as FamilySymbol;
if (fs != null)
{
using (Transaction t = new Transaction(document, "Create a new ViewSheet"))
{
t.Start();
try
{
// Create a sheet view
ViewSheet viewSheet = ViewSheet.Create(document, fs.Id);
if (null == viewSheet)
{
throw new Exception("Failed to create new ViewSheet.");
}
// Add passed in view onto the center of the sheet
UV location = new UV((viewSheet.Outline.Max.U - viewSheet.Outline.Min.U) / 2,
(viewSheet.Outline.Max.V - viewSheet.Outline.Min.V) / 2);
//viewSheet.AddView(view3D, location);
Viewport.Create(document, viewSheet.Id, view3D.Id, new XYZ(location.U, location.V, 0));
^ERROR HAPPENS IN LINE ABOVE AT view3D.Id
// Print the sheet out
if (viewSheet.CanBePrinted)
{
TaskDialog taskDialog = new TaskDialog("Revit");
taskDialog.MainContent = "Print the sheet?";
TaskDialogCommonButtons buttons = TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No;
taskDialog.CommonButtons = buttons;
TaskDialogResult result = taskDialog.Show();
if (result == TaskDialogResult.Yes)
{
viewSheet.Print();
}
}
t.Commit();
}
catch
{
t.RollBack();
}
}
}
}
The Building Coder discussion of exact viewport positioning includes some woking sample calls to ViewSheet.Create and Viewport.Create.
Related
Background: I'm trying to write a program to insert an image into a cell of a spreadsheet. LibreOffice recently changed how this is done, and all the samples I could find use the old method which no longer works.
Technically I know that you can't "insert" an image into a cell and that such an image is an overlay on a DrawPage that sits on top of the spreadsheet to "decorate" it.
One of the first steps in doing this (the new way) is to create an XGraphic object which contains the image. The process is to create an XGraphicProvider and call it with MediaProperties that specify the image file URL to be loaded. I have a program that is supposed to do this but the resulting XGraphic is null. The LO SDK gives pretty much no information when you do something wrong; it just doesn't work.
Here is the code I have, with all the headers removed:
// addpic
// add picture to spreadsheet - debug version
class OpenOfficeApp {
[STAThread]
static void Main(string[] args) {
bool lreadonly;
string pqfile;
string pqURL;
string pqpic;
pqfile = "file:///D:/Documents/NSexeye/ODS%20File%20Access/"+
"addpix/addpic.ods";
pqpic = "addpic2";
pqURL = pqpic+".jpg";
lreadonly = false;
Console.WriteLine("Using: "+pqfile);
// get the desktop
XComponentContext XCC = uno.util.Bootstrap.bootstrap();
XMultiComponentFactory XMCF =
(XMultiComponentFactory)XCC.getServiceManager();
XMultiServiceFactory XMSF = (XMultiServiceFactory)XCC.getServiceManager();
XComponentLoader XCL =
(XComponentLoader)XMSF.createInstance("com.sun.star.frame.Desktop");
// open the spreadsheet
PropertyValue[] pPV = new PropertyValue[2];
pPV[0] = new PropertyValue();
pPV[0].Name = "Hidden";
pPV[0].Value = new uno.Any(true);
pPV[1] = new PropertyValue();
pPV[1].Name = "ReadOnly";
if (lreadonly) pPV[1].Value = new uno.Any(true);
else pPV[1].Value = new uno.Any(false);
XComponent XCo = XCL.loadComponentFromURL(pqfile,"_blank",0,pPV);
// create graphic object containing image
object oGP = XMCF.createInstanceWithContext(
"com.sun.star.graphic.GraphicProvider",XCC);
if (oGP == null) {
Console.WriteLine("oGP is null. Aborting.");
return;
}
XGraphicProvider XGP = (XGraphicProvider)oGP;
if (XGP == null) {
Console.WriteLine("XGP is null. Aborting.");
return;
}
pPV = new PropertyValue[1];
pPV[0] = new PropertyValue();
pPV[0].Name = "URL";
pPV[0].Value = new uno.Any(pqURL);
Console.WriteLine("Creating XGraphic containing "+pqURL);
XGraphic XG = XGP.queryGraphic(pPV);
// *** XG is null here
if (XG == null) {
Console.WriteLine("XG is null. Aborting.");
return;
}
// ... lots of stuff to be added here
// save and close the spreadsheet
XModifiable XM = (XModifiable)XCo;
XM.setModified(true);
XStorable XSt = (XStorable)XCo;
XSt.store();
XCloseable XCl = (XCloseable)XCo;
XCl.close(true);
// terminate LibreOffice
// *** I want this to not terminate it if something else is open
XDesktop XD = (XDesktop)XCL;
if (XD != null) XD.terminate();
}
}
I get a null for the XGraphic, in the place indicated in the comments. I don't know if the call to create it is failing, or if one of the earlier steps of the process are incorrect.
My goal here, in addition to getting my program working, is to create a sample program showing how to add an image to a Calc spreadsheet cell, and to manipulate such images. There are a fair number of people asking questions about this and none of the examples I've found will work. I think a good working sample will be of value.
I've spent a lot of time searching for information and code samples for this, with nothing that helps. I've tried to find ways to verify the validity of the XGraphicProvider interface with no luck. I've run out of things to try.
I'm hoping someone who knows about the LibreOffice SDK can take a look and maybe see what I'm doing wrong.
Update: I figured out what I was doing wrong: I was passing a bare filename in the "URL" property to XGraphicProvider. It has to be the same format (starting with "file:///") as the spreadsheet's file name specification.
Now I'm stuck with another property problem. The XGraphic has to be specified as a parameter to the GraphicObjectShape's Graphic property, but the setPropertyValue() function requires that it be a uno.Any type. I can't figure out how to specify an interface name like XGraphic as a uno.Any.
Here is the piece of code that won't compile, complaining that it can't convert an XGraphic to a uno.Any, in the first setPropertyValue call:
// set image XGraphic
XPropertySet XPS = (XPropertySet)XS;
XPS.setPropertyValue("Graphic",XG);
XPS.setPropertyValue("Name",new uno.Any(pqpic));
XG is an XGraphic type. Using "new uno.Any(XG)" doesn't work either, giving a similar compiler error.
After trying unsuccessfully for a few hours to get the latest LO SDK up and running, let me offer some untested ideas.
First of all, here is some working Basic code, no doubt similar to what you're translating from. The important line is oShape.Graphic = oProvider.queryGraphic(Props()).
oDoc = ThisComponent
oSheet = oDoc.CurrentController.ActiveSheet
pqURL = "file:///C:/Users/JimK/Desktop/addpic.jpg"
oProvider = createUnoService("com.sun.star.graphic.GraphicProvider")
oShape = oDoc.createInstance("com.sun.star.drawing.GraphicObjectShape")
Dim Props(0) as new com.sun.star.beans.PropertyValue
Props(0).Name= "URL"
Props(0).Value = pqURL
oShape.Graphic = oProvider.queryGraphic(Props())
oCell = oSheet.getCellByPosition(5,5)
oShape.Name = oCell.AbsoluteName + "##" + Props(0).Value
oShape.Anchor = oCell
oSheet.DrawPage.add(oShape)
'Resize
w = oShape.Graphic.Size.Width
h = oShape.Graphic.Size.Height
wcl = oCell.Size.Width
hcl = oCell.Size.Height
If w<>0 and h<>0 then
oCell.String=""
Dim Size as new com.sun.star.awt.Size
Size.Width = wcl
Size.Height = h*wcl/w
If Size.Height > hcl then
Size.Width = hcl*w/h
Size.Height = hcl
Endif
oShape.setSize(Size)
oShape.setPosition(oCell.Position)
erase oShape
Else
oShape.dispose()
Endif
Now, how to translate this to C#? It looks like you may need to explicitly specify the type. In the SDK example, there are calls like this.
xFieldProp.setPropertyValue(
"Orientation",
new uno.Any(
typeof (unoidl.com.sun.star.sheet.DataPilotFieldOrientation),
unoidl.com.sun.star.sheet.DataPilotFieldOrientation.DATA ) );
So in your case, something like this:
XPS.setPropertyValue(
"Graphic"
new uno.Any(
typeof(unoidl.com.sun.star.graphic.XGraphic),
XG));
Alternatively, follow the suggestion here: set GraphicURL, which should load the image and set Graphic for you.
I am trying to make shapefiles with point geometries using GDAL. I am following the example given here. I am using Microsoft Visual Studio and the programming language is C#. For now, I am just making one point at the origin and I'm viewing the resulting shapefiles in QGIS. For some reason, I am not being able to view the point which I make. I have tried making a polygon too but I am facing the same problem. Below is the code I have written:
public void testSF(Dataset ds)
{
Console.WriteLine("Writing ERSI shapefile");
// Registering drivers
OSGeo.OGR.Ogr.RegisterAll();
OSGeo.OGR.Driver driverSH = OSGeo.OGR.Ogr.GetDriverByName("ESRI Shapefile");
if (driverSH == null)
{
Console.WriteLine("Cannot get drivers. Exiting");
System.Environment.Exit(-1);
}
Console.WriteLine("Drivers fetched");
// Creating a shapefile
OSGeo.OGR.DataSource dataSourceSH = driverSH.CreateDataSource("ERSI_TEST_ShapeFile.shp", new string[] { });
if (dataSourceSH == null)
{
Console.WriteLine("Cannot create datasource");
System.Environment.Exit(-1);
}
Console.WriteLine("Shapefile created");
// Creating a point layer
OSGeo.OGR.Layer layerSH;
layerSH = dataSourceSH.CreateLayer("PolygonLayer", null, OSGeo.OGR.wkbGeometryType.wkbPoint, new string[] { });
if (layerSH == null)
{
Console.WriteLine("Layer creation failed, exiting...");
System.Environment.Exit(-1);
}
Console.WriteLine("Polygon Layer created");
// Creating and adding attribute fields to layer
OSGeo.OGR.FieldDefn fdefnName = new OSGeo.OGR.FieldDefn("Name", OSGeo.OGR.FieldType.OFTString);
fdefnName.SetWidth(32);
OSGeo.OGR.FieldDefn fdefnGPS = new OSGeo.OGR.FieldDefn("GPS", OSGeo.OGR.FieldType.OFTString);
fdefnGPS.SetWidth(32);
if (layerSH.CreateField(fdefnName, 1) != 0)
{
Console.WriteLine("Creating Name field failed");
System.Environment.Exit(-1);
}
if (layerSH.CreateField(fdefnGPS, 1) != 0)
{
Console.WriteLine("Creating GPS field failed");
System.Environment.Exit(-1);
}
Console.WriteLine("Fields created and added to layer");
OSGeo.OGR.Feature featureSH = new OSGeo.OGR.Feature(layerSH.GetLayerDefn());
featureSH.SetField("Name", "This is a NAME");
featureSH.SetField("GPS", "Test GPS point");
// Outer Ring
// Methodology: Create a linear ring geometry, add it to a polygon geometry. Add polygon geometry to feature. Add feature to layer
OSGeo.OGR.Feature feature = new OSGeo.OGR.Feature( layerSH.GetLayerDefn() );
OSGeo.OGR.Geometry geom = OSGeo.OGR.Geometry.CreateFromWkt("POINT(0.0 0.0)");
feature.SetGeometry(geom);
layerSH.CreateFeature(feature);
}
This code adds a point to the polygon layer at 0.0 and 0.0. However, when I open the resulting layer in QGIS, I can not see/locate the point. Any help would be appreciated.
I have tested your code with last GDAL release and it works.
You have to close the datasource (call Dispose method) to update the file with the created geometry otherwise you will just view an empty file.
I think You are missing to define the spatial reference
I'm trying to create a new plug-in on Revit 2016/2017 with the API.
The idea is to copy a set of element from small revit file to a central one to compile them.
Here is the code I'm using :
FilterableValueProvider provider = new ParameterValueProvider(new ElementId(BuiltInParameter.ALL_MODEL_TYPE_NAME));
FilterRule rule = new FilterStringRule(provider, new FilterStringContains(), "BY_GO", false);
ElementParameterFilter epf = new ElementParameterFilter(rule, true);
ICollection<ElementId> npText = new FilteredElementCollector(secDoc, secView.Id).WherePasses(epf).ToElementIds();
using (TransactionGroup tx = new TransactionGroup(mainDoc, "Insert " + Main._roomFile.Typology))
{
ICollection<ElementId> pastedElements;
tx.Start();
using (Transaction tr = new Transaction(mainDoc, "Copy elements"))
{
tr.Start();
pastedElements = ElementTransformUtils.CopyElements(secView, npText, mainView, null, new CopyPasteOptions());
tr.Commit();
}
using (Transaction tr = new Transaction(mainDoc, "Move elements"))
{
tr.Start();
pastedElements = new FilteredElementCollector(mainDoc, pastedElements).WherePasses(epf).ToElementIds();
XYZ originePoint = new FilteredElementCollector(mainDoc, pastedElements).OfClass(typeof(Floor)).First().get_BoundingBox(null).Min;
XYZ translation = extremitePoint - originePoint;
translation = new XYZ(translation.X, translation.Y, 0);
ElementTransformUtils.MoveElements(mainDoc, pastedElements, translation);
tr.Commit();
}
tx.Assimilate();
}
When I use it, everything is good except the dimensions. They are inside the new document (I can get them with there id and RevitLookup) but they are hidden. If I select on of them and add a witness line the dimension is now visible again.
I tried to close and reopen Revit and place the vien on a sheet bt nothing.
Any idea ?
Thank you !
You need to regenerate the view I believe.
Try adding:
Document.Regenerate();
Here is the answer to the probleme.
It's Autodesk which have to solve it but the workaround is to create Dimensions with the reference of invisible one and then delete them.
I want to use ActiViz .NET and C# to multitexture an object created from .obj file.
As long as I know somehow to use texture with single texture, I have problem with more than one texture. Based on what I found on VTK GitHub I started writing a code, but there comes problem with SetBlendingMode and MapDataArrayToMultiTextureAttribute methods.
I use SetBlendingMode like this:
texture.SetBlendingMode(vtkTexture.VTKTextureBlendingMode.VTK_TEXTURE_BLENDING_MODE_REPLACE);
which results with:
The best overloaded method match for 'Kitware.VTK.vtkTexture.SetBlendingMode(int)' has some invalid arguments
With MapDataArrayToMultiTextureAttribute it looks like this:
mapper.MapDataArrayToMultiTextureAttribute(vtkProperty.VTKTextureUnit.VTK_TEXTURE_UNIT_0, "TCoords", vtkDataObject.FIELD_ASSOCIATION, 0);
which ends with similar message:
The best overloaded method match for 'Kitware.VTK.vtkPolyDataMapper.MapDataArrayToMultiTextureAttribute(int, string, int, int)' has some invalid arguments
The whole code:
private void ReadOBJ(string path)
{
vtkTesting test = vtkTesting.New();
// Varibles for obj file and texture
string filePath = path;
string texturePath0 = #"C:\Users\admin\Desktop\Fox-Skull-obj\Fox Skull_0.jpg";
string texturePath1 = #"C:\Users\admin\Desktop\Fox-Skull-obj\Fox Skull_1.jpg";
string texturePath2 = #"C:\Users\admin\Desktop\Fox-Skull-obj\Fox Skull_2.jpg";
string texturePath3 = #"C:\Users\admin\Desktop\Fox-Skull-obj\Fox Skull_3.jpg";
// Open jpeg file including texture
vtkJPEGReader jpegReader = new vtkJPEGReader();
jpegReader.SetFileName(texturePath0);
jpegReader.Update();
vtkJPEGReader jpegReader1 = new vtkJPEGReader();
jpegReader1.SetFileName(texturePath1);
jpegReader1.Update();
vtkJPEGReader jpegReader2 = new vtkJPEGReader();
jpegReader2.SetFileName(texturePath2);
jpegReader2.Update();
vtkJPEGReader jpegReader3 = new vtkJPEGReader();
jpegReader3.SetFileName(texturePath3);
jpegReader3.Update();
// Open obj file
vtkOBJReader reader = new vtkOBJReader();
if (!File.Exists(filePath))
{
MessageBox.Show("Cannot read file \"" + filePath + "\"", "Error", MessageBoxButtons.OK);
return;
}
reader.SetFileName(filePath);
reader.Update();
vtkTriangleFilter triangleFilter = vtkTriangleFilter.New();
triangleFilter.SetInputConnection(reader.GetOutputPort());
vtkStripper stripper = vtkStripper.New();
stripper.SetInputConnection(triangleFilter.GetOutputPort());
stripper.Update();
vtkPolyData polydata = stripper.GetOutput();
polydata.Register(null);
polydata.GetPointData().SetNormals(null);
vtkFloatArray TCoords = vtkFloatArray.New();
TCoords.SetNumberOfComponents(2);
TCoords.Allocate(8, 0);
TCoords.InsertNextTuple2(0.0, 0.0);
TCoords.InsertNextTuple2(1.0, 0.0);
TCoords.InsertNextTuple2(0.0, 1.0);
TCoords.InsertNextTuple2(1.0, 1.0);
TCoords.SetName("TCoords");
polydata.GetPointData().AddArray(TCoords);
// Create texture
vtkTexture texture = new vtkTexture();
vtkTexture texture1 = new vtkTexture();
vtkTexture texture2 = new vtkTexture();
vtkTexture texture3 = new vtkTexture();
texture.SetInputConnection(jpegReader.GetOutputPort());
texture1.SetInputConnection(jpegReader1.GetOutputPort());
texture2.SetInputConnection(jpegReader2.GetOutputPort());
texture3.SetInputConnection(jpegReader3.GetOutputPort());
texture.SetBlendingMode((int)vtkTexture.VTKTextureBlendingMode.VTK_TEXTURE_BLENDING_MODE_REPLACE);
texture1.SetBlendingMode((int)vtkTexture.VTKTextureBlendingMode.VTK_TEXTURE_BLENDING_MODE_ADD);
texture2.SetBlendingMode((int)vtkTexture.VTKTextureBlendingMode.VTK_TEXTURE_BLENDING_MODE_ADD);
texture3.SetBlendingMode((int)vtkTexture.VTKTextureBlendingMode.VTK_TEXTURE_BLENDING_MODE_ADD);
// Mapping textures
vtkTextureMapToCylinder mapSphere = new vtkTextureMapToCylinder();
mapSphere.SetInputConnection(reader.GetOutputPort());
// Visualize
vtkPolyDataMapper mapper = vtkPolyDataMapper.New();
mapper.SetInput(polydata);
// Get a reference to the renderwindow of our renderWindowControl1
vtkRenderWindow renderWindow = renderWindowControl1.RenderWindow;
// Renderer
vtkRenderer renderer = renderWindow.GetRenderers().GetFirstRenderer();
vtkRenderWindowInteractor iren = vtkRenderWindowInteractor.New();
iren.SetRenderWindow(renderWindow);
// Create actor and add mapper with texture
vtkActor actor = vtkActor.New();
vtkOpenGLHardwareSupport hardware = vtkOpenGLRenderWindow.SafeDownCast(renderWindow).GetHardwareSupport();
bool supported = hardware.GetSupportsMultiTexturing();
int tu = 0;
if (supported)
{
tu = hardware.GetNumberOfFixedTextureUnits();
}
if (supported && tu > 2)
{
mapper.MapDataArrayToMultiTextureAttribute((int)vtkProperty.VTKTextureUnit.VTK_TEXTURE_UNIT_0, "TCoords", (int)vtkDataObject.FieldAssociations.FIELD_ASSOCIATION_POINTS, -1);
mapper.MapDataArrayToMultiTextureAttribute((int)vtkProperty.VTKTextureUnit.VTK_TEXTURE_UNIT_1, "TCoords", (int)vtkDataObject.FieldAssociations.FIELD_ASSOCIATION_POINTS, -1);
mapper.MapDataArrayToMultiTextureAttribute((int)vtkProperty.VTKTextureUnit.VTK_TEXTURE_UNIT_2, "TCoords", (int)vtkDataObject.FieldAssociations.FIELD_ASSOCIATION_POINTS, -1);
mapper.MapDataArrayToMultiTextureAttribute((int)vtkProperty.VTKTextureUnit.VTK_TEXTURE_UNIT_3, "TCoords", (int)vtkDataObject.FieldAssociations.FIELD_ASSOCIATION_POINTS, -1);
actor.GetProperty().SetTexture((int)vtkProperty.VTKTextureUnit.VTK_TEXTURE_UNIT_0, texture);
actor.GetProperty().SetTexture((int)vtkProperty.VTKTextureUnit.VTK_TEXTURE_UNIT_1, texture1);
actor.GetProperty().SetTexture((int)vtkProperty.VTKTextureUnit.VTK_TEXTURE_UNIT_2, texture2);
actor.GetProperty().SetTexture((int)vtkProperty.VTKTextureUnit.VTK_TEXTURE_UNIT_3, texture3);
}
else
{
if (supported)
{
mapper.MapDataArrayToMultiTextureAttribute((int)vtkProperty.VTKTextureUnit.VTK_TEXTURE_UNIT_0, "TCoords", (int)vtkDataObject.AttributeTypes.POINT, 0);
}
actor.SetTexture(texture);
}
actor.SetMapper(mapper);
renderWindow.AddRenderer(renderer);
// Hide current actor
renderer.RemoveAllViewProps();
// Set background color
renderer.SetBackground(0.3, 0.6, 0.3);
// Add new actor to the renderer
renderer.AddActor(actor);
// Render
renderWindow.Render();
}
Does anybody have any experience with multitexture with C# and VTK and can help me? Do you know any other solutions that can help me?
EDIT 01.12.2015
Thanks to JohnnyQ answer I probably make functions mentioned above working. I say "probably" because right now when I'm running code and select .obj file program stops working with one of two errors:
An unhandled exception of type 'System.AccessViolationException' occurred in Kitware.VTK.dll with information about attempt of read or write protected memory or program just stops with vshost32.exe stop working message.
I've updated code above to actual version. Any suggestions are still appreciated.
You have to explicit cast from the enum type to an integral type.
e.g.
texture.SetBlendingMode((int)vtkTexture.VTKTextureBlendingMode.VTK_TEXTURE_BLENDING_MODE_REPLACE);
I want to show c# source code with syntax highlighting and theme coloring inside a wpf control. This is for preview only and I don't need any editing capabilities.
I found some code samples on how to embed a code editor which receives a file path to load.
I loaded it with a temp file I created - and it works, well almost...
The problem is that the loaded code have parsing errors which shows up in the error list.
Is there a way to set those errors to not appear in the error list?
Here is the code:
IVsInvisibleEditorManager invisibleEditorManager = (IVsInvisibleEditorManager)ServiceProvider.GlobalProvider.GetService(typeof(SVsInvisibleEditorManager));
ErrorHandler.ThrowOnFailure(invisibleEditorManager.RegisterInvisibleEditor(csTempFilePath, pProject: null,dwFlags: (uint)_EDITORREGFLAGS.RIEF_ENABLECACHING,
pFactory: null, ppEditor: out this.invisibleEditor));
//The doc data is the IVsTextLines that represents the in-memory version of the file we opened in our invisibe editor, we need
//to extract that so that we can create our real (visible) editor.
IntPtr docDataPointer = IntPtr.Zero;
Guid guidIVSTextLines = typeof(IVsTextLines).GUID;
ErrorHandler.ThrowOnFailure(this.invisibleEditor.GetDocData(fEnsureWritable: 1, riid: ref guidIVSTextLines, ppDocData: out docDataPointer));
try
{
IVsTextLines docData = (IVsTextLines)Marshal.GetObjectForIUnknown(docDataPointer);
//Get the component model so we can request the editor adapter factory which we can use to spin up an editor instance.
IComponentModel componentModel = (IComponentModel)ServiceProvider.GlobalProvider.GetService(typeof(SComponentModel));
IVsEditorAdaptersFactoryService editorAdapterFactoryService = componentModel.GetService<IVsEditorAdaptersFactoryService>();
//Create a code window adapter.
this.codeWindow = editorAdapterFactoryService.CreateVsCodeWindowAdapter(OleServiceProvider);
IVsCodeWindowEx codeWindowEx = (IVsCodeWindowEx)this.codeWindow;
INITVIEW[] initView = new INITVIEW[1];
codeWindowEx.Initialize((uint)_codewindowbehaviorflags.CWB_DISABLESPLITTER,
VSUSERCONTEXTATTRIBUTEUSAGE.VSUC_Usage_Filter,
szNameAuxUserContext: "",
szValueAuxUserContext: "",
InitViewFlags: 0,
pInitView: initView);
ErrorHandler.ThrowOnFailure(this.codeWindow.SetBuffer((IVsTextLines)docData));
//Get our text view for our editor which we will use to get the WPF control that hosts said editor.
ErrorHandler.ThrowOnFailure(this.codeWindow.GetPrimaryView(out this.textView));
//Get our WPF host from our text view (from our code window).
IWpfTextViewHost textViewHost = editorAdapterFactoryService.GetWpfTextViewHost(this.textView);
textViewHost.TextView.Options.SetOptionValue(DefaultTextViewHostOptions.ChangeTrackingId, false);
textViewHost.TextView.Options.SetOptionValue(DefaultTextViewOptions.ViewProhibitUserInputId, true);
var dte = ContainerFactory.GetContainer().Resolve<DTE2>();
var projectItem = dte.Solution.FindProjectItem(csTempFilePath);
projectItem.Properties.Item("BuildAction").Value = prjBuildAction.prjBuildActionNone;
return textViewHost.HostControl;
}
finally
{
if (docDataPointer != IntPtr.Zero)
{
//Release the doc data from the invisible editor since it gave us a ref-counted copy.
Marshal.Release(docDataPointer);
}
}
I've tried to remove the errors from the error list manually. But it didn't work - I think it's because i can only remove errors that I added previously. Here is the code I tried using to remove the errors:
public void RemoveTempFileErrors()
{
var provider = new ErrorListProvider(ServiceProvider.GlobalProvider)
{
ProviderName = "MyProvider",
ProviderGuid = new Guid("41C0915D-A0F4-42B2-985F-D1CC5F65BFFC") // my provider guid
};
var vsTaskList1 = (IVsTaskList) Package.GetGlobalService(typeof (IVsTaskList));
uint providerCookie;
vsTaskList1.RegisterTaskProvider(provider, out providerCookie);
vsTaskList1.RefreshTasks(providerCookie);
var vsTaskList2 = (IVsTaskList2)Package.GetGlobalService(typeof(IVsTaskList));
provider.SuspendRefresh();
IVsEnumTaskItems enumerator;
vsTaskList1.EnumTaskItems(out enumerator);
IVsTaskItem[] arr = new IVsTaskItem[1];
while (enumerator.Next(1, arr, null) == 0)
{
string doc;
arr[0].Document(out doc);
if (doc == csTempFilePath)
{
vsTaskList2.RemoveTasks(providerCookie, 1, arr);
}
}
provider.ResumeRefresh();
provider.Refresh();
vsTaskList1.UnregisterTaskProvider(providerCookie);
}
I solved it partially -
The parsing errors were caused because the code was a method without a class. So i wrapped the method in a class and used an elision buffer to show only the method without the wrapper class
The elision buffer code goes like this:
var subsetSnapshot = new SnapshotSpan(textSnapshot.Lines.First().EndIncludingLineBreak, textSnapshot.Lines.Last().Start);
var projectionBufferFactory = componentModel.GetService<IProjectionBufferFactoryService>();
var projBuffer = projectionBufferFactory.CreateElisionBuffer(null,
new NormalizedSnapshotSpanCollection(subsetSnapshot), ElisionBufferOptions.None);
IVsTextBuffer bufferAdapter = editorAdapterFactoryService.CreateVsTextBufferAdapterForSecondaryBuffer(OleServiceProvider, projBuffer);
projTextView = editorAdapterFactoryService.CreateVsTextViewAdapter(OleServiceProvider);
projTextView.Initialize((IVsTextLines)bufferAdapter, IntPtr.Zero,
(uint)TextViewInitFlags.VIF_HSCROLL | (uint)TextViewInitFlags.VIF_VSCROLL | (uint)TextViewInitFlags3.VIF_NO_HWND_SUPPORT,
new[] { new INITVIEW { fSelectionMargin = 0, fWidgetMargin = 0, fVirtualSpace = 0, fDragDropMove = 0 } };
IWpfTextViewHost projTextViewHost = editorAdapterFactoryService.GetWpfTextViewHost(projTextView);