Example #1
0
        public void GetResult_should_deserialise_a_valid_json_response()
        {
            var stubRestResponse = Substitute.For<HttpResponseMessage>();
            stubRestResponse.Content = new StringContent("[\"string1\", \"string2\", \"string3\"]");

            var getResult = new GetResult<List<string>>(stubRestResponse, "[\"string1\", \"string2\", \"string3\"]");

            Assert.AreNotEqual(HttpStatusCode.BadRequest, getResult.StatusCode);
            Assert.AreEqual(3, getResult.Data.Count);
            StringAssert.IsMatch("string2", getResult.Data[1]);
            Assert.AreEqual(stubRestResponse, getResult.Response);
        }
Example #2
0
        public void GetResult_should_gracefully_handle_a_deserialisation_exception()
        {
            var stubRestResponse = Substitute.For<HttpResponseMessage>();
            stubRestResponse.Content = new StringContent("not json");
            stubRestResponse.StatusCode = HttpStatusCode.BadRequest;

            var getResult = new GetResult<object>(stubRestResponse, "not json");

            Assert.AreEqual(HttpStatusCode.BadRequest, getResult.StatusCode);
            StringAssert.IsMatch("not json", getResult.Body);
            Assert.IsNull(getResult.Data);
            Assert.AreEqual(stubRestResponse, getResult.Response);
        }
        private static void PrintGetResult(GetResult<Tweet> result)
        {
            Console.WriteLine("Get Result: ");

            Console.WriteLine(" _id: " + result._id);
            Console.WriteLine(" _index: " + result._index);
            Console.WriteLine(" _type: " + result._type);
            Console.WriteLine(" _version: " + result._version);
            Console.WriteLine(" _source: " + result._source);

            Console.WriteLine(" Tweet: ");
            Console.WriteLine("     User: "******"     Message: " + result.Document.Message);
            Console.WriteLine();
        }
        //---------------------------------------------------------------------------
        // Helper for GetAttributeValue() test cases
        //---------------------------------------------------------------------------
        internal void GetAttributeValueHelper(SampleText sampleText, TargetRangeType callingRangeType, AttributeType attribType, GetResult getResult, Type expectedException)
        {
            IDictionary attributes = null;
            TextPatternRange callingRange;

            // Pre-Condition Verify text is expected value <<sampleText>> 
            TS_SetText(sampleText, CheckType.IncorrectElementConfiguration);

            // Pre-Condition Create calling range = <<callingRangeType>>
            TS_CreateRange(out callingRange, callingRangeType, null, false, CheckType.Verification);

            // Pre-Condition Identify & use <<attribType>>
            TS_GetAttributeValues(callingRange, out attributes, attribType, CheckType.Verification);

            // For each attribute identified, GetAttributeValue() returns <<getResult>>
            TS_GetAttributeValue(callingRange, attributes, attribType, getResult, expectedException, CheckType.Verification);
        }
        internal void TS_GetAttributeValue(TextPatternRange callingRange, IDictionary attributes, AttributeType attribType, GetResult getResult, Type expectedException, CheckType checkType)
        {
            bool result = false;
            string key = "";
            object valueActual = null;
            object valueExpected = null;
            IDictionaryEnumerator enum1 = null;
            AutomationTextAttribute attrib = null;

            if (attribType == AttributeType.Null)
            {
                Range_GetAttributeValue(callingRange, null, ref valueActual, expectedException, checkType);
                return;
            }
            else
            {
                enum1 = attributes.GetEnumerator();

                for (int i = 0; i < attributes.Count; i++)
                {
                    // Get next item in dictionary
                    valueActual = null;
                    enum1.MoveNext();
                    attrib = (AutomationTextAttribute)enum1.Key;
                    key = Helpers.GetProgrammaticName(attrib);

                    valueExpected = enum1.Value;

                    Range_GetAttributeValue(callingRange, attrib, ref valueActual, expectedException, checkType);

                    switch (getResult)
                    {
                        case GetResult.Exception:
                            // If we get this far, exception was raised correctly
                            if (expectedException != null)
                                result = true;
                            else
                                result = false;
                            break;
                        case GetResult.MatchingAttributeValue: // verify result MATCHES expected attribute values
                            if (valueExpected.ToString() == valueActual.ToString())
                                result = true;
                            else
                                result = false;
                            break;
                        case GetResult.NotSupported:
                            if (valueActual == AutomationElement.NotSupported)
                            {
                                valueActual = "AutomationElement.NotSupported";
                                valueExpected = "AutomationElement.NotSupported";
                                result = true;
                            }
                            break;
                        case GetResult.Null:
                            if (valueActual == null)
                                result = true;
                            else
                                result = false;
                            break;
                        case GetResult.DocumentRange: // verify result matches ENTIRE TextPattern document
                        case GetResult.CallingRangeLength: // verify result matches LENGTH of calling range
                        case GetResult.Empty:  // verify result is EMPTY range
                        default:
                            throw new ArgumentException("TS_GetAttributeValue() has no support for " + ParseType(getResult));
                    }

                    // Start crafting message
                    Comment("GetAttributeValue(" + key + ") returned " +
                            (valueActual == null ? "null" : valueActual.ToString()) +
                            ", expected = " +
                            (valueExpected == null ? "null" : valueExpected.ToString()));
                    if (result != true)
                    {
                        ThrowMe(checkType, "GetAttributeValue did not return expected results, " +
                                Parse(getResult, expectedException));
                    }
                }
            }
            m_TestStep++;
        }
Example #6
0
 public FutureValue(GetResult result, GetResultAsync resultAsync)
 {
     _getResult      = result;
     _getResultAsync = resultAsync;
 }
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            RhinoApp.WriteLine("The {0} command is under construction.", EnglishName);

            //Example code from https://github.com/Dan-Piker/Drop/blob/master/dropitlikeitshotCommand.cs

            Mesh M;

            GetObject getSomething = new GetObject();

            getSomething.SetCommandPrompt("Select a closed mesh");
            if (getSomething.Get() != GetResult.Object)
            {
                RhinoApp.WriteLine("No object selected");
                return(getSomething.CommandResult());
            }

            GetResult result = getSomething.Get();
            var       obj    = getSomething.Objects();

            M = obj[0].Mesh();

            var Pts = M.Vertices.ToPoint3dArray();

            var   VM  = Rhino.Geometry.VolumeMassProperties.Compute(M);
            Plane Pln = new Plane(VM.Centroid, Vector3d.ZAxis);

            Point3d[] PtArray = new Point3d[Pts.Length + 3];
            PtArray[0] = Pln.Origin;
            PtArray[1] = Pln.PointAt(1, 0);
            PtArray[2] = Pln.PointAt(0, 1);

            for (int i = 0; i < Pts.Length; i++)
            {
                PtArray[i + 3] = Pts[i];
            }

            var Ix = new int[PtArray.Length];

            for (int i = 0; i < PtArray.Length; i++)
            {
                Ix[i] = i;
            }

            var Goals = new List <KangarooSolver.IGoal>();
            var G     = new KangarooSolver.Goals.RigidBody(PtArray, M, 100);

            G.PIndex = Ix;
            Goals.Add(G);
            Goals.Add(new KangarooSolver.Goals.FloorPlane(100));

            for (int i = 3; i < PtArray.Length; i++)
            {
                Goals.Add(new KangarooSolver.Goals.Unary(i, new Vector3d(0, 0, -0.1))); //gravity
            }

            var PS = new KangarooSolver.PhysicalSystem();

            PS.SetParticleList(PtArray.ToList());

            int    counter   = 0;
            double threshold = 1e-9;

            do
            {
                PS.Step(Goals, true, threshold);                 // The step will iterate until either reaching 15ms or the energy threshold
                counter++;
            } while (PS.GetvSum() > threshold && counter < 200); //GetvSum returns the current kinetic energy

            Mesh A = PS.GetOutput(Goals)[0] as Mesh;

            doc.Objects.AddMesh(A);
            doc.Views.Redraw();

            return(Result.Success);
        }
Example #8
0
 public T GetData <T>(string SqlStr, CommandType commandType, GetResult <T> getResult, IList <IList <DbParameter> > ListDataParameter) where T : new()
 {
     return(GetData <T>(SqlStr, commandType, getResult, ListDataParameter, TransactionStateType.Close));
 }
        public async void SendMessage()
        {
            try
            {
                if (outgoingText != string.Empty)
                {
                    var msj = OutGoingText;
                    OutGoingText = string.Empty;
                    Messages.Add(new MessageViewModel {
                        Text = msj, IsIncoming = false, MessagDateTime = DateTime.Now.AddMinutes(-25)
                    });
                    TypingVisibility = true;
                    GenerateContent(msj);
                    postResult = JsonConvert.DeserializeObject <PostResult>(await PostAsync(botUriChat, content));
                    if (postResult != null)
                    {
                        if (firstMessage)
                        {
                            getResult    = JsonConvert.DeserializeObject <GetResult>(await chatClient.GetStringAsync(botUriChat));
                            firstMessage = false;
                        }

                        else
                        {
                            string jsonResultFromBot = await chatClient.GetStringAsync(botUriChat + "?watermark=" + getResult.watermark);

                            getResult = JsonConvert.DeserializeObject <GetResult>(jsonResultFromBot);
                        }

                        for (int i = 1; i < getResult.activities.Count; i++)
                        {
                            if (getResult != null)
                            {
                                if (getResult.activities[i].attachments != null)
                                {
                                    if (getResult.activities[i].attachments.Count > 0)
                                    {
                                        foreach (var content in getResult.activities[i].attachments)
                                        {
                                            StringBuilder message = new StringBuilder();

                                            message.AppendLine(content.content.text);

                                            foreach (var button in content.content.buttons)
                                            {
                                                message.AppendLine(button.title);
                                            }
                                            Messages.Add(new MessageViewModel {
                                                Text = "Oxxo-Bot: " + message.ToString(), IsIncoming = true, MessagDateTime = DateTime.Now.AddMinutes(-25)
                                            });
                                        }
                                    }
                                    else
                                    {
                                        Messages.Add(new MessageViewModel {
                                            Text = "Oxxo-Bot: " + getResult.activities[i].text, IsIncoming = true, MessagDateTime = DateTime.Now.AddMinutes(-25)
                                        });
                                    }
                                }
                            }
                        }
                    }
                    TypingVisibility = false;
                    OutGoingText     = string.Empty;
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Example #10
0
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            Result    rc  = Result.Nothing;
            GetResult res = GetResult.Nothing;

            // Select objects to rotate
            TransformObjectList list = new TransformObjectList();

            rc = SelectObjects("Select objects to transform", list);
            if (rc != Result.Success)
            {
                return(rc);
            }

            OptionToggle opt_xset = new OptionToggle(true, "No", "Yes");
            OptionToggle opt_yset = new OptionToggle(true, "No", "Yes");
            OptionToggle opt_zset = new OptionToggle(true, "No", "Yes");

            // Second reference point
            GetSetPointTransform gx = new GetSetPointTransform(true, true, true);

            gx.SetCommandPrompt("Location for points");
            gx.AddTransformObjects(list);
            for (;;)
            {
                gx.ClearCommandOptions();
                gx.AddOptionToggle("XSet", ref opt_xset);
                gx.AddOptionToggle("YSet", ref opt_yset);
                gx.AddOptionToggle("ZSet", ref opt_zset);

                res = gx.GetXform();

                if (res == GetResult.Point)
                {
                    RhinoView view = gx.View();
                    rc = (null != view) ? Result.Success : Result.Failure;
                    if (rc == Result.Success)
                    {
                        Transform xform = gx.CalculateTransform(view.ActiveViewport, gx.Point());
                        rc = (xform.IsValid) ? Result.Success : Result.Failure;
                        if (rc == Result.Success)
                        {
                            TransformObjects(list, xform, false, false);
                            doc.Views.Redraw();
                        }
                    }
                }
                else if (res == GetResult.Option)
                {
                    gx.SetX = opt_xset.CurrentValue;
                    gx.SetY = opt_yset.CurrentValue;
                    gx.SetZ = opt_zset.CurrentValue;
                    continue;
                }
                else
                {
                    rc = Result.Cancel;
                }

                break;
            }

            return(rc);
        }
Example #11
0
        public void Execute()
        {
            Console.WriteLine("CLIENT SAMPLE");

            var client = new ElasticClient <Tweet>(defaultHost: "localhost", defaultPort: 9200);

            var firstTweet = new Tweet
            {
                User    = "******",
                Message = "trying out Elastic Search"
            };

            var anotherTweet = new Tweet
            {
                User    = "******",
                Message = "one more message"
            };


            var indexSettings = new IndexSettingsBuilder()
                                .NumberOfShards(8)
                                .NumberOfReplicas(1)
                                .Analysis(analysis => analysis
                                          .Analyzer(analyzer => analyzer
                                                    .Custom("keyword_lowercase", custom => custom
                                                            .Tokenizer(DefaultTokenizers.keyword)
                                                            .Filter(DefaultTokenFilters.lowercase))));

            client.CreateIndex(new IndexCommand(index: "twitter").Refresh(), indexSettings);


            IndexResult indexResult1 = client.Index(new IndexCommand(index: "twitter", type: "tweet", id: "1").Refresh(),
                                                    firstTweet);

            IndexResult indexResult2 = client.Index(Commands.Index(index: "twitter", type: "tweet", id: "2").Refresh(),
                                                    anotherTweet);

            GetResult <Tweet> getResult = client.Get(new GetCommand(index: "twitter", type: "tweet", id: "2"));

            SearchResult <Tweet> searchResult = client.Search(new SearchCommand("twitter", "tweet").TrackTotalHits(),
                                                              new QueryBuilder <Tweet>()
                                                              .Query(q => q
                                                                     .Term(t => t
                                                                           .Field(tweet => tweet.User)
                                                                           .Value("testUser")
                                                                           .Boost(2)
                                                                           )
                                                                     ));

            DeleteResult deleteResult = client.Delete(Commands.Delete(index: "twitter"));


            PrintIndexResult(indexResult1);

            PrintIndexResult(indexResult2);

            PrintGetResult(getResult);

            PrintSearchResults(searchResult);

            PrintDeleteResult(deleteResult);

            Console.WriteLine("Press any key");
            Console.ReadKey();
        }
Example #12
0
 public FutureValue(GetResult result)
 {
     getResult = result;
 }
Example #13
0
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            // Check the selected dot
            GetObject go = new GetObject();

            go.GroupSelect     = true;
            go.SubObjectSelect = false;
            go.EnableClearObjectsOnEntry(false);
            go.EnableUnselectObjectsOnExit(false);
            go.DeselectAllBeforePostSelect = false;
            go.EnableSelPrevious(true);
            go.EnablePreSelect(true, false);
            go.GeometryFilter = Rhino.DocObjects.ObjectType.Annotation;

            go.SetCommandPrompt("Select Text to append Metrix M01:");
            GetResult result = go.GetMultiple(1, -1);

            if (go.CommandResult() != Rhino.Commands.Result.Success)
            {
                return(go.CommandResult());
            }

            RhinoApp.WriteLine("Object selection counter = {0}", go.ObjectCount);

            List <TextEntity>  textEntityList  = new List <TextEntity>();
            List <RhinoObject> rhinoObjectList = new List <RhinoObject>();

            // Loop through all the objects to find Text
            for (int i = 0; i < go.ObjectCount; i++)
            {
                RhinoObject rhinoObject = go.Object(i).Object();

                if (rhinoObject.ObjectType == ObjectType.Annotation)
                {
                    TextEntity textEntity = rhinoObject.Geometry as TextEntity;

                    if (textEntity != null)
                    {
                        rhinoObjectList.Add(rhinoObject);
                        textEntityList.Add(textEntity);
                    }
                }
            }

            // Sort the text Entity list
            IEnumerable <TextEntity> query       = textEntityList.OrderByDescending(t => t.Plane.OriginY); //.ThenBy(t => t.Plane.OriginX);
            IEnumerable <TextEntity> xSortedList = textEntityList.OrderBy(t => t.Plane.OriginX);           //.ThenBy(t => t.Plane.OriginY);
            IEnumerable <TextEntity> newList     = null;
            List <TextEntity>        toSort      = new List <TextEntity>();
            List <TextEntity>        toRemove    = new List <TextEntity>();
            double  y;
            Point3d previous = new Point3d(0, 0, 0);
            int     maxDigit = (int)Math.Floor(Math.Log10(textEntityList.Count) + 1);

            int     j     = 1;
            Boolean found = false;

            foreach (TextEntity yText in query)
            {
                found = false;
                if (toRemove.Count > 0)
                {
                    foreach (TextEntity deletedElement in toRemove)
                    {
                        if (deletedElement.Equals(yText))
                        {
                            found = true;
                            break;
                        }
                    }
                }
                if (found == false)
                {
                    y      = yText.Plane.OriginY;
                    toSort = new List <TextEntity>();

                    newList = null;
                    // p = textE;
                    foreach (TextEntity t in xSortedList)
                    {
                        if (t.Plane.OriginY == y || t.Plane.OriginY >= y && t.Plane.OriginY <= (y + 200) || t.Plane.OriginY <= y && t.Plane.OriginY >= (y - 1000)) //Check if y is same
                        {
                            toSort.Add(t);
                        }
                    }

                    if (toSort.Count > 0) //If the list is more than 0, sort it by X
                    {
                        //toSort.Add(yText);
                        newList = toSort.OrderBy(t => t.Plane.OriginX);
                        toRemove.AddRange(newList);
                    }


                    foreach (TextEntity textE in newList)
                    {
                        // Test if there is a M_- in front of the text, if yes, remove it
                        if (textE.Text.Count() > 2)
                        {
                            if (textE.Text[0] == 'M')
                            {
                                if (Char.IsNumber(textE.Text[1]))
                                {
                                    if (textE.Text.IndexOf('-') != -1)
                                    {
                                        // This means M0 exist
                                        textE.Text = textE.Text.Substring(textE.Text.IndexOf('-') + 1);
                                    }
                                }
                            }
                        }

                        textE.Text = "M" + j.ToString().PadLeft(maxDigit, '0') + "-" + textE.Text;
                        j++;
                    }
                    //  toRemove.AddRange(newList);
                }
                else
                {
                    continue;
                }
            }


            // Commit the changes for all updated labels
            for (int k = 0; k < rhinoObjectList.Count; k++)
            {
                rhinoObjectList[k].CommitChanges();
            }

            doc.Views.Redraw();

            return(Result.Success);
        }
        /// <summary>
        /// Creates the layout.
        /// </summary>
        /// <param name="doc">The document.</param>
        /// <param name="panel">The panel.</param>
        /// <param name="panelParas">The panel paras.</param>
        /// <returns></returns>
        public Result createLayout(RhinoDoc doc, PerforationPanel panel, PanelParameters panelParas)
        {
            if (panelParas == null)
            {
                panelParas = new PanelParameters();
            }

            if (panel == null)
            {
                panel = new PerforationPanel();
            }

            // Get all selected Objects
            GetObject go = new GetObject();

            go.GroupSelect     = true;
            go.SubObjectSelect = false;
            go.EnableClearObjectsOnEntry(false);
            go.EnableUnselectObjectsOnExit(false);
            go.DeselectAllBeforePostSelect = false;
            go.EnableSelPrevious(true);
            go.EnablePreSelect(true, false);
            go.EnablePressEnterWhenDonePrompt(false);

            go.SetCommandPrompt("Select items for the new layout:");

            // Disable the scaling
            RhinoApp.RunScript("_-DocumentProperties AnnotationStyles ModelSpaceScaling=Disabled LayoutSpaceScaling=Disabled _Enter _Enter", true);

            GetResult result = go.GetMultiple(1, -1);

            if (go.CommandResult() != Rhino.Commands.Result.Success)
            {
                return(go.CommandResult());
            }

            RhinoApp.WriteLine("Total Objects Selected: {0}", go.ObjectCount);

            string  labelName = panel.PartName;
            string  area      = string.Format("{0:0.00}", panel.Area);
            Point2d minPoint  = new Point2d(0, 0);
            Point2d maxPoint  = new Point2d(0, 0);

            // Loop through all the objects to find Text
            for (int i = 0; i < go.ObjectCount; i++)
            {
                BoundingBox bBox = go.Object(i).Object().Geometry.GetBoundingBox(true);

                if (bBox.Min.X < minPoint.X)
                {
                    minPoint.X = bBox.Min.X;
                }

                if (bBox.Min.Y < minPoint.Y)
                {
                    minPoint.Y = bBox.Min.Y;
                }

                if (bBox.Max.X > maxPoint.X)
                {
                    maxPoint.X = bBox.Max.X;
                }

                if (bBox.Max.Y > maxPoint.Y)
                {
                    maxPoint.Y = bBox.Max.Y;
                }
            }

            // If the selected items has no label, return failure
            if (labelName == null)
            {
                return(Rhino.Commands.Result.Failure);
            }

            // Hide all the non selected objects
            foreach (var obj in doc.Objects)
            {
                if (obj.IsSelected(true) == 0)
                {
                    doc.Objects.Hide(obj, false);
                }
            }

            // Add layout
            doc.PageUnitSystem = Rhino.UnitSystem.Millimeters;


            RhinoView currentView = doc.Views.ActiveView;
            var       pageview    = doc.Views.AddPageView(string.Format("{0}", labelName), 210, 297);
            Point2d   bottomLeft  = new Point2d(10, 70);
            Point2d   topRight    = new Point2d(200, 287);

            if (pageview != null)
            {
                pageview.SetPageAsActive();

                var detail = pageview.AddDetailView("Panel", bottomLeft, topRight, Rhino.Display.DefinedViewportProjection.Top);

                // Show all objects
                RhinoApp.RunScript("_-Show _Enter", true);

                if (detail != null)
                {
                    pageview.SetActiveDetail(detail.Id);

                    doc.Views.ActiveView = pageview;

                    // doc.Views.Redraw();
                    // Select all the objects
                    //for (int i = 0; i < go.ObjectCount; i++)
                    //{
                    //   RhinoObject rhinoObject = go.Object(i).Object();

                    //   rhinoObject.Select(true);
                    //}

                    //// Hide all the non selected objects
                    //var filter = new ObjectEnumeratorSettings
                    //{
                    //   NormalObjects = true,
                    //   LockedObjects = false,
                    //   HiddenObjects = false,
                    //   ActiveObjects = true,
                    //   ReferenceObjects = true
                    //};

                    //var rh_objects = doc.Objects.FindByFilter(filter);

                    //// pageview.SetPageAsActive();

                    //doc.Views.Redraw();

                    //foreach (var rh_obj in rh_objects)
                    //{
                    //   var select = 0 == rh_obj.IsSelected(false) && rh_obj.IsSelectable();
                    //   rh_obj.Select(select);
                    //}

                    //RhinoApp.RunScript("_-HideInDetail Enter", true);

                    detail.IsActive = false;
                }

                bottomLeft = new Point2d(10, 40);
                topRight   = new Point2d(135, 70);

                detail = pageview.AddDetailView("Sample", bottomLeft, topRight, Rhino.Display.DefinedViewportProjection.Top);

                // doc.Views.Redraw();
                pageview.SetActiveDetail(detail.Id);

                detail.Viewport.SetCameraLocation(new Point3d(50, 160, 0), true);
                detail.CommitViewportChanges();
                //doc.Views.Redraw();

                detail.DetailGeometry.IsProjectionLocked = true;
                detail.DetailGeometry.SetScale(4.5, doc.ModelUnitSystem, 1, doc.PageUnitSystem);
                detail.CommitChanges();

                //doc.Views.Redraw();


                detail.IsActive = true;
                pageview.SetActiveDetail(detail.Id);

                RhinoApp.WriteLine("Name = {0}: Width = {1}, Height = {2}",
                                   detail.Viewport.Name, detail.Viewport.Size.Width, detail.Viewport.Size.Height);
                detail.CommitViewportChanges();
                // doc.Views.Redraw();

                detail.IsActive = false;

                bottomLeft = new Point2d(5, 5);
                topRight   = new Point2d(205, 35);
                detail     = pageview.AddDetailView("Block", bottomLeft, topRight, Rhino.Display.DefinedViewportProjection.Top);

                //doc.Views.Redraw();

                detail.IsActive = true;
                pageview.SetActiveDetail(detail.Id);

                detail.Viewport.SetCameraLocation(new Point3d(105, 520, 0), true);
                detail.CommitViewportChanges();

                // doc.Views.Redraw();

                detail.DetailGeometry.IsProjectionLocked = true;
                detail.DetailGeometry.SetScale(1, doc.ModelUnitSystem, 1, doc.PageUnitSystem);
                detail.CommitChanges();

                detail.IsActive = false;
                //doc.Views.Redraw();

                drawBlock(doc, labelName, area, panel.PanelNumber, panelParas);

                // doc.Views.Redraw();
            }

            // Show all objects
            RhinoApp.RunScript("_-Show _Enter", true);

            doc.Views.DefaultViewLayout();

            doc.Views.ActiveView = currentView;

            return(Result.Success);
        }
Example #15
0
        internal protected List <T> GetRecords <T>(string query, AddParams addParams, GetResult getResult)
        {
            var result = new List <T>();

            using (var conn = new SqlConnection(connectionString))
                using (var cmd = new SqlCommand(query, conn))
                {
                    if (addParams != null)
                    {
                        addParams(cmd);
                    }
                    cmd.CommandTimeout = cmdTimeout;
                    bool?repeat = null;
                    while (!repeat.HasValue || repeat.Value)
                    {
                        try
                        {
                            cmd.Connection.Open();
                            using (SqlDataReader dr = cmd.ExecuteReader())
                            {
                                while (dr.Read())
                                {
                                    if (getResult != null)
                                    {
                                        result.Add((T)getResult(dr));
                                    }
                                    else
                                    {
                                        if (dr[0] != DBNull.Value)
                                        {
                                            result.Add((T)dr[0]);
                                        }
                                    }
                                }
                                dr.Close();
                            }
                            repeat = false;
                        }
                        catch (SqlException sqlEx)
                        {
                            if ((sqlEx.Number != 6005 && sqlEx.Number != 10054) || (repeat.HasValue && repeat.Value))
                            {
                                repeat = false;
                                ProcessSqlEx(sqlEx, cmd);
                            }
                            else
                            {
                                repeat = true;
                            }
                        }
                    }
Example #16
0
            protected override Result RunCommand(RhinoDoc doc, RunMode mode)
            {
                string family = "";

                // Get family from user
                var getFamily = new GetString();

                getFamily.SetCommandPrompt("Enter Family name");
                getFamily.Get();
                family = getFamily.StringResult();
                if (string.IsNullOrEmpty(family.Trim()))
                {
                    return(Result.Nothing);
                }

                // get point selection in and create blocks from each group
                var getObj = new GetObject();

                getObj.SetCommandPrompt("Select points in order");
                getObj.SubObjectSelect    = false;
                getObj.GeometryFilter     = ObjectType.Point;
                getObj.OneByOnePostSelect = true;
                List <RhinoObject> selectedObjects = new List <RhinoObject>();

                for (; ;)
                {
                    GetResult res = getObj.GetMultiple(3, 0);
                    if (res == GetResult.Object)
                    {
                        //make block from points and assign adaptive component schema
                        var blockName = $"AdaptiveComponent-{Guid.NewGuid()}";

                        // Gather all of the selected objects
                        var geometry   = new List <Rhino.Geometry.GeometryBase>();
                        var attributes = new List <ObjectAttributes>();
                        for (int i = 0; i < getObj.ObjectCount; i++)
                        {
                            var rhinoObject = getObj.Object(i).Object();
                            if (rhinoObject != null)
                            {
                                geometry.Add(rhinoObject.Geometry);
                                attributes.Add(rhinoObject.Attributes);
                            }
                        }
                        var basePoint = geometry.First() as Rhino.Geometry.Point; // Use first selected point as basepoint

                        // Gather all of the selected objects and make definition
                        int definitionIndex = doc.InstanceDefinitions.Add(blockName, string.Empty, basePoint.Location, geometry, attributes);
                        if (definitionIndex < 0)
                        {
                            RhinoApp.WriteLine("Unable to create block definition ", blockName);
                            return(Result.Failure);
                        }

                        // add the objects to a block instance
                        var  transform  = Rhino.Geometry.Transform.Translation(basePoint.Location - doc.ModelBasepoint);
                        Guid instanceId = doc.Objects.AddInstanceObject(definitionIndex, transform);
                        if (instanceId == Guid.Empty)
                        {
                            RhinoApp.WriteLine("Unable to create block instance ", blockName);
                            return(Result.Failure);
                        }
                        var instance = doc.Objects.FindId(instanceId) as InstanceObject;

                        // attach user string to block instance
                        ApplyAdaptiveComponent(instance, family, family, doc);

                        // clear everything for next selection
                        selectedObjects.Clear();
                        getObj.ClearObjects();
                        continue;
                    }
                    else if (res == GetResult.Cancel)
                    {
                        break;
                    }
                    break;
                }

                return(Result.Success);
            }
Example #17
0
        public Boolean createDimensions(List <Guid> guidList)
        {
            doc = RhinoDoc.ActiveDoc;
            go  = new Rhino.Input.Custom.GetObject();
            go.GeometryFilter  = Rhino.DocObjects.ObjectType.Curve;
            go.GroupSelect     = true;
            go.SubObjectSelect = false;
            go.EnableClearObjectsOnEntry(false);
            go.EnableUnselectObjectsOnExit(false);
            go.DeselectAllBeforePostSelect = false;
            go.EnableSelPrevious(true);
            go.EnablePreSelect(true, false);
            go.GeometryFilter = Rhino.DocObjects.ObjectType.Curve;
            go.SetCommandPrompt("Select panels to create dimensions");
            while (true)
            {
                go.ClearCommandOptions();

                // perform the get operation. This will prompt the user to select the list of curves, but also
                // allow for command line options defined above
                GetResult result = go.GetMultiple(1, 0);

                if (result == GetResult.Option)
                {
                    go.EnablePreSelect(false, true);
                    continue;
                }
                else if (result == GetResult.Number)
                {
                    continue;
                }
                else if (result != GetResult.Object)
                {
                }

                if (go.ObjectsWerePreselected)
                {
                    go.EnablePreSelect(true, true);
                    break;
                }

                break;
            }

            int objecTCount = go.ObjectCount;

            foreach (ObjRef objRef in go.Objects()) //Go through each curve  in the objects list
            {
                Curve curve = objRef.Curve();

                // If curve is null, means objRef is not a curve
                if (curve == null)
                {
                    dimensionsCreated = false;
                    continue;
                }

                // If curve is not Closed Curve
                if (curve.IsClosed == false)
                {
                    RhinoApp.WriteLine(objRef.ToString() + " curve is open");
                    dimensionsCreated = false;
                    continue;
                }

                if (curve.IsPlanar() == false)
                {
                    RhinoApp.WriteLine(objRef.ToString() + " curve is not planar");
                    dimensionsCreated = false;
                    continue;
                }
                MetrixUtilities.createMetrixRealDimension();
                BoundingBox boundingBox = curve.GetBoundingBox(Plane.WorldXY);
                Point3d     min         = boundingBox.Min;
                Point3d     max         = boundingBox.Max;

                //Add Horizontal dimension
                origin       = new Point3d(min.X, max.Y, 0);
                offset       = new Point3d(max.X, max.Y, 0);
                pt           = new Point3d((offset.X - origin.X) / 2, max.Y + 180, 0);
                plane        = Plane.WorldXY;
                plane.Origin = origin;
                guidList     = drawDimension(plane, pt, offset, origin, guidList, doc); //draw the dimension


                //Add vertical Dimensions
                origin       = new Point3d(min.X, min.Y, 0);
                offset       = new Point3d(min.X, max.Y, 0); //left
                pt           = new Point3d(min.X - 180, (offset.Y - origin.Y) / 2, 0);
                plane        = Plane.WorldXY;
                plane.XAxis  = new Vector3d(0, -1, 0); //-1 to rotate the dimension vertically
                plane.YAxis  = new Vector3d(-1, 0, 0);
                plane.ZAxis  = new Vector3d(0, 0, -1);
                plane.Origin = origin;
                guidList     = drawDimension(plane, pt, offset, origin, guidList, doc); //draw the dimension

                dimensionsCreated = true;
            }
            doc.Views.Redraw(); //finally redraw to refresh the screen and display dimensions to user
            return(dimensionsCreated);
        }
        //gets the second point from the user
        private Result GetSecondPoint(Point3d firstPt, ref Point3d pt, bool IsFirstRun)
        {
            Run myRun;

            using (GetPoint getPointAction = new GetPoint())
            {
                if (IsFirstRun)
                {
                    getPointAction.AddOptionDouble("Width", ref this.width);
                    getPointAction.AddOptionDouble("RailHeight", ref this.railHeight);
                    getPointAction.AddOptionToggle("LeftRail", ref this.leftRail);
                    getPointAction.AddOptionToggle("RightRail", ref this.rightRail);
                }
                if (!IsFirstRun)
                {
                    getPointAction.AddOptionToggle("Landing", ref this.LandingToggle);
                }

                getPointAction.SetCommandPrompt("Select the ending point of the run (projected)");
                getPointAction.SetBasePoint(firstPt, true);

                Plane hPlane = new Plane(firstPt, Vector3d.ZAxis);
                getPointAction.Constrain(hPlane, false);
                getPointAction.DynamicDraw += (sender, e) =>
                {
                    myRun = new Run(firstPt, e.CurrentPoint, this.width.CurrentValue);
                    e.Display.DrawLines(myRun.getFlatLines(), Color.White);
                    if ((!IsFirstRun) && LandingToggle.CurrentValue)
                    {
                        Landing land = new Landing(this.prevRun, myRun);
                        if (land.IsValid)
                        {
                            e.Display.DrawBrepWires(land.LandingSurface, Color.Blue);
                        }
                    }
                    string textTip = String.Format("N: {0}\nMax.Ht:{1}", myRun.NumSteps, myRun.NumSteps * code.MAX_RISER);
                    e.Display.Draw3dText(new Rhino.Display.Text3d(textTip,
                                                                  new Plane(e.CurrentPoint, Vector3d.ZAxis), code.MIN_TREAD / 2),
                                         Color.Blue,
                                         e.CurrentPoint);
                    //e.Display.Draw2dText("Hello", Color.White, Rhino.UI.MouseCallback.)
                };

                while (true)
                {
                    GetResult get_rc = getPointAction.Get();
                    if (getPointAction.CommandResult() != Result.Success)
                    {
                        return(getPointAction.CommandResult());
                    }
                    if (get_rc == GetResult.Point)
                    {
                        pt = getPointAction.Point();
                    }
                    else if (get_rc == GetResult.Option)
                    {
                        continue;
                    }
                    break;
                }

                return(Result.Success);
            }
        }
        // gets the third point from the user
        private Result GetThirdPoint(Point3d firstPt, Point3d secondPt, ref Point3d pt, bool IsFirstRun)
        {
            Run myRun;

            using (GetPoint getPointAction = new GetPoint())
            {
                if (IsFirstRun)
                {
                    getPointAction.AddOptionDouble("Width", ref this.width);
                    getPointAction.AddOptionDouble("RailHeight", ref this.railHeight);
                    getPointAction.AddOptionToggle("LeftRail", ref this.leftRail);
                    getPointAction.AddOptionToggle("RightRail", ref this.rightRail);
                }
                if (!IsFirstRun)
                {
                    getPointAction.AddOptionToggle("Landing", ref this.LandingToggle);
                }

                getPointAction.SetCommandPrompt("Select the third point to determine the height of the run");
                getPointAction.SetBasePoint(secondPt, true);
                getPointAction.Constrain(secondPt, secondPt + Vector3d.ZAxis);

                getPointAction.DynamicDraw += (sender, e) =>
                {
                    myRun = new Run(firstPt, e.CurrentPoint, this.width.CurrentValue);
                    updateRunOptions(ref myRun);
                    Color drawColor = Color.White;
                    if (!myRun.IsValid)
                    {
                        double validVert = myRun.VerticalDistance;
                        double mySlope   = myRun.VerticalDistance / myRun.HorizontalDistance;
                        if (mySlope < code.MIN_SLOPE)
                        {
                            validVert = myRun.HorizontalDistance * code.MIN_SLOPE;
                        }
                        else if (mySlope > code.MAX_SLOPE)
                        {
                            validVert = myRun.HorizontalDistance * code.MAX_SLOPE;
                        }

                        Point3d validEndPt = secondPt + (myRun.RiserDirection * validVert);
                        Run     validRun   = new Run(firstPt, validEndPt, this.width.CurrentValue);
                        updateRunOptions(ref validRun);
                        e.Display.DrawSurface(validRun.getStepSurface(), drawColor, 1);
                        drawColor = Color.Red;
                    }
                    e.Display.DrawSurface(myRun.getStepSurface(), drawColor, 2);
                    e.Display.DrawLines(myRun.getRails(), drawColor);
                    e.Display.DrawLines(myRun.getBalusters(), drawColor);
                    //drawing the landing if this is not the first run
                    if ((!IsFirstRun) && LandingToggle.CurrentValue)
                    {
                        Landing land = new Landing(this.prevRun, myRun);
                        if (land.IsValid)
                        {
                            e.Display.DrawBrepWires(land.LandingSurface, Color.Blue);
                            List <Curve> railing = land.getRailings(this.leftRail.CurrentValue, this.rightRail.CurrentValue);
                            foreach (Curve rail in railing)
                            {
                                e.Display.DrawCurve(rail, Color.Blue);
                            }
                        }
                    }
                };

                while (true)
                {
                    GetResult get_rc = getPointAction.Get();
                    if (getPointAction.CommandResult() != Result.Success)
                    {
                        return(getPointAction.CommandResult());
                    }
                    if (get_rc == GetResult.Point)
                    {
                        pt = getPointAction.Point();
                    }
                    else if (get_rc == GetResult.Option)
                    {
                        continue;
                    }
                    break;
                }

                return(Result.Success);
            }
        }
Example #20
0
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        waitingEntities.Clear();
        var fetchJob = new FetchRequest
        {
            waitingEntities = waitingEntities,
            requests        = requesters.requestDatas,
            entities        = requesters.entities,
            counter         = counter
        };
        var fetchFence = fetchJob.Schedule(requesters.Length, SimulationState.TinyBatchSize, inputDeps);

        var fillFence = fetchFence;

        for (var i = 0; i < MAX_QUERIES; ++i)
        {
            var fillJob = new FillQuery
            {
                batch           = batches[i],
                waitingEntities = waitingEntities,
                requests        = requestDatas,
                counter         = counter,
                ID = i
            };
            fillFence = fillJob.Schedule(fillFence);
        }
        var fences = new NativeArray <JobHandle>(MAX_QUERIES, Allocator.Temp);

        for (var i = 0; i < MAX_QUERIES; ++i)
        {
            var processJob = new ProcessRequest {
                batch = batches[i]
            };
            fences[i] = processJob.Schedule(fillFence);
        }
        var processFence = JobHandle.CombineDependencies(fences);
        var getFence     = processFence;

        for (var i = 0; i < MAX_QUERIES; ++i)
        {
            var getJob = new GetResult
            {
                batch    = batches[i],
                paths    = paths,
                requests = requestDatas,
                counter  = counter
            };
            getFence = getJob.Schedule(getFence);
        }

        for (var i = 0; i < MAX_QUERIES; ++i)
        {
            var clearResultJob = new ClearResult
            {
                batch = batches[i]
            };
            fences[i] = clearResultJob.Schedule(getFence);
        }
        endFence = JobHandle.CombineDependencies(fences);

        fences.Dispose();

        return(endFence);
    }
Example #21
0
        public T GetData <T>(string SqlStr, CommandType commandType, GetResult <T> getResult, TransactionStateType transactionStateType) where T : new()
        {
            IList <DbParameter> ListDataParameter = null;

            return(GetData <T>(SqlStr, commandType, getResult, ListDataParameter, transactionStateType));
        }
Example #22
0
        public string info()
        {
            if (UserId == 0)
            {
                return("Nenhum usuário selecionado");
            }

            if (authKey == "")
            {
                Console.WriteLine("Chave de autenticação inválida");
                return("");
            }

            var loginRequest = new
            {
                apiver     = "1.0",
                method     = "user.get",
                parameters = new
                {
                    userid = UserId
                },
                auth = this.authKey,
                id   = 1
            };

            JavaScriptSerializer _ser = new JavaScriptSerializer();
            String jData = _ser.Serialize(loginRequest);

            GetResult ret = JSON.JsonWebRequest <GetResult>(server, jData, "application/json", null, "POST");

            if (ret == null)
            {
                Console.WriteLine("Retorno vazio");
                return("");
            }
            else if (ret.error != null)
            {
                Console.WriteLine(ret.error.data);
                Console.WriteLine(ret.error.message);
                return("");
            }
            else if (ret.result == null || ret.result.info == null)
            {
                Console.WriteLine("Nenhum usuário encontrado com o ID " + UserId);
                return("");
            }


            String mask = "{0,-30} | {1,-" + (Console.WindowWidth - 30 - 10).ToString() + "}";

            Console.WriteLine(String.Format(mask, new String("-".ToCharArray()[0], 30), new String("-".ToCharArray()[0], (Console.WindowWidth - 30 - 10))));
            Console.WriteLine(String.Format(mask, "Propriedade", "Valor"));
            Console.WriteLine(String.Format(mask, new String("-".ToCharArray()[0], 30), new String("-".ToCharArray()[0], (Console.WindowWidth - 30 - 10))));

            Console.WriteLine(String.Format(mask, "Nome completo", ret.result.info.full_name));
            Console.WriteLine(String.Format(mask, "Login", ret.result.info.login));
            Console.WriteLine(String.Format(mask, "Bloqueado", ret.result.info.locked));
            Console.WriteLine(String.Format(mask, "Criado em", ((DateTime)DateTime.Now).AddSeconds(ret.result.info.create_date).ToString("yyyy-MM-dd HH:mm:ss")));
            Console.WriteLine(String.Format(mask, "Troca de senha", ((DateTime)DateTime.Now).AddSeconds(ret.result.info.change_password).ToString("yyyy-MM-dd HH:mm:ss")));
            Console.WriteLine(String.Format(mask, "Ultimo login", ((DateTime)DateTime.Now).AddSeconds(ret.result.info.last_login).ToString("yyyy-MM-dd HH:mm:ss")));

            Console.WriteLine("");

            if (ret.result.properties != null)
            {
                mask = "{0,-15} | {1,-30} | {2,-" + (Console.WindowWidth - 46 - 10).ToString() + "}";
                Console.WriteLine(String.Format(mask, new String("-".ToCharArray()[0], 15), new String("-".ToCharArray()[0], 30), new String("-".ToCharArray()[0], (Console.WindowWidth - 46 - 10))));
                Console.WriteLine(String.Format(mask, "Recurso", "Propriedade", "Valor"));
                Console.WriteLine(String.Format(mask, new String("-".ToCharArray()[0], 15), new String("-".ToCharArray()[0], 30), new String("-".ToCharArray()[0], (Console.WindowWidth - 46 - 10))));

                foreach (UserDataProperty p in ret.result.properties)
                {
                    Console.WriteLine(String.Format(mask, corte(p.resource_name, 15), p.name, corte(p.value, 28)));
                }


                Console.WriteLine("");
            }

            //vw_entity_roles
            if (ret.result.roles != null)
            {
                mask = "{0,-15} | {1,-" + (Console.WindowWidth - 39 - 10).ToString() + "}";
                Console.WriteLine(String.Format(mask, new String("-".ToCharArray()[0], 6), new String("-".ToCharArray()[0], (Console.WindowWidth - 39 - 10))));
                Console.WriteLine(String.Format(mask, "Recurso", "Perfil"));
                Console.WriteLine(String.Format(mask, new String("-".ToCharArray()[0], 6), new String("-".ToCharArray()[0], (Console.WindowWidth - 39 - 10))));

                foreach (UserDataRole r in ret.result.roles)
                {
                    Console.WriteLine(String.Format(mask, corte(r.name, 15), corte(r.name, 30)));
                }
            }

            return("");
        }
Example #23
0
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            bool bHavePreselectedObjects = false;

            const ObjectType geometryFilter = ObjectType.MeshFace;

            OptionDouble  minEdgeLengthOption     = new OptionDouble(minEdgeLength, 0.001, 200);
            OptionDouble  maxEdgeLengthOption     = new OptionDouble(maxEdgeLength, 0.001, 200);
            OptionDouble  constriantAngleOption   = new OptionDouble(constriantAngle, 0.001, 360);
            OptionInteger smoothStepsOptions      = new OptionInteger(smoothSteps, 0, 100);
            OptionDouble  smoothSpeedOption       = new OptionDouble(smoothSpeed, 0.01, 1.0);
            OptionDouble  projectAmountOption     = new OptionDouble(projectedAmount, 0.01, 1.0);
            OptionDouble  projectedDistanceOption = new OptionDouble(projectedDistance, 0.01, 100000.0);

            GetObject go = new GetObject();

            go.SetCommandPrompt("Select mesh faces to project onto another mesh");
            go.GeometryFilter = geometryFilter;

            go.AddOptionDouble("ConstraintAngle", ref constriantAngleOption);
            go.AddOptionDouble("MinEdge", ref minEdgeLengthOption);
            go.AddOptionDouble("MaxEdge", ref maxEdgeLengthOption);
            go.AddOptionInteger("SmoothSteps", ref smoothStepsOptions);
            go.AddOptionDouble("SmoothSpeed", ref smoothSpeedOption);

            go.GroupSelect     = true;
            go.SubObjectSelect = true;

            for (; ;)
            {
                GetResult faceres = go.GetMultiple(1, 0);

                if (faceres == GetResult.Option)
                {
                    go.EnablePreSelect(false, true);
                    continue;
                }

                else if (go.CommandResult() != Result.Success)
                {
                    return(go.CommandResult());
                }

                if (go.ObjectsWerePreselected)
                {
                    bHavePreselectedObjects = true;
                    go.EnablePreSelect(false, true);
                    continue;
                }

                break;
            }

            minEdgeLength   = minEdgeLengthOption.CurrentValue;
            maxEdgeLength   = maxEdgeLengthOption.CurrentValue;
            constriantAngle = constriantAngleOption.CurrentValue;
            smoothSteps     = smoothStepsOptions.CurrentValue;
            smoothSpeed     = smoothSpeedOption.CurrentValue;

            //System.Collections.Generic.List<System.Guid> meshes = new System.Collections.Generic.List<System.Guid>();

            System.Guid rhinoMesh = System.Guid.Empty;

            System.Collections.Generic.List <int> removeFaces = new System.Collections.Generic.List <int>();

            g3.DMesh3 projectFaces = new g3.DMesh3(true, false, false, false);

            Rhino.Geometry.Mesh rhinoInputMesh = new Rhino.Geometry.Mesh();

            for (int i = 0; i < go.ObjectCount; i++)
            {
                ObjRef obj = go.Object(i);

                if (rhinoMesh == System.Guid.Empty)
                {
                    rhinoMesh      = obj.ObjectId;
                    rhinoInputMesh = obj.Mesh();

                    for (int j = 0; j < rhinoInputMesh.Vertices.Count; j++)
                    {
                        var vertex = new g3.NewVertexInfo();
                        vertex.n = new g3.Vector3f(rhinoInputMesh.Normals[j].X, rhinoInputMesh.Normals[j].Y, rhinoInputMesh.Normals[j].Z);
                        vertex.v = new g3.Vector3d(rhinoInputMesh.Vertices[j].X, rhinoInputMesh.Vertices[j].Y, rhinoInputMesh.Vertices[j].Z);
                        projectFaces.AppendVertex(vertex);
                    }
                }

                var m = rhinoInputMesh;

                if (rhinoMesh != obj.ObjectId)
                {
                    continue;
                }

                removeFaces.Add(obj.GeometryComponentIndex.Index);

                var mf = rhinoInputMesh.Faces[obj.GeometryComponentIndex.Index];


                if (mf.IsQuad)
                {
                    double dist1 = m.Vertices[mf.A].DistanceTo(m.Vertices[mf.C]);
                    double dist2 = m.Vertices[mf.B].DistanceTo(m.Vertices[mf.D]);
                    if (dist1 > dist2)
                    {
                        projectFaces.AppendTriangle(mf.A, mf.B, mf.D);
                        projectFaces.AppendTriangle(mf.B, mf.C, mf.D);
                    }
                    else
                    {
                        projectFaces.AppendTriangle(mf.A, mf.B, mf.C);
                        projectFaces.AppendTriangle(mf.A, mf.C, mf.D);
                    }
                }
                else
                {
                    projectFaces.AppendTriangle(mf.A, mf.B, mf.C);
                }
            }

            if (rhinoInputMesh == null)
            {
                return(Result.Failure);
            }

            removeFaces.Sort();
            removeFaces.Reverse();

            foreach (var removeFace in removeFaces)
            {
                rhinoInputMesh.Faces.RemoveAt(removeFace);
            }

            rhinoInputMesh.Compact();

            GetObject goProjected = new GetObject();

            goProjected.EnablePreSelect(false, true);
            goProjected.SetCommandPrompt("Select mesh to project to");
            goProjected.GeometryFilter = ObjectType.Mesh;
            goProjected.AddOptionDouble("ConstraintAngle", ref constriantAngleOption);
            goProjected.AddOptionDouble("MinEdge", ref minEdgeLengthOption);
            goProjected.AddOptionDouble("MaxEdge", ref maxEdgeLengthOption);
            goProjected.AddOptionInteger("SmoothSteps", ref smoothStepsOptions);
            goProjected.AddOptionDouble("SmoothSpeed", ref smoothSpeedOption);
            goProjected.AddOptionDouble("ProjectAmount", ref projectAmountOption);
            goProjected.AddOptionDouble("ProjectDistance", ref projectedDistanceOption);

            goProjected.GroupSelect     = true;
            goProjected.SubObjectSelect = false;
            goProjected.EnableClearObjectsOnEntry(false);
            goProjected.EnableUnselectObjectsOnExit(false);


            for (; ;)
            {
                GetResult resProject = goProjected.Get();

                if (resProject == GetResult.Option)
                {
                    continue;
                }
                else if (goProjected.CommandResult() != Result.Success)
                {
                    return(goProjected.CommandResult());
                }

                break;
            }


            minEdgeLength     = minEdgeLengthOption.CurrentValue;
            maxEdgeLength     = maxEdgeLengthOption.CurrentValue;
            constriantAngle   = constriantAngleOption.CurrentValue;
            smoothSteps       = smoothStepsOptions.CurrentValue;
            smoothSpeed       = smoothSpeedOption.CurrentValue;
            projectedAmount   = projectAmountOption.CurrentValue;
            projectedDistance = projectedDistanceOption.CurrentValue;

            if (bHavePreselectedObjects)
            {
                // Normally, pre-selected objects will remain selected, when a
                // command finishes, and post-selected objects will be unselected.
                // This this way of picking, it is possible to have a combination
                // of pre-selected and post-selected. So, to make sure everything
                // "looks the same", lets unselect everything before finishing
                // the command.
                for (int i = 0; i < go.ObjectCount; i++)
                {
                    RhinoObject rhinoObject = go.Object(i).Object();
                    if (null != rhinoObject)
                    {
                        rhinoObject.Select(false);
                    }
                }
                doc.Views.Redraw();
            }

            bool result = false;

            if (goProjected.ObjectCount < 1)
            {
                return(Result.Failure);
            }


            var rhinoMeshProject = goProjected.Object(0).Mesh();

            if (rhinoMeshProject == null || !rhinoMeshProject.IsValid)
            {
                return(Result.Failure);
            }

            var meshProjected = GopherUtil.ConvertToD3Mesh(rhinoMeshProject);

            var res = GopherUtil.RemeshMesh(projectFaces, (float)minEdgeLength, (float)maxEdgeLength, (float)constriantAngle, (float)smoothSpeed, smoothSteps, meshProjected, (float)projectedAmount, (float)projectedDistance);

            var newRhinoMesh = GopherUtil.ConvertToRhinoMesh(res);

            if (newRhinoMesh != null && newRhinoMesh.IsValid)
            {
                newRhinoMesh.Append(rhinoInputMesh);

                result |= doc.Objects.Replace(rhinoMesh, newRhinoMesh);
            }

            doc.Views.Redraw();

            return(Result.Success);
        }
Example #24
0
 static public string Parse(GetResult value, Type type)
 {
     switch (value)
     {
         case GetResult.DocumentRange: return "verify result matches ENTIRE TextPattern document";
         case GetResult.CallingRangeLength: return "verify result matches LENGTH of calling range";
         case GetResult.Empty: return "verify result is EMPTY range";
         case GetResult.Exception:
             if (type == null)
                 throw new ArgumentException("Can't have GetResult.Exception with null Type y");
             return ParseEx1(type);
         case GetResult.MatchingAttributeValue: return "verify result MATCHES expected attribute values";
         case GetResult.Null: return "verify result returns NULL";
         case GetResult.NotSupported: return "verify result returns AutomationElement.NotSupported";
         default:
             throw new ArgumentException("Parse() has no support for " + ParseType(value));
     }
 }
Example #25
0
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            if (!(RhinoApp.GetPlugInObject("Grasshopper") is GH_RhinoScriptInterface Grasshopper))
            {
                return(Result.Cancel);
            }

            GetOption go = null;

            while (true)
            {
                var port     = new OptionInteger(Port, 1024, 65535);
                var toggle   = new OptionToggle(ShowEditor, "Hide", "Show");
                var debugger = new OptionToggle(Debug, "Off", "On");

                go = new GetOption();

                go.SetCommandPrompt("Noah Server");
                go.AddOption("Connect");
                go.AddOption("Stop");
                go.AddOption("Observer");
                go.AddOptionInteger("Port", ref port);
                go.AddOptionToggle("Editor", ref toggle);
                go.AddOptionToggle("Debug", ref debugger);
                go.AddOption("Workspace");

                GetResult result = go.Get();
                if (result != GetResult.Option)
                {
                    break;
                }

                ShowEditor = toggle.CurrentValue;
                Debug      = debugger.CurrentValue;

                string whereToGo = go.Option().EnglishName;

                if (whereToGo == "Connect")
                {
                    if (Port == 0)
                    {
                        RhinoApp.WriteLine("Please set Port you want to connect!");
                        continue;
                    }

                    if (WorkDir == null)
                    {
                        RhinoApp.WriteLine("Noah can not work without workspace!");
                        continue;
                    }

                    if (Client == null)
                    {
                        try
                        {
                            Grasshopper.DisableBanner();

                            if (!Grasshopper.IsEditorLoaded())
                            {
                                Grasshopper.LoadEditor();
                            }

                            Client               = new NoahClient(Port, WorkDir);
                            Client.InfoEvent    += Client_MessageEvent;
                            Client.ErrorEvent   += Client_ErrorEvent;
                            Client.WarningEvent += Client_WarningEvent;
                            Client.DebugEvent   += Client_DebugEvent;
                        }
                        catch (Exception ex)
                        {
                            RhinoApp.WriteLine("Error: " + ex.Message);
                        }

                        Client.Connect();
                    }
                    else
                    {
                        Client.Reconnect();
                    }

                    if (Debug)
                    {
                        try
                        {
                            if (Logger == null)
                            {
                                Panels.OpenPanel(LoggerPanel.PanelId);
                            }
                            Logger = Panels.GetPanel <LoggerPanel>(doc);
                        }
                        catch (Exception ex)
                        {
                            RhinoApp.WriteLine("Error: " + ex.Message);
                        }
                    }

                    if (ShowEditor)
                    {
                        Grasshopper.ShowEditor();
                    }

                    break;
                }

                if (whereToGo == "Stop")
                {
                    if (Port == 0)
                    {
                        continue;
                    }

                    if (Client != null)
                    {
                        Client.Close();
                    }
                    break;
                }

                if (whereToGo == "Workspace")
                {
                    RhinoGet.GetString("Noah Workspace", false, ref WorkDir);
                }

                if (whereToGo == "Observer")
                {
                    if (Port == 0)
                    {
                        RhinoApp.WriteLine("Server connecting need a port!");
                        continue;
                    }

                    Process.Start("http://localhost:" + Port + "/data/center");
                    break;
                }

                if (whereToGo == "Port")
                {
                    Port = port.CurrentValue;
                    RhinoApp.WriteLine("Port is set to " + Port.ToString());
                    continue;
                }
            }

            return(Result.Nothing);
        }
Example #26
0
 /// ---------------------------------------------------------------------------
 /// <summary>Parses values for enum</summary>
 /// ---------------------------------------------------------------------------
 static public string ParseType(GetResult value)
 {
     return ParseType(value.GetType().ToString(), value.ToString());
 }
Example #27
0
        private async void Submit_Click(object sender, EventArgs e)
        {
            //Emp_Code = FindViewById<EditText>(Resource.Id.txtempcode);
            Store           = FindViewById <EditText>(Resource.Id.txtStore);
            Code            = FindViewById <EditText>(Resource.Id.txtCode);
            Quantity        = FindViewById <EditText>(Resource.Id.txtQuantity);
            VendorName      = FindViewById <EditText>(Resource.Id.txtVendorName);
            VendorContact   = FindViewById <EditText>(Resource.Id.txtVendorContact);
            VendorAddress   = FindViewById <EditText>(Resource.Id.txtVendorAddress);
            VendorCost      = FindViewById <EditText>(Resource.Id.txtVendorCost);
            SellingCost     = FindViewById <EditText>(Resource.Id.txtSellingCost);
            CustomerName    = FindViewById <EditText>(Resource.Id.txtCustomerName);
            CustomerContact = FindViewById <EditText>(Resource.Id.txtCustomerContact);

            VendorModel vendorModel = new VendorModel()
            {
                //emp_code = Emp_Code.Text,
                store           = Store.Text,
                code            = Code.Text,
                quantity        = Quantity.Text,
                vendorname      = VendorName.Text,
                vendorcontact   = VendorContact.Text,
                vendoraddress   = VendorAddress.Text,
                vendorcost      = VendorCost.Text,
                sellingcost     = SellingCost.Text,
                customername    = CustomerName.Text,
                customercontact = CustomerContact.Text,
            };
            ReturnValidation returnValidation = new ReturnValidation();

            if (returnValidation.DecimalValidation(Quantity.Text) && returnValidation.DecimalValidation(VendorCost.Text) && returnValidation.DecimalValidation(SellingCost.Text))
            {
                string            Json              = JsonConvert.SerializeObject(vendorModel);
                HttpContent       stringContent     = new StringContent(Json, encoding: Encoding.UTF8, mediaType: "application/json");
                ReturnGenericPost returnGenericPost = new ReturnGenericPost();
                string            CS = PathLink.VendorURI;

                JObject obj = await returnGenericPost.ReturnGeneralPosMeth(CS, stringContent);

                GetResult getResult1 = obj.ToObject <GetResult>();
                if (getResult1.Status == 1)
                {
                    Android.App.AlertDialog.Builder dialog = new AlertDialog.Builder(this);
                    AlertDialog alert = dialog.Create();
                    alert.SetTitle("Done");
                    alert.SetMessage("Data is Posted");
                    alert.SetButton("OK", (c, ev) =>
                    {
                        // Ok button click task
                    });
                    alert.Show();
                }
            }
            else
            {
                Android.App.AlertDialog.Builder dialog = new AlertDialog.Builder(this);
                AlertDialog alert = dialog.Create();
                alert.SetTitle("Validation Error");
                alert.SetMessage("Add genuine values in Quantity or VendorCost or SellingCost Textboxes!!!!");

                alert.SetButton("OK", (c, ev) =>
                {
                    // Ok button click task
                });
                alert.Show();
            }
        }
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            const ObjectType geometryFilter = ObjectType.Mesh;

            OptionDouble  minEdgeLengthOption   = new OptionDouble(minEdgeLength, 0.001, 200);
            OptionDouble  maxEdgeLengthOption   = new OptionDouble(maxEdgeLength, 0.001, 200);
            OptionDouble  constriantAngleOption = new OptionDouble(constriantAngle, 0.001, 360);
            OptionInteger smoothStepsOptions    = new OptionInteger(smoothSteps, 0, 10000);
            OptionDouble  smoothSpeedOption     = new OptionDouble(smoothSpeed, 0.01, 1.0);

            GetObject go = new GetObject();

            go.SetCommandPrompt("Select meshes to remesh");
            go.GeometryFilter = geometryFilter;
            go.AddOptionDouble("ConstraintAngle", ref constriantAngleOption);
            go.AddOptionDouble("MinEdge", ref minEdgeLengthOption);
            go.AddOptionDouble("MaxEdge", ref maxEdgeLengthOption);
            go.AddOptionInteger("SmoothSteps", ref smoothStepsOptions);
            go.AddOptionDouble("SmoothSpeed", ref smoothSpeedOption);

            go.GroupSelect     = true;
            go.SubObjectSelect = false;
            go.EnableClearObjectsOnEntry(false);
            go.EnableUnselectObjectsOnExit(false);
            go.DeselectAllBeforePostSelect = false;

            bool bHavePreselectedObjects = false;

            for (;;)
            {
                GetResult res = go.GetMultiple(1, 0);

                if (res == GetResult.Option)
                {
                    go.EnablePreSelect(false, true);
                    continue;
                }

                else if (go.CommandResult() != Result.Success)
                {
                    return(go.CommandResult());
                }

                if (go.ObjectsWerePreselected)
                {
                    bHavePreselectedObjects = true;
                    go.EnablePreSelect(false, true);
                    continue;
                }

                break;
            }

            minEdgeLength   = minEdgeLengthOption.CurrentValue;
            maxEdgeLength   = maxEdgeLengthOption.CurrentValue;
            constriantAngle = constriantAngleOption.CurrentValue;
            smoothSteps     = smoothStepsOptions.CurrentValue;
            smoothSpeed     = smoothSpeedOption.CurrentValue;

            if (bHavePreselectedObjects)
            {
                // Normally, pre-selected objects will remain selected, when a
                // command finishes, and post-selected objects will be unselected.
                // This this way of picking, it is possible to have a combination
                // of pre-selected and post-selected. So, to make sure everything
                // "looks the same", lets unselect everything before finishing
                // the command.
                for (int i = 0; i < go.ObjectCount; i++)
                {
                    RhinoObject rhinoObject = go.Object(i).Object();
                    if (null != rhinoObject)
                    {
                        rhinoObject.Select(false);
                    }
                }
                doc.Views.Redraw();
            }

            bool result = false;

            foreach (var obj in go.Objects())
            {
                var rhinoMesh = obj.Mesh();

                if (rhinoMesh == null || !rhinoMesh.IsValid)
                {
                    continue;
                }

                var mesh = GopherUtil.ConvertToD3Mesh(obj.Mesh());

                var res = GopherUtil.RemeshMesh(mesh, (float)minEdgeLength, (float)maxEdgeLength, (float)constriantAngle, (float)smoothSpeed, smoothSteps);

                var newRhinoMesh = GopherUtil.ConvertToRhinoMesh(mesh);

                if (newRhinoMesh != null && newRhinoMesh.IsValid)
                {
                    doc.Objects.Replace(obj, newRhinoMesh);
                }

                if (newRhinoMesh != null && newRhinoMesh.IsValid)
                {
                    result |= doc.Objects.Replace(obj, newRhinoMesh);
                }
            }

            doc.Views.Redraw();

            return(Result.Success);
        }
        internal void TS_VerifyTextLength(GetResult getResult, string actualText, string expectedText, int maxLength, Type expectedException, CheckType checkType)
        {
            int expectedLength = 0;

            Library.ValidateArgumentNonNull(actualText, "actualText cannot be null");
            Library.ValidateArgumentNonNull(expectedText, "expectedText cannot be null");

            // Level the playing field...
            TrimTrailingCRLF(m_le, ref actualText);
            TrimTrailingCRLF(m_le, ref expectedText);

            switch (getResult)
            {
                case GetResult.DocumentRange:
                    expectedLength = expectedText.Length;
                    break;
                case GetResult.CallingRangeLength:
                    expectedLength = actualText.Length;
                    break;
                case GetResult.Empty:
                    expectedLength = 0;
                    break;
                case GetResult.Exception:
                    if (expectedException == null)
                        ThrowMe(checkType, "Test code error, null expected exception is incorrect when getresult = " + Parse(getResult, expectedException));
                    actualText = ""; // Not really, but it gets us the right reporting below
                    expectedText = "";
                    expectedLength = actualText.Length;
                    break;
                case GetResult.Null:
                    if (actualText != null)
                        ThrowMe(checkType, "Expected null value to be returned from GetText(" + maxLength + ")");
                    actualText = ""; // Not really, but it gets us the right reporting below
                    expectedText = "";
                    expectedLength = actualText.Length;
                    break;
                case GetResult.MatchingAttributeValue:
                default:
                    throw new ArgumentException("TS_VerifyTextLength() has no support for " + ParseType(getResult));
            }

            if (actualText.Length == expectedLength)
                Comment("GetText(" + maxLength + ") returned correct result :" + Parse(getResult, expectedException));
            else
            {
                ThrowMe(checkType, "GetText(" + maxLength + ") returned text of size " + actualText.Length +
                         ", expected size " + expectedLength + " for getResult = " + Parse(getResult, expectedException));
            }

            m_TestStep++;
        }
Example #30
0
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            //look at this for a summary of all the GET commands.

            // https://developer.rhino3d.com/api/RhinoCommon/html/T_Rhino_Input_Custom_GetBaseClass.htm.

            /*System.Object
             * Rhino.Input.Custom.GetBaseClass
             *  Rhino.Input.Custom.GetInteger
             *  Rhino.Input.Custom.GetNumber
             *  Rhino.Input.Custom.GetObject
             *  Rhino.Input.Custom.GetOption
             *  Rhino.Input.Custom.GetPoint
             *  Rhino.Input.Custom.GetString
             *
             * */
            var gc = new GetObject();

            gc.SetCommandPrompt("Select objects");
            gc.GeometryFilter = ObjectType.AnyObject;

            OptionInteger intOption  = new OptionInteger(1, 1, 99);
            OptionDouble  dblOption  = new OptionDouble(2.2, 0, 99);
            OptionToggle  boolOption = new OptionToggle(true, "off", "on");

            gc.AddOptionInteger("Integer", ref intOption);
            gc.AddOptionDouble("Double", ref dblOption);
            gc.AddOptionToggle("Boolean", ref boolOption);

            int listIndex = 0;

            string[] listValues = new string[] { "Bran", "Bob", "Arya", "Sansa", "Rickon" };

            int optList = gc.AddOptionList("List", listValues, listIndex);

            while (true)
            {
                GetResult res = gc.GetMultiple(1, 0);

                //we can check if the user selected something
                if (gc.CommandResult() != Result.Success)
                {
                    return(gc.CommandResult());
                }

                if (res == Rhino.Input.GetResult.Object)
                {
                    RhinoApp.WriteLine("Command line option values are");
                    RhinoApp.WriteLine("Integer = {0}", intOption.CurrentValue);
                    RhinoApp.WriteLine("Double = {0}", dblOption.CurrentValue);
                    RhinoApp.WriteLine("Boolean = {0}", boolOption.CurrentValue);
                    RhinoApp.WriteLine("List = {0}", listValues[listIndex]);
                }
                else if (res == Rhino.Input.GetResult.Option)
                {
                    if (gc.OptionIndex() == optList)
                    {
                        listIndex = gc.Option().CurrentListOptionIndex; //this updates the list option to whatever index the user has picked
                    }
                    continue;
                }

                break;
            }

            return(Result.Success);
        }
        //---------------------------------------------------------------------------
        // Helper for GetText() test cases
        //---------------------------------------------------------------------------
        internal void GetTextHelper(SampleText sampleText, TargetRangeType callingRangeType, MaxLength maxLengthType, GetResult getResult, Type expectedException)
        {
            int maxLength = 0;
            string actualText = "";
            string expectedText = "";
            TextPatternRange callingRange;

            // Pre-Condition Verify text is expected value <<sampleText>> 
            TS_SetText(sampleText, out expectedText, CheckType.IncorrectElementConfiguration);

            // Pre-Condition Create calling range = <<callingRangeType>>
            TS_CreateRange(out callingRange, callingRangeType, null, false, CheckType.Verification);

            // Pre-Condition Determine length of text to get = <<maxLength>>
            TS_CalcMaxLength(maxLengthType, out maxLength, expectedText);

            // Call GetText(<<maxLength>>) <<expectedException>>
            TS_GetText(callingRange, ref actualText, maxLength, expectedException, CheckType.Verification);

            // Validate text is <<getResult>>
            TS_VerifyTextLength(getResult, actualText, expectedText, maxLength, expectedException, CheckType.Verification);
        }
Example #32
0
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            // Check the selected dot
            GetObject go = new GetObject();

            go.GroupSelect     = true;
            go.SubObjectSelect = false;
            go.EnableClearObjectsOnEntry(false);
            go.EnableUnselectObjectsOnExit(false);
            go.DeselectAllBeforePostSelect = false;
            go.EnableSelPrevious(true);
            go.EnablePreSelect(true, false);
            go.GeometryFilter = Rhino.DocObjects.ObjectType.Annotation;

            go.SetCommandPrompt("Select Text to append Metrix M01:");
            GetResult result = go.GetMultiple(1, -1);

            if (go.CommandResult() != Rhino.Commands.Result.Success)
            {
                return(go.CommandResult());
            }

            RhinoApp.WriteLine("Object selection counter = {0}", go.ObjectCount);

            List <TextEntity>  textEntityList  = new List <TextEntity>();
            List <RhinoObject> rhinoObjectList = new List <RhinoObject>();

            // Loop through all the objects to find Text
            for (int i = 0; i < go.ObjectCount; i++)
            {
                RhinoObject rhinoObject = go.Object(i).Object();

                if (rhinoObject.ObjectType == ObjectType.Annotation)
                {
                    TextEntity textEntity = rhinoObject.Geometry as TextEntity;

                    if (textEntity != null)
                    {
                        rhinoObjectList.Add(rhinoObject);
                        textEntityList.Add(textEntity);
                    }
                }
            }

            // Sort the text Entity list
            IEnumerable <TextEntity> query = textEntityList.OrderByDescending(t => t.Plane.OriginY).ThenBy(t => t.Plane.OriginX);

            int maxDigit = (int)Math.Floor(Math.Log10(textEntityList.Count) + 1);

            int j = 1;

            foreach (TextEntity textE in query)
            {
                textE.Text = textE.Text + "-Q1";
                j++;
            }


            // Commit the changes for all updated labels
            for (int k = 0; k < rhinoObjectList.Count; k++)
            {
                rhinoObjectList[k].CommitChanges();
            }

            doc.Views.Redraw();

            return(Result.Success);
        }
Example #33
0
            protected override Result RunCommand(RhinoDoc doc, RunMode mode)
            {
                // Command variables
                var    selectedObjects = new List <RhinoObject>();
                string selectedSchema  = "";
                bool   automatic       = true;
                bool   directShape     = false;

                // Construct an objects getter
                // This includes an option toggle for "Automatic" (true means automagic schema application, no directshapes)
                var getObj = new GetObject();

                getObj.SetCommandPrompt("Select geometry");
                var toggleAutomatic = new OptionToggle(true, "Off", "On");

                getObj.AddOptionToggle("Automatic", ref toggleAutomatic);
                getObj.GroupSelect     = true;
                getObj.SubObjectSelect = false;
                getObj.EnableClearObjectsOnEntry(false);
                getObj.EnableUnselectObjectsOnExit(false);
                getObj.DeselectAllBeforePostSelect = false;

                // Get objects
                for (; ;)
                {
                    GetResult res = getObj.GetMultiple(1, 0);
                    if (res == GetResult.Option)
                    {
                        getObj.EnablePreSelect(false, true);
                        continue;
                    }
                    else if (res != GetResult.Object)
                    {
                        return(Result.Cancel);
                    }
                    if (getObj.ObjectsWerePreselected)
                    {
                        getObj.EnablePreSelect(false, true);
                        continue;
                    }
                    break;
                }

                selectedObjects = getObj.Objects().Select(o => o.Object()).ToList();
                automatic       = toggleAutomatic.CurrentValue;

                // Construct an options getter if "Automatic" was set to "off"
                if (!automatic)
                {
                    // Construct an options getter for schema options
                    // This includes an option toggle for "DirectShape" (true will asign selected schema as the family)
                    // Also includes an option list of supported schemas
                    var getOpt = new GetOption();
                    getOpt.SetCommandPrompt("Select schema options. Press Enter when done");
                    var           toggleDirectShape     = new OptionToggle(false, "Off", "On");
                    var           directShapeIndex      = getOpt.AddOptionToggle("DirectShape", ref toggleDirectShape);
                    List <string> schemas               = Enum.GetNames(typeof(SchemaObjectFilter.SupportedSchema)).ToList();
                    int           schemaListOptionIndex = getOpt.AddOptionList("Schema", schemas, 0);

                    // Get options
                    while (getOpt.Get() == GetResult.Option)
                    {
                        if (getOpt.OptionIndex() == schemaListOptionIndex)
                        {
                            selectedSchema = schemas[getOpt.Option().CurrentListOptionIndex];
                        }
                        if (getOpt.OptionIndex() == directShapeIndex)
                        {
                            directShape = toggleDirectShape.CurrentValue;
                        }
                    }
                }

                // Apply schemas
                if (automatic)
                {
                    ApplySchemas(selectedObjects, doc);
                }
                else
                {
                    ApplySchema(selectedObjects, selectedSchema, doc, directShape);
                }
                return(Result.Success);
            }
        private async Task PopulatePeriodDates()
        {
            GetResult <IEnumerable <PeriodDto> > getPeriodsResult = await _accountingManager.GetAllPeriods();

            if (!getPeriodsResult.IsSuccess)
            {
                this.ShowErrorMessage("Failed to retrieve periods.", getPeriodsResult.FailureMessage);
                Close();
                return;
            }

            PeriodDto lastPeriod = getPeriodsResult.Result.LastOrDefault();

            DateTime?periodStart = lastPeriod?.End.AddDays(1);

            if (!periodStart.HasValue)
            {
                DateTime now = DateTime.Now;

                periodStart = new DateTime(
                    now.Year,
                    now.Month,
                    1);
            }

            DateTime?periodEnd = lastPeriod?.End.AddMonths(1);

            if (periodEnd.HasValue)
            {
                bool doesPreviousPeriodEndOnLastDayOfMonth =
                    lastPeriod.End.Day == DateTime.DaysInMonth(lastPeriod.End.Year, lastPeriod.End.Month);

                if (doesPreviousPeriodEndOnLastDayOfMonth)
                {
                    periodEnd = new DateTime(
                        periodEnd.Value.Year,
                        periodEnd.Value.Month,
                        DateTime.DaysInMonth(periodEnd.Value.Year, periodEnd.Value.Month));
                }
            }
            else
            {
                DateTime now = DateTime.Now;

                periodEnd = new DateTime(
                    now.Year,
                    now.Month,
                    DateTime.DaysInMonth(now.Year, now.Month));
            }

            _newPeriod = new PeriodDto(periodStart.Value, periodEnd.Value);

            _synchronizationContext.Post(
                p =>
            {
                var period = (PeriodDto)p;

                _startDateValueLabel.Text = $"{period.Start:yyyy-MM-dd}";
                _endDatePicker.Value      = period.End;
            },
                _newPeriod);
        }
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            // 1 - Select a site curve

            GetObject obj = new GetObject();

            obj.GeometryFilter = Rhino.DocObjects.ObjectType.Curve;
            obj.SetCommandPrompt("Please select a curve representing your site");

            GetResult res = obj.Get();

            Curve site;

            if (res != GetResult.Object)
            {
                RhinoApp.WriteLine("The user did not select a curve");
                return(Result.Failure); // Failed to get a curve
            }
            if (obj.ObjectCount == 1)
            {
                site = obj.Object(0).Curve();
            }
            else
            {
                return(Result.Failure); //Failed to get a curve
            }



            // 2 - Extract the border from the precinct surface
            //Offset for Shop
            Curve[] offsets      = site.Offset(Plane.WorldXY, -2.5, RhinoDoc.ActiveDoc.ModelAbsoluteTolerance, CurveOffsetCornerStyle.Chamfer);
            Curve[] joinedoffset = Curve.JoinCurves(offsets); //join offset curves

            //Offset for Apartment
            Curve[] offsetBst       = site.Offset(Plane.WorldXY, -4, RhinoDoc.ActiveDoc.ModelAbsoluteTolerance, CurveOffsetCornerStyle.Chamfer);
            Curve[] joinedoffsetBst = Curve.JoinCurves(offsetBst); //join offset curves

            //Offset for Base
            Curve[] offsetTop       = site.Offset(Plane.WorldXY, -3, RhinoDoc.ActiveDoc.ModelAbsoluteTolerance, CurveOffsetCornerStyle.Chamfer);
            Curve[] joinedoffsetTop = Curve.JoinCurves(offsetTop); //join offset curves

            //List of offset curves
            List <Curve> buildingsCrv = new List <Curve>();

            buildingsCrv.AddRange(offsets);
            buildingsCrv.AddRange(offsetBst);
            buildingsCrv.AddRange(offsetTop);



            // 3 - Extrude all the offset curves
            //Extrusions
            Extrusion Shop = Extrusion.Create(buildingsCrv[0], 3.1, true);
            Extrusion Apa  = Extrusion.Create(buildingsCrv[1], 18.6, true);
            Extrusion Base = Extrusion.Create(buildingsCrv[2], -3.1, true);

            //List of extrusions
            List <Extrusion> buildingsExt = new List <Extrusion>();

            buildingsExt.Add(Shop);
            buildingsExt.Add(Apa);
            buildingsExt.Add(Base);

            //Draw all the extrusions
            foreach (Extrusion itExt in buildingsExt)
            {
                RhinoDoc.ActiveDoc.Objects.Add(itExt);
            }



            // 4 - Create contour lines on extrusions to represent floors
            //Define extrusions as Breps for contours
            Brep ShopBrep = Shop.ToBrep();
            Brep BrepApa  = Apa.ToBrep();

            //List of Breps
            List <Brep> BuildingBreps = new List <Brep>();

            BuildingBreps.Add(ShopBrep);
            BuildingBreps.Add(BrepApa);

            //Points to define contours
            Point3d start = new Point3d(0, 0, 0);
            Point3d end   = new Point3d(0, 0, 30);

            //Contours
            Curve[] Shopflr = Brep.CreateContourCurves(ShopBrep as Brep, start, end, 3.1);
            Curve[] ApaFlr  = Brep.CreateContourCurves(BrepApa as Brep, start, end, 3.1);

            //List of Contour Curves
            List <Curve> Floors = new List <Curve>();

            Floors.AddRange(Shopflr);
            Floors.AddRange(ApaFlr);

            //Draw all the Contour curves
            foreach (Curve itCrv in Floors)
            {
                RhinoDoc.ActiveDoc.Objects.Add(itCrv);
            }



            RhinoDoc.ActiveDoc.Views.Redraw();

            return(Result.Success);
        }
Example #36
0
 public DelayedEnumerator(GetResult result)
 {
     this.result = result;
 }
 public DelayedEnumerator(GetResult result, GetResultAsync resultAsync)
 {
     _result      = result;
     _resultAsync = resultAsync;
 }
Example #38
0
        public T GetData <T>(string SqlStr, CommandType commandType, GetResult <T> getResult) where T : new()
        {
            IList <DbParameter> ListDataParameter = null;

            return(GetData <T>(SqlStr, commandType, getResult, ListDataParameter));
        }
Example #39
0
        private async void BtnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                // Emp_Code = view.FindViewById<EditText>(Resource.Id.txtempcode);
                Store           = view.FindViewById <EditText>(Resource.Id.txtStore);
                Code            = view.FindViewById <EditText>(Resource.Id.txtCode);
                Quantity        = view.FindViewById <EditText>(Resource.Id.txtQuantity);
                VendorName      = view.FindViewById <EditText>(Resource.Id.txtVendorName);
                VendorContact   = view.FindViewById <EditText>(Resource.Id.txtVendorContact);
                VendorAddress   = view.FindViewById <EditText>(Resource.Id.txtVendorAddress);
                VendorCost      = view.FindViewById <EditText>(Resource.Id.txtVendorCost);
                SellingCost     = view.FindViewById <EditText>(Resource.Id.txtSellingCost);
                CustomerName    = view.FindViewById <EditText>(Resource.Id.txtCustomerName);
                CustomerContact = view.FindViewById <EditText>(Resource.Id.txtCustomerContact);

                VendorModel vendorModel = new VendorModel()
                {
                    //emp_code = Emp_Code.Text,
                    store           = Store.Text,
                    code            = Code.Text,
                    quantity        = Quantity.Text,
                    vendorname      = VendorName.Text,
                    vendorcontact   = VendorContact.Text,
                    vendoraddress   = VendorAddress.Text,
                    vendorcost      = VendorCost.Text,
                    sellingcost     = SellingCost.Text,
                    customername    = CustomerName.Text,
                    customercontact = CustomerContact.Text,
                };
                ReturnValidation returnValidation = new ReturnValidation();


                if (returnValidation.DecimalValidation(Quantity.Text) && returnValidation.DecimalValidation(VendorCost.Text) && returnValidation.DecimalValidation(SellingCost.Text))
                {
                    string            Json              = JsonConvert.SerializeObject(vendorModel);
                    HttpContent       stringContent     = new StringContent(Json, encoding: Encoding.UTF8, mediaType: "application/json");
                    ReturnGenericPost returnGenericPost = new ReturnGenericPost();
                    string            CS = PathLink.VendorURI;

                    JObject obj = await returnGenericPost.ReturnGeneralPosMeth(CS, stringContent);

                    GetResult getResult1 = obj.ToObject <GetResult>();
                    if (getResult1.Status == 1)
                    {
                        View view = LayoutInflater.Inflate(Resource.Layout.UIVendorModel, null);
                        Android.Support.V7.App.AlertDialog alert = new Android.Support.V7.App.AlertDialog.Builder(Context).Create();

                        alert.SetTitle("Done");
                        alert.SetMessage("Data is Posted");
                        //	alert.Dismiss();
                        //	Toast.MakeText(Context, "Alert Dialog dismissed!!!", ToastLength.Short).Show();
                        alert.Show();
                    }
                }
                else
                {
                    Android.Support.V7.App.AlertDialog alert = new Android.Support.V7.App.AlertDialog.Builder(Context).Create();
                    alert.SetTitle("What the Hell !!!!");
                    alert.SetMessage("Please add genuine value in Quantity, VendorCost and Selling Textboxes");
                    //alert.Dismiss();
                    alert.Show();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #40
0
 public PropertyHandler(GetResult get, SetResult set)
 {
     _get = get;
     _set = set;
 }