Ejemplo n.º 1
0
        public static IHttpHandler GetHandler(string virtualPath)
        {
            IHttpHandler handler = null;
            var handlerType = BuildManager.GetCompiledType(virtualPath);
            if (handlerType == null)
                return handler;

            CheckKernel();
            
            var componentContext = Kernel.GetComponentContextByNamedArgs(virtualPath, null);
            if (componentContext != null
                && componentContext.Component.Implementation == handlerType)
            {
                handler = componentContext.LifestyleManager.Get(componentContext) as IHttpHandler;
                RegisterUserControl(handler);
                return handler;
            }

            var componentInfo = new ComponentInfo(virtualPath, typeof(IHttpHandler), handlerType, LifestyleFlags.Transient);
            lock (Kernel)
            {
                if (Kernel.HasRegister(virtualPath))
                    Kernel.UnRegister(virtualPath);
                Kernel.Register(componentInfo);
            }

            handler = Kernel.Get<IHttpHandler>(virtualPath);

            RegisterUserControl(handler);
            return handler;
        }
        public bool CanResolve(string key, Type type, ComponentInfo componentContext)
        {
            if (string.IsNullOrEmpty(key))
                return false;

            return componentContext.Parameters.ContainsKey(key);
        }
Ejemplo n.º 3
0
    public static ComponentInfo[] GetComponentsInfo()
    {
      List<ComponentInfo> components = new List<ComponentInfo>();

      string[] versionFiles = Directory.GetFiles(MapPath("."), "*.version");
      foreach (string file in versionFiles)
      {
        Match m = Regex.Match(Path.GetFileName(file), @"^(?<progName>.*)\.version$");
        ComponentInfo info = new ComponentInfo();
        info.Name = m.Groups["progName"].Value;
        info.Version = File.ReadAllText(file);

        string historyFile = ApplicationHlp.MapPath(info.Name + ".history.html");
        if (File.Exists(historyFile))
        {
          info.History = File.ReadAllText(historyFile);
          try
          {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(info.History);
            info.History = doc.InnerText;
          }
          catch (Exception exc)
          {
            //Это не ошибка, просто не Xml - формат
            Logger.WriteException(exc);
          }
        }
        else
          info.History = string.Empty;

        components.Add(info);
      }
      return components.ToArray();
    }
			public Point(Vector2 point, LayoutTag tag, WindowComponent component) {
				
				this.x = point.x;
				this.y = point.y;

				this.componentInfo = new ComponentInfo(tag, component);
				
			}
        public override ConstructorInfo SelectConstructor(ComponentInfo componentInfo)
        {
            var ctor =
                componentInfo.Classtype.GetConstructors().SingleOrDefault(c => c.GetCustomAttributes(attributeType, false).Any())
                ?? base.SelectConstructor(componentInfo);

            return ctor;
        }
        public bool CanResolve(string key, Type type, ComponentInfo componentContext)
        {
            if (!type.IsArray)
                return false;

            var arrayType = type.GetElementType();
            return container.HasComponent(arrayType);
        }
Ejemplo n.º 7
0
    public ColorCompass(Modkit module, int moduleId, ComponentInfo info) : base(module, moduleId, info)
    {
        Debug.LogFormat("[The Modkit #{0}] Solving Color Compass. Arrows: [Up: {1}, Right: {2}, Down: {3}, Left: {4}].", moduleId, ComponentInfo.COLORNAMES[info.arrows[ComponentInfo.UP]], ComponentInfo.COLORNAMES[info.arrows[ComponentInfo.RIGHT]], ComponentInfo.COLORNAMES[info.arrows[ComponentInfo.DOWN]], ComponentInfo.COLORNAMES[info.arrows[ComponentInfo.LEFT]]);
        LED = info.LED.ToList();
        off = new int[] { 0, 1, 2 }.OrderBy(x => rnd.Range(0, 1000)).ToList();

        Debug.LogFormat("[The Modkit #{0}] Different LED colors: [ {1} ].", moduleId, info.LED.Distinct().Select(x => ComponentInfo.COLORNAMES[x]).Join(", "));

        index = CalcIndex();

        Debug.LogFormat("[The Modkit #{0}] Which gives the input sequence: [ {1} ].", moduleId, GetSequenceString());
    }
        public MainWindow()
        {
            InitializeComponent();

            ComponentInfo.SetLicense("FREE-LIMITED-KEY");
            ComponentInfo.FreeLimitReached += (sender, e) => e.FreeLimitReachedAction = FreeLimitReachedAction.ContinueAsTrial;

            MyTimer timer = new MyTimer(10000);

            timer.Elapsed += Timer_Elapsed;
            timer.Start();
        }
        // function for geting the text from the word file
        static public string GetTextFromWordFile(string filePath)
        {
            ComponentInfo.SetLicense("AKSJUY-9IUEY-2YUW7-HSGDT-6NHJY");

            // Load Word document from file's path.
            var document = DocumentModel.Load(filePath);

            // Get Word document's plain text.
            string text = document.Content.ToString();

            return(text);
        }
Ejemplo n.º 10
0
        public string StringGetGemBox(string sSource)
        {
            //ComponentInfo.SetLicense("FREE-LIMITED-KEY");
            ComponentInfo.SetLicense("DH5L-ED6Q-R7O0-DY0H");
            var document = DocumentModel.Load(sSource);

            //StringBuilder text = new StringBuilder();



            return(document.Content.ToString());
        }
Ejemplo n.º 11
0
    static void Main()
    {
        // If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        using (var document = PdfDocument.Load("LoremIpsum.pdf"))
        {
            // Get document's trailer dictionary.
            var trailer = document.GetDictionary();
            // Get document catalog dictionary from the trailer.
            var catalog = (PdfDictionary)((PdfIndirectObject)trailer[PdfName.Create("Root")]).Value;

            // Either retrieve "PieceInfo" entry value from document catalog or create a page-piece dictionary and set it to document catalog under "PieceInfo" entry.
            PdfDictionary pieceInfo;
            var           pieceInfoKey   = PdfName.Create("PieceInfo");
            var           pieceInfoValue = catalog[pieceInfoKey];
            switch (pieceInfoValue.ObjectType)
            {
            case PdfBasicObjectType.Dictionary:
                pieceInfo = (PdfDictionary)pieceInfoValue;
                break;

            case PdfBasicObjectType.IndirectObject:
                pieceInfo = (PdfDictionary)((PdfIndirectObject)pieceInfoValue).Value;
                break;

            case PdfBasicObjectType.Null:
                pieceInfo             = PdfDictionary.Create();
                catalog[pieceInfoKey] = PdfIndirectObject.Create(pieceInfo);
                break;

            default:
                throw new InvalidOperationException("PieceInfo entry must be dictionary.");
            }

            // Create page-piece data dictionary for "GemBox.Pdf" conforming product and set it to page-piece dictionary.
            var data = PdfDictionary.Create();
            pieceInfo[PdfName.Create("GemBox.Pdf")] = data;

            // Create a private data dictionary that will hold private data that "GemBox.Pdf" conforming product understands.
            var privateData = PdfDictionary.Create();
            data[PdfName.Create("Data")] = privateData;

            // Set "Title" and "Version" entries to private data.
            privateData[PdfName.Create("Title")]   = PdfString.Create(ComponentInfo.Title);
            privateData[PdfName.Create("Version")] = PdfString.Create(ComponentInfo.Version);

            // Specify date of the last modification of "GemBox.Pdf" private data (required by PDF specification).
            data[PdfName.Create("LastModified")] = PdfString.Create("D:" + DateTimeOffset.Now.ToString("yyyyMMddHHmmssK", CultureInfo.InvariantCulture).Replace(':', '\'') + "'", PdfEncoding.ASCII, PdfStringForm.Literal);

            document.Save("Basic Objects.pdf");
        }
    }
        public object Resolve(string key, Type type, ComponentInfo componentContext)
        {
            var dependency = componentContext.Parameters[key];

            if (type.IsAssignableFrom(dependency.GetType()) == false)
            {
                throw new CompactContainerException("Cannot convert parameter override \"" + key + "\" to type " + type.FullName +
                                                    " for component " + componentContext);
            }

            return dependency;
        }
Ejemplo n.º 13
0
 static void Main(string[] args)
 {
     ComponentInfo.SetLicense("FREE-LIMITED-KEY");
     using (ImapClient imap = new ImapClient("imap.gmail.com", 993)){
         imap.ConnectTimeout = TimeSpan.FromSeconds(10);
         imap.Connect();
         imap.Authenticate("*****@*****.**", "MySuperSecretPassword", ImapAuthentication.Native);
         imap.SelectInbox();
         IList <int> messages = imap.SearchMessageNumbers("UNSEEN");
         Console.WriteLine($"Number of unseen messages {messages.Count}");
     }
 }
Ejemplo n.º 14
0
    public PreciseWires(Modkit module, int moduleId, ComponentInfo info) : base(module, moduleId, info)
    {
        Debug.LogFormat("[The Modkit #{0}] Solving Precise Wires. Alphanumeric keys present are: {1}. LEDs are: {2}.", moduleId, info.alphabet.Join(", "), info.LED.Select(x => ComponentInfo.COLORNAMES[x]).Join(", "));

        for (int i = 0; i < info.alphabet.Length; i++)
        {
            keyColors[i] = map[info.alphabet[i][1] - '0'][info.alphabet[i][0] - 'A'];
        }

        Debug.LogFormat("[The Modkit #{0}] Alphanumeric keys colors are: {1}.", moduleId, keyColors.Select(x => ComponentInfo.COLORNAMES[x]).Join(", "));
        CalcSolution();
    }
        public MainWindow()
        {
            this.InitializeComponent();

            // If using Professional version, put your serial key below.
            ComponentInfo.SetLicense("FREE-LIMITED-KEY");

            string path      = "Reading.docx";
            int    pageIndex = 0;

            this.SetImageControl(path, pageIndex);
        }
        public object Resolve(string key, Type type, ComponentInfo componentContext)
        {
            if (!type.IsArray)
                return null;

            var arrayType = type.GetElementType();
            var services = container.GetServices(arrayType).ToArray();
            var typedArray = Array.CreateInstance(arrayType, services.Length);
            Array.Copy(services, typedArray, services.Length);

            return typedArray;
        }
Ejemplo n.º 17
0
    public void AddNeedComponentInfo(ECSDefine.ComponentType componentType, int componentId = -1)
    {
        ComponentInfo componentInfo = ExecuteSystemUnit.PopSystemComponentInfo();

        if (componentInfo != null)
        {
            componentInfo.ComponentId   = componentId;
            componentInfo.ComponentType = componentType;

            componentInfoList.Add(componentInfo);
        }
    }
Ejemplo n.º 18
0
        public static void VerifySpecificTextInPDF(string filepath, string pattern)
        {
            // If using Professional version, put your serial key below.
            ComponentInfo.SetLicense("FREE-LIMITED-KEY");

            DocumentModel document = DocumentModel.Load(filepath);

            StringBuilder sb = new StringBuilder();

            // Read PDF file's document properties.
            sb.AppendFormat("Author: {0}", document.DocumentProperties.BuiltIn[BuiltInDocumentProperty.Author]).AppendLine();
            sb.AppendFormat("DateContentCreated: {0}", document.DocumentProperties.BuiltIn[BuiltInDocumentProperty.DateLastSaved]).AppendLine();

            // Sample's input parameter.
            //string pattern = @"(?<WorkHours>\d+)\s+(?<UnitPrice>\d+\.\d{2})\s+(?<Total>\d+\.\d{2})";
            Regex regex = new Regex(pattern);

            int           row  = 0;
            StringBuilder line = new StringBuilder();

            // Read PDF file's text content and match a specified regular expression.
            foreach (Match match in regex.Matches(document.Content.ToString()))
            {
                line.Length = 0;
                line.AppendFormat("Result: {0}: ", ++row);

                // Either write only successfully matched named groups or entire match.
                bool hasAny = false;
                for (int i = 0; i < match.Groups.Count; ++i)
                {
                    string groupName  = regex.GroupNameFromNumber(i);
                    Group  matchGroup = match.Groups[i];
                    if (matchGroup.Success && groupName != i.ToString())
                    {
                        line.AppendFormat("{0}= {1}, ", groupName, matchGroup.Value);
                        hasAny = true;
                    }
                }

                if (hasAny)
                {
                    line.Length -= 2;
                }
                else
                {
                    line.Append(match.Value);
                }

                sb.AppendLine(line.ToString());
            }

            Console.WriteLine(sb.ToString());
        }
Ejemplo n.º 19
0
    public override void GenerateUI()
    {
        StringBuilder init = new StringBuilder();
        ComponentInfo info = GetComponentInfo();
        string        gameObjectInitTemplate = "    0} = transform:Find(\"{1}\").gameObject;\n";
        string        transformInitTemplate  = "    {0} = transform:Find(\"{1}\");\n";
        string        componentInitTemplate  = "    {0} = transform:Find(\"{1}\"):GetComponent(\"{2}\");\n";

        foreach (Transform tran in GetChildrenTransform())
        {
            string name = tran.name;
            string tag  = tran.gameObject.tag;

            if (CheckTag(tag))
            {
                CheckPrefabName(name);
                if (tag == TagType.UI_Button)
                {
                    init.Append(string.Format(componentInitTemplate, name, GetHierarchy(tran), info.GetButton()));
                }
                else if (tag == TagType.UI_GameObject)
                {
                    init.Append(string.Format(gameObjectInitTemplate, name, GetHierarchy(tran)));
                }
                else if (tag == TagType.UI_Lable)
                {
                    init.Append(string.Format(componentInitTemplate, name, GetHierarchy(tran), info.GetLable()));
                }
                else if (tag == TagType.UI_Sprite)
                {
                    init.Append(string.Format(componentInitTemplate, name, GetHierarchy(tran), info.GetSprite()));
                }
                else if (tag == TagType.UI_Texture)
                {
                    init.Append(string.Format(componentInitTemplate, name, GetHierarchy(tran), info.GetTexture()));
                }
                else if (tag == TagType.UI_Toggle)
                {
                    init.Append(string.Format(componentInitTemplate, name, GetHierarchy(tran), info.GetToggle()));
                }
                else if (tag == TagType.UI_Transform)
                {
                    init.Append(string.Format(transformInitTemplate, name, GetHierarchy(tran)));
                }
            }
        }

        content = ReadTemplateString();
        content = content.Replace("{#class#}", GetClassName());
        content = content.Replace("{#init#}", init.ToString());
        SaveFile();
    }
Ejemplo n.º 20
0
    public void ChangePlaySpeed(EFxLODLevel lv, float psSpeed, float animatorSpeed)
    {
        ComponentInfo curInfo = null;

        if (FxComponentInfos.Length == 1 && FxComponentInfos[0] != null)
        {
            curInfo = FxComponentInfos[0];
        }
        else if (FxComponentInfos.Length == 3)
        {
            for (int i = (int)lv; i >= 0; i--)
            {
                // 如果当前LOD等级无有效资源,则降一级查找;直至找到有效资源
                if (FxComponentInfos[i] != null)
                {
                    curInfo = FxComponentInfos[i];
                    break;
                }
            }
        }

        if (curInfo != null)
        {
            foreach (var v in curInfo.ParticleSystems)
            {
                if (v.Comp != null)
                {
                    if (psSpeed < Util.FloatZero)
                    {
                        v.Comp.Pause();
                    }
                    else
                    {
                        var mainModule = v.Comp.main;
                        mainModule.simulationSpeed = psSpeed;
                        if (!v.Comp.isPlaying)
                        {
                            v.Comp.Play();
                        }
                    }
                }
            }

            foreach (var v in curInfo.Animators)
            {
                if (v.Comp != null)
                {
                    v.Comp.speed = animatorSpeed;
                }
            }
        }
    }
Ejemplo n.º 21
0
    static void Main()
    {
        // If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        var presentation = PresentationDocument.Load("Reading.pptx");

        var slide = presentation.Slides[0];

        slide.Content.Drawings.Clear();

        // Create "Built-in document properties" text box.
        var textBox = slide.Content.AddTextBox(ShapeGeometryType.Rectangle, 0.5, 0.5, 12, 10, LengthUnit.Centimeter);

        textBox.Shape.Format.Outline.Fill.SetSolid(Color.FromName(ColorName.DarkBlue));

        var paragraph = textBox.AddParagraph();

        paragraph.Format.Alignment = HorizontalAlignment.Left;

        var run = paragraph.AddRun("Built-in document properties:");

        run.Format.Bold = true;

        paragraph.AddLineBreak();

        foreach (var docProp in presentation.DocumentProperties.BuiltIn)
        {
            paragraph.AddRun(string.Format("{0}: {1}", docProp.Key, docProp.Value));
            paragraph.AddLineBreak();
        }

        // Create "Custom document properties" text box.
        textBox = slide.Content.AddTextBox(ShapeGeometryType.Rectangle, 14, 0.5, 12, 10, LengthUnit.Centimeter);
        textBox.Shape.Format.Outline.Fill.SetSolid(Color.FromName(ColorName.DarkBlue));

        paragraph = textBox.AddParagraph();
        paragraph.Format.Alignment = HorizontalAlignment.Left;

        run             = paragraph.AddRun("Custom document properties:");
        run.Format.Bold = true;

        paragraph.AddLineBreak();

        foreach (var docProp in presentation.DocumentProperties.Custom)
        {
            paragraph.AddRun(string.Format("{0}: {1} (Type: {2})", docProp.Key, docProp.Value, docProp.Value.GetType()));
            paragraph.AddLineBreak();
        }

        presentation.Save("Document Properties.pptx");
    }
    static void Main()
    {
        // If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        var presentation = new PresentationDocument();

        // Create new presentation slide.
        var slide = presentation.Slides.AddNew(SlideLayoutType.Custom);

        // Create and add audio content.
        AudioContent audio = null;

        using (var stream = File.OpenRead("Applause.wav"))
            audio = slide.Content.AddAudio(AudioContentType.Wav, stream, 2, 2, LengthUnit.Centimeter);

        // Set the ending fade durations for the media.
        audio.Fade.End = TimeOffset.From(300, TimeOffsetUnit.Millisecond);

        // Get the picture associated with this media.
        var picture = audio.Picture;

        // Set drawing properties.
        picture.Action.Click.Set(ActionType.PlayMedia);
        picture.Layout.Width  = Length.From(7, LengthUnit.Centimeter);
        picture.Layout.Height = Length.From(7, LengthUnit.Centimeter);
        picture.Name          = "Applause.wav";

        // Create and add video content.
        VideoContent video = null;

        using (var stream = File.OpenRead("Wildlife.wmv"))
            video = slide.Content.AddVideo("video/x-ms-wmv", stream, 10, 2, 10, 5.6, LengthUnit.Centimeter);

        // Set drawing properties.
        video.Picture.Action.Click.Set(ActionType.PlayMedia);
        video.Picture.Name = "Wildlife.wmv";

        // Set the amount of time to be trimmed from the start and end of the media.
        video.Trim.Start = TimeOffset.From(600, TimeOffsetUnit.Millisecond);
        video.Trim.End   = TimeOffset.From(800, TimeOffsetUnit.Millisecond);

        // Set the starting and ending fade durations for the media.
        video.Fade.Start = TimeOffset.From(100, TimeOffsetUnit.Millisecond);
        video.Fade.End   = TimeOffset.From(200, TimeOffsetUnit.Millisecond);

        // Add video bookmarks.
        video.Bookmarks.Add(TimeOffset.From(1500, TimeOffsetUnit.Millisecond));
        video.Bookmarks.Add(TimeOffset.From(3000, TimeOffsetUnit.Millisecond));

        presentation.Save("Audio and Video.pptx");
    }
Ejemplo n.º 23
0
    static void Main(string[] args)
    {
        // If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        DocumentModel document = DocumentModel.Load("Reading.docx");

        // In order to achieve the conversion of a loaded Word file to PDF,
        // or to some other Word format,
        // we just need to save a DocumentModel object to desired output file format.

        document.Save("Convert.pdf");
    }
        public object Resolve(string key, Type type, ComponentInfo componentContext)
        {
            var configKey = GetKey(componentContext, key);
            var configValue = container.Configuration[configKey];

            if (type.IsAssignableFrom(configValue.GetType()) == false)
            {
                throw new CompactContainerException("Cannot convert configuration \"" + configKey + "\" to type " + type.FullName +
                                                    " for component " + componentContext);
            }

            return configValue;
        }
Ejemplo n.º 25
0
 public static void CheckComponent(ComponentInfo a, ComponentInfo b)
 {
     Assert.Equal(a.DisplayName, b.DisplayName);
     Assert.Equal(a.SystemName, b.SystemName);
     CheckDateTimesEqualBySeconds(a.CreatedDate, b.CreatedDate);
     Assert.Equal(a.Id, b.Id);
     Assert.NotEqual(a.Id, Guid.Empty);
     Assert.Equal(a.ParentId, b.ParentId);
     Assert.Equal(a.Type.Id, b.Type.Id);
     Assert.Equal(a.Version, b.Version);
     CheckComponentType(a.Type, b.Type);
     CheckExtentionProperties(a.Properties, b.Properties);
 }
Ejemplo n.º 26
0
    static void Main(string[] args)
    {
        // If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        DocumentModel document = DocumentModel.Load("HtmlExport.docx");

        // Images will be embedded directly in HTML img src attribute.
        document.Save("Html Export.html", new HtmlSaveOptions()
        {
            EmbedImages = true
        });
    }
Ejemplo n.º 27
0
    static void Main(string[] args)
    {
        // If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        DocumentModel document = DocumentModel.Load("MergeIfFields.docx");

        var customer = new { Gender = "M", CustomerName = "John", Surname = "Doe" };

        document.MailMerge.Execute(customer);

        document.Save("If Fields.docx");
    }
        public object Resolve(string key, Type type, ComponentInfo componentContext)
        {
            var configKey   = GetKey(componentContext, key);
            var configValue = container.Configuration[configKey];

            if (type.IsAssignableFrom(configValue.GetType()) == false)
            {
                throw new CompactContainerException("Cannot convert configuration \"" + configKey + "\" to type " + type.FullName +
                                                    " for component " + componentContext);
            }

            return(configValue);
        }
Ejemplo n.º 29
0
 public bool checkForm(string phone, string email, string hometown_addr, string house_addr)
 {
     ComponentInfo.SetLicense("FREE-LIMITED-KEY");
     //MailAddressValidationResult result = MailAddressValidator.Validate(email);
     if (phone == "" || email == "" || hometown_addr == "" || house_addr == "" || checkPhoneForm(phone))
     {
         return(false);
     }
     else
     {
         return(true);
     }
 }
Ejemplo n.º 30
0
    public SequenceCut(Modkit module, int moduleId, ComponentInfo info) : base(module, moduleId, info)
    {
        Debug.LogFormat("[The Modkit #{0}] Solving Sequence Cut. Symbols present are: {1}. Alphanumeric keys present are: {2}.", moduleId, info.GetSymbols(), info.alphabet.Join(", "));
        row = info.symbols.Select(x => symbolToRow[x]).Min();
        seq = sequences[row];
        Debug.LogFormat("[The Modkit #{0}] Using sequence {1} - [ {2} ].", moduleId, row + 1, seq.Select(x => ComponentInfo.COLORNAMES[x]).Join(", "));

        CalcKeysSwitches();

        Debug.LogFormat("[The Modkit #{0}] New sequence is [ {1} ].", moduleId, seq.Select(x => ComponentInfo.COLORNAMES[x]).Join(", "));

        CalcWireCuts();
    }
Ejemplo n.º 31
0
        void CopyModelFiles()
        {
            ModelFolderInDump = $@"{NowDumpFolder}\Models";
            Body     body     = ((MainForm)System.Windows.Forms.Application.OpenForms["MainForm"]).body;
            TreeList treeView = ((MainForm)System.Windows.Forms.Application.OpenForms["MainForm"]).treeList1;

            foreach (TreeListNode node in treeView.Nodes)
            {
                ComponentInfo component = (ComponentInfo)node.Tag;
                body.SetSourseChancge(component.FFN, $@"{ModelFolderInDump}\{Directory.GetParent(component.FFN).Name}\{Path.GetFileName(component.FFN)}");
            }
            AddWaitStatus("Скопированы модели");
        }
Ejemplo n.º 32
0
    static void Main(string[] args)
    {
        // If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        var document = DocumentModel.Load("Reading.docx");

        // Disallow all editing in the document (document is read-only).
        // Since password is not specified, all users can stop enforcing protection in MS Word.
        document.Protection.StartEnforcingProtection(EditingRestrictionType.NoChanges, null);

        document.Save("Restrict Editing.docx");
    }
Ejemplo n.º 33
0
    void CheckComponentLogic(DebugMsg msg, EntityInfo entityInfo, ComponentInfo compInfo)
    {
        //Debug.Log("CheckComponentLogic");

        if (!m_world.GetExistRecordSystem(compInfo.m_compName))
        {
            return;
        }

        RecordSystemBase rsb       = m_world.GetRecordSystemBase(compInfo.m_compName);
        ComponentBase    compLocal = rsb.GetRecord(entityInfo.id, msg.frame);

        if (IsFilter(compInfo.m_compName))
        {
            if (compLocal != null)
            {
                string content = Serializer.Serialize(compLocal);

                if (!content.Equals(compInfo.content))
                {
                    string log = "error: frame " + msg.frame + " currentFrame:" + m_world.FrameCount + " id:" + entityInfo.id + " comp:" + compInfo.m_compName
                                 + "\n remote:" + compInfo.content
                                 + "\n local:" + content + "\n";
                    Debug.LogWarning(log);
                    rsb.PrintRecord(entityInfo.id);

                    Time.timeScale = 0;
                    Record(log);
                    OutPutDebugRecord();
                }
                else
                {
                    //Debug.Log("ReceviceDebugMsg  correct! frame " + msg.frame + " currentFrame:" + m_world.FrameCount + " id:" + entityInfo.id + " comp:" + compInfo.m_compName + " content :" + compInfo.content);
                }

                //派发冲突
                GlobalEvent.DispatchEvent(c_isConflict, msg.frame);
            }
            else
            {
                //string log = "not find Record ->> frame:" + msg.frame + " id " + entityInfo.id + " compName: " + compInfo.m_compName + " currentframe: " + m_world.FrameCount + " content " + compInfo.content;

                //Debug.LogWarning(log);
                //syncLog += log;
            }
        }
        else
        {
            Debug.Log("Not is filter " + compInfo.m_compName);
        }
    }
    static void Main()
    {
        // If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        var presentation = new PresentationDocument();

        // Create new slide.
        var slide = presentation.Slides.AddNew(SlideLayoutType.Custom);

        // Create new "rounded rectangle" shape.
        var shape = slide.Content.AddShape(
            ShapeGeometryType.RoundedRectangle, 2, 2, 5, 4, LengthUnit.Centimeter);

        // Get shape format.
        var format = shape.Format;

        // Get shape fill format.
        var fillFormat = format.Fill;

        // Set shape fill format as solid fill.
        fillFormat.SetSolid(Color.FromName(ColorName.DarkBlue));

        // Create new "rectangle" shape.
        shape = slide.Content.AddShape(
            ShapeGeometryType.Rectangle, 8, 2, 5, 4, LengthUnit.Centimeter);

        // Set shape fill format as solid fill.
        shape.Format.Fill.SetSolid(Color.FromName(ColorName.Yellow));

        // Set shape outline format as solid fill.
        shape.Format.Outline.Fill.SetSolid(Color.FromName(ColorName.Green));

        // Create new "rounded rectangle" shape.
        shape = slide.Content.AddShape(
            ShapeGeometryType.RoundedRectangle, 14, 2, 5, 4, LengthUnit.Centimeter);

        // Set shape fill format as no fill.
        shape.Format.Fill.SetNone();

        // Get shape outline format.
        var lineFormat = shape.Format.Outline;

        // Set shape outline format as single solid red line.
        lineFormat.Fill.SetSolid(Color.FromName(ColorName.Red));
        lineFormat.DashType     = LineDashType.Solid;
        lineFormat.Width        = Length.From(0.8, LengthUnit.Centimeter);
        lineFormat.CompoundType = LineCompoundType.Single;

        presentation.Save("Shape Formatting.pptx");
    }
Ejemplo n.º 35
0
        private LotInfo SplitLot(LotInfo distinctLot, bool isRelative, TransactionStamp txnStamp)
        {
            LotInfo lotData = LotInfo.GetLotByLot(distinctLot.Lot);

            List <SqlAgent>      splitLotArchiSQLList = new List <SqlAgent>();
            List <ComponentInfo> lsComponentDatas     = new List <ComponentInfo>();

            if (isRelative)
            {
                // 找出相同批號的所有Component
                _RelativePackingList.FindAll(lot => lot.LotInfo.Lot == lotData.Lot).ForEach(pack =>
                {
                    lsComponentDatas.Add(ComponentInfo.GetComponentByComponentID(pack.ComponentID));
                });
            }
            else
            {
                // 找出相同批號的所有Component
                _PackingList.FindAll(lot => lot.LotInfo.Lot == lotData.Lot).ForEach(pack =>
                {
                    lsComponentDatas.Add(ComponentInfo.GetComponentByComponentID(pack.ComponentID));
                });
            }

            var generator = NamingIDGenerator.GetRule("SplitLot");

            if (generator == null)
            {
                //WRN-00411,找不到可產生的序號,請至命名規則維護設定,規則名稱:{0}!!!
                throw new Exception(TextMessage.Error.T00437("SplitLot"));
            }
            var serialData = generator.GenerateNextIDs(1, lotData, new string[] { }, User.Identity.Name);

            splitLotArchiSQLList = serialData.Second;
            var splitLotID = serialData.First[0];

            var          reasonCategoryInfo = ReasonCategoryInfo.GetReasonCategoryByCategoryNameAndReason("Common", "OTHER");
            SplitLotInfo splitLotData       = SplitLotInfo.CreateSplitLotByLotAndQuantity(lotData.Lot, splitLotID, lsComponentDatas, reasonCategoryInfo, "Pack");

            WIPTxn.SplitIndicator splitInd = WIPTxn.SplitIndicator.Create();
            // 拆批交易
            WIPTxn.Default.SplitLot(lotData, splitLotData, splitInd, txnStamp);

            //若子單元為自動產生,更新序號至DB
            if (splitLotArchiSQLList != null && splitLotArchiSQLList.Count > 0)
            {
                DBCenter.ExecuteSQL(splitLotArchiSQLList);
            }

            return(LotInfo.GetLotByLot(splitLotID));
        }
Ejemplo n.º 36
0
    public EntityInfo CreateEntityInfo(EntityBase entity, SyncSession session)
    {
        EntityInfo Data = new EntityInfo();

        Data.id    = entity.ID;
        Data.infos = new List <ComponentInfo>();

        foreach (var c in entity.m_compDict)
        {
            Type type = c.Value.GetType();

            if (!type.IsSubclassOf(typeof(ServiceComponent)) &&
                type != typeof(SyncComponent))
            {
                try
                {
                    ComponentInfo info = new ComponentInfo();
                    info.m_compName = type.Name;
                    info.content    = Serializer.Serialize(c.Value);

                    Data.infos.Add(info);
                }
                catch (StackOverflowException e)
                {
                    Debug.LogError("Serializer error " + type.FullName + " " + e.ToString());
                }
            }
        }

        //给有连接组件的增加Self组件
        if (entity.GetExistComp <ConnectionComponent>())
        {
            ConnectionComponent comp = entity.GetComp <ConnectionComponent>();
            if (comp.m_session == session)
            {
                ComponentInfo info = new ComponentInfo();
                info.m_compName = "SelfComponent";
                info.content    = "{}";
                Data.infos.Add(info);
            }
            else
            {
                ComponentInfo info = new ComponentInfo();
                info.m_compName = "TheirComponent";
                info.content    = "{}";
                Data.infos.Add(info);
            }
        }

        return(Data);
    }
Ejemplo n.º 37
0
    static void Main()
    {
        // If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        var document = new DocumentModel();

        // Set footnotes and endnotes number style for all sections in the document.
        document.Settings.Footnote.NumberStyle = NumberStyle.LowerLetter;
        document.Settings.Endnote.NumberStyle  = NumberStyle.LowerRoman;

        var section = new Section(document);

        document.Sections.Add(section);

        // Set footnotes number style for the current section.
        section.FootnoteSettings.NumberStyle = NumberStyle.Decimal;

        section.Blocks.Add(
            new Paragraph(document,
                          new Run(document, "GemBox.Document"),
                          new Note(document, NoteType.Footnote,
                                   new Paragraph(document,
                                                 new Run(document, "Read more about GemBox.Document on "),
                                                 new Hyperlink(document, "https://www.gemboxsoftware.com/document", "overview page"),
                                                 new Run(document, "."))),
                          new Run(document, " is a .NET component that enables developers to read, write, convert and print document files (DOCX, DOC, PDF, HTML, XPS, RTF and TXT)"),
                          new Note(document, NoteType.Footnote, "Image formats like PNG, JPEG, GIF, BMP, TIFF and WMP are also supported."),
                          new Run(document, " from .NET"),
                          new Note(document, NoteType.Endnote, "GemBox.Document works on .NET Framework 3.5 or higher and platforms that implement .NET Standard 2.0 or higher."),
                          new Run(document, " applications in a simple and efficient way.")));

        section = new Section(document);
        document.Sections.Add(section);

        // Set endnotes number style for the current section.
        section.EndnoteSettings.NumberStyle = NumberStyle.UpperRoman;

        section.Blocks.Add(
            new Paragraph(document,
                          new Run(document, "The latest version of GemBox.Document can be downloaded from "),
                          new Hyperlink(document, "https://www.gemboxsoftware.com/document/free-version", "here"),
                          new Note(document, NoteType.Endnote,
                                   new Paragraph(document,
                                                 new Run(document, "The latest fixes for all GemBox.Document versions can be downloaded from "),
                                                 new Hyperlink(document, "https://www.gemboxsoftware.com/document/downloads/BugFixes.htm", "here"),
                                                 new Run(document, "."))),
                          new Run(document, ".")));

        document.Save("Footnotes and Endnotes.docx");
    }
Ejemplo n.º 38
0
        /// <summary>
        /// Тестовой вариант
        /// </summary>
        static void GetBoxCreateWord()
        {
            string[] temZnach = new string[] { "Gthdjt", "Массив представляет", "мы можем" };
            string   temp     = "";

            //Лицензия
            ComponentInfo.SetLicense("FREE-LIMITED-KEY");

            // Создание нового дока.
            var document = new DocumentModel();

            try
            {
                for (int i = 0; i < temZnach.Length; i++)
                {
                    // temp += (temZnach[i] + Environment.NewLine);
                    temp += (temZnach[i] + "\t\n");
                    // temp += (temZnach[i]);
                    document.Content.LoadText(temp);
                }
                ;

                //document.Sections.Add(
                //    new Section(document,
                //      new Paragraph(document,
                //          new Run(document, temp),
                //          new SpecialCharacter(document, SpecialCharacterType.LineBreak)
                //      // new Run(document, ""/*"***"*//*"\xFC" + "\xF0" + "\x32"*/) { CharacterFormat = { FontName = "Wingdings", Size = 48 } }
                //      )));



                //// Добавление нового раздела с двумя абзацами, содержащими некоторый текст и символы
                //document.Sections.Add(
                //new Section(document,
                //    new Paragraph(document,
                //        new Run(document, "Это наш первый абзац с символами, добавленными в новую строку."),
                //        new SpecialCharacter(document, SpecialCharacterType.LineBreak),
                //        new Run(document, ""/*"***"*//*"\xFC" + "\xF0" + "\x32"*/) { CharacterFormat = { FontName = "Wingdings", Size = 48 } }),
                //    new Paragraph(document, "Это наш второй абзац."))
                //);

                // Save Word document to file's path.
                document.Save("TestSaveDoc.docx");
                document.Save("TestSaveDoc.pdf");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Ошибка при работе" + ex);
            }
        }
Ejemplo n.º 39
0
    static void Main()
    {
        // If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        var document = DocumentModel.Load("Reading.docx");

        EditingRestrictionType restriction = EditingRestrictionType.NoChanges;
        string password = "******";

        document.Protection.StartEnforcingProtection(restriction, password);

        document.Save("Restrict Editing.docx");
    }
    void generates(ComponentInfo componentInfo, string expectedFileContent)
    {
        expectedFileContent = expectedFileContent.ToUnixLineEndings();
        var files = new ComponentsGenerator().Generate(new[] { componentInfo });
        var expectedFilePath = componentInfo.fullTypeName + classSuffix;

        files.Length.should_be(1);
        var file = files[0];

        #pragma warning disable
        if (logResults) {
            Console.WriteLine("should:\n" + expectedFileContent);
            Console.WriteLine("was:\n" + file.fileContent);
        }

        file.fileName.should_be(expectedFilePath);
        file.fileContent.should_be(expectedFileContent);
    }
    static void generates(ComponentInfo[] componentInfos, string[] lookupNames, string[] lookupCodes)
    {
        var files = new ComponentIndicesGenerator().Generate(componentInfos);
        files.Length.should_be(lookupNames.Length);

        for (int i = 0; i < lookupNames.Length; i++) {
            var lookupName = lookupNames[i];
            var expectedLookupCode = lookupCodes[i].ToUnixLineEndings();
            files.Any(f => f.fileName == lookupName).should_be_true();
            var file = files.Single(f => f.fileName == lookupName);
            #pragma warning disable
            if (logResults) {
                Console.WriteLine("should:\n" + expectedLookupCode);
                Console.WriteLine("was:\n" + file.fileContent);
            }
            file.fileContent.should_be(expectedLookupCode);
        }
    }
        public virtual ConstructorInfo SelectConstructor(ComponentInfo componentInfo)
        {
            ConstructorInfo selectedCtor = null;
            var missingComponents = new StringBuilder();

            foreach (var constructorInfo in componentInfo.Classtype.GetConstructors())
            {
                var parameters = constructorInfo.GetParameters();
                if (selectedCtor != null && parameters.Length <= selectedCtor.GetParameters().Length)
                    continue;

                var proposeNewConstructor = true;

                foreach (var parameterInfo in parameters)
                {
                    if (!container.DependencyResolver.CanResolve(parameterInfo.Name, parameterInfo.ParameterType, componentInfo))
                    {
                        missingComponents.Append(parameterInfo.ParameterType.Name + "; ");
                        proposeNewConstructor = false;
                        break;
                    }
                }

                if (proposeNewConstructor)
                {
                    selectedCtor = constructorInfo;
                }
            }

            if (selectedCtor == null)
            {
                throw new CompactContainerException("Cannot infer constructor to instantiate " + componentInfo.Classtype.Name +
                                                    " - missing components: " + missingComponents);
            }

            return selectedCtor;
        }
Ejemplo n.º 43
0
	private void PreviewWeaponParts(ComponentInfo cInfo) {
		Weapon w = weapon.GetComponent<Weapon>();
		foreach (KeyValuePair<string, List<ComponentInfo>> tList in cInfo.attachable) {
			WeaponPart part = w.FindPartByType(tList.Key);
			if (part == null) {
				if (tList.Value.Count > 0) {
					tList.Value[0].Instance.GetComponent<WeaponPart>().JointTo(
						cInfo.Instance.GetComponent<WeaponComponent>());
					tList.Value[0].Instance.transform.parent = preview;
				}
			} else {
				ComponentInfo componentInfo = new ComponentInfo();
				if (FindComponentInfo(part.gameObject, partInfo, ref componentInfo))
					PreviewWeaponParts(componentInfo);
			}
		}
	}
 public object Resolve(string key, Type type, ComponentInfo componentContext)
 {
     return container.Resolve(type);
 }
Ejemplo n.º 45
0
	public bool FindComponentInfo(GameObject gameObj, List<ComponentInfo> cList, ref ComponentInfo cInfo) {
		if (cList.Exists(c => c.Instance.Equals(gameObj))) {
			cInfo = cList.Find(c => c.Instance.Equals(gameObj));
			return true;
		} else {
			cInfo = new ComponentInfo();
			return false;
		}
	}
Ejemplo n.º 46
0
	public bool FindComponentInfo(string objId, List<ComponentInfo> cList, ref ComponentInfo cInfo) {
		if (cList.Exists(c => c.id == objId)) {
			cInfo = cList.Find(c => c.id == objId);
			return true;
		} else {
			cInfo = new ComponentInfo();
			return false;
		}
	}
 public bool CanResolve(string key, Type type, ComponentInfo componentContext)
 {
     return container.HasComponent(type);
 }
Ejemplo n.º 48
0
        public static bool FindRandomCollectableItemInPlaceArea(long entityId, HashSet<MyDefinitionId> itemDefinitions, out ComponentInfo result)
        {
            result = default(ComponentInfo);
            result.IsBlock = true;

            MyPlaceArea area = MyPlaceArea.FromEntity(entityId);
            if (area == null) return false;

            var areaBoundingBox = area.WorldAABB;
            List<MyEntity> entities = null;
            try
            {
                entities = MyEntities.GetEntitiesInAABB(ref areaBoundingBox);

                for (int i = entities.Count - 1; i >= 0; i--)
                {
                    var entity = entities[i];

                    if (MyManipulationTool.IsEntityManipulated(entity))
                    {
                        entities.RemoveAtFast(i);
                        continue;
                    }

                    var cubeGrid = entity as MyCubeGrid;
                    var fo = entity as MyFloatingObject;
                    if (fo == null && (cubeGrid == null || cubeGrid.BlocksCount != 1))
                    {
                        entities.RemoveAtFast(i);
                        continue;
                    }

                    if (cubeGrid != null)
                    {
                        MySlimBlock first = cubeGrid.CubeBlocks.First();
                        if (!itemDefinitions.Contains(first.BlockDefinition.Id))
                        {
                            entities.RemoveAtFast(i);
                            continue;
                        }
                    }
                    else if (fo != null)
                    {
                        var id = fo.Item.Content.GetId();
                        if (!itemDefinitions.Contains(id))
                        {
                            entities.RemoveAtFast(i);
                            continue;
                        }
                    }
                }

                if (entities.Count() == 0)
                    return false;

                int randIdx = (int)Math.Round(MyRandom.Instance.NextFloat() * (entities.Count() - 1));
                var selectedEntity = entities[randIdx];
                result.EntityId = selectedEntity.EntityId;

                if (selectedEntity is MyCubeGrid)
                {
                    var selectedCube = selectedEntity as MyCubeGrid;
                    var first = selectedCube.GetBlocks().First();

                    result.EntityId = selectedCube.EntityId;
                    result.BlockPosition = first.Position;
                    result.ComponentDefinitionId = GetComponentId(first);
                    result.IsBlock = true;
                }
                else
                {
                    result.IsBlock = false;
                }

                return true;
            }
            finally
            {
                entities.Clear();
            }
        }
Ejemplo n.º 49
0
	//从<Object>节点中读取装配信息
	private void ReadAssemblyInfo(XmlNode obj, ref ComponentInfo cInfo) {
		foreach (XmlNode aType in obj.ChildNodes) {
			List<ComponentInfo> attachableList = new List<ComponentInfo>();
			foreach (XmlNode aObj in aType) {
				ComponentInfo componentInfo = new ComponentInfo();
				if (FindComponentInfo(aObj.Attributes["id"].Value, partInfo, ref componentInfo))
					attachableList.Add(componentInfo);
			}
			cInfo.attachable.Add(aType.Attributes["type"].Value, attachableList);
		}
	}
Ejemplo n.º 50
0
	public bool FindAttachablesByType(ComponentInfo cInfo, string type, ref List<ComponentInfo> cInfoList) {
		return cInfo.attachable.TryGetValue(type, out cInfoList);
	}
Ejemplo n.º 51
0
        public static List<ComponentInfo> FindComponentsInRadius(Vector3D fromPosition, double radius)
        {
            Debug.Assert(m_retvalBlockInfos.Count == 0, "The result of the last call of FindComponentsInRadius was not cleared!");

            BoundingSphereD sphere = new BoundingSphereD(fromPosition, radius);

            var entities = MyEntities.GetEntitiesInSphere(ref sphere);
            foreach (var entity in entities)
            {
                if (entity is MyFloatingObject)
                {
                    var floatingObject = entity as MyFloatingObject;
                    if (floatingObject.Item.Content is MyObjectBuilder_Component)
                    {
                        ComponentInfo info = new ComponentInfo();
                        info.EntityId = floatingObject.EntityId;
                        info.BlockPosition = Vector3I.Zero;
                        info.ComponentDefinitionId = floatingObject.Item.Content.GetObjectId();
                        info.IsBlock = false;
                        info.ComponentCount = (int)floatingObject.Item.Amount;
                        m_retvalBlockInfos.Add(info);
                    }
                }
                else
                {
                    MyCubeBlock block = null;
                    MyCubeGrid grid = TryGetAsComponent(entity, out block);
                    if (grid == null) continue;

                    ComponentInfo info = new ComponentInfo();
                    info.IsBlock = true;
                    info.EntityId = grid.EntityId;
                    info.BlockPosition = block.Position;
                    info.ComponentDefinitionId = GetComponentId(block.SlimBlock);

                    if (block.BlockDefinition.Components != null)
                        info.ComponentCount = block.BlockDefinition.Components[0].Count;
                    else
                    {
                        Debug.Assert(false, "Block definition does not have any components!");
                        info.ComponentCount = 0;
                    }
                    m_retvalBlockInfos.Add(info);
                }               
            }

			entities.Clear();

            return m_retvalBlockInfos;
        }
Ejemplo n.º 52
0
	public void PreviewWeaponComponents() {
		//清理之前残余的Preview
		ClearPreviews();
		//新的Preview
		Weapon w = weapon.GetComponent<Weapon>();
		if (w == null) {
			if (bodyInfo.Count > 0) {
				bodyInfo[0].Instance.transform.position = bodyAnchor.position;
				bodyInfo[0].Instance.transform.rotation = bodyAnchor.rotation;
				bodyInfo[0].Instance.transform.parent = preview;
			}
		} else {
			ComponentInfo componentInfo = new ComponentInfo();
			if (FindComponentInfo(w.Body.gameObject, bodyInfo, ref componentInfo))
				PreviewWeaponParts(componentInfo);
		}
	}
Ejemplo n.º 53
0
	//从<Object>节点中读取组件信息
	private void ReadComponentInfo(XmlNode obj, ref ComponentInfo cInfo) {
		cInfo = new ComponentInfo();
		cInfo.id = obj.Attributes["id"].Value;
		if (obj.Attributes["category"] != null) 
			cInfo.category = obj.Attributes["category"].Value;
		foreach (XmlNode info in obj.ChildNodes) {
			switch (info.Name) {
			case "name" :
				cInfo.name = info.InnerText;
				break;
			case "parameter" :
				foreach (XmlNode param in info.ChildNodes)
					cInfo.parameters.Add(param.Attributes["name"].Value, param.InnerText);
				break;
			case "description" :
				cInfo.description = info.InnerText;
				break;
			}
		}
	}
Ejemplo n.º 54
0
	private void InitializeNullComponent() {
		NullComponent = new ComponentInfo();
		NullComponent.id = "NullCube";
		NullComponent.name = "Null Component";
		NullComponent.parameters.Add("Paremeter", "Null");
		NullComponent.description = "Null component is the component you choose when you decide not to select for this component type.";
	}
 static void generates(ComponentInfo componentInfo, string lookupName, string lookupCode)
 {
     generates(new [] { componentInfo }, lookupName, lookupCode);
 }
 static void generates(ComponentInfo[] componentInfos, string lookupName, string lookupCode)
 {
     generates(componentInfos, new [] { lookupName }, new [] { lookupCode });
 }
Ejemplo n.º 57
0
        public static bool FindCollectableItemInRadius(Vector3D position, float radius, HashSet<MyDefinitionId> itemDefs, Vector3D initialPosition, float ignoreRadius, out ComponentInfo result)
        {
            BoundingSphereD sphere = new BoundingSphereD(position, radius);
            var entities = MyEntities.GetEntitiesInSphere(ref sphere);

            result = default(ComponentInfo);

            double closestCubeDistanceSq = double.MaxValue;

            foreach (var entity in entities)
            {
                if (MyManipulationTool.IsEntityManipulated(entity))
                    continue;

                if (entity is MyCubeGrid) // TODO: Add logs and timbers
                {
                    var cubeGrid = entity as MyCubeGrid;
                    if (cubeGrid.BlocksCount == 1)
                    {
                        var first = cubeGrid.CubeBlocks.First();
                        if (itemDefs.Contains(first.BlockDefinition.Id))
                        {
                            var worldPosition = cubeGrid.GridIntegerToWorld(first.Position);
                            var cubeDistanceFromSpawnSq = Vector3D.DistanceSquared(worldPosition, initialPosition);
                            if (cubeDistanceFromSpawnSq <= ignoreRadius * ignoreRadius)
                                continue;
                            var cubeDistanceFromCharacterSq = Vector3D.DistanceSquared(worldPosition, position);
                            if (cubeDistanceFromCharacterSq < closestCubeDistanceSq)
                            {
                                closestCubeDistanceSq = cubeDistanceFromCharacterSq;
                                result.EntityId = cubeGrid.EntityId;
                                result.BlockPosition = first.Position;
                                result.ComponentDefinitionId = GetComponentId(first);
                                result.IsBlock = true;
                            }
                        }
                    }
                }

                if (entity is MyFloatingObject)
                {
                    var fo = entity as MyFloatingObject;
                    var id = fo.Item.Content.GetId();
                    if (itemDefs.Contains(id))
                    {
                        var foToPlayerDistSq = Vector3D.DistanceSquared(fo.PositionComp.WorldMatrix.Translation, position);
                        if (foToPlayerDistSq < closestCubeDistanceSq)
                        {
                            closestCubeDistanceSq = foToPlayerDistSq;
                            result.EntityId = fo.EntityId;
                            result.IsBlock = false;
                        }
                    }
                }
            }
            entities.Clear();

            return closestCubeDistanceSq != double.MaxValue;
        }
Ejemplo n.º 58
0
        public static bool FindClosestCollectableItemInPlaceArea(Vector3D fromPosition, long entityId, HashSet<MyDefinitionId> itemDefinitions, out ComponentInfo result)
        {
            List<MyEntity> entities = null;
            result = default(ComponentInfo);

            try
            {
                MyEntity containingEntity = null;
                MyPlaceArea area = null;

                if (!MyEntities.TryGetEntityById(entityId, out containingEntity))
                    return false;
                if (!containingEntity.Components.TryGet<MyPlaceArea>(out area))
                    return false;

                var areaBoundingBox = area.WorldAABB;
                entities = MyEntities.GetEntitiesInAABB(ref areaBoundingBox);

                MyEntity closestObject = null;
                MySlimBlock first = null;
                double closestObjectDistanceSq = double.MaxValue;
                bool closestIsBlock = false;

                foreach (var entity in entities)
                {
                    if (MyManipulationTool.IsEntityManipulated(entity))
                        continue;

                    if (entity is MyCubeGrid)
                    {
                        var cubeGrid = entity as MyCubeGrid;
                        if (cubeGrid.BlocksCount == 1)
                        {
                            first = cubeGrid.CubeBlocks.First();
                            if (itemDefinitions.Contains(first.BlockDefinition.Id))
                            {
                                var worldPosition = cubeGrid.GridIntegerToWorld(first.Position);
                                var cubeDistanceFromCharacterSq = Vector3D.DistanceSquared(worldPosition, fromPosition);

                                if (cubeDistanceFromCharacterSq < closestObjectDistanceSq)
                                {
                                    closestObjectDistanceSq = cubeDistanceFromCharacterSq;
                                    closestObject = cubeGrid;
                                    closestIsBlock = true;
                                }
                            }
                        }
                    }

                    if (entity is MyFloatingObject)
                    {
                        var fo = entity as MyFloatingObject;
                        var id = fo.Item.Content.GetId();
                        if (itemDefinitions.Contains(id))
                        {
                            var foToPlayerDistSq = Vector3D.DistanceSquared(fo.PositionComp.WorldMatrix.Translation, fromPosition);
                            if (foToPlayerDistSq < closestObjectDistanceSq)
                            {
                                closestObjectDistanceSq = foToPlayerDistSq;
                                closestObject = fo;
                                closestIsBlock = false;
                            }
                        }
                    }
                }

                if (closestObject == null)
                    return false;

                result.IsBlock = closestIsBlock;
                result.EntityId = closestObject.EntityId;
                if (closestIsBlock)
                {
                    result.BlockPosition = first.Position;
                    result.ComponentDefinitionId = GetComponentId(first);
                }

                return true;
            }
            finally
            {
                if (entities != null)
                {
                    entities.Clear();
                }
            }
        }
Ejemplo n.º 59
0
	private void LoadXML() {
		XmlDocument xmlFile = new XmlDocument();
		xmlFile.LoadXml(assemblyInfo.text);
		//读取<Component>节点
		XmlNodeList componentList = xmlFile.GetElementsByTagName("component")[0].ChildNodes;
		foreach (XmlNode component in componentList) {
			XmlNodeList objectList = component.ChildNodes;
			foreach (XmlNode obj in objectList) {
				ComponentInfo componentInfo = new ComponentInfo();
				ReadComponentInfo(obj, ref componentInfo);
				switch (component.Name) {
				case "body" :
					bodyInfo.Add(componentInfo);
					break;
				case "part" :
					partInfo.Add(componentInfo);
					break;
				}
			}
		}
		//读取<Assembly>节点
		XmlNodeList assemblyList = xmlFile.GetElementsByTagName("assembly")[0].ChildNodes;
		foreach (XmlNode obj in assemblyList) {
			ComponentInfo componentInfo = new ComponentInfo();
			if (FindComponentInfo(obj.Attributes["id"].Value, bodyInfo, ref componentInfo))
				ReadAssemblyInfo(obj, ref componentInfo);
			else if (FindComponentInfo(obj.Attributes["id"].Value, partInfo, ref componentInfo))
				ReadAssemblyInfo(obj, ref componentInfo);
		}
	}
Ejemplo n.º 60
0
        public static void Initialize()
        {
            Debug.Log("RA3Injection::Plugin Initialized\n");

            ComponentInfoList.CreateFromFileOrResource(Application.dataPath + "/Components.json", "Databases/Components");

            GameObject go = (GameObject)UnityEngine.Object.Instantiate(Resources.Load("ComponentPrefabs/CompSawBlade60"));
            TweakHelpers.LogTransform(go.transform, "");

            string jsonString = System.IO.File.ReadAllText(@"D:\components.json");
            System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
            JsonData jsonData = JsonMapper.ToObject(jsonString);
            Debug.Log(jsonString);

            ComponentInfo[] items = new ComponentInfo[jsonData.Count];
            for (int i = 0; i < jsonData.Count; i++)
            {
                int mSubCategory = -1;
                int mCategory = -1;
                items[i] = new ComponentInfo();
                jsonData[i].Read("active", ref items[i].mActive);
                jsonData[i].Read("displaymass", ref items[i].mDisplayMass);
                jsonData[i].Read("name", ref items[i].mName);
                jsonData[i].Read("description", ref items[i].mDescription);
                jsonData[i].Read("thumbnail", ref items[i].mThumbnailName);
                jsonData[i].Read("componentprefabname", ref items[i].mPrefabName);
                jsonData[i].Read("attchassis", ref items[i].mAttChassis);
                jsonData[i].Read("mirrorx", ref items[i].mMirrorX);
                jsonData[i].Read("mirrory", ref items[i].mMirrorY);
                jsonData[i].Read("mirrorz", ref items[i].mMirrorZ);
                jsonData[i].Read("mass", ref items[i].mMass);
                jsonData[i].Read("elecsupply", ref items[i].mElecSupply);
                jsonData[i].Read("elecdraw", ref items[i].mElecDraw);
                jsonData[i].Read("airsupply", ref items[i].mAirSupply);
                jsonData[i].Read("airdraw", ref items[i].mAirDraw);
                jsonData[i].Read("dpiblunt", ref items[i].mDpiBlunt);
                jsonData[i].Read("dpipierce", ref items[i].mDpiPierce);
                jsonData[i].Read("dpiflame", ref items[i].mDpiFlame);
                jsonData[i].Read("dpielec", ref items[i].mDpiElec);
                jsonData[i].Read("dpsblunt", ref items[i].mDpsBlunt);
                jsonData[i].Read("dpspierce", ref items[i].mDpsPierce);
                jsonData[i].Read("dpsflame", ref items[i].mDpsFlame);
                jsonData[i].Read("dpselec", ref items[i].mDpsElec);
                jsonData[i].Read("hpfactblunt", ref items[i].mHpFactBlunt);
                jsonData[i].Read("hpfactpierce", ref items[i].mHpFactPierce);
                jsonData[i].Read("hpfactflame", ref items[i].mHpFactFlame);
                jsonData[i].Read("hpfactelec", ref items[i].mHpFactElec);
                jsonData[i].Read("hitpoints", ref items[i].mHitPoints);
                jsonData[i].Read("uispecial", ref items[i].mUISpecial);
                jsonData[i].Read("attachsound", ref items[i].mAttachSound);
                jsonData[i].Read("spinupsound", ref items[i].mSpinUpSound);
                jsonData[i].Read("spinupvol", ref items[i].mSpinUpVol);
                jsonData[i].Read("spindownsound", ref items[i].mSpinDownSound);
                jsonData[i].Read("spindownvol", ref items[i].mSpinDownVol);
                jsonData[i].Read("loopsound", ref items[i].mLoopSound);
                jsonData[i].Read("looppitchmin", ref items[i].mLoopPitchMin);
                jsonData[i].Read("looppitchmax", ref items[i].mLoopPitchMax);
                jsonData[i].Read("loopvolmin", ref items[i].mLoopVolMin);
                jsonData[i].Read("loopvolmax", ref items[i].mLoopVolMax);
                jsonData[i].Read("active", ref items[i].mActive);
                jsonData[i].Read("category", ref mCategory);
                jsonData[i].Read("subcatagory", ref mSubCategory);
                jsonData[i].Read("displaymass", ref items[i].mDisplayMass);
                jsonData[i].Read("name", ref items[i].mName);
                jsonData[i].Read("description", ref items[i].mDescription);
                jsonData[i].Read("thumbnail", ref items[i].mThumbnailName);
                jsonData[i].Read("componentprefabname", ref items[i].mPrefabName);
                jsonData[i].Read("attchassis", ref items[i].mAttChassis);
                jsonData[i].Read("mirrorx", ref items[i].mMirrorX);
                jsonData[i].Read("mirrory", ref items[i].mMirrorY);
                jsonData[i].Read("mirrorz", ref items[i].mMirrorZ);
                jsonData[i].Read("mass", ref items[i].mMass);
                jsonData[i].Read("elecsupply", ref items[i].mElecSupply);
                jsonData[i].Read("elecdraw", ref items[i].mElecDraw);
                jsonData[i].Read("airsupply", ref items[i].mAirSupply);
                jsonData[i].Read("airdraw", ref items[i].mAirDraw);
                jsonData[i].Read("dpiblunt", ref items[i].mDpiBlunt);
                jsonData[i].Read("dpipierce", ref items[i].mDpiPierce);
                jsonData[i].Read("dpiflame", ref items[i].mDpiFlame);
                jsonData[i].Read("dpielec", ref items[i].mDpiElec);
                jsonData[i].Read("dpsblunt", ref items[i].mDpsBlunt);
                jsonData[i].Read("dpspierce", ref items[i].mDpsPierce);
                jsonData[i].Read("dpsflame", ref items[i].mDpsFlame);
                jsonData[i].Read("dpselec", ref items[i].mDpsElec);
                jsonData[i].Read("hpfactblunt", ref items[i].mHpFactBlunt);
                jsonData[i].Read("hpfactpierce", ref items[i].mHpFactPierce);
                jsonData[i].Read("hpfactflame", ref items[i].mHpFactFlame);
                jsonData[i].Read("hpfactelec", ref items[i].mHpFactElec);
                jsonData[i].Read("hitpoints", ref items[i].mHitPoints);
                jsonData[i].Read("uispecial", ref items[i].mUISpecial);
                jsonData[i].Read("attachsound", ref items[i].mAttachSound);
                jsonData[i].Read("spinupsound", ref items[i].mSpinUpSound);
                jsonData[i].Read("spinupvol", ref items[i].mSpinUpVol);
                jsonData[i].Read("spindownsound", ref items[i].mSpinDownSound);
                jsonData[i].Read("spindownvol", ref items[i].mSpinDownVol);
                jsonData[i].Read("loopsound", ref items[i].mLoopSound);
                jsonData[i].Read("looppitchmin", ref items[i].mLoopPitchMin);
                jsonData[i].Read("looppitchmax", ref items[i].mLoopPitchMax);
                jsonData[i].Read("loopvolmin", ref items[i].mLoopVolMin);
                jsonData[i].Read("loopvolmax", ref items[i].mLoopVolMax);
                items[i].mCategory = (ComponentInfo.CATEGORY)mCategory;
                items[i].mSubCategory = (ComponentInfo.CATEGORY)mSubCategory;
            }

            Type type = typeof(ComponentInfoList);
            FieldInfo info = type.GetField("_instance", BindingFlags.NonPublic | BindingFlags.Static);
            ComponentInfoList infoList = info.GetValue(null) as ComponentInfoList;
            Debug.Log(infoList);

            ComponentInfo[] oldItems = infoList.mItems;
            infoList.mItems = new ComponentInfo[oldItems.Length + items.Length];
            for (int i = 0; i < infoList.mItems.Length; i++)
            {
                if (i < oldItems.Length)
                {
                    infoList.mItems[i] = oldItems[i];
                }
                else
                {
                    infoList.mItems[i] = items[i - oldItems.Length];
                }
            }
        }