コード例 #1
0
 private void CreateTileNotification()
 {
     var text1 = new TextElement() { StringData = this.Group1Tbx.Text };
     var text2 = new TextElement() { StringData = this.Group2Tbx.Text };
     var defaultImgPath = "ms-appx:///Assets/Logo.png";
     var imgPath1 = this.Group1ImgTbx.Text;
     if (String.IsNullOrEmpty(imgPath1) || String.IsNullOrWhiteSpace(imgPath1))
         imgPath1 = defaultImgPath;
     var imgPath2 = this.Group2ImgTbx.Text;
     if (String.IsNullOrEmpty(imgPath2) || String.IsNullOrWhiteSpace(imgPath2))
         imgPath2 = defaultImgPath;
     var image1 = new ImageElement() { ImageSource = imgPath1, IsRemoveMargin = true };
     var image2 = new ImageElement() { ImageSource = imgPath2, IsRemoveMargin = true };
     var subgroup1 = new SubGroupElement() { weight = 1, ChildElements = new IChildElement[] { text1, image1 } };
     var subgroup2 = new SubGroupElement() { weight = 1, ChildElements = new IChildElement[] { text2, image2 } };
     var group1 = new GroupElement() { Subgroups = new SubGroupElement[] { subgroup1, subgroup2 } };
     var group2 = new GroupElement() { Subgroups = new SubGroupElement[] { subgroup1, subgroup2 } };
     var visual = new TileVisualElement()
     {
         version = 3,
         BindingElements = new TileBindingElement[]
         {
             new TileBindingElement() { TileTemplate = AdaptiveTileSizeEnum.TileWide, Group = group1 },
             new TileBindingElement() { TileTemplate = AdaptiveTileSizeEnum.TileMedium, Group = group2 }
         }
     };
     var tile = new TileElement() { visual = visual };
     var notification = new TileNotification(AdaptiveShellHelper.TrySerializeTileTemplateToXml(tile));
     TileUpdateManager.CreateTileUpdaterForApplication().Update(notification);
 }
コード例 #2
0
 /// <summary>
 /// Constructs a new parameter set.
 /// </summary>
 /// <param name="name">The name of set.</param>
 /// <param name="group">The group.</param>
 /// <param name="g">An array of group generators.</param>
 /// <param name="gd">The device generator.</param>
 internal ParameterSet(string name, Group group, GroupElement[] g, GroupElement gd)
 {
     this.Name = name;
     this.Group = group;
     this.G = g;
     this.Gd = gd;
 }
コード例 #3
0
ファイル: materials.cs プロジェクト: IgorGorbunov/SemToTemp
 /// <summary>
 /// Конструктор для записи данных о покупном инструменте в БД Темп2.
 /// </summary>
 /// <param name="name">Наименование</param>
 /// <param name="title">Обозначение</param>
 /// <param name="groupElement">Группа, в которую входит инструмент</param>
 /// <param name="parametrs">Параметры группы</param>
 /// <param name="doc">Обозначение документа без года</param>
 /// <param name="docYear">Год документа</param>
 public Materials(string name, string title, GroupElement groupElement, Dictionary<string, string> parametrs, string doc, string docYear)
     : base(name, title, groupElement, parametrs, doc, docYear)
 {
     AddSqlPosParam();
     Stype = ((int)ElementType.Material).ToString();
     Stool = ((int)ToolType.Gost).ToString();
     SvidOsn = "МО";
 }
コード例 #4
0
 public AnotherGroupDialog(Position pos, GroupElement oldGroup, GroupElement newGroup)
     : this()
 {
     lMessage.Text =
         string.Format(
             "Позиция \"{0}\" уже существует в справочнике. Она расположена в группе \"{1}\", хотя во входном файле позиция принадлежит группе \"{2}\". Перенести позицию в группу из входного файла?",
             pos.Title, oldGroup.Name, newGroup.Name);
 }
コード例 #5
0
 public AnotherGroupDialog(GroupElement groupElement)
     : this()
 {
     lMessage.Text =
         string.Format(
             "Группа \"{0}\" уже существует в справочнике. Параметры существуюзей группы отличаются от параметров из входного файла. Обновить параметры?",
             groupElement.Name);
 }
コード例 #6
0
 /// <summary>
 /// Конструктор для записи данных о покупном инструменте в БД Темп2.
 /// </summary>
 /// <param name="name">Наименование</param>
 /// <param name="title">Обозначение</param>
 /// <param name="groupElement">Группа, в которую входит инструмент</param>
 /// <param name="parametrs">Параметры группы</param>
 /// <param name="doc">Обозначение документа без года</param>
 /// <param name="docYear">Год документа</param>
 public AssembleInstrument(string name, string title, GroupElement groupElement, Dictionary<string, string> parametrs, string doc, string docYear)
     : base(name, title, groupElement, parametrs, doc, docYear)
 {
     AddSqlPosParam();
     Stype = ((int)ElementType.Tool).ToString();
     Stool = ((int)ToolType.Gost).ToString();
     SvidOsn = "СЛ";
 }
コード例 #7
0
 /// <summary>
 /// Конструктор для записи данных о покупном инструменте в БД Темп2.
 /// </summary>
 /// <param name="name">Наименование</param>
 /// <param name="title">Обозначение</param>
 /// <param name="groupElement">Группа, в которую входит инструмент</param>
 /// <param name="parametrs">Параметры группы</param>
 /// <param name="doc">Обозначение документа без года</param>
 /// <param name="docYear">Год документа</param>
 public BuyInstrument(string name, string title, GroupElement groupElement, Dictionary<string, string> parametrs, string doc, string docYear)
     : base(name, title, groupElement, parametrs, doc, docYear)
 {
     AddSqlPosParam();
     Stype = ((int)ElementType.Tool).ToString();
     Stool = ((int)ToolType.Gost).ToString();
     SvidOsn = GetEnumSql(EquipType.CuttingTool);
 }
コード例 #8
0
 /// <summary>
 /// Constructs a SubgroupGroup.
 /// </summary>
 /// <param name="p">The value p.</param>
 /// <param name="q">The value q.</param>
 /// <param name="g">The value g.</param>
 /// <param name="groupName">The known name of the group, or null.</param>
 /// <param name="domainParameterSeed">The domain parameter seed if the NIST generation 
 /// is used, or null.</param>
 internal SubgroupGroupBCImpl(
     byte[] p, 
     byte[] q, 
     byte[] g, 
     string groupName, 
     byte[] domainParameterSeed) : 
     base(q, groupName, domainParameterSeed)
 {
     P = p;
     this.gElement = CreateGroupElement(g);
 }
コード例 #9
0
        public void SMBadSetMembershipProofTest()
        {
            ProverSetMembershipParameters prover = new ProverSetMembershipParameters(_cryptoParameters);

            prover.setProverParameters(ValidDaysOfTheWeek[3], ValidDaysOfTheWeek);
            SetMembershipProof proof = new SetMembershipProof(prover);

            // verification fail because verifier parameters don't verify
            VerifierSetMembershipParameters verifier = new VerifierSetMembershipParameters(_cryptoParameters);

            Assert.IsFalse(proof.Verify(verifier), "proof should fail since verifier parameters fail.");

            // verification fail because verifier uses wrong length memberset
            FieldZqElement[] badMemberSet = new FieldZqElement[ValidDaysOfTheWeek.Length + 1];
            for (int i = 0; i < ValidDaysOfTheWeek.Length; ++i)
            {
                badMemberSet[i] = ValidDaysOfTheWeek[i];
            }
            badMemberSet[badMemberSet.Length - 1] = _cryptoParameters.FieldZq.One;
            verifier.setVerifierParameters(prover.ClosedCommitment, badMemberSet);
            Assert.IsFalse(proof.Verify(verifier), "should fail because memberset too long.");

            // verification should fail because memberset too short
            badMemberSet = new FieldZqElement[ValidDaysOfTheWeek.Length - 1];
            for (int i = 0; i < badMemberSet.Length; ++i)
            {
                badMemberSet[i] = ValidDaysOfTheWeek[i];
            }
            verifier.setVerifierParameters(prover.ClosedCommitment, badMemberSet);
            Assert.IsFalse(proof.Verify(verifier), "should fail because memberset too long.");

            // verification should fail because closed commitment is wrong
            verifier.setVerifierParameters(prover.G, prover.MemberSet);
            Assert.IsFalse(proof.Verify(verifier), "should fail because closed commitment is wrong.");

            // verification fail because generators are wrong
            GroupElement [] badGenerators = new GroupElement[2] {
                _cryptoParameters.H, _cryptoParameters.G
            };
            CryptoParameters badcrypto = new CryptoParameters(_cryptoParameters.Group, badGenerators, _cryptoParameters.HashFunctionName);

            verifier = new VerifierSetMembershipParameters(badcrypto);
            verifier.setVerifierParameters(prover.ClosedCommitment, prover.MemberSet);
            Assert.IsFalse(proof.Verify(verifier), "should fail because crypto parameters use wrong generators.");

            // verification fail because hash function is wrong
            badcrypto = new CryptoParameters(_cryptoParameters.Group, _cryptoParameters.Generators, "SHA-512");
            verifier  = new VerifierSetMembershipParameters(badcrypto);
            verifier.setVerifierParameters(prover.ClosedCommitment, prover.MemberSet);
            Assert.IsFalse(proof.Verify(verifier), "should fail because hash function is wrong.");
        }
コード例 #10
0
        public void TryStrictMultiplyWithExponentsTest()
        {
            bool success;

            DLRepOfGroupElement [] dlArray;
            FieldZqElement []      exponents;
            DLRepOfGroupElement    product;

            for (int paramIndex = 0; paramIndex < _parameters.Length; ++paramIndex)
            {
                dlArray = new DLRepOfGroupElement[128];
                GroupElement expectedProduct = _parameters[paramIndex].Group.Identity;
                for (int i = 0; i < dlArray.Length; ++i)
                {
                    exponents        = StaticHelperClass.GenerateRandomExponents(5, paramIndex);
                    dlArray[i]       = new DLRepOfGroupElement(exponents, _parameters[paramIndex]);
                    expectedProduct *= dlArray[i].Value;
                }

                DLRepOfGroupElement actualProduct;
                success = DLRepOfGroupElement.TryStrictMultiply(dlArray, out actualProduct);
                Assert.IsTrue(success, "TryStrictMultiply should have succeeded.");
                Assert.IsNotNull(actualProduct, "actualProduct should be set to a value.");
                Assert.IsTrue(actualProduct.AreBasesEqual(dlArray[0]), "Bases should be the same.");
                Assert.AreEqual(expectedProduct, actualProduct.Value, "Value computed incorrectly.");
            }

            // fail on null/ empty input
            DLRepOfGroupElement dl;

            success = DLRepOfGroupElement.TryStrictMultiply(null, out dl);
            Assert.IsFalse(success);

            DLRepOfGroupElement[] emptyArray = new DLRepOfGroupElement[0];
            success = DLRepOfGroupElement.TryStrictMultiply(emptyArray, out dl);
            Assert.IsFalse(success);

            // fail because bases are different
            dlArray = new DLRepOfGroupElement[5];
            GroupElement [] bases = StaticHelperClass.GenerateRandomBases(8, 5);
            for (int dlIndex = 0; dlIndex < dlArray.Length - 1; ++dlIndex)
            {
                exponents        = StaticHelperClass.GenerateRandomExponents(8, 5);
                dlArray[dlIndex] = new DLRepOfGroupElement(bases, exponents, _parameters[5].Group);
            }
            GroupElement [] badBases = StaticHelperClass.GenerateRandomBases(8, 5);
            exponents = StaticHelperClass.GenerateRandomExponents(8, 5);
            dlArray[dlArray.Length - 1] = new DLRepOfGroupElement(badBases, exponents, _parameters[5].Group);
            success = DLRepOfGroupElement.TryStrictMultiply(dlArray, out product);
            Assert.IsFalse(success, "should fail since one of the elements in dlArray has different bases.");
        }
コード例 #11
0
        /// <summary>
        /// For g find a: g * a = a * g  = e
        /// </summary>
        /// <param name="g"></param>
        /// <param name="G"></param>
        /// <returns></returns>
        public static GroupElement ReverseElement(GroupElement g, Group G)
        {
            GroupElement temp = new GroupElement(0, "1");

            foreach (var a in G.Elements)
            {
                if (a * g == neutral)
                {
                    temp = a;
                }
            }

            return(temp);
        }
コード例 #12
0
        public void ExponentiateTest()
        {
            for (int paramIndex = 0; paramIndex < _parameters.Length; ++paramIndex)
            {
                GroupElement[]            bases    = StaticHelperClass.GenerateRandomBases(8, paramIndex);
                FieldZqElement[]          exponent = StaticHelperClass.GenerateRandomExponents(1, paramIndex);
                GroupElement              value    = _parameters[paramIndex].Generators[0];
                ClosedDLRepOfGroupElement udl      = new ClosedDLRepOfGroupElement(bases, value, _parameters[paramIndex].Group);

                ClosedDLRepOfGroupElement actualUDL = udl.Exponentiate(exponent[0]);
                Assert.IsTrue(actualUDL.AreBasesEqual(udl), "bases should be the same.");
                Assert.AreEqual(udl.Value.Exponentiate(exponent[0]), actualUDL.Value, "Value computed incorrectly.");
            }
        }
コード例 #13
0
        /// <summary>
        /// Verifies a non-revocation proof.
        /// </summary>
        /// <param name="ip">The issuer parameters associated with the proof.</param>
        /// <param name="revocationCommitmentIndex">The 0-based index corresponding to the revocation commitment in the proof.</param>
        /// <param name="proof">The presentation proof.</param>
        /// <param name="nrProof">The non-revocation proof.</param>
        /// <exception cref="InvalidUProveArtifactException">Thrown if the proof is invalid.</exception>
        public void VerifyNonRevocationProof(IssuerParameters ip, int revocationCommitmentIndex, PresentationProof proof, NonRevocationProof nrProof)
        {
            Group        Gq       = ip.Gq;
            FieldZq      Zq       = Gq.FieldZq;
            GroupElement tildeCid = proof.Commitments[revocationCommitmentIndex].TildeC;
            // T1 = (V Y^-1 Cd^-1)^c' * X^s1 * (tildeCid K)^-s2 * g1^s3
            GroupElement T1 = Gq.MultiExponentiate(
                new GroupElement[] {
                Accumulator *nrProof.Y.Exponentiate(Zq.NegativeOne) * nrProof.Cd.Exponentiate(Zq.NegativeOne),      // TODO: is there a better way to calculate this
                nrProof.X,
                tildeCid * RAParameters.K,
                RAParameters.g1
            },
                new FieldZqElement[] {
                nrProof.cPrime,
                nrProof.s[0],          // s1
                nrProof.s[1].Negate(), // s2
                nrProof.s[2]           // s3
            });
            // T2 = tildeCid^c' g^s1 g1^s4
            GroupElement T2 = Gq.MultiExponentiate(
                new GroupElement[] {
                tildeCid,
                RAParameters.g,
                RAParameters.g1
            },
                new FieldZqElement[] {
                nrProof.cPrime,
                nrProof.s[0],     // s1
                nrProof.s[3],     // s4
            });
            // T3 = gt^c' Cd^s5 g1^s6
            GroupElement T3 = Gq.MultiExponentiate(
                new GroupElement[] {
                RAParameters.gt,
                nrProof.Cd,
                RAParameters.g1
            },
                new FieldZqElement[] {
                nrProof.cPrime,
                nrProof.s[4],     // s5
                nrProof.s[5],     // s6
            });

            if (!nrProof.cPrime.Equals(Zq.GetElementFromDigest(RAParameters.ComputeChallenge(tildeCid, nrProof.X, nrProof.Y, nrProof.Cd, T1, T2, T3))) ||
                !nrProof.Y.Equals(nrProof.X.Exponentiate(PrivateKey)))
            {
                throw new InvalidUProveArtifactException("Invalid non-revocation proof");
            }
        }
コード例 #14
0
        public void DefaultArrangeTest()
        {
            CodeArranger arranger = new CodeArranger(CodeConfiguration.Default);

            ReadOnlyCollection <ICodeElement> arranged = arranger.Arrange(_testElements);

            //
            // Verify using statements were grouped and sorted correctly
            //
            Assert.AreEqual(2, arranged.Count, "An unexpected number of root elements were returned from Arrange.");

            RegionElement regionElement = arranged[0] as RegionElement;

            Assert.IsNotNull(regionElement, "Expected a region element.");
            Assert.AreEqual("Header", regionElement.Name);

            //
            // Verify the namespace arrangement
            //
            NamespaceElement namespaceElement = arranged[1] as NamespaceElement;

            Assert.IsNotNull(namespaceElement, "Expected a namespace element.");
            Assert.IsTrue(namespaceElement.Children.Count > 0);

            GroupElement groupElement = namespaceElement.Children[0] as GroupElement;

            Assert.IsNotNull(groupElement, "Expected a group element.");
            Assert.AreEqual("Namespace", groupElement.Name, "Unexpected group name.");
            Assert.AreEqual(1, groupElement.Children.Count, "Group contains an unexpected number of child elements.");

            groupElement = groupElement.Children[0] as GroupElement;
            Assert.IsNotNull(groupElement, "Expected a group element.");
            Assert.AreEqual("System", groupElement.Name, "Unexpected group name.");
            Assert.AreEqual(8, groupElement.Children.Count, "Group contains an unexpected number of child elements.");

            string lastUsingName = null;

            foreach (CodeElement groupedElement in groupElement.Children)
            {
                UsingElement usingElement = groupedElement as UsingElement;
                Assert.IsNotNull(usingElement, "Expected a using element.");

                string usingName = usingElement.Name;
                if (lastUsingName != null)
                {
                    Assert.AreEqual(
                        -1, lastUsingName.CompareTo(usingName), "Expected using statements to be sorted by name.");
                }
            }
        }
コード例 #15
0
        public void InsertTest()
        {
            GroupBy groupBy = new GroupBy();

            groupBy.By = ElementAttributeType.Name;
            groupBy.AttributeCapture = "^(.*?)(\\.|$)";

            GroupedInserter groupedInserter = new GroupedInserter(groupBy);

            //
            // Create a parent element
            //
            GroupElement groupElement = new GroupElement();

            Assert.AreEqual(0, groupElement.Children.Count, "Parent element should not have any children.");

            //
            // With no criteria specified, elements should just be inserted
            // at the end of the collection.
            //
            UsingElement using1 = new UsingElement();

            using1.Name = "System.IO";
            groupedInserter.InsertElement(groupElement, using1);
            Assert.AreEqual(1, groupElement.Children.Count, "Group element was not inserted into the parent.");
            Assert.IsTrue(groupElement.Children[0] is GroupElement, "Group element was not inserted into the parent.");
            Assert.AreEqual(1, groupElement.Children[0].Children.Count, "Element was not inserted into the parent.");
            Assert.AreEqual(0, groupElement.Children[0].Children.IndexOf(using1), "Element was not inserted at the correct index.");

            UsingElement using2 = new UsingElement();

            using2.Name = "System";
            groupedInserter.InsertElement(groupElement, using2);
            Assert.AreEqual(1, groupElement.Children.Count, "Group element was not inserted into the parent.");
            Assert.IsTrue(groupElement.Children[0] is GroupElement, "Group element was not inserted into the parent.");
            Assert.AreEqual(2, groupElement.Children[0].Children.Count, "Element was not inserted into the parent.");
            Assert.AreEqual(0, groupElement.Children[0].Children.IndexOf(using1), "Element is not at the correct index.");
            Assert.AreEqual(1, groupElement.Children[0].Children.IndexOf(using2), "Element is not at the correct index.");

            UsingElement using3 = new UsingElement();

            using3.Name = "System.Text";
            groupedInserter.InsertElement(groupElement, using3);
            Assert.AreEqual(1, groupElement.Children.Count, "Group element was not inserted into the parent.");
            Assert.IsTrue(groupElement.Children[0] is GroupElement, "Group element was not inserted into the parent.");
            Assert.AreEqual(3, groupElement.Children[0].Children.Count, "Element was not inserted into the parent.");
            Assert.AreEqual(0, groupElement.Children[0].Children.IndexOf(using1), "Element is not at the correct index[0].Children.");
            Assert.AreEqual(1, groupElement.Children[0].Children.IndexOf(using2), "Element is not at the correct index.");
            Assert.AreEqual(2, groupElement.Children[0].Children.IndexOf(using3), "Element is not at the correct index.");
        }
コード例 #16
0
        public void ClosedPedConstructorTests()
        {
            GroupElement[]            badbases = StaticHelperClass.GenerateRandomBases(3, 0);
            GroupElement              value    = badbases[2];
            ClosedDLRepOfGroupElement baddl    = new ClosedDLRepOfGroupElement(badbases, value, _parameters[0].Group);
            bool threwException = false;

            try
            {
                ClosedPedersenCommitment ped = new ClosedPedersenCommitment(badbases, value, _parameters[0].Group);
            }
            catch (Exception)
            {
                threwException = true;
            }
            Assert.IsTrue(threwException, "ClosedPedersenCommitment constructor should throw Exception when length of bases is not 2");
            threwException = false;
            try
            {
                ClosedPedersenCommitment ped = new ClosedPedersenCommitment(baddl);
            }
            catch (Exception)
            {
                threwException = true;
            }


            badbases       = StaticHelperClass.GenerateRandomBases(1, 0);
            baddl          = new ClosedDLRepOfGroupElement(badbases, value, _parameters[0].Group);
            threwException = false;
            try
            {
                ClosedPedersenCommitment ped = new ClosedPedersenCommitment(badbases, value, _parameters[0].Group);
            }
            catch (Exception)
            {
                threwException = true;
            }
            Assert.IsTrue(threwException, "ClosedPedersenCommitment constructor should throw Exception when length of bases is 1.");
            threwException = false;
            try
            {
                ClosedPedersenCommitment ped = new ClosedPedersenCommitment(baddl);
            }
            catch (Exception)
            {
                threwException = true;
            }
            Assert.IsTrue(threwException, "ClosedPedersenCommitment constructor should throw Exception when length of bases is 1.");
        }
コード例 #17
0
        public void TransformationsDontRuinEquality()
        {
            var one     = new Scalar(1);
            var gej     = EC.G * one;
            var ge      = gej.ToGroupElement();
            var sameGej = ge.ToGroupElementJacobian();

            var a = new GroupElement(ge);
            var b = new GroupElement(gej);
            var c = new GroupElement(sameGej);

            Assert.Equal(a, b);
            Assert.Equal(a, c);
        }
コード例 #18
0
        /// <summary>
        /// Builds rule definition.
        /// </summary>
        /// <returns>Rule definition.</returns>
        public IRuleDefinition Build()
        {
            Validate();

            IBuilder <GroupElement> groupBuilder = _groupBuilder;
            GroupElement            conditions   = groupBuilder.Build();

            IBuilder <ActionGroupElement> actionBuilder = _actionGroupBuilder;
            ActionGroupElement            actions       = actionBuilder.Build();

            var ruleDefinition = new RuleDefinition(_name, _description, _tags, _priority, conditions, actions);

            return(ruleDefinition);
        }
コード例 #19
0
        /// <summary>
        /// Returns array of ClosedDLRepOfGroupElement objects, where output[i] = A[i] / B[i].
        /// If verifier.IntegerBIsKnown is true, replaces input B with default B.
        /// </summary>
        /// <param name="verifier">Used to get bases G and H. If verifier knows B, generates new array B.</param>
        /// <param name="A">Array of group elements.</param>
        /// <param name="B">Array of group elements of same length as A. May be null if verifier.IntegerBIsKnown is true.</param>
        /// <returns></returns>
        public static GroupElement[] ComputeClosedAdivB(VerifierRangeProofParameters verifier, GroupElement[] A, GroupElement[] B)
        {
            if (verifier.IntegerBIsKnown)
            {
                B = DefaultClosedDecompositionOfIntegerB(verifier);
            }

            GroupElement [] closedAdivB = new GroupElement[A.Length];
            for (int i = 0; i < closedAdivB.Length; ++i)
            {
                closedAdivB[i] = verifier.Group.Divide(A[i], B[i]);
            }
            return(closedAdivB);
        }
コード例 #20
0
ファイル: ECGroupBCImpl.cs プロジェクト: Eurodocs/p2abcengine
        private void CheckOnCurve(GroupElement e)
        {
            ECGroupElementBCImpl ecge = e as ECGroupElementBCImpl;

            if (ecge == null)
            {
                throw new ArgumentNullException();
            }

            if (!ecge.Point.Y.Square().Equals(ecge.Point.X.Multiply(ecge.Point.X.Square().Add(domainParams.Curve.A)).Add(domainParams.Curve.B)))
            {
                throw new InvalidUProveArtifactException("point is not on curve");
            }
        }
コード例 #21
0
        public PedersenCommitment(DLRepOfGroupElement dl)
        {
            if ((dl == null) || (dl.RepresentationLength != 2))
            {
                throw new ArgumentException("Cannot convert input into Pedersen Commitment");
            }

            GroupElement [] bases = new GroupElement[2] {
                dl.BaseAtIndex(0), dl.BaseAtIndex(1)
            };
            FieldZqElement[] exponents = new FieldZqElement[] { dl.ExponentAtIndex(0), dl.ExponentAtIndex(1) };
            this.Group = dl.Group;
            this.ComputeValue(bases, exponents);
        }
コード例 #22
0
        /// <summary>
        /// Bouncy castle implementation of multi-exponentiation.
        /// </summary>
        /// <param name="g">bases</param>
        /// <param name="f">exponents</param>
        /// <returns></returns>
        public override GroupElement MultiExponentiate(GroupElement[] g, FieldZqElement[] f)
        {
            if (g == null || f == null || g.Length != f.Length)
            {
                throw new ArgumentException("g and f must be non-null and of the same length");
            }
            GroupElement value = Identity;

            for (int i = 0; i < g.Length; i++)
            {
                value *= g[i].Exponentiate(f[i]);
            }
            return(value);
        }
コード例 #23
0
        /// <summary>
        /// Arranges the code elements according to the configuration supplied
        /// in the constructor.
        /// </summary>
        /// <param name="originalElements">Original elements</param>
        /// <returns>An arranged collection of code elements.</returns>
        public ReadOnlyCollection <ICodeElement> Arrange(ReadOnlyCollection <ICodeElement> originalElements)
        {
            GroupElement rootElement = new GroupElement();

            if (originalElements != null)
            {
                List <ICodeElement> elements       = new List <ICodeElement>();
                NamespaceElement    firstNamespace = null;
                for (int elementIndex = 0; elementIndex < originalElements.Count; elementIndex++)
                {
                    ICodeElement element      = originalElements[elementIndex];
                    ICodeElement elementClone = element.Clone() as ICodeElement;
                    elements.Add(elementClone);

                    if (firstNamespace == null)
                    {
                        Action <ICodeElement> findFirstNamespace = delegate(ICodeElement processElement)
                        {
                            if (firstNamespace == null)
                            {
                                NamespaceElement namespaceElement = processElement as NamespaceElement;
                                if (namespaceElement != null)
                                {
                                    firstNamespace = namespaceElement;
                                }
                            }
                        };

                        ElementUtilities.ProcessElementTree(elementClone, findFirstNamespace);
                    }
                }

                MoveUsings(elements, firstNamespace);

                foreach (ICodeElement element in elements)
                {
                    ArrangerChain.ArrangeElement(rootElement, element);
                }
            }

            List <ICodeElement> arranged = new List <ICodeElement>(rootElement.Children);

            foreach (ICodeElement arrangedElement in arranged)
            {
                // Remove the root element as the parent.
                arrangedElement.Parent = null;
            }

            return(arranged.AsReadOnly());
        }
コード例 #24
0
        public void AddWorldItem(WorldItemType item)
        {
            PlatformerEditor actualGame = (PlatformerEditor)UIManager.Game;
            GroupElement     group      = new GroupElement(UIManager, new Vector2(0, 0), new Vector2(128, 32), Layer + 0.01f, Name + "_" + item.Name);
            ButtonElement    itemButton = new ButtonElement(UIManager, new Vector2(0, 0), new Vector2(96, 32), Layer + 0.01f, group.Name + "_button", item.Name);

            itemButton.Click = () =>
            {
                actualGame.CurrentWorldItemType = item;
            };
            group.Elements.Add(itemButton);
            WorldItemTypes.Add(item);
            AddItem(group);
        }
コード例 #25
0
        public void UnknownDLRepConstructorTest()
        {
            for (int i = 0; i < _parameters.Length; ++i)
            {
                FieldZqElement committedValue = _parameters[i].FieldZq.GetRandomElement(true);
                GroupElement   g = _parameters[i].G;
                GroupElement   h = _parameters[i].H;

                PedersenCommitment pedCom = new PedersenCommitment(committedValue, _parameters[i]);
                IStatement         udl    = pedCom.GetStatement();
                Assert.IsFalse(pedCom.Equals(udl), "pedCom does not equal udl due to class hierarchy");
                Assert.IsTrue(PedersenCommitment.IsValidOpenClosedPair(pedCom, udl), "should be valid open closed pair.");
            }
        }
コード例 #26
0
        private ZenfolioTreeViewModel(GroupElement groupElement, ZenfolioTreeViewModel parent)
        {
            GroupElement = groupElement;
            Parent       = parent;

            if (groupElement is Group)
            {
                Children = (GroupElement as Group).Elements != null ? new ObservableCollection <ZenfolioTreeViewModel>(
                    (from child in (GroupElement as Group).Elements
                     select new ZenfolioTreeViewModel(child, this))
                    .ToList <ZenfolioTreeViewModel>())
                         : null;
            }
        }
コード例 #27
0
        /// <summary>
        /// Deserialize A and B. Finish deserialing Proof.
        /// </summary>
        public override void FinishDeserializing()
        {
            GroupElement[] AB = CryptoSerializer.DeserializeGroupElementArray(this._AB, 0, 2, "AB", this.Group);
            this.A = AB[0];
            this.B = AB[1];

            if (this.Proof != null)
            {
                this.Proof.FinishDeserializing(this.Group);
            }
            if (this.UPIProof != null)
            {
                this.UPIProof.FinishDeserializing(this.Group);
            }
        }
コード例 #28
0
        private void ItemGroupsChanged(object sender, RoutedEventArgs e)
        {
            bool isEnabled = false;

            GroupElement groupElement = ItemGroups.SelectedItem as GroupElement;

            if (groupElement != null)
            {
                ItemGroupElement selElm = groupElement.ElementBase as ItemGroupElement;
                isEnabled = (selElm != null);
            }

            DeleteItemGroupBtn.IsEnabled = isEnabled;
            AddItemBtn.IsEnabled         = isEnabled;
        }
コード例 #29
0
        /// <summary>
        /// Computes a commitment to this object - first element in EqualityProof Sigma protocol.
        /// </summary>
        /// <param name="randomData">Randomness for creating commitment.  Length of array should be equal to the RepresentationLength</param>
        /// <returns></returns>
        public override GroupElement ComputeCommitment(FieldZqElement[] randomData)
        {
            if ((randomData == null) || (randomData.Length != this.RepresentationLength))
            {
                throw new ArgumentException("First argument to ComputeCommitment should be an array of length " + this.RepresentationLength + ".");
            }

            GroupElement[] bases = new GroupElement[this.RepresentationLength];
            bases[0] = this.PublicKey;
            for (int i = 1; i < bases.Length; ++i)
            {
                bases[i] = this.G[i];
            }
            return(this.Group.MultiExponentiate(bases, randomData));
        }
コード例 #30
0
        private void TargetsChanged(object sender, RoutedEventArgs e)
        {
            bool isEnabled = false;

            GroupElement groupElement = Targets.SelectedItem as GroupElement;

            if (groupElement != null)
            {
                TargetElement selElm = groupElement.ElementBase as TargetElement;
                isEnabled = (selElm != null);
            }

            DeleteTargetBtn.IsEnabled = isEnabled;
            AddTaskBtn.IsEnabled      = isEnabled;
        }
コード例 #31
0
            public static Point operator +(Point p1, Point p2)
            {
                if (p1.IsZero)
                {
                    return(p2);
                }

                if (p2.IsZero)
                {
                    return(p1);
                }

                if (p1 == p2 && p1.Y != 0)
                {
                    long a, b;
                    long g = gcd(2 * p1.Y, Q, out a, out b);

                    GroupElement lambda = (3 * p1.X * p1.X + A) * a;
                    GroupElement x      = lambda * lambda - 2 * p1.X;
                    GroupElement y      = lambda * (p1.X - x) - p1.Y;

                    return(new Point(x, y));
                }
                if (p1.X != p2.X)
                {
                    GroupElement dy = p2.Y - p1.Y;
                    GroupElement dx = p2.X - p1.X;

                    long a, b;
                    long g = gcd(dx, Q, out a, out b);

                    if (g != 1)
                    {
                        Console.WriteLine("Не существует!");
                    }

                    GroupElement lambda = dy * a;
                    GroupElement x      = lambda * lambda - p1.X - p2.X;
                    GroupElement y      = lambda * (p1.X - x) - p1.Y;

                    return(new Point(x, y));
                }
                if (p1.X == p2.X && p2.Y == -(p1.Y))
                {
                    return(new Point(0, 0));
                }
                return(new Point(0, 0));
            }
コード例 #32
0
        /// <summary>
        /// Get group default data by group name
        /// </summary>
        /// <param name="groupName">group name</param>
        /// <returns>group data without servers info</returns>
        public GroupElement getGroupDefaultInfo(string groupName)
        {
            XmlDocument xmlDocument = new XmlDocument();

            xmlDocument.Load(Settings.Default.cfgpath);

            string groupDefaultHostname = "";
            string groupDefaultPort     = "";
            string groupDefaultUsername = "";
            string groupDefaultPassword = "";

            XmlNodeList groupNodes = xmlDocument.SelectNodes("//*[@GroupName='" + groupName + "']");

            if (groupNodes != null)
            {
                if (groupNodes.Count > 0)
                {
                    foreach (XmlElement groupNode in groupNodes[0].ChildNodes)
                    {
                        switch (groupNode.Name)
                        {
                        case "DefaultHost":
                            groupDefaultHostname = CryptHelper.Decrypt(groupNode.InnerText);
                            break;

                        case "DefaultPort":
                            groupDefaultPort = CryptHelper.Decrypt(groupNode.InnerText);
                            break;

                        case "DefaultUsername":
                            groupDefaultUsername = CryptHelper.Decrypt(groupNode.InnerText);
                            break;

                        case "DefaultPassword":
                            groupDefaultPassword = CryptHelper.Decrypt(groupNode.InnerText);
                            break;
                        }
                    }
                }
                else
                {
                    return(null);
                }
            }
            var groupsElement = new GroupElement(groupName, groupDefaultHostname, groupDefaultPort, groupDefaultUsername, groupDefaultPassword, null);

            return(groupsElement);
        }
コード例 #33
0
        public void NullEquality()
        {
            var one = new Scalar(1);
            var ge  = new GroupElement(EC.G) * one;

            // Kinda clunky, but otherwise CodeFactor won't be happy.
            GroupElement?n = null;

            Assert.False(ge == n);
            Assert.True(ge != n);

            Assert.False(n == ge);
            Assert.True(n != ge);

            Assert.False(ge.Equals(n));
        }
コード例 #34
0
ファイル: Position.cs プロジェクト: IgorGorbunov/SemToTemp
 protected Position(string name, string title, GroupElement groupElement, Dictionary<string, string> parametrs, string doc, string docYear)
 {
     _name = name;
     Title = title;
     if (parametrs == null)
     {
         _parametrs = new Dictionary<string, string>();
     }
     else
     {
         _parametrs = parametrs;
     }
     _groupElement = groupElement;
     _doc = doc;
     _docYear = docYear;
 }
コード例 #35
0
        /// <summary>
        /// Verifies that the response to the Sigma protocol, given the commitment and challenge.
        /// </summary>
        /// <param name="commitment">Commitment generated during ComputeCommitment</param>
        /// <param name="challenge">Random challenge</param>
        /// <param name="response">Response generated by ComputeResponse</param>
        /// <returns></returns>
        public override bool Verify(GroupElement commitment, FieldZqElement challenge, FieldZqElement[] response)
        {
            GroupElement[]   vBases     = new GroupElement[this.RepresentationLength + 1];
            FieldZqElement[] vExponents = new FieldZqElement[this.RepresentationLength + 1];
            for (int i = 0; i < this.RepresentationLength; ++i)
            {
                vBases[i]     = this.Bases[i];
                vExponents[i] = response[i];
            }
            vBases[this.RepresentationLength]     = this.Value;
            vExponents[this.RepresentationLength] = challenge;

            GroupElement rightSide = this.Group.MultiExponentiate(vBases, vExponents);

            return(commitment == rightSide);
        }
コード例 #36
0
        /// <summary>
        ///  Checks that <c>sk</c> is consistent with this public key and <c>param</c>.
        /// </summary>
        /// <returns><c>true</c> if valid, <c>false</c> otherwise.</returns>
        public bool Verify(IDEscrowParams param, IDEscrowPrivateKey sk)
        {
            if (!param.ip.Zq.IsElement(sk.X))  // is x in the right field?
            {
                return(false);
            }

            GroupElement hPrime = param.Ge.Exponentiate(sk.X);

            if (!hPrime.Equals(h))                      // is h = ge^x ?
            {
                return(false);
            }

            return(true);
        }
コード例 #37
0
 /// <summary>
 /// Sets verifier parameters.
 /// </summary>
 /// <param name="closedCommittedBits">Array of Pedersen Commitments to a sequence of bits.</param>
 /// <param name="closedCommitment">Value of Pedersen Commitment.</param>
 public void setVerifierParameters(GroupElement [] closedCommittedBits, GroupElement closedCommitment)
 {
     if ((closedCommittedBits == null) ||
         (closedCommitment == null))
     {
         base.setVerifierParameters(null);
         return;
     }
     GroupElement[] publicValues = new GroupElement[closedCommittedBits.Length + 1];
     for (int i = 0; i < closedCommittedBits.Length; ++i)
     {
         publicValues[i] = closedCommittedBits[i];
     }
     publicValues[publicValues.Length - 1] = closedCommitment;
     this.setVerifierParameters(publicValues);
 }
コード例 #38
0
ファイル: FilterWindow.cs プロジェクト: vault51/Graphics
        void ListGUI(Element[] tree, float anim, GroupElement parent, GroupElement grandParent)
        {
            // Smooth the fractional part of the anim value
            anim = Mathf.Floor(anim) + Mathf.SmoothStep(0, 1, Mathf.Repeat(anim, 1));

            // Calculate rect for animated area
            var animRect = position;

            animRect.x       = position.width * (1 - anim) + 1;
            animRect.y       = k_HeaderHeight;
            animRect.height -= k_HeaderHeight + k_HelpHeight;
            animRect.width  -= 2;

            // Start of animated area (the part that moves left and right)
            GUILayout.BeginArea(animRect);

            // Header
            var    headerRect = GUILayoutUtility.GetRect(10, 25);
            string name       = parent.name;

            GUI.Label(headerRect, name, s_Styles.header);

            // Back button
            if (grandParent != null)
            {
                var arrowRect = new Rect(headerRect.x + 4, headerRect.y + 7, 13, 13);
                var e         = Event.current;

                if (e.type == EventType.Repaint)
                {
                    s_Styles.leftArrow.Draw(arrowRect, false, false, false, false);
                }

                if (e.type == EventType.MouseDown && headerRect.Contains(e.mousePosition))
                {
                    GoToParent();
                    e.Use();
                }
            }

            if (!parent.OnGUI(s_FilterWindow))
            {
                ListGUI(tree, parent);
            }

            GUILayout.EndArea();
        }
コード例 #39
0
        private void HandleKeyboard()
        {
            Event current = Event.current;

            if (current.type == EventType.KeyDown)
            {
                if (current.keyCode == KeyCode.DownArrow)
                {
                    activeParent.selectedIndex++;
                    activeParent.selectedIndex = Mathf.Min(activeParent.selectedIndex,
                                                           GetChildren(activeTree, activeParent).Count - 1);
                    scrollToSelected = true;
                    current.Use();
                }
                if (current.keyCode == KeyCode.UpArrow)
                {
                    GroupElement element2 = activeParent;
                    element2.selectedIndex--;
                    activeParent.selectedIndex = Mathf.Max(activeParent.selectedIndex, 0);
                    scrollToSelected           = true;
                    current.Use();
                }
                if (current.keyCode == KeyCode.Return || current.keyCode == KeyCode.KeypadEnter)
                {
                    GoToChild(activeElement, true);
                    current.Use();
                }
                if (!hasSearch)
                {
                    if (current.keyCode == KeyCode.LeftArrow || current.keyCode == KeyCode.Backspace)
                    {
                        GoToParent();
                        current.Use();
                    }
                    if (current.keyCode == KeyCode.RightArrow)
                    {
                        GoToChild(activeElement, false);
                        current.Use();
                    }
                    if (current.keyCode == KeyCode.Escape)
                    {
                        Close();
                        current.Use();
                    }
                }
            }
        }
コード例 #40
0
 /// <summary>
 /// Returns <code>this*a</code>.
 /// </summary>
 /// <param name="a">The operand.</param>
 /// <returns>A group element.</returns>
 public override GroupElement Multiply(GroupElement a)
 {
     return new ECGroupElementBCImpl(
         Point.Add( (a as ECGroupElementBCImpl).Point) as FpPoint );
 }
コード例 #41
0
        /// <summary>
        /// Verifies if e is a group element.
        /// </summary>
        /// <param name="e">The element to test.</param>
        /// <exception cref="InvalidUProveArtifactException">Thrown if i is not in the group.</exception>
        public override void ValidateGroupElement(GroupElement e)
        {
            if (domainParams.H != BCBigInt.One)
            {
                throw new NotImplementedException("only curves with a cofactor of 1 are supported");
            }

            CheckOnCurve(e);
        }
コード例 #42
0
        /// <summary>
        /// Constructs an ECCGroup.
        /// <param name="p">The p parameter, representing the prime field domain for the 
        /// x and y coordinate spaces.</param>
        /// <param name="a">The a parameter for the eliptic curve.</param>
        /// <param name="b">The b parameter for the eliptic curve.</param>
        /// <param name="g_x">The x coordinate of the generator point.</param>
        /// <param name="g_y">The y coordinate of the generator point.</param>
        /// <param name="n">The order of the group.</param>
        /// <param name="groupName">The known name of the group, or null.</param>
        /// <param name="curveName">The known name of the curve, or null.</param>
        /// </summary>
        public ECGroupBCImpl(
            byte[] p, 
            byte[] a, 
            byte[] b, 
            byte[] g_x, 
            byte[] g_y, 
            byte[] n, 
            string groupName, 
            string curveName)
            : base(p, a, b, g_x, g_y, n, groupName, curveName)
        {
            this.curve = new BouncyCastle.FpCurve(
                new BCBigInt(1, p), 
                new BCBigInt(1, a), 
                new BCBigInt(1, b));

            BouncyCastle.ECPoint generator = this.curve.CreatePoint(
                new BCBigInt(1, g_x), 
                new BCBigInt(1, g_y), 
                false);

            this.domainParams = new BouncyCastle.ECDomainParameters(
                                    this.curve,
                                    generator,
                                    new BCBigInt(1, n));

            this.g = new ECGroupElementBCImpl(
                this.domainParams.G as BouncyCastle.FpPoint);
        }
コード例 #43
0
 public override GroupElement Multiply(GroupElement a)
 {
     return new SubgroupGroupElementBCImpl(i * ((SubgroupGroupElementBCImpl)a).i % p, p);
 }
コード例 #44
0
ファイル: Processor.cs プロジェクト: IgorGorbunov/SemToTemp
    private static void ProcessOneRow2(ExcelClass xls, int iRow, ref string message, List<Position> positions, GroupElement group, string fileName, int posType)
    {
        string name = xls.GetCellStringValue(_nameColName, iRow);
        string title = xls.GetCellStringValue(_titleColName, iRow);
        if (string.IsNullOrEmpty(title))
        {
            message +=
                fileName + " - в " + iRow +
                " строке позиция без обозначения!" + Environment.NewLine;
            _userLog.WriteLine("*** Ошибка! *** " + message);
            _logger.WriteError(message);
            return;
        }

        string doc, year = "";
        if (_docColName == _yearColName)
        {
            doc = xls.GetCellStringValue(_docColName, iRow);
            string[] split = doc.Split('-');
            if (split.Length > 0)
            {
                doc = "";
                for (int i = 0; i < split.Length - 1; i++)
                {
                    doc += split[i];
                }
                year = split[split.Length - 1];
            }

        }
        else if (string.IsNullOrEmpty(_yearColName.Trim()))
        {
            doc = xls.GetCellStringValue(_docColName, iRow);
            year = "";
        }
        else
        {
            doc = xls.GetCellStringValue(_docColName, iRow);
            year = xls.GetCellStringValue(_yearColName, iRow);
        }

        Position pos = null;
        switch (posType)
        {
                case 2:
                    pos = new Materials(name, title, group,
                                                             GetPositionParams(xls, iRow),
                                                             doc,
                                                             year);
                break;
                case 1:
                    pos = new BuyInstrument(name, title, group,
                                                         GetPositionParams(xls, iRow),
                                                         doc,
                                                         year);
                    break;
                case 0:
                    pos = new Machine(name, title, group,
                                                         GetPositionParams(xls, iRow),
                                                         doc,
                                                         year);
                    break;
                case 3:
                    pos = new AssembleInstrument(name, title, group,
                                                         GetPositionParams(xls, iRow),
                                                         doc,
                                                         year);
                    break;
                case 4:
                    pos = new MeasureInstrument(name, title, group,
                                                         GetPositionParams(xls, iRow),
                                                         doc,
                                                         year);
                break;
        }

        positions.Add(pos);
    }
コード例 #45
0
ファイル: Processor.cs プロジェクト: IgorGorbunov/SemToTemp
    /// <summary>
    /// Обработка Excel документов
    /// </summary>
    /// <param name="nameColName"></param>
    /// <param name="titleColName"></param>
    /// <param name="docColName"></param>
    /// <param name="yearColName"></param>
    public static void SelectXlsFiles(string nameColName, string titleColName, string docColName, string yearColName, ProgressBar bar, int type, Label status, Label nFiles)
    {
        _nameColName = nameColName;
        _titleColName = titleColName;
        _docColName = docColName;
        _yearColName = yearColName;

        string mess = "";
        OpenFileDialog xlsBooks = new OpenFileDialog();
        xlsBooks.Title = "Выберите файлы Excel с позициями";
        xlsBooks.Multiselect = true;
        xlsBooks.DefaultExt = "xlsx";
        xlsBooks.Filter = "Файлы Excel (*.xls;*.xlsx)|*.xls;*.xlsx|All files (*.*)|*.*";
        if (xlsBooks.ShowDialog() != DialogResult.OK)
            return;

        _userLog = new StreamWriter(_USER_LOG_FULL_PATH, false, Encoding.UTF8);
        _userLog.WriteLine(DateTime.Now.ToLongTimeString());
        _userLog.WriteLine("Начало работы");
        _logger = new Logger();
        _logger.WriteLine("----------------------------------------- NEW SESSION ----------------------------------------------");

        ExcelClass xls = new ExcelClass();
        try
        {
            bool cancel = false;
            for (int i = 0; i < xlsBooks.FileNames.Length; i++)
            {
                status.Text = "Чтение файлов";
                nFiles.Text = i.ToString();
                Application.DoEvents();
                List<Position> instruments = new List<Position>();
                int iRow = _FIRST_ROW;
                GroupElement group;

                bool exist;
                bool groupExist = false;
                try
                {
                    xls.OpenDocument(xlsBooks.FileNames[i], false);
                    _userLog.WriteLine("Открыт файл " + xlsBooks.FileNames[i]);
                    _logger.WriteLine("Открыт файл " + xlsBooks.FileNames[i]);

                    string shortFileName = GetShortFileName(xlsBooks.FileNames[i]);
                    _logger.WriteLine("Короткое имя группы - " + shortFileName);

                    string fullName = xls.GetCellStringValue("A", 1);
                    _logger.WriteLine("Полный путь группы - " + fullName);

                    group = new GroupElement(shortFileName, GetGroupParams(xls), fullName);
                    int oldId;
                    exist = GroupElement.Exist(group.Name, out oldId);
                    if (exist)
                    {
                        group = new GroupElement(oldId, group.Name, group.FullName);
                        groupExist = true;
                        _userLog.WriteLine("Группа уже существует. Найдена группа \"" + group.Name + "\"");
                        _logger.WriteLine("Группа уже существует. Найдена группа \"" + group.Name + "\"");
                    }
                    while (!xls.CellIsNullOrVoid(_nameColName, iRow) ||
                           !xls.CellIsNullOrVoid(_titleColName, iRow) ||
                           !xls.CellIsNullOrVoid(_docColName, iRow))
                    {
                        ProcessOneRow2(xls, iRow, ref mess, instruments, group,
                                      shortFileName, type);

                        iRow++;
                    }
                }
                finally
                {
                    xls.CloseDocument();
                }
                if (instruments.Count > 0)
                {
                    if (!exist)
                    {
                        group.WriteToDb();
                        group.AddGeneralFolders(@"Справочники цеха 254\");
                        _userLog.WriteLine("Группа записана в БД");
                        _logger.WriteLine("Группа \"" + group.Name + "\" записана в БД");
                    }
                }
                bar.Maximum = instruments.Count;
                bar.Value = 0;
                status.Text = "Запись в БД";
                foreach (Position pos in instruments)
                {
                    int oldPosId;
                    if (Position.Exist(pos.Title, out oldPosId))
                    {
                        int dbGroupId = Position.GetGroupId(oldPosId);
                        if (group.Id != dbGroupId)
                        {
                            DialogResult result = MessageBox.Show("Позиция \"" + pos.Title + "\" уже существует и находится в другой группе (\"" + GroupElement.GetName(dbGroupId) + "\"). Перенести в группу из электронной таблицы (\"" + group.Name + "\") ?", "Внимание!", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                            switch (result)
                            {
                                case DialogResult.Cancel:
                                    cancel = true;
                                    goto Cancel;
                                case DialogResult.Yes:
                                    pos.SetNewGroup(oldPosId, group.Id);
                                break;
                            }
                        }
                        string message;
                        Dictionary<int, string> differentParams;
                        if (pos.IsSimilarPositionParams(oldPosId, out message, out differentParams))
                        {
                            _userLog.WriteLine(message);
                            _logger.WriteLine(message);
                            DialogResult result = MessageBox.Show(message + Environment.NewLine + "Обновить параметры?", "Внимание!", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                            switch (result)
                            {
                                case DialogResult.Cancel:
                                    cancel = true;
                                    goto Cancel;
                                case DialogResult.Yes:
                                    Position.EditParametrs(oldPosId, differentParams);
                                    break;
                            }
                        }
                    }
                    else
                    {
                        string message;
                        pos.IsSimilarGroupParams(group.GetParamCodes(), out message);
                        _userLog.WriteLine(message);
                        pos.WriteToDb2();
                    }
                    bar.Increment(1);
                    Application.DoEvents();
                }
                _userLog.WriteLine("Записано " + instruments.Count + " позиций");
                _userLog.Flush();
                _userLog.WriteLine();
                _logger.WriteLine("Записано " + instruments.Count + " позиций");

            }
        Cancel:
            if (cancel)
            {
                _userLog.WriteLine("***Операция отменена пользователем");
                _userLog.Flush();
                _userLog.WriteLine();
                _logger.WriteLine("***Операция отменена пользователем");
            }
        }
        finally
        {
            xls.Dispose();
            _userLog.Close();
        }
        Process.Start(_USER_LOG_FULL_PATH);
        MessageBox.Show("Готово!");
    }
コード例 #46
0
ファイル: MainForm.cs プロジェクト: danrichardson/ZenSync
        /// <summary>
        /// Creates a TreeNode representing Group element.
        /// </summary>
        /// <param name="element">Group element to wrap.</param>
        /// <returns>Constructed tree node.</returns>
        private TreeNode CreateGroupNode(
            GroupElement element
            )
        {
            TreeNode ret = new TreeNode(element.Title);
            ret.Tag = element;

            Group group = element as Group;
            PhotoSet photoSet = element as PhotoSet;

            if (group != null)
            {
                ret.ImageIndex = (int)NodeType.Group;
                foreach (GroupElement child in group.Elements)
                    ret.Nodes.Add(CreateGroupNode(child));
            }
            else if (photoSet != null)
            {
                ret.ImageIndex = photoSet.Type == PhotoSetType.Gallery
                                 ? (int)NodeType.Gallery
                                 : (int)NodeType.Collection;

                // photoSets contain photos which are not loaded yet; add
                // a dummy node for lazy expansion
                if (photoSet.PhotoCount > 0)
                    ret.Nodes.Add("_Dummy_");
            }

            ret.SelectedImageIndex = ret.ImageIndex;
            return ret;
        }
コード例 #47
0
 public ProductElement(GroupElement group, Product product)
 {
     Group = group;
         Product = product;
 }
コード例 #48
0
		private void ListGUI(Element[] tree, float anim, GroupElement parent, GroupElement grandParent) {
			anim = Mathf.Floor(anim) + Mathf.SmoothStep(0f, 1f, Mathf.Repeat(anim, 1f));
			Rect rectArea = position;
			rectArea.x = position.width * (1f - anim) + 1f;
			rectArea.y = useSearch ? 30f : 0;
			rectArea.height -= useSearch ? 30f : 0;
			rectArea.width -= 2f;
			GUILayout.BeginArea(rectArea);
			{
				var rectHeader = GUILayoutUtility.GetRect(10f, 25f);
				var nameHeader = parent.name;
				GUI.Label(rectHeader, nameHeader, styles.header);
				if (grandParent != null) {
					var rectHeaderBackArrow = new Rect(rectHeader.x + 4f, rectHeader.y + 7f, 13f, 13f);
					if (Event.current.type == EventType.Repaint)
						styles.leftArrow.Draw(rectHeaderBackArrow, false, false, false, false);
					if (Event.current.type == EventType.MouseDown && rectHeader.Contains(Event.current.mousePosition)) {
						GoToParent();
						Event.current.Use();
					}
				}
				ListGUI(tree, parent);
			}
			GUILayout.EndArea();
		}
コード例 #49
0
		private void ListGUI(Element[] tree, GroupElement parent) {
			parent.scroll = GUILayout.BeginScrollView(parent.scroll, new GUILayoutOption[0]);
			EditorGUIUtility.SetIconSize(new Vector2(16f, 16f));
			var children = GetChildren(tree, parent);
			var rect = new Rect();
			for (int i = 0; i < children.Count; i++) {
				var e = children[i];
				var options = new[] { GUILayout.ExpandWidth(true) };
				var rectElement = GUILayoutUtility.GetRect(16f, elementHeight, options);
				if ((Event.current.type == EventType.MouseMove || Event.current.type == EventType.MouseDown) 
					&& parent.selectedIndex != i && rectElement.Contains(Event.current.mousePosition)) {
					parent.selectedIndex = i;
					Repaint();
				}
				bool on = false;
				if (i == parent.selectedIndex) {
					on = true;
					rect = rectElement;
				}
				if (Event.current.type == EventType.Repaint) {
					(e.content.image != null ? styles.componentItem : styles.groupItem).Draw(rectElement, e.content, false, false, on, on);
					if (!(e is CallElement)) {
						var rectElementForwardArrow = new Rect(rectElement.x + rectElement.width - 13f, rectElement.y + 4f, 13f, 13f);
						styles.rightArrow.Draw(rectElementForwardArrow, false, false, false, false);
					}
				}
				if (Event.current.type == EventType.MouseDown && rectElement.Contains(Event.current.mousePosition)) {
					Event.current.Use();
					parent.selectedIndex = i;
					GoToChild(e, true);
				}
			}
			EditorGUIUtility.SetIconSize(Vector2.zero);
			GUILayout.EndScrollView();
			if (scrollToSelected && Event.current.type == EventType.Repaint) {
				scrollToSelected = false;
				var lastRect = GUILayoutUtility.GetLastRect();
				if ((rect.yMax - lastRect.height) > parent.scroll.y) {
					parent.scroll.y = rect.yMax - lastRect.height;
					Repaint();
				}
				if (rect.y < parent.scroll.y) {
					parent.scroll.y = rect.y;
					Repaint();
				}
			}
		}
コード例 #50
0
        private void CheckOnCurve(GroupElement e)
        {
            ECGroupElementBCImpl ecge = e as ECGroupElementBCImpl;
            if (ecge == null)
            {
                throw new ArgumentNullException();
            }

            if (!ecge.Point.Y.Square().Equals(ecge.Point.X.Multiply(ecge.Point.X.Square().Add(domainParams.Curve.A)).Add(domainParams.Curve.B)))
            {
                throw new InvalidUProveArtifactException("point is not on curve");
            }

        }
コード例 #51
0
        /// <summary>
        /// Verifies that e is an element of the group.
        /// </summary>
        /// <param name="e">The element to test.</param>
        /// <exception cref="InvalidUProveArtifactException">
        /// Thrown if i is not in the group.</exception>
        public override void ValidateGroupElement(GroupElement e)
        {
            SubgroupGroupElementBCImpl sge = e as SubgroupGroupElementBCImpl;
            if (sge == null)
            {
                throw new InvalidUProveArtifactException(
                    "Invalid group element (wrong construction)");
            }

            // verify that 1 < g < p
            if (sge.i <= BCBigInt.One || sge.i >= pValue)
            {
                throw new InvalidUProveArtifactException(
                    "Invalid group element (out of range)");
            }

            // verify that g^q mod p = 1
            BCBigInt modpow = sge.i.ModPow(qValue, pValue);
            if (sge.i.ModPow(qValue, pValue) != BCBigInt.One)
            {
                throw new InvalidUProveArtifactException(
                    "Invalid group element (i^Q mod P != 1)");
            }
        }
コード例 #52
0
 /// <summary>
 /// Bouncy castle implementation of multi-exponentiation.
 /// </summary>
 /// <param name="g">bases</param>
 /// <param name="f">exponents</param>
 /// <returns></returns>
 public override GroupElement MultiExponentiate(GroupElement[] g, FieldZqElement[] f)
 {
     if (g == null || f == null || g.Length != f.Length)
     {
         throw new ArgumentException("g and f must be non-null and of the same length");
     }
     GroupElement value = Identity;
     for (int i = 0; i < g.Length; i++)
     {
         value *= g[i].Exponentiate(f[i]);
     }
     return value;
 }
コード例 #53
0
ファイル: GroupElement.cs プロジェクト: raghurana/NArrange
        /// <summary>
        /// Creates a clone of this instance.
        /// </summary>
        /// <returns>Clone of the code element.</returns>
        protected override CodeElement DoClone()
        {
            GroupElement clone = new GroupElement();
            clone._customSeparator = _customSeparator;
            clone._separatorType = _separatorType;

            return clone;
        }