REVIT Transfer floor sketch to Void Extrusion in Family - revit-api
Struggling with some Revit code to copy the profile of a floor and use it as the sketch profile for a void extrusion in a family.
Here is the Full Sharp Development Code. It half works in my custom project template, when I try to use it in an out of the box project generated from revit default template it gives the error "a managed exception was thrown by revit or by one of its external applications"
In my template it cannot properly split the curves into a secondary array. It says the array elements are being changed but when the loop runs again the element i is back to it's original content??? The TaskDialog clearly says the elements have changed, until the loop iterates again.
Full code: To work it requires a generic family with the name "Void - Custom" to be in the project. The "If found" near the bottom last page and a half of code, is where the for loop is not behaving as expected.
/*
* Created by SharpDevelop.
* User: arautio
* Date: 4/30/2019
* Time: 11:10 AM
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Architecture;
using Autodesk.Revit.DB.Structure;
using Autodesk.Revit.UI.Selection;
using System.Collections.Generic;
using System.Linq;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using System.Text;
using System.IO;
using System.Diagnostics;
namespace ARC
{
[Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
[Autodesk.Revit.DB.Macros.AddInId("3411F411-6FC1-4A4D-9CFD-37ABB2028A15")]
public partial class ThisApplication
{
private void Module_Startup(object sender, EventArgs e)
{
}
private void Module_Shutdown(object sender, EventArgs e)
{
}
#region Revit Macros generated code
private void InternalStartup()
{
this.Startup += new System.EventHandler(Module_Startup);
this.Shutdown += new System.EventHandler(Module_Shutdown);
}
#endregion
public void FloorGrating()
{
StringBuilder sb = new StringBuilder();
Dictionary<Floor, List<ModelCurve>> dict_SketchLines = new Dictionary<Floor, List<ModelCurve>>();
UIDocument uidoc = this.ActiveUIDocument;
Document document = uidoc.Document;
View activev = document.ActiveView;
ElementId levelId = null;
levelId = activev.LevelId;
Element levelem = document.GetElement( levelId );
Level lev = document.ActiveView.GenLevel;
Reference refsel = uidoc.Selection.PickObject(ObjectType.Element, "Select Floor to Add Grating To");
Element elem = document.GetElement(refsel.ElementId);
Floor f = elem as Floor;
List<ElementId> _deleted = null;
using (Transaction t = new Transaction(document, "temp"))
{
t.Start();
document.Regenerate();
_deleted = document.Delete(elem.Id).ToList();
t.RollBack();
}
bool SketchLinesFound = false;
List<ModelCurve> _sketchCurves = new List<ModelCurve>();
foreach (var id in _deleted)
{
ModelCurve mc = document.GetElement(id) as ModelCurve;
if (mc != null)
{
_sketchCurves.Add(mc);
SketchLinesFound = true;
}
else
{
if (SketchLinesFound) break;
}
}
dict_SketchLines.Add(f, _sketchCurves);
foreach (Floor key in dict_SketchLines.Keys)
{
List<ModelCurve> _curves = dict_SketchLines[key];
sb.AppendLine(string.Format("floor {0} has sketchlines:", key.Id));
foreach (ModelCurve mc in _curves)
{
sb.AppendLine(string.Format("{0} <{1}>", mc.GetType(), mc.Id));
sb.AppendLine(string.Format("<{0}>", mc.GeometryCurve.IsBound.ToString()));
if (mc.GetType().ToString() == "Autodesk.Revit.DB.ModelArc" && mc.GeometryCurve.IsBound == false)
{
TaskDialog.Show("Revit", "Circle Found");
}
try
{
sb.AppendLine(string.Format("<{0} -- {1}>", mc.GeometryCurve.GetEndPoint(0), mc.GeometryCurve.GetEndPoint(1)));
}
catch
{
}
}
sb.AppendLine();
}
//TaskDialog.Show("debug", sb.ToString());
Document docfamily;
Family fam;
string ftitle = document.Title;
string fpath = document.PathName;
int ftitlelen = ftitle.Length + 4;
int fpathlen = fpath.Length;
int finpathlen = fpathlen - ftitlelen;
string sfinpath = fpath.Substring(0,finpathlen);
string famname = "GratingVoid";
string fext = ".rfa";
int counter = 1;
while (counter < 100)
{
famname = ("GratingVoid" + counter as String);
Family family = FindElementByName(document,typeof(Family),famname)as Family;
if( null == family )
{
sfinpath = (sfinpath + famname + fext);
counter = 1000;
}
counter += 1;
}
FilteredElementCollector collector0 = new FilteredElementCollector(document);
ICollection<Element> collection0 = collector0.WhereElementIsNotElementType().ToElements();
List<FamilySymbol> fsym0 = new FilteredElementCollector(document).OfClass(typeof(FamilySymbol)).Cast<FamilySymbol>().ToList();
FamilySymbol famsymb0 = null;
foreach (FamilySymbol symb in fsym0)
{
if (symb.Name == "Void - Custom")
{
famsymb0 = symb as FamilySymbol;
}
}
fam = famsymb0.Family;
docfamily = document.EditFamily(fam);
try
{
docfamily.SaveAs(#sfinpath);
}
catch
{
TaskDialog.Show("Revit", "Could Not Save Void Family");
}
using (Transaction trans = new Transaction(docfamily))
{
trans.Start("family");
bool circleflag = false;
ElementId delid = null;
FilteredElementCollector collector = new FilteredElementCollector( docfamily );
foreach(Element element in collector.OfClass(typeof(GenericForm)))
{
delid = element.Id;
}
docfamily.Delete(delid);
CurveArray loccurva = new CurveArray();
foreach (Floor key in dict_SketchLines.Keys)
{
List<ModelCurve> _curves = dict_SketchLines[key];
foreach (ModelCurve mc in _curves)
{
if (mc.GetType().ToString() == "Autodesk.Revit.DB.ModelArc" && mc.GeometryCurve.IsBound == false)
{
circleflag = true;
}
LocationCurve lcurve = mc.Location as LocationCurve;
Curve c = lcurve.Curve as Curve;
loccurva.Append(c);
}
}
try
{
if (circleflag == true && loccurva.Size == 2)
{
Curve tempc;
if (loccurva.get_Item(0).GetType().ToString() == "Autodesk.Revit.DB.Arc")
{
tempc = loccurva.get_Item(0);
}
else
{
tempc = loccurva.get_Item(1);
}
loccurva.Clear();
loccurva.Append(tempc);
}
CurveArrArray newcurarr = new CurveArrArray();
newcurarr.Append(loccurva);
SortCurvesContiguousArray(newcurarr);
TaskDialog.Show("Revit CurveArray Array Size" , newcurarr.Size.ToString());
foreach (CurveArray ca in newcurarr)
{
TaskDialog.Show("Revit CurveArray within Array Size" , ca.Size.ToString());
}
// Below is edited for error control - leaving out the secondary loops for now
CurveArrArray switcharr = new CurveArrArray();
//switcharr.Append(newcurarr.get_Item(1));
switcharr.Append(newcurarr.get_Item(0));
//SortCurvesContiguousArray(loccurva);
//CurveArrArray newcurarr = new CurveArrArray();
//newcurarr.Append(loccurva);
double end = 1;
SketchPlane sketch = FindElementByName( docfamily,typeof( SketchPlane ), "Ref. Level" ) as SketchPlane;
docfamily.FamilyCreate.NewExtrusion(false, switcharr, sketch, end);
}
catch
{
TaskDialog.Show("Revit", "Could Not Write to Curve Array or Create Extrusion");
}
trans.Commit();
}
docfamily.Save();
docfamily.LoadFamily(document, new CustomFamilyLoadOption());
docfamily.Close();
File.Delete(sfinpath);
Family familynew = FindElementByName(document,typeof(Family),famname)as Family;
if( null == familynew )
{
TaskDialog.Show("Revit", "Family Does Not Exist");
}
FilteredElementCollector collector1 = new FilteredElementCollector(document);
ICollection<Element> collection = collector1.WhereElementIsNotElementType().ToElements();
List<FamilySymbol> fsym = new FilteredElementCollector(document).OfClass(typeof(FamilySymbol)).Cast<FamilySymbol>().ToList();
FamilySymbol famsymb = null;
foreach (FamilySymbol symb in fsym)
{
if (symb.Name == famname)
{
famsymb = symb as FamilySymbol;
}
}
using (Transaction trans = new Transaction(document))
{
trans.Start("PlaceVoid");
if( ! famsymb.IsActive )
{
famsymb.Activate();
}
XYZ p = new XYZ(0,0,0);
FamilyInstance gratingvoid = document.Create.NewFamilyInstance( p, famsymb, lev, lev, StructuralType.NonStructural );
document.Regenerate();
trans.Commit();
}
}
//--------------------------------------------------------------------------------------------------------------------------------------------------------
static public Element FindElementByName(Document doc,Type targetType,string targetName)
{
return new FilteredElementCollector( doc ).OfClass( targetType ).FirstOrDefault<Element>(e => e.Name.Equals( targetName ) );
}
//--------------------------------------------------------------------------------------------------------------------------------------------------------
public class CustomFamilyLoadOption : IFamilyLoadOptions
{
public bool OnFamilyFound(bool familyInUse, out bool overwriteParameterValues)
{
overwriteParameterValues = true;
return true;
}
public bool OnSharedFamilyFound(Family sharedFamily,bool familyInUse,out FamilySource source, out bool overwriteParameterValues)
{
source = FamilySource.Family;
overwriteParameterValues = true;
return true;
}
}
//--------------------------------------------------------------------------------------------------------------------------------------------------------
const double _inch = 1.0 / 12.0;
const double _sixteenth = _inch / 16.0;
static Curve CreateReversedCurve(Curve orig )
{
//if( !IsSupported( orig ) )
//{
// throw new NotImplementedException("CreateReversedCurve for type " + orig.GetType().Name );
//}
if( orig is Line )
{
//return creapp.NewLineBound(orig.GetEndPoint( 1 ), orig.GetEndPoint( 0 ) );
return Line.CreateBound(orig.GetEndPoint( 1 ), orig.GetEndPoint( 0 ) );
}
else if( orig is Arc )
{
// return creapp.NewArc( orig.GetEndPoint( 1 ), orig.GetEndPoint( 0 ), orig.Evaluate( 0.5, true ) );
return Arc.Create( orig.GetEndPoint( 1 ), orig.GetEndPoint( 0 ), orig.Evaluate( 0.5, true ) );
}
else
{
throw new Exception(
"CreateReversedCurve - Unreachable" );
}
}
public static void SortCurvesContiguousArray(CurveArrArray curvesarr)
{
double _precision1 = 1.0 / 12.0 / 16.0; // around 0.00520833
double _precision2 = 0.001; // limit for CurveLoop.Create(...)
int cn = curvesarr.Size;
int ci = 0;
while (ci < cn)
{
CurveArray curves = curvesarr.get_Item(ci);
ci +=1;
// account for multiple curve loops with secondary array
CurveArray loop1 = new CurveArray();
CurveArray loop2 = new CurveArray();
int n = curves.Size;
int split = 1;
// Walk through each curve (after the first)
// to match up the curves in order
for (int i = 0; i < n; ++i)
{
TaskDialog.Show("Revit I Loop Run", i.ToString());
Curve curve = curves.get_Item(i);
if (curve.GetType().ToString() == "Autodesk.Revit.DB.Arc" && curve.IsBound == false)
{
break;
}
XYZ beginPoint = curve.GetEndPoint(0);
XYZ endPoint = curve.GetEndPoint(1);
XYZ p,q;
// Find curve with start point = end point
bool found = (i + 1 >= n);
for (int j = i + 1; j < n; ++j)
{
p = curves.get_Item(j).GetEndPoint(0);
q = curves.get_Item(j).GetEndPoint(1);
// If there is a match end->start,
// this is the next curve
if (p.DistanceTo(endPoint) < _precision1)
{
if (p.DistanceTo(endPoint) > _precision2)
{
XYZ intermediate = new XYZ((endPoint.X + p.X) / 2.0, (endPoint.Y + p.Y) / 2.0, (endPoint.Z + p.Z) / 2.0);
curves.set_Item(i, Line.CreateBound(beginPoint, intermediate));
curves.set_Item(j, Line.CreateBound(intermediate, q));
}
if (i + 1 != j)
{
Curve tmp = curves.get_Item(i + 1);
curves.set_Item(i + 1, curves.get_Item(j));
curves.set_Item(j, tmp);
}
found = true;
break;
}
// If there is a match end->end,
// reverse the next curve
if (q.DistanceTo(endPoint) < _precision1)
{
if (q.DistanceTo(endPoint) > _precision2)
{
XYZ intermediate = new XYZ((endPoint.X + q.X) / 2.0, (endPoint.Y + q.Y) / 2.0, (endPoint.Z + q.Z) / 2.0);
curves.set_Item(i, Line.CreateBound(beginPoint, intermediate));
curves.set_Item(j, Line.CreateBound(p, intermediate));
}
if (i + 1 == j)
{
curves.set_Item(i + 1, CreateReversedCurve(curves.get_Item(j)));
}
else
{
Curve tmp = curves.get_Item(i + 1);
curves.set_Item(i + 1, CreateReversedCurve(curves.get_Item(j)));
curves.set_Item(j, tmp);
}
found = true;
break;
}
}
if (!found)
{
// if not found, must be part of a new loop - move it to the back and keep going and add to second array
TaskDialog.Show("Revit No Match Found for item", i.ToString());
TaskDialog.Show("Revit", "Moveing it to back of list");
Curve tmp1 = curves.get_Item(i);
TaskDialog.Show("Revit tmp1 Current i item endpt", tmp1.GetEndPoint(0).ToString());
loop2.Append(tmp1);
Curve tmp2 = curves.get_Item(n - split);
TaskDialog.Show("Revit tmp2 Back of list item endpt", tmp2.GetEndPoint(0).ToString());
// set current item to rear
curves.set_Item(i, tmp2);
// set rear item to current
curves.set_Item(n - split, tmp1);
TaskDialog.Show("Revit new item i endpt", curves.get_Item(i).GetEndPoint(0).ToString());
TaskDialog.Show("Revit moved item endpt", curves.get_Item(n - split).GetEndPoint(0).ToString());
// error testing - try to append in a different manner and check values
//curves.set_Item(i, Line.CreateBound(curves.get_Item(i).GetEndPoint(0), curves.get_Item(i).GetEndPoint(1)));
//curves.set_Item(n - split, Line.CreateBound(curves.get_Item(n - split).GetEndPoint(0), curves.get_Item(n - split).GetEndPoint(1)));
//Curve ncurve = Line.CreateBound(curves.get_Item(n - split).GetEndPoint(0), curves.get_Item(n - split).GetEndPoint(1));
//TaskDialog.Show("Revit Appended to Loop2 Endpoint", ncurve.GetEndPoint(0).ToString());
//loop2.Append(ncurve);
//set the split off counter so items not fitting in first loop can be split to new array.
split += 1;
//reset the counter back so item moved from rear can be checked in next run of for loop
i -= 2;
}
//set counter to end for loop when all items that do not fit in first loop are processed
if (i >= n - (split + 1))
{
TaskDialog.Show("Revit", "End Of Looping");
TaskDialog.Show("Revit - The Split Number", split.ToString());
i = n;
}
}
int counter = 0;
// recreate array with only items from first loop found
while (counter <= (n - split))
{
loop1.Append(curves.get_Item(counter));
counter += 1;
}
TaskDialog.Show("Revit loop1 Size", loop1.Size.ToString());
curvesarr.Clear();
curvesarr.Append(loop1);
if (loop2.Size > 0)
{
string stringinfo = "";
// run the loop detection on a second array that was split from the first
TaskDialog.Show("Revit loop2 Size", loop2.Size.ToString());
CurveArrArray tmpcurvesarr = new CurveArrArray();
tmpcurvesarr.Append(loop2);
SortCurvesContiguousArray(tmpcurvesarr);
loop2.Clear();
loop2 = tmpcurvesarr.get_Item(0);
curvesarr.Append(loop2);
foreach (Curve ccc in loop2)
{
stringinfo = (stringinfo + " " + ccc.GetEndPoint(0).ToString() + " - " + ccc.GetEndPoint(1).ToString());
}
TaskDialog.Show("Revit", stringinfo);
}
}
}
}
}
Thanks for any and all help.
Shane
Related
How to detect window state in linux?
I need to find out if a native linux application window is maximized or minimized in a java program. I tried using X11.XGetWindowProperty() and I get some results also, but I cant make out any useful information in it. I am using JNA 4.2.1, Java 8 update72 on Ubuntu 14.04 LTS. Any pointers will be very helpful. Thanks in advance to all. [Edit] I have the code below which gives me the result I need. But the result is not same for every invocation. The atoms which are returned for the window vary within invocations. Is there any other reliable way to get the window state? private static X11 x11 = X11.INSTANCE; private static Display dispy = x11.XOpenDisplay(null); public static void main(String[] args) { try { X11.Atom[] atoms = getAtomProperties( bytesToInt(getProperty(X11.XA_ATOM, X11.INSTANCE.XInternAtom(dispy, "_NET_WM_STATE", false)))); boolean hidden = false; boolean vmax = false; boolean hmax = false; for (int i = 0; i < atoms.length; i++) { X11.Atom atom = atoms[i]; if (atom == null) continue; String atomName = X11.INSTANCE.XGetAtomName(dispy, atom); if ("_NET_WM_STATE_HIDDEN".equals(atomName)) { hidden = true; } else if ("_NET_WM_STATE_MAXIMIZED_VERT".equals(atomName)) { vmax = true; } else if ("_NET_WM_STATE_MAXIMIZED_HORZ".equals(atomName)) { hmax = true; } } if (hidden) System.out.println("Window minimized"); else if (vmax && hmax && !hidden) System.out.println("Window maximized"); else System.out.println("Window normal"); } catch (X11Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static X11.Atom[] getAtomProperties(int[] ids) { X11.Atom[] atoms = new X11.Atom[ids.length]; for (int i = 0; i < ids.length; i++) { if (ids[i] == 0) continue; atoms[i] = new X11.Atom(ids[i]); } return atoms; } private static int[] bytesToInt(byte[] prop) { if (prop == null) return null; int[] res = new int[prop.length / 4]; for (int i = 0; i < res.length; i++) { res[i] = ((prop[i * 4 + 3] & 0xff) << 24) | ((prop[i * 4 + 2] & 0xff) << 16) | ((prop[i * 4 + 1] & 0xff) << 8) | ((prop[i * 4 + 0] & 0xff)); if (res[i] != 0) continue; } return res; } private static byte[] getProperty(X11.Atom xa_prop_type, X11.Atom xa_prop_name) throws X11Exception { X11.Window window = new X11.Window(73400355); X11.AtomByReference xa_ret_type_ref = new X11.AtomByReference(); IntByReference ret_format_ref = new IntByReference(); NativeLongByReference ret_nitems_ref = new NativeLongByReference(); NativeLongByReference ret_bytes_after_ref = new NativeLongByReference(); PointerByReference ret_prop_ref = new PointerByReference(); NativeLong long_offset = new NativeLong(0); NativeLong long_length = new NativeLong(4096 / 4); /* * MAX_PROPERTY_VALUE_LEN / 4 explanation (XGetWindowProperty manpage): * * long_length = Specifies the length in 32-bit multiples of the data to be retrieved. */ if (x11.XGetWindowProperty(dispy, window, xa_prop_name, long_offset, long_length, false, xa_prop_type, xa_ret_type_ref, ret_format_ref, ret_nitems_ref, ret_bytes_after_ref, ret_prop_ref) != X11.Success) { String prop_name = x11.XGetAtomName(dispy, xa_prop_name); throw new X11Exception("Cannot get " + prop_name + " property."); } X11.Atom xa_ret_type = xa_ret_type_ref.getValue(); Pointer ret_prop = ret_prop_ref.getValue(); if (xa_ret_type == null) { // the specified property does not exist for the specified window return null; } if (xa_ret_type == null || xa_prop_type == null || !xa_ret_type.toNative().equals(xa_prop_type.toNative())) { x11.XFree(ret_prop); String prop_name = x11.XGetAtomName(dispy, xa_prop_name); throw new X11Exception("Invalid type of " + prop_name + " property"); } int ret_format = ret_format_ref.getValue(); long ret_nitems = ret_nitems_ref.getValue().longValue(); // null terminate the result to make string handling easier int nbytes; if (ret_format == 32) nbytes = Native.LONG_SIZE; else if (ret_format == 16) nbytes = Native.LONG_SIZE / 2; else if (ret_format == 8) nbytes = 1; else if (ret_format == 0) nbytes = 0; else throw new X11Exception("Invalid return format"); int length = Math.min((int) ret_nitems * nbytes, 4096); byte[] ret = ret_prop.getByteArray(0, length); x11.XFree(ret_prop); return ret; }
Accessing Map Value
static void getRecommendations(Map<User, HashMap<Item, Double>> map, User to) { scores = sortMapByScore(scores, to); TreeMap<User, Double> scores1 = (TreeMap<User, Double>) scores.get(to); Set<User> user = (Set<User>) scores1.keySet(); Iterator<User> itr = user.iterator(); Map<Item, Double> rec = new HashMap<Item, Double>(); int i = 0; while (itr.hasNext() && i < 5) { User u = itr.next(); /* for(Item e:map.get(to).keySet()){ */ for (Item e1 : map.get(u).keySet()) { if (!map.get(to).containsKey(e1)) { if (rec.containsKey(e1)) { double sc = rec.get(e1); rec.put(e1, sc + map.get(u).get(e1) * scores.get(to).get(u)); } else { // System.out.println(scores); rec.put(e1, map.get(u).get(e1) * scores.get(to).get(u)); } // } } } i++; } TreeMap<Item, Double> res = new TreeMap<Item, Double>( new ValueComparator(rec)); res.putAll(rec); int k=0; for(Item d:res.keySet()){ System.out.println(d.getmTitle()); k++; if(k==5){break;} } } I am using nested HashMap and TreeMap in this example.But I am facing the below problem. In the code above in the line rec.put(e1, map.get(u).get(e1) * scores.get(u).get(to)); I am getting a NullPointerException, even though I am using the same HashMap's keyset to get the Values.
How to make parent child relationship in C1flexgrid
I am using C1Flexgrid and I need to make parent child relation in this grid. But child details need to show in same grid (no other grid ) and when I clicked on + expand should happen and vice versa. I have written below code where I am having one column in datatable related to parent and child . If it is parent then I am making it 1 else 0. When I tried with this code. R2 row is coming as child node of r which should not be a case as it is parent node. Please help me on this . private void Form3_Load(object sender, EventArgs e) { DataTable dt = new DataTable("customers"); dt.Columns.Add("abc"); dt.Columns.Add("ddd"); dt.Columns.Add("eee"); dt.Columns.Add("parent"); var r = dt.NewRow(); r["abc"] = "11"; r["ddd"] = "12"; r["eee"] = "13"; r["parent"] = "1"; var r1 = dt.NewRow(); r1["ddd"] = "12"; r1["eee"] = "14"; r1["parent"] = "0"; var r2 = dt.NewRow(); r2["abc"] = "11"; r2["ddd"] = "1222"; r2["eee"] = "14"; r2["parent"] = "1"; var rr32 = dt.NewRow(); rr32["abc"] = "11"; rr32["ddd"] = "1222"; rr32["eee"] = "14"; rr32["parent"] = "0"; dt.Rows.Add(r); dt.Rows.Add(r1); dt.Rows.Add(r2); dt.Rows.Add(rr32); grid1.DataSource = dt; GroupBy("parent", 1); // show outline tree grid1.Tree.Column = 2; // autosize to accommodate tree grid1.AutoSizeCol(grid1.Tree.Column); grid1.Tree.Show(1); } void GroupBy(string columnName, int level) { object current = null; for (int r = grid1.Rows.Fixed; r < grid1.Rows.Count; r++) { if (!grid1.Rows[r].IsNode) { var value = grid1[r, columnName]; string value2 = grid1[r, "parent"].ToString(); if (!object.Equals(value, current)) { // value changed: insert node, apply style if (value2.Equals("0")) { grid1.Rows.InsertNode(r, level); grid1.Rows[r].Style = _nodeStyle[Math.Min(level, _nodeStyle.Length - 1)]; r++; } // show group name in first scrollable column //grid1[r, grid1.Cols.Fixed+1] = value; // update current value current = value; } } } } }
Your code was almost there, i have manipulated GroupBy method to fit your need. It solves your current requirement but you have to handle sorting and other functionalists of grid yourself. Hope this helps! void GroupBy(string columnName, int level) { object current = null; for (int r = grid1.Rows.Fixed; r < grid1.Rows.Count; r++) { if (!grid1.Rows[r].IsNode) { var value = grid1[r, columnName]; if (!object.Equals(value, current)) { // value changed: insert node, apply style grid1.Rows.InsertNode(r, level); grid1.Rows[r].Style = _nodeStyle[Math.Min(level, _nodeStyle.Length - 1)]; // show group name in first scrollable column Row row = grid1.Rows[r + 1]; for (int i = 0; i < grid1.Cols.Count; i++) { grid1[r, i] = row[i]; } grid1.Rows[r + 1].Visible = false; r++; // update current value current = value; } } } }
Why is parallel.Invoke not working in this case
I have an array of files like this.. string[] unZippedFiles; the idea is that I want to parse these files in paralle. As they are parsed a record gets placed on a concurrentbag. As record is getting placed I want to kick of the update function. Here is what I am doing in my Main(): foreach(var file in unZippedFiles) { Parallel.Invoke ( () => ImportFiles(file), () => UpdateTest() ); } this is what the code of Update loooks like. static void UpdateTest( ) { Console.WriteLine("Updating/Inserting merchant information."); while (!merchCollection.IsEmpty || producingRecords ) { merchant x; if (merchCollection.TryTake(out x)) { UPDATE_MERCHANT(x.m_id, x.mInfo, x.month, x.year); } } } This is what the import code looks like. It's pretty much a giant string parser. System.IO.StreamReader SR = new System.IO.StreamReader(fileName); long COUNTER = 0; StringBuilder contents = new StringBuilder( ); string M_ID = ""; string BOF_DELIMITER = "%%MS_SKEY_0000_000_PDF:"; string EOF_DELIMITER = "%%EOF"; try { record_count = 0; producingRecords = true; for (COUNTER = 0; COUNTER <= SR.BaseStream.Length - 1; COUNTER++) { if (SR.EndOfStream) { break; } contents.AppendLine(Strings.Trim(SR.ReadLine())); contents.AppendLine(System.Environment.NewLine); //contents += Strings.Trim(SR.ReadLine()); //contents += Strings.Chr(10); if (contents.ToString().IndexOf((EOF_DELIMITER)) > -1) { if (contents.ToString().StartsWith(BOF_DELIMITER) & contents.ToString().IndexOf(EOF_DELIMITER) > -1) { string data = contents.ToString(); M_ID = data.Substring(data.IndexOf("_M") + 2, data.Substring(data.IndexOf("_M") + 2).IndexOf("_")); Console.WriteLine("Merchant: " + M_ID); merchant newmerch; newmerch.m_id = M_ID; newmerch.mInfo = data.Substring(0, (data.IndexOf(EOF_DELIMITER) + 5)); newmerch.month = DateTime.Now.AddMonths(-1).Month; newmerch.year = DateTime.Now.AddMonths(-1).Year; //Update(newmerch); merchCollection.Add(newmerch); } contents.Clear(); //GC.Collect(); } } SR.Close(); // UpdateTest(); } catch (Exception ex) { producingRecords = false; } finally { producingRecords = false; } } the problem i am having is that the Update runs once and then the importfile function just takes over and does not yield to the update function. Any ideas on what am I doing wrong would be of great help.
Here's my stab at fixing your thread synchronisation. Note that I haven't changed any of the code from the functional standpoint (with the exception of taking out the catch - it's generally a bad idea; exceptions need to be propagated). Forgive if something doesn't compile - I'm writing this based on incomplete snippets. Main foreach(var file in unZippedFiles) { using (var merchCollection = new BlockingCollection<merchant>()) { Parallel.Invoke ( () => ImportFiles(file, merchCollection), () => UpdateTest(merchCollection) ); } } Update private void UpdateTest(BlockingCollection<merchant> merchCollection) { Console.WriteLine("Updating/Inserting merchant information."); foreach (merchant x in merchCollection.GetConsumingEnumerable()) { UPDATE_MERCHANT(x.m_id, x.mInfo, x.month, x.year); } } Import Don't forget to pass in merchCollection as a parameter - it should not be static. System.IO.StreamReader SR = new System.IO.StreamReader(fileName); long COUNTER = 0; StringBuilder contents = new StringBuilder( ); string M_ID = ""; string BOF_DELIMITER = "%%MS_SKEY_0000_000_PDF:"; string EOF_DELIMITER = "%%EOF"; try { record_count = 0; for (COUNTER = 0; COUNTER <= SR.BaseStream.Length - 1; COUNTER++) { if (SR.EndOfStream) { break; } contents.AppendLine(Strings.Trim(SR.ReadLine())); contents.AppendLine(System.Environment.NewLine); //contents += Strings.Trim(SR.ReadLine()); //contents += Strings.Chr(10); if (contents.ToString().IndexOf((EOF_DELIMITER)) > -1) { if (contents.ToString().StartsWith(BOF_DELIMITER) & contents.ToString().IndexOf(EOF_DELIMITER) > -1) { string data = contents.ToString(); M_ID = data.Substring(data.IndexOf("_M") + 2, data.Substring(data.IndexOf("_M") + 2).IndexOf("_")); Console.WriteLine("Merchant: " + M_ID); merchant newmerch; newmerch.m_id = M_ID; newmerch.mInfo = data.Substring(0, (data.IndexOf(EOF_DELIMITER) + 5)); newmerch.month = DateTime.Now.AddMonths(-1).Month; newmerch.year = DateTime.Now.AddMonths(-1).Year; //Update(newmerch); merchCollection.Add(newmerch); } contents.Clear(); //GC.Collect(); } } SR.Close(); // UpdateTest(); } finally { merchCollection.CompleteAdding(); } }
how to extract Paragraph text color from ms word using apache poi
i am using apache POI , is it possible to read text background and foreground color from ms word paragraph
I got the solution HWPFDocument doc = new HWPFDocument(fs); WordExtractor we = new WordExtractor(doc); Range range = doc.getRange(); String[] paragraphs = we.getParagraphText(); for (int i = 0; i < paragraphs.length; i++) { org.apache.poi.hwpf.usermodel.Paragraph pr = range.getParagraph(i); System.out.println(pr.getEndOffset()); int j=0; while (true) { CharacterRun run = pr.getCharacterRun(j++); System.out.println("-------------------------------"); System.out.println("Color---"+ run.getColor()); System.out.println("getFontName---"+ run.getFontName()); System.out.println("getFontSize---"+ run.getFontSize()); if( run.getEndOffset()==pr.getEndOffset()){ break; } } }
I found it in : CharacterRun run = para.getCharacterRun(i) i should be integer and should be incremented so the code will be as follow : int c=0; while (true) { CharacterRun run = para.getCharacterRun(c++); int x = run.getPicOffset(); System.out.println("pic offset" + x); if (run.getEndOffset() == para.getEndOffset()) { break; } }
if (paragraph != null) { int numberOfRuns = paragraph.NumCharacterRuns; for (int runIndex = 0; runIndex < numberOfRuns; runIndex++) { CharacterRun run = paragraph.GetCharacterRun(runIndex); string color = getColor24(run.GetIco24()); } } GetColor24 Function to Convert Color in Hex Format for C# public static String getColor24(int argbValue) { if (argbValue == -1) return ""; int bgrValue = argbValue & 0x00FFFFFF; int rgbValue = (bgrValue & 0x0000FF) << 16 | (bgrValue & 0x00FF00) | (bgrValue & 0xFF0000) >> 16; StringBuilder result = new StringBuilder("#"); String hex = rgbValue.ToString("X"); for (int i = hex.Length; i < 6; i++) { result.Append('0'); } result.Append(hex); return result.ToString(); }
if you are working on docx(OOXML), you may want to take a look on this: import java.io.* import org.apache.poi.xwpf.usermodel.XWPFDocument fun test(){ try { val file = File("file.docx") val fis = FileInputStream(file.absolutePath) val document = XWPFDocument(fis) val paragraphs = document.paragraphs for (para in paragraphs) { println("-- ("+para.alignment+") " + para.text) para.runs.forEach { it -> println( "text:" + it.text() + " " + "(color:" + it.color + ",fontFamily:" + it.fontFamily + ")" ) } } fis.close() } catch (e: Exception) { e.printStackTrace() } }