Exemplo n.º 1
0
        /// <summary>
        /// 输出类定义开始段代码
        /// </summary>
        /// <param name="language">代码生成语言</param>
        /// <param name="isOutDefinition">是否输出类定义</param>
        /// <returns>类定义</returns>
        protected bool outStart(CodeLanguage language, bool isOutDefinition)
        {
            _definition_ = null;
            _language_   = language;
            if (isOutDefinition)
            {
                _code_.Length = 0;
                if (Coder.Add(GetType(), Type.Type))
                {
                    switch (_language_)
                    {
                    case CodeLanguage.JavaScript:
                    case CodeLanguage.TypeScript:
                        _definition_ = new JavaScriptTypeDefinition(Type);
                        break;

                    default: _definition_ = new CSharpTypeDefinition(Type, true, false); break;
                    }
                    _code_.Add(_definition_.Start);
                    return(true);
                }
                return(false);
            }
            return(true);
        }
Exemplo n.º 2
0
        void Command_Image_Size(ImageSizeDialog.Result result)
        {
            var variables = GetVariables();
            var width     = new NEExpression(result.WidthExpression).Evaluate <int>(variables);
            var height    = new NEExpression(result.HeightExpression).Evaluate <int>(variables);

            var bitmap       = GetBitmap();
            var resultBitmap = new System.Drawing.Bitmap(width, height, bitmap.PixelFormat);

            resultBitmap.SetResolution(bitmap.HorizontalResolution, bitmap.VerticalResolution);
            using (var graphics = System.Drawing.Graphics.FromImage(resultBitmap))
            {
                graphics.CompositingMode    = System.Drawing.Drawing2D.CompositingMode.SourceCopy;
                graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                graphics.InterpolationMode  = result.InterpolationMode;
                graphics.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                graphics.PixelOffsetMode    = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;

                using (var wrapMode = new System.Drawing.Imaging.ImageAttributes())
                {
                    wrapMode.SetWrapMode(System.Drawing.Drawing2D.WrapMode.TileFlipXY);
                    graphics.DrawImage(bitmap, new System.Drawing.Rectangle(0, 0, width, height), 0, 0, bitmap.Width, bitmap.Height, System.Drawing.GraphicsUnit.Pixel, wrapMode);
                }
            }

            Replace(new List <Range> {
                FullRange
            }, new List <string> {
                Coder.BitmapToString(resultBitmap)
            });
            SetSelections(new List <Range> {
                BeginRange
            });
        }
Exemplo n.º 3
0
        void VerifyCoder(Coder.CodePage codePage, string value, byte[] expected, bool bom, string reverse = null)
        {
            if (reverse == null)
            {
                reverse = value;
            }

            var result = Coder.TryStringToBytes(value, codePage, bom);

            Assert.AreEqual(result != null, expected != null);
            if (expected == null)
            {
                return;
            }

            var str = Coder.BytesToString(result, codePage, bom);

            Assert.AreEqual(str, reverse);

            Assert.AreEqual(expected.Length, result.Length);
            for (var ctr = 0; ctr < result.Length; ctr++)
            {
                Assert.AreEqual(expected[ctr], result[ctr]);
            }
        }
Exemplo n.º 4
0
    public static StoryData CreateFromJSON(string json)
    {
        var jsonPath   = Application.dataPath + "/StreamingAssets/" + json + ".dt";
        var jsonString = Coder.EncodeDecrypt(File.ReadAllText(jsonPath));

        return(JsonUtility.FromJson <StoryData>(jsonString));
    }
Exemplo n.º 5
0
		public static Result Run(Window parent, Coder.CodePage codePage = Coder.CodePage.Default, Coder.CodePage detected = Coder.CodePage.None)
		{
			var dialog = new EncodingDialog(codePage, detected) { Owner = parent };
			if (!dialog.ShowDialog())
				return null;
			return dialog.result;
		}
Exemplo n.º 6
0
		CompressDataDialog(Coder.CodePage _codePage, bool compress)
		{
			InitializeComponent();

			Title = compress ? "Compress Data" : "Decompress Data";

			inputCodePage.ItemsSource = Coder.GetAllCodePages().ToDictionary(page => page, page => Coder.GetDescription(page));
			inputCodePage.SelectedValuePath = "Key";
			inputCodePage.DisplayMemberPath = "Value";

			compressorType.ItemsSource = Enum.GetValues(typeof(Compressor.Type)).Cast<Compressor.Type>().Where(type => type != Compressor.Type.None).ToList();

			outputCodePage.ItemsSource = Coder.GetAllCodePages().ToDictionary(page => page, page => Coder.GetDescription(page));
			outputCodePage.SelectedValuePath = "Key";
			outputCodePage.DisplayMemberPath = "Value";

			if (compress)
			{
				InputCodePage = _codePage;
				CompressorType = Compressor.Type.GZip;
				OutputCodePage = Coder.CodePage.Hex;
			}
			else
			{
				InputCodePage = Coder.CodePage.Hex;
				CompressorType = Compressor.Type.GZip;
				OutputCodePage = _codePage;
			}
		}
Exemplo n.º 7
0
        public void GetLocationCodes_Level1And2And3Correct_Level1And2And3CodesAdded()
        {
            // Arrange
            // gazetteer data - contains codes for names1 and names2
            GazetteerRecords gazetteerRecords = GazetteerTestData();

            // input data - all spelt correctly
            string[] inputNames = { "P1", "T1", "V1" };
            Location location   = new Location(
                inputNames[0],
                inputNames[1],
                inputNames[2]);

            // no saved matches
            MatchProviderStub matchProviderStub = MatchProviderStubEmpty(inputNames);

            Coder coder = new Coder(
                gazetteerRecords.GadmList(),
                matchProviderStub.MatchProvider());

            // Act
            CodedLocation codedLocation = coder.GetCodes(location);

            // Assert
            // code 1, 2 and 3 codes added
            Assert.AreEqual(codes1[0], codedLocation.GeoCode1.Code);
            Assert.AreEqual(names1[0], codedLocation.GeoCode1.Name);
            Assert.AreEqual(codes1[1], codedLocation.GeoCode2.Code);
            Assert.AreEqual(names1[1], codedLocation.GeoCode2.Name);
            Assert.AreEqual(codes1[2], codedLocation.GeoCode3.Code);
            Assert.AreEqual(names1[2], codedLocation.GeoCode3.Name);
        }
Exemplo n.º 8
0
        GetLocationCodes_GazContainsDuplicateCombinedLevel2And3_CorrectCodesAdded()
        {
            // Arrange
            // gazetteer data
            GazetteerRecords gazetteerRecords = GazetteerTestData();

            // input data -
            string[] inputNames = { "P1", "T1V", "1" }; // names 4
            Location location   = new Location(
                inputNames[0],
                inputNames[1],
                inputNames[2]);

            // no saved matches
            MatchProviderStub matchProviderStub = MatchProviderStubEmpty(inputNames);

            Coder coder = new Coder(
                gazetteerRecords.GadmList(),
                matchProviderStub.MatchProvider());

            // Act
            CodedLocation codedLocation = coder.GetCodes(location);

            // Assert
            // correct codes added (codes 4)
            Assert.AreEqual(codes4[0], codedLocation.GeoCode1.Code);
            Assert.AreEqual(codes4[1], codedLocation.GeoCode2.Code);
            Assert.AreEqual(codes4[2], codedLocation.GeoCode3.Code);
        }
Exemplo n.º 9
0
        public void GetLocationCodes_Level1Incorrect_NoCodesAdded()
        {
            // Arrange
            // gazetteer data - contains codes for names1 and names2
            GazetteerRecords gazetteerRecords = GazetteerTestData();

            // input data - level 2 miss-spelt
            string[] inputNames = { "P1x", "T1", "V1" };
            Location location   = new Location(
                inputNames[0],
                inputNames[1],
                inputNames[2]);

            // no saved matches
            MatchProviderStub matchProviderStub = MatchProviderStubEmpty(inputNames);

            Coder coder = new Coder(
                gazetteerRecords.GadmList(),
                matchProviderStub.MatchProvider());

            // Act
            CodedLocation codedLocation = coder.GetCodes(location);

            // Assert
            // no codes added
            Assert.AreEqual(null, codedLocation.GeoCode1);
            Assert.AreEqual(null, codedLocation.GeoCode2);
            Assert.AreEqual(null, codedLocation.GeoCode3);
        }
Exemplo n.º 10
0
        public void GetLocationCodes_Level1Correct_Level1CodeAdded()
        {
            // Arrange
            // gazetteer data - contains codes for names1 and names2
            GazetteerRecords gazetteerRecords = GazetteerTestData();

            // input data - no level 3 supplied
            string[] inputNames = { "P1", null, null };
            Location location   = new Location(
                inputNames[0]);

            // no saved matches
            MatchProviderStub matchProviderStub = MatchProviderStubEmpty(inputNames);

            Coder coder = new Coder(
                gazetteerRecords.GadmList(),
                matchProviderStub.MatchProvider());

            // Act
            CodedLocation codedLocation = coder.GetCodes(location);

            // Assert
            // level 1 code only added
            Assert.AreEqual(codes1[0], codedLocation.GeoCode1.Code);
            Assert.AreEqual(names1[0], codedLocation.GeoCode1.Name);
            Assert.AreEqual(null, codedLocation.GeoCode2);
            Assert.AreEqual(null, codedLocation.GeoCode3);
        }
Exemplo n.º 11
0
        void Command_Image_Rotate(ImageRotateDialog.Result result)
        {
            var variables = GetVariables();
            var angle     = new NEExpression(result.AngleExpression).Evaluate <float>(variables, "deg");

            var bitmap = GetBitmap();
            var path   = new System.Drawing.Drawing2D.GraphicsPath();

            path.AddRectangle(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height));
            var matrix = new System.Drawing.Drawing2D.Matrix();

            matrix.Rotate(angle);
            var rect         = path.GetBounds(matrix);
            var resultBitmap = new System.Drawing.Bitmap((int)rect.Width, (int)rect.Height, bitmap.PixelFormat);

            using (var g = System.Drawing.Graphics.FromImage(resultBitmap))
            {
                g.TranslateTransform(-rect.X, -rect.Y);
                g.RotateTransform(angle);
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
                g.DrawImageUnscaled(bitmap, 0, 0);
            }

            Replace(new List <Range> {
                FullRange
            }, new List <string> {
                Coder.BitmapToString(resultBitmap)
            });
            SetSelections(new List <Range> {
                BeginRange
            });
        }
Exemplo n.º 12
0
        GetLocationCodes_Leve1And2CorrectAndLevel3Incorrect_Level1And2CodeAddedOnly()
        {
            // Arrange
            // gazetteer data - contains codes for names1 and names2
            GazetteerRecords gazetteerRecords = GazetteerTestData();

            // input data - level 3 miss-spelt
            string[] inputNames = { "P1", "T1", "V1x" };
            Location location   = new Location(
                inputNames[0],
                inputNames[1],
                inputNames[2]);

            // no saved matches
            MatchProviderStub matchProviderStub = MatchProviderStubEmpty(inputNames);

            Coder coder = new Coder(
                gazetteerRecords.GadmList(),
                matchProviderStub.MatchProvider());

            // Act
            CodedLocation codedLocation = coder.GetCodes(location);

            // Assert
            // code 1 and 2 only are added, no level 3 code added
            Assert.AreEqual(codes1[0], codedLocation.GeoCode1.Code);
            Assert.AreEqual(names1[0], codedLocation.GeoCode1.Name);
            Assert.AreEqual(codes1[1], codedLocation.GeoCode2.Code);
            Assert.AreEqual(names1[1], codedLocation.GeoCode2.Name);
            Assert.AreEqual(null, codedLocation.GeoCode3);
        }
Exemplo n.º 13
0
        public ActionResult RecoverPasswordPost(string CorreoElectronico)
        {
            try
            {
                if (string.IsNullOrEmpty(CorreoElectronico))
                {
                    throw new Exception("Debe ingresar su Correo Electrónico.");
                }

                var Usuario_ = UserService.GetByEMail(CorreoElectronico);

                if (Usuario_ == null)
                {
                    throw new Exception(string.Format("El Usuario con Correo Electrónico <strong>{0}</strong> no existe.", CorreoElectronico));
                }

                var Email_ = EmailService.GetById((int)EmailTemplate.PasswordRecovery);
                if (Email_ == null)
                {
                    throw new Exception("No se encontró una <strong>Plantilla de Correo<strong> para esta Solicitud.");
                }
                var NewPassword = Membership.GeneratePassword(8, 0);

                var NombreReceptor    = string.Format("{0} {1} {2}", Usuario_.Nombre.Trim(), Usuario_.Apellido_Paterno.Trim(), Usuario_.Apellido_Materno.Trim());
                var DireccionReceptor = new List <string> {
                    Usuario_.Email
                };
                var Mensaje = Email_.Cuerpo;
                Mensaje = Mensaje.Replace("{NombreDestinatario}", NombreReceptor);
                Mensaje = Mensaje.Replace("{NombreAplicacion}", "Template");
                Mensaje = Mensaje.Replace("{NuevaPassword}", NewPassword);

                var EmailSent = Email.EnviarEmail(Email_.NombreRemitente, Email_.DireccionRemitente, Email_.Asunto, NombreReceptor, DireccionReceptor, Mensaje);

                if (!EmailSent)
                {
                    throw new Exception("Ocurrió un <strong>Error</strong> al Enviar por Correo su <strong>Nueva Contraseña</strong>, por favor contacte a su <strong>Adminsitrador</strong>.");
                }

                NewPassword = Coder.Encode(NewPassword);
                var Result = UserService.ChangePassword(Usuario_.Id, NewPassword, true);

                if (Result)
                {
                    this.Flash("Su <strong>Nueva Contraseña</strong> ha sido enviada a su <strong>Correo Electrónico</strong><br><span>Recuerde por seguridad Actualizarla lo antes posible</span>.");
                }
                else
                {
                    throw new Exception("Ocurrió un <strong>Error</strong> al restablecer su <strong>Contraseña</strong>, por favor contacte a su <strong>Adminsitrador</strong>.");
                }

                return(RedirectToAction("RecoverPassword"));
            }
            catch (Exception Ex)
            {
                this.Flash(Ex.GetBaseException().Message, MessageType.Error);
                return(RedirectToAction("RecoverPassword"));
            }
        }
Exemplo n.º 14
0
    public void SaveToJson()
    {
        var jsonPath   = Application.dataPath + "/StreamingAssets/GSI.dt";
        var jsonString = JsonUtility.ToJson(this);
        var coded      = Coder.EncodeDecrypt(jsonString);

        File.WriteAllText(jsonPath, coded);
    }
Exemplo n.º 15
0
        public void TestCase01()
        {
            var message = "What hath God wrought";

            var codedMessage = Coder.Perform(message);
            
            Assert.AreEqual(codedMessage, ".-- .... .- - / .... .- - .... / --. --- -.. / .-- .-. --- ..- --. .... -");
        }
Exemplo n.º 16
0
    public static GameStartInfo LoadFromJson()
    {
        var jsonPath   = Application.dataPath + "/StreamingAssets/GSI.dt";
        var jsonString = File.ReadAllText(jsonPath);
        var encoded    = Coder.EncodeDecrypt(jsonString);

        return(JsonUtility.FromJson <GameStartInfo>(encoded));
    }
Exemplo n.º 17
0
        public ActionResult DeleteConfirmed(int id)
        {
            Coder coder = db.Coders.Find(id);

            db.Coders.Remove(coder);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Exemplo n.º 18
0
        public void ConvertBytesToString_ForSameBytes_ReturnSameString(byte[] data, char[] alphabet)
        {
            //arrange
            var coder = new Coder();

            //assert
            Assert.AreEqual(coder.ConvertBytesToString(data, alphabet), coder.ConvertBytesToString(data, alphabet));
        }
Exemplo n.º 19
0
 private static Coder ImplementOnEnterMethod(
     Coder originCoder,
     Coder coder,
     MethodBuilderInfo <MethodBuilderInfoItem <BuilderTypeIMethodInterceptor, BuilderTypeISimpleMethodInterceptor> > method,
     Method attributedMethod,
     MethodBuilderInfoItem <BuilderTypeIMethodInterceptor, BuilderTypeISimpleMethodInterceptor>[] fullMethodInterceptors,
     Func <MethodBuilderInfoItem <BuilderTypeIMethodInterceptor, BuilderTypeISimpleMethodInterceptor>, Method> onEnterMethod)
 => ImplementOnEnterMethod(originCoder, coder, coder, method, attributedMethod, fullMethodInterceptors, onEnterMethod);
 public EncodDecodEventArgs(EncryptionEnum processType, Coder coderType, string text, int key1, int key2)
 {
     ProcessType = processType;
     Text        = text;
     KeyOne      = key1 == 0 ? 3: key1;
     KeyTwo      = key2 == 0 ? 5 : key2;
     CoderType   = coderType;
 }
Exemplo n.º 21
0
        public void TestUnicode()
        {
            var dir = Path.Combine(Directory.GetCurrentDirectory(), "TestData");

            Directory.CreateDirectory(dir);

            using (var combined = File.Create(Path.Combine(dir, "Combined.txt")))
            {
                foreach (var codePage in Coder.GetStringCodePages())
                {
                    if (Coder.PreambleSize(codePage) == 0)
                    {
                        continue;
                    }
                    for (var useBom = 0; useBom < 2; ++useBom)
                    {
                        var bom = useBom == 0;
                        foreach (var ending in GetValues <Endings>())
                        {
                            Encoding encoder = null;
                            switch (codePage)
                            {
                            case Coder.CodePage.UTF8:
                                encoder = new UTF8Encoding(false);
                                break;

                            case Coder.CodePage.UTF16LE:
                            case Coder.CodePage.UTF16BE:
                                encoder = new UnicodeEncoding(codePage == Coder.CodePage.UTF16BE, false);
                                break;

                            case Coder.CodePage.UTF32BE:
                            case Coder.CodePage.UTF32LE:
                                encoder = new UTF32Encoding(codePage == Coder.CodePage.UTF32BE, false);
                                break;

                            default:
                                throw new Exception("No encoder found");
                            }
                            var filename = Path.Combine(dir, $"{codePage}-{bom}-{ending}.txt");
                            var str      = GetText(codePage, bom, ending);
                            File.WriteAllText(filename, str, encoder);

                            var bytes = File.ReadAllBytes(filename);
                            combined.Write(bytes, 0, bytes.Length);

                            var encoding2 = Coder.GuessUnicodeEncoding(bytes);
                            var str2      = Coder.BytesToString(bytes, encoding2);
                            var bom2      = (str2.Length > 0) && (str2[0] == '\ufeff');

                            Assert.AreEqual(codePage, encoding2);
                            Assert.AreEqual(bom, bom2);
                            Assert.AreEqual(str, str2);
                        }
                    }
                }
            }
        }
Exemplo n.º 22
0
        public void Should_EncodeSelectReq()
        {
            var selectReq = new SelectReq(1, 9);

            var actual   = Coder.Encode(selectReq).Skip(4).ToArray();
            var expected = new byte[] { 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x09 };

            CollectionAssert.AreEqual(expected, actual);
        }
Exemplo n.º 23
0
        public void SetVisible(bool visible)
        {
            mVisible = visible;

            if (mVisible == false)
            {
                Coder.SetRenderOffset(UPoint.Zero);
            }
        }
Exemplo n.º 24
0
        private void button1_Click(object sender, EventArgs e)
        {
            aaa   = Convert.ToInt32(Send.Text.Length);
            coder = new Coder(aaa);
            coder.Code(Converter.ConvertToArray(Send.Text));

            Stat.Text = coder.PrintInformation();
            Recv.Text = coder.PrintInformation1();
        }
Exemplo n.º 25
0
        public async Task <IActionResult> DeleteConfirmed(Coder cod)
        {
            var coder = await _context.Coders.FindAsync(cod.CoderID);

            _context.Coders.Remove(coder);
            await _context.SaveChangesAsync();

            return(RedirectToAction(nameof(Index)));
        }
Exemplo n.º 26
0
 protected EntityTypeState GetEntityType(Coder code)
 {
     EntityTypeState entityTypeEntityType;
     if (!AcDomain.EntityTypeSet.TryGetEntityType(code, out entityTypeEntityType))
     {
         throw new InvalidEntityTypeCodeException(code);
     }
     return entityTypeEntityType;
 }
Exemplo n.º 27
0
 FilesOperationsEncodingDialog()
 {
     InitializeComponent();
     inputCodePage.ItemsSource       = outputCodePage.ItemsSource = Coder.GetAllCodePages().Select(codePage => Tuple.Create(codePage, Coder.GetDescription(codePage)));
     inputCodePage.SelectedValuePath = outputCodePage.SelectedValuePath = "Item1";
     inputCodePage.DisplayMemberPath = outputCodePage.DisplayMemberPath = "Item2";
     InputCodePage  = Coder.CodePage.AutoByBOM;
     OutputCodePage = Coder.CodePage.UTF8;
 }
Exemplo n.º 28
0
        EditDataSignDialog(Coder.CodePage codePage)
        {
            InitializeComponent();

            CodePages    = Coder.GetAllCodePages().ToDictionary(page => page, page => Coder.GetDescription(page));
            CryptorTypes = Enum.GetValues(typeof(Cryptor.Type)).Cast <Cryptor.Type>().Where(type => type != Cryptor.Type.None).Where(type => type.SigningHashes().Any()).ToList();

            CryptorType = CryptorTypes.First();
            CodePage    = codePage;
        }
Exemplo n.º 29
0
 /// <summary>
 /// 安装入口
 /// </summary>
 /// <param name="type">数据类型</param>
 /// <param name="primaryKeys">数据类型</param>
 public void Run(Type type, MemberIndex[] primaryKeys)
 {
     if (primaryKeys.Length > 1 && !Coder.CheckCodeType(typeof(Generator), type))
     {
         Type        = type;
         Attribute   = type.customAttribute <AutoCSer.Data.PrimaryKeyAttribute>() ?? AutoCSer.Data.PrimaryKeyAttribute.Default;
         PrimaryKeys = primaryKeys;
         nextCreate();
     }
 }
Exemplo n.º 30
0
 private void Code_click(object sender, RoutedEventArgs e)
 {
     if (MainText.Text != "")
     {
         if (KeyText.Text != "")
         {
             ResultText.Text = Coder.Еncrypt(MainText.Text, KeyText.Text);
         }
     }
 }
Exemplo n.º 31
0
        private static EntityTypeState GetEntityType(this IAcDomain acDomain, Coder code)
        {
            EntityTypeState entityTypeState;

            if (!acDomain.EntityTypeSet.TryGetEntityType(code, out entityTypeState))
            {
                throw new InvalidEntityTypeCodeException(code);
            }
            return(entityTypeState);
        }
Exemplo n.º 32
0
        private void button2_Click(object sender, EventArgs e)
        {
            Coder             coder = new Coder(_point_State_color, new TimeSpan(0, 2, 0));
            CancellationToken token = _tokenSrcCancel.Token;
            Task task = new Task(() => coder.Code(token), token);

            task.ContinueWith(coding_exception_handler, TaskContinuationOptions.OnlyOnFaulted);
            task.ContinueWith(coding_done_handler, TaskContinuationOptions.OnlyOnRanToCompletion);
            task.Start();
        }
Exemplo n.º 33
0
        FilesInsertDialog()
        {
            InitializeComponent();

            CodePage = Coder.CodePage.AutoByBOM;

            codePage.ItemsSource       = Coder.GetAllCodePages().ToDictionary(page => page, page => Coder.GetDescription(page));
            codePage.SelectedValuePath = "Key";
            codePage.DisplayMemberPath = "Value";
        }
Exemplo n.º 34
0
		SignDataDialog(Coder.CodePage codePage)
		{
			InitializeComponent();

			CodePages = Coder.GetAllCodePages().ToDictionary(page => page, page => Coder.GetDescription(page));
			CryptorTypes = Enum.GetValues(typeof(Cryptor.Type)).Cast<Cryptor.Type>().Where(type => type != Cryptor.Type.None).Where(type => type.SigningHashes().Any()).ToList();

			CryptorType = CryptorTypes.First();
			CodePage = codePage;
		}
Exemplo n.º 35
0
		HashDataDialog(Coder.CodePage _codePage)
		{
			InitializeComponent();

			codePage.ItemsSource = Coder.GetAllCodePages().ToDictionary(page => page, page => Coder.GetDescription(page));
			codePage.SelectedValuePath = "Key";
			codePage.DisplayMemberPath = "Value";

			hashType.ItemsSource = Enum.GetValues(typeof(Hasher.Type)).Cast<Hasher.Type>().Where(type => type != Hasher.Type.None).ToList();

			CodePage = _codePage;
		}
Exemplo n.º 36
0
		CreateFilesDialog(NEVariables variables, Coder.CodePage defaultCodePage)
		{
			Variables = variables;
			InitializeComponent();

			FileName = Data = "x";
			CodePage = defaultCodePage;

			codePage.ItemsSource = Coder.GetAllCodePages().ToDictionary(page => page, page => Coder.GetDescription(page));
			codePage.SelectedValuePath = "Key";
			codePage.DisplayMemberPath = "Value";
		}
Exemplo n.º 37
0
		void Command_Network_Fetch(Coder.CodePage codePage = Coder.CodePage.None)
		{
			var urls = GetSelectionStrings();
			var results = Task.Run(() => GetURLs(urls, codePage).Result).Result;
			if (results.Any(result => result.Item3))
				new Message(WindowParent)
				{
					Title = "Error",
					Text = $"Failed to fetch the URLs:\n{string.Join("\n", results.Where(result => result.Item3).Select(result => result.Item1))}",
					Options = Message.OptionsEnum.Ok,
				}.Show();
			ReplaceSelections(results.Select(result => result.Item2).ToList());
		}
Exemplo n.º 38
0
		async Task<string> GetURL(string url, Coder.CodePage codePage = Coder.CodePage.None)
		{
			using (var client = new WebClient())
			{
				client.Headers["User-Agent"] = "Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)";
				client.Encoding = Encoding.UTF8;
				var uri = new Uri(url);
				if (codePage == Coder.CodePage.None)
					return await client.DownloadStringTaskAsync(uri);

				var data = await client.DownloadDataTaskAsync(uri);
				return Coder.BytesToString(data, codePage);
			}
		}
Exemplo n.º 39
0
		EncryptDataDialog(Coder.CodePage _codePage, bool encrypt)
		{
			this.encrypt = encrypt;
			InitializeComponent();

			Title = encrypt ? "Encrypt Data" : "Decrypt Data";

			CodePages = Coder.GetAllCodePages().ToDictionary(page => page, page => Coder.GetDescription(page));
			CryptorTypes = Enum.GetValues(typeof(Cryptor.Type)).Cast<Cryptor.Type>().Where(type => type != Cryptor.Type.None).ToList();

			CryptorType = Cryptor.Type.AES;
			InputCodePage = encrypt ? _codePage : Coder.CodePage.Hex;
			OutputCodePage = encrypt ? Coder.CodePage.Hex : _codePage;
		}
Exemplo n.º 40
0
		void VerifyCoder(Coder.CodePage codePage, string value, byte[] expected, bool bom, string reverse = null)
		{
			if (reverse == null)
				reverse = value;

			var result = Coder.TryStringToBytes(value, codePage, bom);
			Assert.AreEqual(result != null, expected != null);
			if (expected == null)
				return;

			var str = Coder.BytesToString(result, codePage, bom);
			Assert.AreEqual(str, reverse);

			Assert.AreEqual(expected.Length, result.Length);
			for (var ctr = 0; ctr < result.Length; ctr++)
				Assert.AreEqual(expected[ctr], result[ctr]);
		}
Exemplo n.º 41
0
		EncodingDialog(Coder.CodePage _CodePage, Coder.CodePage _Detected)
		{
			InitializeComponent();

			codePage.ItemsSource = Coder.GetAllCodePages().ToDictionary(page => page, page => Coder.GetDescription(page));
			codePage.SelectedValuePath = "Key";
			codePage.DisplayMemberPath = "Value";

			CodePage = _CodePage;
			if (_Detected == Coder.CodePage.None)
				content.Children.Cast<UIElement>().Where(child => Grid.GetRow(child) == Grid.GetRow(setDetected)).ToList().ForEach(child => child.Visibility = Visibility.Collapsed);
			else
			{
				Detected = _Detected;
				DetectedStr = Coder.GetDescription(Detected);
			}
		}
Exemplo n.º 42
0
		async Task<List<Tuple<string, string, bool>>> GetURLs(List<string> urls, Coder.CodePage codePage = Coder.CodePage.None)
		{
			var tasks = urls.Select(url => GetURL(url, codePage)).ToList();
			var results = new List<Tuple<string, string, bool>>();
			for (var ctr = 0; ctr < tasks.Count; ++ctr)
			{
				string data;
				bool error = false;
				try { data = await tasks[ctr]; }
				catch (Exception ex)
				{
					error = true;
					data = $"<error>{Data.DefaultEnding}";
					data += $"\t<url>{urls[ctr]}</url>{Data.DefaultEnding}";
					data += $"\t<data>{Data.DefaultEnding}";
					for (; ex != null; ex = ex.InnerException)
						data += $"\t\t{ex.Message}{Data.DefaultEnding}";
					data += $"\t</data>{Data.DefaultEnding}";
					data += $"</error>{Data.DefaultEnding}";
				}
				results.Add(Tuple.Create(urls[ctr], data, error));
			}
			return results;
		}
Exemplo n.º 43
0
 private static EntityTypeState GetEntityType(this IAcDomain acDomain, Coder code)
 {
     EntityTypeState entityTypeState;
     if (!acDomain.EntityTypeSet.TryGetEntityType(code, out entityTypeState))
     {
         throw new InvalidEntityTypeCodeException(code);
     }
     return entityTypeState;
 }
Exemplo n.º 44
0
            private static void AdjustFilesetForEncryption(FileSet fileset, EncryptionProvider encryption, long outputSize, uint? outputHash)
            {
                if (fileset.InputStreams.Length != 1)
                    throw new NotSupportedException();

                master._7zip.Legacy.CMethodId methodId;
                byte[] settings;
                encryption.GetCoderInfo(out methodId, out settings);

                var encryptedStreamRef = new InputStreamRef { PackedStreamIndex = 0 };
                var decryptedStreamRef = new CoderStreamRef { CoderIndex = fileset.Coders.Length, StreamIndex = 0 };

                // TODO: this is wrong, outputSize/outputHash is the INPUT of the decoder,
                //       however see comment at call site for why this works for now
                //       (we also need to replace the filesets input stream with our own
                //       input stream, namely outputSize/outputHash)
                var decryptionCoder = new Coder
                {
                    MethodId = methodId,
                    Settings = settings,
                    InputStreams = new[] { encryptedStreamRef },
                    OutputStreams = new[] { new CoderStream { Size = outputSize, Hash = outputHash } },
                };

                fileset.Coders = fileset.Coders
                    .Select(x => AdjustCoderForEncryption(x, decryptedStreamRef))
                    .Concat(new[] { decryptionCoder })
                    .ToArray();
            }
Exemplo n.º 45
0
		public static Result Run(Window parent, NEVariables variables, Coder.CodePage codePage)
		{
			var dialog = new CreateFilesDialog(variables, codePage) { Owner = parent };
			return dialog.ShowDialog() ? dialog.result : null;
		}
 public InvalidResourceTypeCodeException(Coder code, Exception innerException)
     : base("codespace:" + code.Codespace + ",resourceTypeCode:" + code.Code, innerException)
 {
 }
 public InvalidEntityTypeCodeException(Coder code)
     : base("codespace:" + code.Codespace + ",entityTypeCode:" + code.Code)
 {
 }
Exemplo n.º 48
0
			public CodePageItem(Coder.CodePage codePage)
			{
				CodePage = codePage;
				Content = Coder.GetDescription(CodePage);
			}
Exemplo n.º 49
0
		public bool CanFullyEncode(Coder.CodePage codePage) => Coder.CanFullyEncode(Data, codePage);
Exemplo n.º 50
0
            private static Coder AdjustCoderForEncryption(Coder coder, StreamRef adjustedInputStream)
            {
                if (coder.InputStreams.Length != 1 || !(coder.InputStreams[0] is InputStreamRef) || ((InputStreamRef)coder.InputStreams[0]).PackedStreamIndex != 0)
                    throw new NotSupportedException();

                return new Coder
                {
                    MethodId = coder.MethodId,
                    Settings = coder.Settings,
                    InputStreams = new[] { adjustedInputStream },
                    OutputStreams = coder.OutputStreams,
                };
            }
Exemplo n.º 51
0
		public static Result Run(Window parent, Coder.CodePage codePage, bool compress)
		{
			var dialog = new CompressDataDialog(codePage, compress) { Owner = parent };
			return dialog.ShowDialog() == true ? dialog.result : null;
		}
Exemplo n.º 52
0
		public void LaunchTextEditor(string fileName = null, string displayName = null, byte[] bytes = null, Coder.CodePage codePage = Coder.CodePage.AutoByBOM, bool? modified = null, bool forceCreate = false) => textEditorLauncher?.Invoke(fileName, displayName, bytes, codePage, modified, forceCreate);
Exemplo n.º 53
0
		public void LaunchHexEditor(string fileName = null, byte[] bytes = null, Coder.CodePage codePage = Coder.CodePage.AutoByBOM, bool modified = false, bool forceCreate = false) => fileHexEditorLauncher?.Invoke(fileName, bytes, codePage, modified, forceCreate);
Exemplo n.º 54
0
		public static Result Run(Window parent, Coder.CodePage codePage)
		{
			var dialog = new SignDataDialog(codePage) { Owner = parent };
			return dialog.ShowDialog() == true ? dialog.result : null;
		}
 public InvalidEntityTypeCodeException(Coder code, Exception innerException)
     : base("codespace:" + code.Codespace + ",entityTypeCode:" + code.Code, innerException)
 {
 }
Exemplo n.º 56
0
		public static void SaveEncoding(string inputFile, string outputFile, Coder.CodePage outCodePage)
		{
			MultiProgressDialog.Run("Changing encoding...", new List<string> { inputFile }, (progress, cancel) =>
			{
				using (var input = File.OpenRead(inputFile))
				{
					var header = Read(input, 0, (int)Math.Min(input.Length, 4));
					var inCodePage = Coder.CodePageFromBOM(header);

					if (inCodePage == outCodePage)
						throw new Exception("File already has that encoding.");

					long position = Coder.PreambleSize(inCodePage);
					var size = input.Length;
					using (var output = File.Create(outputFile))
					{
						var bom = Coder.StringToBytes("", outCodePage, true);
						output.Write(bom, 0, bom.Length);
						var decoder = Coder.GetEncoding(inCodePage).GetDecoder();
						var encoder = Coder.GetEncoding(outCodePage).GetEncoder();
						var chars = new char[65536];
						var bytes = new byte[chars.Length * 5]; // Should be big enough to hold any resulting output
						while (position < size)
						{
							if (cancel())
								return;

							var inByteCount = (int)Math.Min(chars.Length, size - position);
							TextData.Read(input, position, inByteCount, bytes);

							var numChars = decoder.GetChars(bytes, 0, inByteCount, chars, 0);
							var outByteCount = encoder.GetBytes(chars, 0, numChars, bytes, 0, false);

							output.Write(bytes, 0, outByteCount);

							position += inByteCount;
							progress(0, position, size);
						}
					}
				}
			});
		}
Exemplo n.º 57
0
		public static Result Run(Window parent, Coder.CodePage codePage, bool encrypt)
		{
			var dialog = new EncryptDataDialog(codePage, encrypt) { Owner = parent };
			return dialog.ShowDialog() == true ? dialog.result : null;
		}
Exemplo n.º 58
0
		public byte[] GetBytes(Coder.CodePage codePage) => Coder.StringToBytes(Data, codePage, true);