예제 #1
0
    public bool PosTest1()
    {
        bool retVal = true;

        // Add your scenario description here
        TestLibrary.TestFramework.BeginScenario("PosTest1: Verify method GetByteCount with a non-null Byte[]");

        try
        {
            Byte[] bytes = new Byte[] {
                                         85,  84,  70,  56,  32,  69, 110,
                                         99, 111, 100, 105, 110, 103,  32,
                                         69, 120,  97, 109, 112, 108, 101};

            UTF8Encoding utf8 = new UTF8Encoding();
            int charCount = utf8.GetCharCount(bytes, 2, 8);

            if (charCount != 8)
            {
                TestLibrary.TestFramework.LogError("001.1", "Method GetByteCount Err.");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
        public void Mockfile_Create_OverwritesExistingFile()
        {
            string path = XFS.Path(@"c:\some\file.txt");
            var fileSystem = new MockFileSystem();

            var mockFile = new MockFile(fileSystem);

            fileSystem.Directory.CreateDirectory(Path.GetDirectoryName(path));

            // Create a file
            using (var stream = mockFile.Create(path))
            {
                var contents = new UTF8Encoding(false).GetBytes("Test 1");
                stream.Write(contents, 0, contents.Length);
            }

            // Create new file that should overwrite existing file
            var expectedContents = new UTF8Encoding(false).GetBytes("Test 2");
            using (var stream = mockFile.Create(path))
            {
                stream.Write(expectedContents, 0, expectedContents.Length);
            }

            var actualContents = fileSystem.GetFile(path).Contents;

            Assert.That(actualContents, Is.EqualTo(expectedContents));
        }
예제 #3
0
 public void PosTest1()
 {
     String chars = "UTF8 Encoding Example";
     UTF8Encoding utf8 = new UTF8Encoding();
     int byteCount = utf8.GetByteCount(chars);
     Assert.Equal(chars.Length, byteCount);
 }
예제 #4
0
 public void PosTest2()
 {
     String chars = "";
     UTF8Encoding utf8 = new UTF8Encoding();
     int byteCount = utf8.GetByteCount(chars);
     Assert.Equal(0, byteCount);
 }
예제 #5
0
 public void PosTest2()
 {
     Byte[] bytes = new Byte[] { };
     UTF8Encoding utf8 = new UTF8Encoding();
     int charCount = utf8.GetCharCount(bytes, 0, 0);
     Assert.Equal(0, charCount);
 }
	public virtual void Post(string url, Dictionary<string, string> data, System.Action<HttpResult> onResult) {
	
		this.MakeRequest(url, HttpMethods.POST, onResult, (r) => {

			JSONObject js = new JSONObject(data);
			var requestPayload = js.ToString();

			UTF8Encoding encoding = new UTF8Encoding();
			r.ContentLength = encoding.GetByteCount(requestPayload);
			r.Credentials = CredentialCache.DefaultCredentials;
			r.Accept = "application/json";
			r.ContentType = "application/json";
			
			//Write the payload to the request body.
			using ( Stream requestStream = r.GetRequestStream())
			{
				requestStream.Write(encoding.GetBytes(requestPayload), 0,
				                    encoding.GetByteCount(requestPayload));
			}

			return false;

		});

	}
 // Token: 0x06000EF7 RID: 3831 RVA: 0x00045348 File Offset: 0x00043548
 public static string Encrypt(string unencrypted)
 {
     RijndaelManaged rijndaelManaged = new RijndaelManaged();
     ICryptoTransform encryptor = rijndaelManaged.CreateEncryptor(SimpleAES.key, SimpleAES.vector);
     UTF8Encoding uTF8Encoding = new UTF8Encoding();
     return Convert.ToBase64String(SimpleAES.Encrypt(uTF8Encoding.GetBytes(unencrypted), encryptor));
 }
예제 #8
0
    public static string DecryptRijndael(string encryptedString)
    {
        byte[] encrypted;

        byte[] fromEncrypted;

        UTF8Encoding utf8Converter = new UTF8Encoding();

        encrypted = Convert.FromBase64String(encryptedString);

        RijndaelManaged myRijndael = new RijndaelManaged();

        ICryptoTransform decryptor = myRijndael.CreateDecryptor(Key, IV);

        MemoryStream ms = new MemoryStream(encrypted);

        CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read);

        fromEncrypted = new byte[encrypted.Length];

        cs.Read(fromEncrypted, 0, fromEncrypted.Length);

        string decryptedString = utf8Converter.GetString(fromEncrypted);
        int indexNull = decryptedString.IndexOf("\0");
        if (indexNull > 0)
        {
            decryptedString = decryptedString.Substring(0, indexNull);
        }
        return decryptedString;
    }
예제 #9
0
 public static string get_uft8(string unicodeString)
 {
     UTF8Encoding utf8 = new UTF8Encoding();
     byte[] encodedBytes = utf8.GetBytes(unicodeString);
     string decodedString = utf8.GetString(encodedBytes);
     return decodedString;
 }
 // Token: 0x06000EF8 RID: 3832 RVA: 0x00045384 File Offset: 0x00043584
 public static string Decrypt(string encrypted)
 {
     RijndaelManaged rijndaelManaged = new RijndaelManaged();
     ICryptoTransform decryptor = rijndaelManaged.CreateDecryptor(SimpleAES.key, SimpleAES.vector);
     UTF8Encoding uTF8Encoding = new UTF8Encoding();
     return uTF8Encoding.GetString(SimpleAES.Decrypt(Convert.FromBase64String(encrypted), decryptor));
 }
예제 #11
0
    /// <summary>
    /// Private accessor for all GET and POST requests.
    /// </summary>
    /// <param name="url">Web url to be accessed.</param>
    /// <param name="post">Place POST request information here. If a GET request, use null. </param>
    /// <param name="attempts"># of attemtps before sending back an empty string.</param>
    /// <returns>Page HTML if access was successful, otherwise will return a blank string. </returns>
    private String getHtml(String url, String post, int attempts)
    {
        WebClient webClient = new WebClient();
            UTF8Encoding utfObj = new UTF8Encoding();
            byte[] reqHTML;

            while (attempts > 0)// Will keep trying to access until attempts reach zero.
            {
                try
                {
                    if (post != null) //If post is null, then no post request is required.
                        reqHTML = webClient.UploadData(url, "POST", System.Text.Encoding.ASCII.GetBytes(post));
                    else
                        reqHTML = webClient.DownloadData(url);
                    String input = utfObj.GetString(reqHTML);
                    return input;
                }
                catch (WebException e)
                {
                    errorLog.WriteMessage("Could not contact to " + url + "  -  " + e.Message);
                    Thread.Sleep(2000);
                }
                catch (ArgumentNullException e)
                {
                    errorLog.WriteMessage("Could not retrieve data from " + url + "  -  " + e.Message);
                    Thread.Sleep(2000);
                }
                attempts--;
            }
            return "";
    }
예제 #12
0
        public void PosTest1()
        {
            UTF8Encoding UTF8NoPreamble = new UTF8Encoding();
            Byte[] preamble;

            preamble = UTF8NoPreamble.GetPreamble();
        }
예제 #13
0
    public void In(
      [FriendlyName("Key", "The string to be used to check against the provided SHA1 hash.")]
      string Key,
      
      [FriendlyName("SHA1 Hash", "The SHA1 Hash to check the key against.")]
      string Hash
      )
    {
        if (Key != "" && Hash != "")
          {
         UTF8Encoding ue = new UTF8Encoding();
         byte[] bytes = ue.GetBytes(Key);

         // encrypt bytes
         SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
         byte[] hashBytes = sha1.ComputeHash(bytes);

         // Convert the encrypted bytes back to a string (base 16)
         string tmpHash = "";

         for (int i = 0; i < hashBytes.Length; i++)
         {
            tmpHash += System.Convert.ToString(hashBytes[i], 16).PadLeft(2, '0');
         }

         string finalHash = tmpHash.PadLeft(32, '0');

         if (finalHash == Hash)
         {
            m_GoodHash = true;
         }
          }
    }
예제 #14
0
    public bool PosTest1()
    {
        bool retVal = true;

        // Add your scenario description here
        TestLibrary.TestFramework.BeginScenario("PosTest1: ");

        try
        {
            Byte[] bytes = new Byte[] {
                             85,  84,  70,  56,  32,  69, 110,
                             99, 111, 100, 105, 110, 103,  32,
                             69, 120,  97, 109, 112, 108, 101};

            UTF8Encoding utf8 = new UTF8Encoding();
            string str = utf8.GetString(bytes, 0, bytes.Length);
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
    public void In(
      [FriendlyName("Key", "The string to be used to generate the hash from.")]
      string Key,
      
      [FriendlyName("SHA1 Hash", "The SHA1 Hash generated by the Key.")]
      out string Hash
      )
    {
        if (Key != "")
          {
         UTF8Encoding ue = new UTF8Encoding();
         byte[] bytes = ue.GetBytes(Key);

         // encrypt bytes
         SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
         byte[] hashBytes = sha1.ComputeHash(bytes);

         // Convert the encrypted bytes back to a string (base 16)
         string tmpHash = "";

         for (int i = 0; i < hashBytes.Length; i++)
         {
            tmpHash += System.Convert.ToString(hashBytes[i], 16).PadLeft(2, '0');
         }

         Hash = tmpHash.PadLeft(32, '0');
          }
          else
          {
         uScriptDebug.Log("[Generate SHA1 Hash] The Key provided was empty, returning an empty string for the SHA1 Hash.", uScriptDebug.Type.Warning);
         Hash = "";
          }
    }
예제 #16
0
    public bool NegTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentNullException is not thrown when bytes is a null reference");

        try
        {
            Byte[] bytes = null;

            UTF8Encoding utf8 = new UTF8Encoding();
            string str = utf8.GetString(bytes, 0, 2);

            TestLibrary.TestFramework.LogError("101.1", "ArgumentNullException is not thrown when bytes is a null reference.");
            retVal = false;
        }
        catch (ArgumentNullException) { }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
예제 #17
0
 public static void SaveContentsAsFile(string content, string path)
 {
     Byte[] info = new UTF8Encoding (true).GetBytes (content);
     FileStream fs = File.Create (path);
     fs.Write (info, 0, info.Length);
     fs.Close ();
 }
예제 #18
0
 /// <summary>
 /// Main constructor of the Tag. This reads information from the given filename and initializes all fields of the tag.
 /// It's important to know that this constructor has a considerable weight in term of processor time because it calculates two SHA1 hash:
 /// one for the entire file and one for the relevant tag information.
 /// </summary>
 /// <param name="filename">Filename from whom extract the information for the tag</param>
 public CompleteTag(string filename)
 {
     byte[] retVal;
     SHA1 crypto = new SHA1CryptoServiceProvider();
     using (FileStream file = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
     {
     retVal = crypto.ComputeHash(file);
     file.Close();
     }
     StringBuilder sb = new StringBuilder();
     for (int i = 0; i < retVal.Length; i++)
     {
     sb.Append(retVal[i].ToString("x2"));
     }
     this.FileHash= sb.ToString();
     this.FillTag(filename);
     System.Text.UTF8Encoding enc= new UTF8Encoding();
     byte[] tHashByte = crypto.ComputeHash(enc.GetBytes(this.contentString()));
     crypto.ComputeHash(tHashByte);
     sb.Clear();
     for (int i = 0; i < tHashByte.Length; i++)
     {
     sb.Append(tHashByte[i].ToString("x2"));
     }
     this.TagHash = sb.ToString();
 }
예제 #19
0
 public void PosTest2()
 {
     Char[] chars = new Char[] { };
     UTF8Encoding utf8 = new UTF8Encoding();
     int byteCount = utf8.GetByteCount(chars, 0, 0);
     Assert.Equal(0, byteCount);
 }
    public bool PosTest1()
    {
        bool retVal = true;

        // Add your scenario description here
        TestLibrary.TestFramework.BeginScenario("PosTest1: Verify method GetByteCount(Char[],Int32,Int32) with non-null char[]");

        try
        {
            Char[] chars = new Char[] {
                            '\u0023', 
                            '\u0025', 
                            '\u03a0', 
                            '\u03a3'  };

            UTF8Encoding utf8 = new UTF8Encoding();
            int byteCount = utf8.GetByteCount(chars, 1, 2);

        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
예제 #21
0
    public bool PosTest2()
    {
        bool retVal = true;

        // Add your scenario description here
        TestLibrary.TestFramework.BeginScenario("PosTest2: Two return value is not equal with two instance");

        try
        {
            UTF8Encoding utf8a = new UTF8Encoding(true);
            UTF8Encoding utf8b = new UTF8Encoding(true,true);

            if (utf8a.GetHashCode() == utf8b.GetHashCode())
            {
                TestLibrary.TestFramework.LogError("002.1", "Method GetHashCode Err.");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
예제 #22
0
    public bool PosTest2()
    {
        bool retVal = true;

        // Add your scenario description here
        TestLibrary.TestFramework.BeginScenario("PosTest2: Verify ctor(true,true) of UTF8Encoding");

        try
        {
            UTF8Encoding utf8 = new UTF8Encoding(true,true);

            if (utf8 == null)
            {
                TestLibrary.TestFramework.LogError("002.1", "Ctor of UTF8Encoding Err.");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
예제 #23
0
파일: AES.cs 프로젝트: SteinLabs/Gravity
	public AES()
	{
		RijndaelManaged rm = new RijndaelManaged();
		_encryptor = rm.CreateEncryptor(_key, _vector);
		_decryptor = rm.CreateDecryptor(_key, _vector);
		encoder = new UTF8Encoding();
	}
    public bool NegTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentOutOfRangeException is not thrown when charCount is less than zero.");

        try
        {
            UTF8Encoding utf8 = new UTF8Encoding();
            int charCount = -1;
            int maxByteCount = utf8.GetMaxByteCount(charCount);

            TestLibrary.TestFramework.LogError("101.1", "ArgumentOutOfRangeException is not thrown when charCount is less than zero. ");
            retVal = false;
        }
        catch (ArgumentOutOfRangeException) { }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
    public bool PosTest1()
    {
        bool retVal = true;

        // Add your scenario description here
        TestLibrary.TestFramework.BeginScenario("PosTest1: Verify method GetByteCount(string) with non-null string");

        try
        {
            String chars = "UTF8 Encoding Example";

            UTF8Encoding utf8 = new UTF8Encoding();
            int byteCount = utf8.GetByteCount(chars);

            if (byteCount != chars.Length)
            {
                TestLibrary.TestFramework.LogError("001.1", "Method GetByteCount Err.");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
    public bool PosTest2()
    {
        bool retVal = true;

        // Add your scenario description here
        TestLibrary.TestFramework.BeginScenario("PosTest2: Verify method GetByteCount(Char[],Int32,Int32) with null char[]");

        try
        {
            Char[] chars = new Char[] { };

            UTF8Encoding utf8 = new UTF8Encoding();
            int byteCount = utf8.GetByteCount(chars, 0, 0);

            if (byteCount != 0)
            {
                TestLibrary.TestFramework.LogError("001.1", "Method GetByteCount Err.");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
예제 #27
0
    public bool PosTest2()
    {
        bool retVal = true;

        // Add your scenario description here
        TestLibrary.TestFramework.BeginScenario("PosTest2: Verify a instance of UTF8Encoding equals to another one");

        try
        {
            UTF8Encoding utf8a = new UTF8Encoding();
            UTF8Encoding utf8b = new UTF8Encoding();

            if (utf8a.Equals(utf8b) != true)
            {
                TestLibrary.TestFramework.LogError("002.1", "Method Equals Err.");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
예제 #28
0
    public static DataSet ToDataSet(DataSetData dsd)
    {
        DataSet ds = new DataSet();
        UTF8Encoding encoding = new UTF8Encoding();
        Byte[] byteArray = encoding.GetBytes(dsd.DataXML);
        MemoryStream stream = new MemoryStream(byteArray);
        XmlReader reader = new XmlTextReader(stream);
        ds.ReadXml(reader);
        XDocument xd = XDocument.Parse(dsd.DataXML);
        foreach (DataTable dt in ds.Tables)
        {						
            var rs = from row in xd.Descendants(dt.TableName)
                     select row;			
 			
            int i = 0;
            foreach (var r in rs)
            {
                DataRowState state = (DataRowState)Enum.Parse(typeof(DataRowState), r.Attribute("RowState").Value);
                DataRow dr = dt.Rows[i];
                dr.AcceptChanges();
                if (state == DataRowState.Deleted)
                    dr.Delete();
                else if (state == DataRowState.Added)
                    dr.SetAdded();
                else if (state == DataRowState.Modified)
                    dr.SetModified();               
                i++;
            }
        }            
        return ds;
    }
예제 #29
0
    public bool PosTest2()
    {
        bool retVal = true;

        // Add your scenario description here
        TestLibrary.TestFramework.BeginScenario("PosTest2: Verify method GetBytes(String,Int32,Int32,Byte[],Int32) with null chars");

        try
        {
            Byte[] bytes;
            String chars = "";

            UTF8Encoding utf8 = new UTF8Encoding();

            int byteCount = chars.Length;
            bytes = new Byte[byteCount];
            int bytesEncodedCount = utf8.GetBytes(chars, 0, byteCount, bytes, 0);


            if (bytesEncodedCount != 0)
            {
                TestLibrary.TestFramework.LogError("002.1", "Method GetBytes Err.");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
예제 #30
0
        public static int Main(string[] args)
        {
            string referenceItemsResponsePath = null;
            string compileItemsResponsePath   = null;
            string outputPath      = null;
            string genListFilePath = null;
            bool   listAllFiles    = false;
            string processorPath   = null;
            string processorArgs   = null;

            for (int i = 0; i < args.Length; i++)
            {
                args[i] = args[i].Replace("\\\\", "\\");
            }

            ArgumentSyntax.Parse(args, syntax =>
            {
                syntax.DefineOption("ref", ref referenceItemsResponsePath, true, "The semicolon-separated list of references to compile against.");
                syntax.DefineOption("src", ref compileItemsResponsePath, true, "The semicolon-separated list of source files to compile.");
                syntax.DefineOption("out", ref outputPath, true, "The output path for the generated shaders.");
                syntax.DefineOption("genlist", ref genListFilePath, true, "The output file to store the list of generated files.");
                syntax.DefineOption("listall", ref listAllFiles, false, "Forces all generated files to be listed in the list file. By default, only bytecode files will be listed and not the original shader code.");
                syntax.DefineOption("processor", ref processorPath, false, "The path of an assembly containing IShaderSetProcessor types to be used to post-process GeneratedShaderSet objects.");
                syntax.DefineOption("processorargs", ref processorArgs, false, "Custom information passed to IShaderSetProcessor.");
            });

            referenceItemsResponsePath = NormalizePath(referenceItemsResponsePath);
            compileItemsResponsePath   = NormalizePath(compileItemsResponsePath);
            outputPath      = NormalizePath(outputPath);
            genListFilePath = NormalizePath(genListFilePath);
            processorPath   = NormalizePath(processorPath);

            if (!File.Exists(referenceItemsResponsePath))
            {
                Console.Error.WriteLine("Reference items response file does not exist: " + referenceItemsResponsePath);
                return(-1);
            }
            if (!File.Exists(compileItemsResponsePath))
            {
                Console.Error.WriteLine("Compile items response file does not exist: " + compileItemsResponsePath);
                return(-1);
            }
            if (!Directory.Exists(outputPath))
            {
                try
                {
                    Directory.CreateDirectory(outputPath);
                }
                catch
                {
                    Console.Error.WriteLine($"Unable to create the output directory \"{outputPath}\".");
                    return(-1);
                }
            }

            string[] referenceItems = File.ReadAllLines(referenceItemsResponsePath);
            string[] compileItems   = File.ReadAllLines(compileItemsResponsePath);

            List <MetadataReference> references = new List <MetadataReference>();

            foreach (string referencePath in referenceItems)
            {
                if (!File.Exists(referencePath))
                {
                    Console.Error.WriteLine("Error: reference does not exist: " + referencePath);
                    return(1);
                }

                using (FileStream fs = File.OpenRead(referencePath))
                {
                    references.Add(MetadataReference.CreateFromStream(fs, filePath: referencePath));
                }
            }

            List <SyntaxTree> syntaxTrees = new List <SyntaxTree>();

            foreach (string sourcePath in compileItems)
            {
                string fullSourcePath = Path.Combine(Environment.CurrentDirectory, sourcePath);
                if (!File.Exists(fullSourcePath))
                {
                    Console.Error.WriteLine("Error: source file does not exist: " + fullSourcePath);
                    return(1);
                }

                using (FileStream fs = File.OpenRead(fullSourcePath))
                {
                    SourceText text = SourceText.From(fs);
                    syntaxTrees.Add(CSharpSyntaxTree.ParseText(text, path: fullSourcePath));
                }
            }

            Compilation compilation = CSharpCompilation.Create(
                "ShaderGen.App.GenerateShaders",
                syntaxTrees,
                references,
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            HlslBackend      hlsl      = new HlslBackend(compilation);
            Glsl330Backend   glsl330   = new Glsl330Backend(compilation);
            GlslEs300Backend glsles300 = new GlslEs300Backend(compilation);
            Glsl450Backend   glsl450   = new Glsl450Backend(compilation);
            MetalBackend     metal     = new MetalBackend(compilation);

            LanguageBackend[] languages = new LanguageBackend[]
            {
                hlsl,
                glsl330,
                glsles300,
                glsl450,
                metal,
            };

            List <IShaderSetProcessor> processors = new List <IShaderSetProcessor>();

            if (processorPath != null)
            {
                try
                {
                    Assembly           assm           = Assembly.LoadFrom(processorPath);
                    IEnumerable <Type> processorTypes = assm.GetTypes().Where(
                        t => t.GetInterface(nameof(ShaderGen) + "." + nameof(IShaderSetProcessor)) != null);
                    foreach (Type type in processorTypes)
                    {
                        IShaderSetProcessor processor = (IShaderSetProcessor)Activator.CreateInstance(type);
                        processor.UserArgs = processorArgs;
                        processors.Add(processor);
                    }
                }
                catch (ReflectionTypeLoadException rtle)
                {
                    string msg = string.Join(Environment.NewLine, rtle.LoaderExceptions.Select(e => e.ToString()));
                    Console.WriteLine("FAIL: " + msg);
                    throw new Exception(msg);
                }
            }

            ShaderGenerator        sg = new ShaderGenerator(compilation, languages, processors.ToArray());
            ShaderGenerationResult shaderGenResult;

            try
            {
                shaderGenResult = sg.GenerateShaders();
            }
            catch (Exception e) when(!Debugger.IsAttached)
            {
                StringBuilder sb = new StringBuilder();

                sb.AppendLine("An error was encountered while generating shader code:");
                sb.AppendLine(e.ToString());
                Console.Error.WriteLine(sb.ToString());
                return(-1);
            }

            Encoding      outputEncoding     = new UTF8Encoding(false);
            List <string> generatedFilePaths = new List <string>();

            foreach (LanguageBackend lang in languages)
            {
                string extension = BackendExtension(lang);
                IReadOnlyList <GeneratedShaderSet> sets = shaderGenResult.GetOutput(lang);
                foreach (GeneratedShaderSet set in sets)
                {
                    string name = set.Name;
                    if (set.VertexShaderCode != null)
                    {
                        string vsOutName = name + "-vertex." + extension;
                        string vsOutPath = Path.Combine(outputPath, vsOutName);
                        File.WriteAllText(vsOutPath, set.VertexShaderCode, outputEncoding);
                        bool succeeded = CompileCode(
                            lang,
                            vsOutPath,
                            set.VertexFunction.Name,
                            ShaderFunctionType.VertexEntryPoint,
                            out string[] genPaths);
                        if (succeeded)
                        {
                            generatedFilePaths.AddRange(genPaths);
                        }
                        if (!succeeded || listAllFiles)
                        {
                            generatedFilePaths.Add(vsOutPath);
                        }
                    }
                    if (set.FragmentShaderCode != null)
                    {
                        string fsOutName = name + "-fragment." + extension;
                        string fsOutPath = Path.Combine(outputPath, fsOutName);
                        File.WriteAllText(fsOutPath, set.FragmentShaderCode, outputEncoding);
                        bool succeeded = CompileCode(
                            lang,
                            fsOutPath,
                            set.FragmentFunction.Name,
                            ShaderFunctionType.FragmentEntryPoint,
                            out string[] genPaths);
                        if (succeeded)
                        {
                            generatedFilePaths.AddRange(genPaths);
                        }
                        if (!succeeded || listAllFiles)
                        {
                            generatedFilePaths.Add(fsOutPath);
                        }
                    }
                    if (set.ComputeShaderCode != null)
                    {
                        string csOutName = name + "-compute." + extension;
                        string csOutPath = Path.Combine(outputPath, csOutName);
                        File.WriteAllText(csOutPath, set.ComputeShaderCode, outputEncoding);
                        bool succeeded = CompileCode(
                            lang,
                            csOutPath,
                            set.ComputeFunction.Name,
                            ShaderFunctionType.ComputeEntryPoint,
                            out string[] genPaths);
                        if (succeeded)
                        {
                            generatedFilePaths.AddRange(genPaths);
                        }
                        if (!succeeded || listAllFiles)
                        {
                            generatedFilePaths.Add(csOutPath);
                        }
                    }
                }
            }

            File.WriteAllLines(genListFilePath, generatedFilePaths);

            return(0);
        }
예제 #31
0
        private void btnContinue_Click(object sender, EventArgs e)
        {
            string             Hashb;
            List <Active_User> myUser = new List <Active_User>();

            try
            {
                myUser = db.Active_User.Where(someuser => someuser.Username == txtEmail.Text).ToList();
            }
            catch (Exception)
            {
                throw;
            }
            try
            {
                Active_User emp = myUser[0];
                clsGlobals.Userlogin = myUser[0];
            }
            catch (Exception)
            {
                throw;
            }

            db.SaveChanges();
            try
            {
                SHA1CryptoServiceProvider sh = new SHA1CryptoServiceProvider();
                UTF8Encoding  utf8           = new UTF8Encoding();
                string        hash           = BitConverter.ToString(sh.ComputeHash(utf8.GetBytes(txtPassword.Text)));
                SqlConnection con            = new SqlConnection("Data Source=.;Initial Catalog=SP;Integrated Security=True");
                SqlCommand    cmd            = new SqlCommand("select pass from Active_User where Username=@Username", con);
                cmd.Parameters.AddWithValue("@Username", txtEmail.Text);
                con.Open();
                SqlDataReader dr = cmd.ExecuteReader();
                dr.Read();

                Hashb = dr[0].ToString();
                con.Close();
                if (txtEmail.Text == "")
                {
                    lbWarningEmail.Visible = true;
                    //label4.Text = "Please Provide the username you wish to reset";

                    //correct = false;
                }
                if (txtPassword.Text == "")
                {
                    lbWarningPassword.Visible = true;
                    //label4.Text = "Please Provide the username you wish to reset";

                    //correct = false;
                }
                if (hash == Hashb)
                {
                    MessageBox.Show("Authorization was successful");
                    this.Dispose();
                    Users.FrmResetPassword rs = new Users.FrmResetPassword(3);
                    rs.ShowDialog();
                    rs.Focus();
                }
                else
                {
                    MessageBox.Show("Authorization failed, please try again");
                    lbWarningEmail.Visible    = true;
                    lbWarningPassword.Visible = true;
                }
            }
            catch (InvalidOperationException ex)
            {
                MessageBox.Show("Error has occured:" + ex.Message);
            }
        }
예제 #32
0
        static void Main(string[] args)
        {
            Options options = null;

            try
            {
                ParseCommandlineParameters(args, out options);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            if (options == null)
            {
                throw new ArgumentException(nameof(options));
            }

            // ReSharper disable once PossibleNullReferenceException
            using (_logStream = string.IsNullOrWhiteSpace(options.LogFile)
                ? Console.OpenStandardOutput()
                : File.OpenWrite(ReplaceWildCards(options.LogFile)))
            {
                try
                {
                    var maxTasks = SetMaxConcurrencyLevel(options);

                    if (options.InputIsList)
                    {
                        _itemsToConvert = new ConcurrentQueue <ConversionItem>();
                        _itemsConverted = new ConcurrentQueue <ConversionItem>();

                        WriteToLog($"Reading input file '{options.Input}'");
                        var lines = File.ReadAllLines(options.Input);
                        foreach (var line in lines)
                        {
                            var inputUri   = new ConvertUri(line);
                            var outputPath = Path.GetFullPath(options.Output);

                            var outputFile = inputUri.IsFile
                                ? Path.GetFileName(inputUri.AbsolutePath)
                                : FileManager.RemoveInvalidFileNameChars(inputUri.ToString());

                            outputFile = Path.ChangeExtension(outputFile, ".pdf");

                            _itemsToConvert.Enqueue(new ConversionItem(inputUri,
                                                                       // ReSharper disable once AssignNullToNotNullAttribute
                                                                       Path.Combine(outputPath, outputFile)));
                        }

                        WriteToLog($"{_itemsToConvert.Count} items read");

                        if (options.UseMultiThreading)
                        {
                            _workerTasks = new List <Task>();

                            WriteToLog($"Starting {maxTasks} processing tasks");
                            for (var i = 0; i < maxTasks; i++)
                            {
                                var i1 = i;
                                _workerTasks.Add(_taskFactory.StartNew(() =>
                                                                       ConvertWithTask(options, (i1 + 1).ToString())));
                            }

                            WriteToLog("Started");

                            // Waiting until all tasks are finished
                            foreach (var task in _workerTasks)
                            {
                                task.Wait();
                            }
                        }
                        else
                        {
                            ConvertWithTask(options, null);
                        }

                        // Write conversion information to output file
                        using (var output = File.OpenWrite(options.Output))
                        {
                            foreach (var itemConverted in _itemsConverted)
                            {
                                var bytes = new UTF8Encoding(true).GetBytes(itemConverted.OutputLine);
                                output.Write(bytes, 0, bytes.Length);
                            }
                        }
                    }
                    else
                    {
                        Convert(options);
                    }

                    Environment.Exit(0);
                }
                catch (Exception exception)
                {
                    WriteToLog(exception.StackTrace + ", " + exception.Message);
                    Environment.Exit(1);
                }
            }
        }
 public bool LoadData(string filename)
 {
     if (!File.Exists(filename))
     {
         return(false);
     }
     using (FileStream fs = new FileStream(filename, FileMode.Open))
     {
         string s = "";
         using (BufferedStream bs = new BufferedStream(fs))
         {
             byte[]       b    = new byte[fs.Length];
             UTF8Encoding temp = new UTF8Encoding(true);
             while (bs.Read(b, 0, b.Length) > 0)
             {
                 s += temp.GetString(b);
             }
         }
         s = s.Replace("\r", "");
         var strs = s.Split('\n');
         if (strs[0].Contains("CountLeveles"))
         {                //считываем кол-во уровней
             int count = Convert.ToInt32(strs[0].Split(':')[1]);
             if (parkingStages != null)
             {
                 parkingStages.Clear();
             }
             parkingStages = new List <ClassArray <ITechnique> >(count);
         }
         else
         {                 /// если нет такой записи, то это не те данные
             return(false);
         }
         int counter = -1;
         for (int i = 1; i < strs.Length; ++i)
         {                //идем по считанным записям
             if (strs[i] == "Level")
             {            //Начинаем новый уровень
                 counter++;
                 parkingStages.Add(new ClassArray <ITechnique>(countPlaces, null));
             }
             else if (strs[i].Split(':')[0] == "Plane")
             {
                 ITechnique plane  = new Plane(strs[i].Split(':')[1]);
                 int        number = parkingStages[counter] + plane;
                 if (number == -1)
                 {
                     return(false);
                 }
             }
             else if (strs[i].Split(':')[0] == "Bombardir")
             {
                 ITechnique plane  = new Bombardir(strs[i].Split(':')[1]);
                 int        number = parkingStages[counter] + plane;
                 if (number == -1)
                 {
                     return(false);
                 }
             }
         }
     }
     return(true);
 }
예제 #34
0
        protected static int GetUTF8StringLength(string s)
        {
            UTF8Encoding enc = new UTF8Encoding();

            return(enc.GetByteCount(s));
        }
예제 #35
0
        public static void GetRSSFeed(string rssfeedlink, string append2filename, string queryString)
        {
            XmlReader reader   = XmlReader.Create(rssfeedlink); //Default is ENglish
            string    fileName = "";

            fileName = @"C:\Temp\" + DateTime.Today.Date.DayOfWeek.ToString() + append2filename + ".txt";
            FileStream fsc = File.Create(fileName);

            fsc.Close();
            SyndicationFeed feed = SyndicationFeed.Load(reader);

            foreach (SyndicationItem item in feed.Items)
            {
                string strTitle = item.Title.Text.ToString().Replace("Azure", "#Azure") + " #azure4developers";
                Console.WriteLine(strTitle);
                string strNewlink = item.Links[0].Uri.ToString() + queryString;

                string strShortenLink = "http://tinyurl.com/api-create.php?url=" + strNewlink;
                var    request        = WebRequest.Create(strShortenLink);
                var    res            = request.GetResponse();
                string strreceiveShortenLink;
                using (var responsereader = new StreamReader(res.GetResponseStream()))
                {
                    strreceiveShortenLink = responsereader.ReadToEnd();

                    Console.WriteLine(strShortenLink);
                }

                try
                {
                    // Create a new file
                    using (FileStream fs = File.Open(fileName, FileMode.Append))
                    {
                        byte[] newline = Encoding.ASCII.GetBytes(Environment.NewLine);
                        // Add some text to file
                        Byte[] title = new UTF8Encoding(true).GetBytes(strTitle);
                        fs.Write(title, 0, title.Length);
                        fs.Write(newline, 0, newline.Length);

                        Byte[] publishDate = new UTF8Encoding(true).GetBytes(item.PublishDate.ToString());
                        fs.Write(publishDate, 0, publishDate.Length);
                        fs.Write(newline, 0, newline.Length);

                        byte[] summary = new UTF8Encoding(true).GetBytes(item.Summary.Text.ToString());
                        fs.Write(summary, 0, summary.Length);
                        fs.Write(newline, 0, newline.Length);

                        byte[] link = new UTF8Encoding(true).GetBytes(strreceiveShortenLink);
                        fs.Write(link, 0, link.Length);
                        fs.Write(newline, 0, newline.Length);
                        fs.Write(newline, 0, newline.Length);
                        fs.Write(newline, 0, newline.Length);
                        fs.Write(newline, 0, newline.Length);
                        fs.Write(newline, 0, newline.Length);
                        fs.Write(newline, 0, newline.Length);

                        fs.Close();
                    }
                }
                catch (Exception Ex)
                {
                    Console.WriteLine(Ex.ToString());
                }
            }
        }
예제 #36
0
        private Hashtable CopyInventoryFromNotecard(Hashtable mDhttpMethod, UUID agentID)
        {
            OSDMap            rm           = (OSDMap)OSDParser.DeserializeLLSDXml((string)mDhttpMethod["requestbody"]);
            UUID              FolderID     = rm["folder-id"].AsUUID();
            UUID              ItemID       = rm["item-id"].AsUUID();
            UUID              NotecardID   = rm["notecard-id"].AsUUID();
            UUID              ObjectID     = rm["object-id"].AsUUID();
            InventoryItemBase notecardItem = null;

            if (ObjectID != UUID.Zero)
            {
                ISceneChildEntity part = m_scene.GetSceneObjectPart(ObjectID);
                if (part != null)
                {
                    TaskInventoryItem item = part.Inventory.GetInventoryItem(NotecardID);
                    if (m_scene.Permissions.CanCopyObjectInventory(NotecardID, ObjectID, agentID))
                    {
                        notecardItem = new InventoryItemBase(NotecardID, agentID)
                        {
                            AssetID = item.AssetID
                        };
                    }
                }
            }
            else
            {
                notecardItem = m_scene.InventoryService.GetItem(new InventoryItemBase(NotecardID));
            }
            if (notecardItem != null && notecardItem.Owner == agentID)
            {
                AssetBase asset = m_scene.AssetService.Get(notecardItem.AssetID.ToString());
                if (asset != null)
                {
                    UTF8Encoding enc =
                        new UTF8Encoding();
                    List <string> notecardData  = SLUtil.ParseNotecardToList(enc.GetString(asset.Data));
                    AssetNotecard noteCardAsset = new AssetNotecard(UUID.Zero, asset.Data);
                    noteCardAsset.Decode();
                    bool found       = false;
                    UUID lastOwnerID = UUID.Zero;
#if (!ISWIN)
                    foreach (InventoryItem notecardObjectItem in noteCardAsset.EmbeddedItems)
                    {
                        if (notecardObjectItem.UUID == ItemID)
                        {
                            //Make sure that it exists
                            found       = true;
                            lastOwnerID = notecardObjectItem.OwnerID;
                            break;
                        }
                    }
#else
                    foreach (InventoryItem notecardObjectItem in noteCardAsset.EmbeddedItems.Where(notecardObjectItem => notecardObjectItem.UUID == ItemID))
                    {
                        //Make sure that it exists
                        found       = true;
                        lastOwnerID = notecardObjectItem.OwnerID;
                        break;
                    }
#endif
                    if (found)
                    {
                        InventoryItemBase  item            = null;
                        ILLClientInventory inventoryModule = m_scene.RequestModuleInterface <ILLClientInventory>();
                        if (inventoryModule != null)
                        {
                            item = inventoryModule.GiveInventoryItem(agentID, lastOwnerID, ItemID, FolderID);
                        }

                        IClientAPI client;
                        m_scene.ClientManager.TryGetValue(agentID, out client);
                        if (item != null)
                        {
                            client.SendBulkUpdateInventory(item);
                        }
                        else
                        {
                            client.SendAlertMessage("Failed to retrieve item");
                        }
                    }
                }
            }

            //Send back data
            Hashtable responsedata = new Hashtable();
            responsedata["int_response_code"]   = 200; //501; //410; //404;
            responsedata["content_type"]        = "text/plain";
            responsedata["keepalive"]           = false;
            responsedata["str_response_string"] = "";
            return(responsedata);
        }
예제 #37
0
        //Format and construct the body of the printer string
        private void sendZplReceipt(IConnection printerConnection)
        {
            /*
             * This routine is provided to you as an example of how to create a variable length label with user specified data.
             * The basic flow of the example is as follows
             *
             *  Header of the label with some variable data
             *  REMOVED TO TAKE THE EXAMPLE AS SIMPLE AS POSSIBLE Body of the label
             *  REMOVED TO TAKE THE EXAMPLE AS SIMPLE AS POSSIBLE     Loops thru user content and creates small line items of printed material
             *  REMOVED TO TAKE THE EXAMPLE AS SIMPLE AS POSSIBLE Footer of the label
             *
             * As you can see, there are some variables that the user provides in the header, body and footer, and this routine uses that to build up a proper ZPL string for printing.
             * Using this same concept, you can create one label for your receipt header, one for the body and one for the footer. The body receipt will be duplicated as many items as there are in your variable data
             *
             */
            System.String tmpHeader =

/*
 * Some basics of ZPL. Find more information here : http://www.zebra.com
 *
 * ^XA indicates the beginning of a label
 * ^PW sets the width of the label (in dots)
 * ^MNN sets the printer in continuous mode (variable length receipts only make sense with variably sized labels)
 * ^LL sets the length of the label (we calculate this value at the end of the routine)
 * ^LH sets the reference axis for printing.
 *  You will notice we change this positioning of the 'Y' axis (length) as we build up the label. Once the positioning is changed, all new fields drawn on the label are rendered as if '0' is the new home position
 * ^FO sets the origin of the field relative to Label Home ^LH
 * ^A sets font information
 * ^FD is a field description
 * ^GB is graphic boxes (or lines)
 * ^B sets barcode information
 * ^XZ indicates the end of a label
 */

                "^XA" +
                "^ FO90,200 ^ GFA,7638,7638,38,,::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::g0IFEIFEIF81IF81IFI07FFC0IFC3F9FE7KF8,g0IFEIFEIFE1IFC1IFI07IF0IFE3F9FE7KF8,g0IFEIFEJF1IFE1IFI07IF8JF3F9FF7KF8,:g0IFEIFEJF9JF1IFI07IFCJFBF9FF7KF8,:g0IFEIFEFF7F9JF1IF8007IFCLF9NF8,gG03FCFF80FF7F9FEFF1IF8007FBFCFF7IF9JF87FE,gG03FCFF00FF7F9FEFF1IF8007F9FCFF7IF9JF83F8,gG03FCFF00FF7F9FEFF1IF8007F9FEFF7IF9JF83F8,gG07F8FF00FF7F9FEFF3IF8007F9JF7IF9JF83F8,:gG0FF8FF00JF9JF3IF8007F9FCJFBF9JF83F8,gG0FF0IFCJF1JF3IF8007FBFCJFBF9JF83F8,gG0FF0IFCIFE1IFE3IF8007IFCJF3F9JF83F8,g01FF0IFCIFE1IFE3IF8007IFCJF3F9JF83F8,g01FE0IFCJF1IFC3IFC007IFCIFE3F9JF83F8,g01FE0IFCJF1IFE3FBFC007IF8JF3F9JF83F8,g03FC0IFCJF9IFE3FBFC007IF8JF3F9JF83F8,g03FC0IFCFF7F9JF3FBFC007IF0JFBF9JF83F8,g03FC0FF00FF3F9FEFF3FBFC007FFE0FF7FBF9JF83F8,g07F80FF00FF3F9FEFF7F9FC007F800FF7FBF9JF83F8,g07F80FF00FF3F9FEFF7IFC007F800FF7FBF9JF83F8,:g0FF00FF00FF3F9FEFF7IFC007F800FF7FBF9JF83F8,:Y01FF00FF00FF7F9FEFF7IFC007F800FF7FBF9JF83F8,Y01IFEIFEJF9FEFF7IFE007F800FF7FBF9JF83F8,Y01IFEIFEJF9FEFF7IFE007F800FF7FBF9FEFF83F8,Y01IFEIFEJF1FEJF1FE007F800FF7FBF9FEFF83F8,:Y01IFEIFEJF1FEJF1FE007F800FF7FBF9FE7F83F8,Y01IFEIFEIFE1FEJF0FE007F800FF7FBF9FE7F83F8,Y01IFEIFEIFC1FEJF0FE007F800FF7FBF9FE7F83F8,,:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::^ FS"
                + "\r\n" +
                "^FO130,320" + "\r\n" + "^ASN,40,40" + "\r\n" + "^FDAbove is an Image^FS" + "\r\n" +
                "^ FO40,40" +
                "^ GB500,1050,2 ^ FS" +
                "\r\n" +
                "\r\n" +
                "^POI^PW700^MNN^LL500^LH50,60" +
                "\r\n" +
                " FS" +
                "\r\n" +
                "^FO50,400" + "\r\n" + "^ASN,15,15" + "\r\n" + "^FDDate :^FS" + "\r\n" +
                "^FO350,400" + "\r\n" + "^ASN,15,15" + "\r\n" + "^FDTIME :^FS" + "\r\n" +
                "^FO50,450" + "\r\n" + "^ASN,25,25" + "\r\n" + "^FDEGM # :^FS" + "\r\n" +
                "^FO50,500" + "\r\n" + "^ASN,25,25" + "\r\n" + "^FDPlayer Name :^FS" +
                "^FO50,550" + "\r\n" + "^ASN,25,25" + "\r\n" + "^FDCredit & Club Meter :^FS" +
                "\r\n" +
                "^ FO50,800 ^ GB400,0,4,^ FS" +
                "^FO50,850" + "\r\n" + "^A0,N,25,30" + "\r\n" + "^FDLocked by :^FS" +
                "\r\n\n\n\n" +
                "^FO50,300" + "\r\n\n\n\n\n\n\n\n\n" + "^GB350,5,5,B,0^FS" + "^ XZ";
            DateTime date       = DateTime.Now;
            string   dateString = date.ToString("MMM dd, yyyy");
            string   header     = string.Format(tmpHeader, dateString);
            var      t          = new UTF8Encoding().GetBytes(header);

            printerConnection.Write(t);
        }
예제 #38
0
        public void ChecksumAndBOM()
        {
            const string source            = "Hello, World!";
            var          checksumAlgorithm = SourceHashAlgorithm.Sha1;
            var          encodingNoBOM     = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
            var          encodingBOM       = new UTF8Encoding(encoderShouldEmitUTF8Identifier: true);

            var checksumNoBOM = ImmutableArray.Create <byte>(0xa, 0xa, 0x9f, 0x2a, 0x67, 0x72, 0x94, 0x25, 0x57, 0xab, 0x53, 0x55, 0xd7, 0x6a, 0xf4, 0x42, 0xf8, 0xf6, 0x5e, 0x1);
            var checksumBOM   = ImmutableArray.Create <byte>(0xb2, 0x19, 0x0, 0x9b, 0x61, 0xce, 0xcd, 0x50, 0x7b, 0x2e, 0x56, 0x3c, 0xc0, 0xeb, 0x96, 0xe2, 0xa1, 0xd9, 0x3f, 0xfc);

            // SourceText from string. Checksum should include BOM from explicit encoding.
            VerifyChecksum(SourceText.From(source, encodingNoBOM, checksumAlgorithm), checksumNoBOM);
            VerifyChecksum(SourceText.From(source, encodingBOM, checksumAlgorithm), checksumBOM);

            var bytesNoBOM = new byte[] { 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x21 };
            var bytesBOM   = new byte[] { 0xef, 0xbb, 0xbf, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x21 };

            var streamNoBOM = new MemoryStream(bytesNoBOM);
            var streamBOM   = new MemoryStream(bytesBOM);

            // SourceText from bytes no BOM. Checksum should ignore explicit encoding.
            VerifyChecksum(SourceText.From(bytesNoBOM, bytesNoBOM.Length, null, checksumAlgorithm), checksumNoBOM);
            VerifyChecksum(SourceText.From(bytesNoBOM, bytesNoBOM.Length, encodingNoBOM, checksumAlgorithm), checksumNoBOM);
            VerifyChecksum(SourceText.From(bytesNoBOM, bytesNoBOM.Length, encodingBOM, checksumAlgorithm), checksumNoBOM);

            // SourceText from bytes with BOM. Checksum should include BOM.
            VerifyChecksum(SourceText.From(bytesBOM, bytesBOM.Length, null, checksumAlgorithm), checksumBOM);
            VerifyChecksum(SourceText.From(bytesBOM, bytesBOM.Length, encodingNoBOM, checksumAlgorithm), checksumBOM);
            VerifyChecksum(SourceText.From(bytesBOM, bytesBOM.Length, encodingBOM, checksumAlgorithm), checksumBOM);

            // SourceText from stream no BOM. Checksum should ignore explicit encoding.
            VerifyChecksum(SourceText.From(streamNoBOM, null, checksumAlgorithm), checksumNoBOM);
            VerifyChecksum(SourceText.From(streamNoBOM, encodingNoBOM, checksumAlgorithm), checksumNoBOM);
            VerifyChecksum(SourceText.From(streamNoBOM, encodingBOM, checksumAlgorithm), checksumNoBOM);

            // SourceText from stream with BOM. Checksum should include BOM.
            VerifyChecksum(SourceText.From(streamBOM, null, checksumAlgorithm), checksumBOM);
            VerifyChecksum(SourceText.From(streamBOM, encodingNoBOM, checksumAlgorithm), checksumBOM);
            VerifyChecksum(SourceText.From(streamBOM, encodingBOM, checksumAlgorithm), checksumBOM);

            // LargeText from stream no BOM. Checksum should ignore explicit encoding.
            VerifyChecksum(LargeText.Decode(streamNoBOM, encodingNoBOM, checksumAlgorithm, throwIfBinaryDetected: false, canBeEmbedded: false), checksumNoBOM);
            VerifyChecksum(LargeText.Decode(streamNoBOM, encodingBOM, checksumAlgorithm, throwIfBinaryDetected: false, canBeEmbedded: false), checksumNoBOM);

            // LargeText from stream with BOM. Checksum should include BOM.
            VerifyChecksum(LargeText.Decode(streamBOM, encodingNoBOM, checksumAlgorithm, throwIfBinaryDetected: false, canBeEmbedded: false), checksumBOM);
            VerifyChecksum(LargeText.Decode(streamBOM, encodingBOM, checksumAlgorithm, throwIfBinaryDetected: false, canBeEmbedded: false), checksumBOM);

            // LargeText from writer no BOM. Checksum includes BOM
            // from explicit encoding. This is inconsistent with the
            // LargeText cases above but LargeTextWriter is only used
            // for unsaved edits where the checksum is ignored.
            VerifyChecksum(FromLargeTextWriter(source, encodingNoBOM, checksumAlgorithm), checksumNoBOM);
            VerifyChecksum(FromLargeTextWriter(source, encodingBOM, checksumAlgorithm), checksumBOM);

            // SourceText from string with changes. Checksum includes BOM from explicit encoding.
            VerifyChecksum(FromChanges(SourceText.From(source, encodingNoBOM, checksumAlgorithm)), checksumNoBOM);
            VerifyChecksum(FromChanges(SourceText.From(source, encodingBOM, checksumAlgorithm)), checksumBOM);

            // SourceText from stream with changes, no BOM. Checksum includes BOM
            // from explicit encoding. This is inconsistent with the SourceText cases but
            // "with changes" is only used for unsaved edits where the checksum is ignored.
            VerifyChecksum(FromChanges(SourceText.From(streamNoBOM, encodingNoBOM, checksumAlgorithm)), checksumNoBOM);
            VerifyChecksum(FromChanges(SourceText.From(streamNoBOM, encodingBOM, checksumAlgorithm)), checksumBOM);

            // SourceText from stream with changes, with BOM. Checksum includes BOM.
            VerifyChecksum(FromChanges(SourceText.From(streamBOM, encodingNoBOM, checksumAlgorithm)), checksumBOM);
            VerifyChecksum(FromChanges(SourceText.From(streamBOM, encodingBOM, checksumAlgorithm)), checksumBOM);
        }
예제 #39
0
    public static void usp_InsertSessionInformation(string SessionID, short goal1, short goal2,
                                                    short minor_goal, short howto_goal, string name, short age, string gender, string UserId,
                                                    short q1, short q2, short q3, short q4, short q5,
                                                    float fat, float sugar, float fruits, float iron, float calcium, float habits,
                                                    string mealInfoXML)
    {
        // Notes:
        // 2007-09-25 by kjt: I had to pass in the Guids as strings and then created new ones set to the same ID
        // in order to get this to handle GUIDS correctly.

        DataSet      mealInfo = new DataSet();
        UTF8Encoding encoding = new UTF8Encoding();

        using (MemoryStream ms = new MemoryStream(encoding.GetBytes(mealInfoXML)))
        {
            mealInfo.ReadXml(ms);
        }

        // Put your code here
        SqlConnection con = new SqlConnection("Context Connection=true");
        SqlCommand    cmd = new SqlCommand();

        cmd.Connection = con;
        // Added open statement:
        con.Open();

        Guid guid = new Guid(SessionID);
        // This is most likely no longer needed because we're only saving the session information on completion.

        /*
         * //First wipe out any existing information with this SessionID (since we don't want the same person
         * //being counted twice
         *
         * string deleteSession = "DELETE FROM Session WHERE SessionID = " + SessionID;
         *
         * cmd.CommandText = deleteSession;
         * cmd.ExecuteNonQuery();
         *
         * */

        //Now insert the session information into the database
        string insertSession = "INSERT session (session_id, goal1, goal2, minor_goal, howto_goal, name"
                               + ", age, gender, person_id, q1, q2, q3, q4, q5, calcium, iron, habits, fruits"
                               + ", sugar, fat, created)"
                               + "VALUES (@SessionID,@goal1,@goal2,@minor_goal,@howto_goal,@name"
                               + ",@age,@gender, @UserId,@q1,@q2,@q3,@q4,@q5,@calcium,@iron,@habits,@fruits"
                               + ",@sugar,@fat,@created)";

        cmd.CommandText = insertSession;
        cmd.Parameters.AddWithValue("@SessionID", guid);
        cmd.Parameters.AddWithValue("@goal1", goal1);
        cmd.Parameters.AddWithValue("@goal2", goal2);
        cmd.Parameters.AddWithValue("@minor_goal", minor_goal);
        cmd.Parameters.AddWithValue("@howto_goal", howto_goal);
        cmd.Parameters.AddWithValue("@name", name);
        cmd.Parameters.AddWithValue("@age", age);
        cmd.Parameters.AddWithValue("@gender", gender);
        cmd.Parameters.AddWithValue("@UserId", new Guid(UserId));
        cmd.Parameters.AddWithValue("@q1", q1);
        cmd.Parameters.AddWithValue("@q2", q2);
        cmd.Parameters.AddWithValue("@q3", q3);
        cmd.Parameters.AddWithValue("@q4", q4);
        cmd.Parameters.AddWithValue("@q5", q5);

        cmd.Parameters.AddWithValue("@fat", fat);
        cmd.Parameters.AddWithValue("@sugar", sugar);
        cmd.Parameters.AddWithValue("@fruits", fruits);
        cmd.Parameters.AddWithValue("@iron", iron);
        cmd.Parameters.AddWithValue("@calcium", calcium);
        cmd.Parameters.AddWithValue("@habits", habits);

        cmd.Parameters.AddWithValue("@created", DateTime.Now);

        /*
         * string insertSession = "exec dbo.session_CreateSession '" +guid + "'," + goal1 + "," + goal2 + "," + minor_goal + "," + howto_goal + ",'" + name + "'," + age + "," + q1 + age + "," + q2 + "," + q3 + "," + q4 + "," + q5;
         * cmd.CommandText = insertSession;
         * */
        cmd.ExecuteNonQuery();

        cmd.Parameters.Clear();//remove all parameters

        //Now insert the foodIDs to from the mealInfo dataSet into the db
        if (mealInfo.Tables.Count != 0)
        {
            foreach (DataRow dr in mealInfo.Tables[0].Rows)
            {
                //for each row, insert the relevant information into the database
                string insertMeal = "INSERT Meal (session_goal_id, food_id, quantity) VALUES (@Session_goal_id, @food_id, @quantity)";
                cmd.CommandText = insertMeal;

                cmd.Parameters.AddWithValue("@Session_goal_id", guid);
                cmd.Parameters.AddWithValue("@food_id", dr["foodid"]);
                cmd.Parameters.AddWithValue("@quantity", dr["Quantity"]);

                cmd.ExecuteNonQuery();
                cmd.Parameters.Clear();
            }
        }

        // Added statement to close database connection.
        con.Close();
    }
예제 #40
0
        /// <summary>
        /// Grava XML com algumas informações do aplicativo, dentre elas os dados do certificado digital configurado nos parâmetros, versão, última modificação, etc.
        /// </summary>
        /// <param name="sArquivo">Pasta e nome do arquivo XML a ser gravado com as informações</param>
        public void GravarXMLInformacoes(string sArquivo)
        {
            int emp = Empresas.FindEmpresaByThread();

            string cStat   = "1";
            string xMotivo = "Consulta efetuada com sucesso";

            //Ler os dados do certificado digital
            string sSubject = "";
            string sValIni  = "";
            string sValFin  = "";

            CertificadoDigital cert = new CertificadoDigital();

            if (cert.PrepInfCertificado(Empresas.Configuracoes[emp]))
            {
                sSubject = cert.sSubject;
                sValIni  = cert.dValidadeInicial.ToString();
                sValFin  = cert.dValidadeFinal.ToString();
            }
            else
            {
                if (!Empresas.Configuracoes[emp].UsaCertificado)
                {
                    xMotivo = "Empresa sem certificado digital informado e/ou não necessário";
                }
                else
                {
                    cStat   = "2";
                    xMotivo = "Certificado digital não foi localizado";
                }
            }

            //danasa 22/7/2011
            //pega a data da ultima modificacao do 'uninfe.exe' diretamente porque pode ser que esteja sendo executado o servico
            //então, precisamos dos dados do uninfe.exe e não do servico
            string dtUltModif;
            URLws  item;
            string tipo = "";

            dtUltModif = File.GetLastWriteTime(Propriedade.NomeAplicacao + ".exe").ToString("dd/MM/yyyy - HH:mm:ss");

            //Gravar o XML com as informações do aplicativo
            try
            {
                bool   isXml = false;
                object oXmlGravar;

                if (Path.GetExtension(sArquivo).ToLower() == ".txt")
                {
                    oXmlGravar = new System.IO.StringWriter();
                }
                else
                {
                    isXml = true;

                    XmlWriterSettings oSettings = new XmlWriterSettings();
                    UTF8Encoding      c         = new UTF8Encoding(true);

                    //Para começar, vamos criar um XmlWriterSettings para configurar nosso XML
                    oSettings.Encoding            = c;
                    oSettings.Indent              = true;
                    oSettings.IndentChars         = "";
                    oSettings.NewLineOnAttributes = false;
                    oSettings.OmitXmlDeclaration  = false;

                    //Agora vamos criar um XML Writer
                    oXmlGravar = XmlWriter.Create(sArquivo, oSettings);
                }
                //Abrir o XML
                if (isXml)
                {
                    ((XmlWriter)oXmlGravar).WriteStartDocument();
                    ((XmlWriter)oXmlGravar).WriteStartElement("retConsInf");
                }
                Functions.GravaTxtXml(oXmlGravar, NFe.Components.TpcnResources.cStat.ToString(), cStat);
                Functions.GravaTxtXml(oXmlGravar, NFe.Components.TpcnResources.xMotivo.ToString(), xMotivo);

                //Dados do certificado digital
                if (isXml)
                {
                    ((XmlWriter)oXmlGravar).WriteStartElement("DadosCertificado");
                }
                Functions.GravaTxtXml(oXmlGravar, "sSubject", sSubject);
                Functions.GravaTxtXml(oXmlGravar, "dValIni", sValIni);
                Functions.GravaTxtXml(oXmlGravar, "dValFin", sValFin);
                if (isXml)
                {
                    ((XmlWriter)oXmlGravar).WriteEndElement();        //DadosCertificado
                }
                //Dados gerais do Aplicativo
                if (isXml)
                {
                    ((XmlWriter)oXmlGravar).WriteStartElement("DadosUniNfe");
                }
                Functions.GravaTxtXml(oXmlGravar, NFe.Components.TpcnResources.versao.ToString(), Propriedade.Versao);
                Functions.GravaTxtXml(oXmlGravar, "dUltModif", dtUltModif);
                Functions.GravaTxtXml(oXmlGravar, "PastaExecutavel", Propriedade.PastaExecutavel);
                Functions.GravaTxtXml(oXmlGravar, "NomeComputador", Environment.MachineName);
                //danasa 22/7/2011
                Functions.GravaTxtXml(oXmlGravar, "ExecutandoPeloServico", Propriedade.ServicoRodando.ToString());
                Functions.GravaTxtXml(oXmlGravar, "ConexaoInternet", Functions.IsConnectedToInternet().ToString());

                if (isXml)
                {
                    ((XmlWriter)oXmlGravar).WriteEndElement();        //DadosUniNfe
                }
                //Dados das configurações do aplicativo
                if (isXml)
                {
                    ((XmlWriter)oXmlGravar).WriteStartElement(NFeStrConstants.nfe_configuracoes);
                }
                //Functions.GravaTxtXml(oXmlGravar, NFe.Components.NFeStrConstants.DiretorioSalvarComo, Empresas.Configuracoes[emp].DiretorioSalvarComo.ToString());

                bool hasFTP = false;
                foreach (var pT in Empresas.Configuracoes[emp].GetType().GetProperties())
                {
                    if (pT.CanWrite)
                    {
                        if (pT.Name.Equals("diretorioSalvarComo"))
                        {
                            continue;
                        }

                        if (isXml)
                        {
                            if (!hasFTP && pT.Name.StartsWith("FTP"))
                            {
                                ((XmlWriter)oXmlGravar).WriteStartElement("FTP");
                                hasFTP = true;
                            }
                            else
                            if (hasFTP && !pT.Name.StartsWith("FTP"))
                            {
                                ((XmlWriter)oXmlGravar).WriteEndElement();
                                hasFTP = false;
                            }
                        }
                        object v = pT.GetValue(Empresas.Configuracoes[emp], null);
                        NFe.Components.Functions.GravaTxtXml(oXmlGravar, pT.Name, v == null ? "" : v.ToString());
                    }
                }
                if (hasFTP && isXml)
                {
                    ((XmlWriter)oXmlGravar).WriteEndElement();
                }

                ///
                /// o ERP poderá verificar se determinado servico está definido no UniNFe
                ///
                foreach (webServices list in WebServiceProxy.webServicesList)
                {
                    if (list.ID == Empresas.Configuracoes[emp].UnidadeFederativaCodigo)
                    {
                        if (isXml)
                        {
                            ((XmlWriter)oXmlGravar).WriteStartElement(list.UF);
                        }
                        if (Empresas.Configuracoes[emp].AmbienteCodigo == 2)
                        {
                            item = list.LocalHomologacao;
                            if (isXml)
                            {
                                ((XmlWriter)oXmlGravar).WriteStartElement("Homologacao");
                            }
                            else
                            {
                                tipo = list.UF + ".Homologacao.";
                            }
                        }
                        else
                        {
                            item = list.LocalProducao;
                            if (isXml)
                            {
                                ((XmlWriter)oXmlGravar).WriteStartElement("Producao");
                            }
                            else
                            {
                                tipo = list.UF + ".Producao.";
                            }
                        }
                        switch (Empresas.Configuracoes[emp].Servico)
                        {
                        case TipoAplicativo.Nfse:
                            Functions.GravaTxtXml(oXmlGravar, tipo + NFe.Components.Servicos.NFSeCancelar.ToString(), (!string.IsNullOrEmpty(item.CancelarNfse)).ToString());
                            Functions.GravaTxtXml(oXmlGravar, tipo + NFe.Components.Servicos.NFSeConsultarLoteRps.ToString(), (!string.IsNullOrEmpty(item.ConsultarLoteRps)).ToString());
                            Functions.GravaTxtXml(oXmlGravar, tipo + NFe.Components.Servicos.NFSeConsultar.ToString(), (!string.IsNullOrEmpty(item.ConsultarNfse)).ToString());
                            Functions.GravaTxtXml(oXmlGravar, tipo + NFe.Components.Servicos.NFSeConsultarPorRps.ToString(), (!string.IsNullOrEmpty(item.ConsultarNfsePorRps)).ToString());
                            Functions.GravaTxtXml(oXmlGravar, tipo + NFe.Components.Servicos.NFSeConsultarSituacaoLoteRps.ToString(), (!string.IsNullOrEmpty(item.ConsultarSituacaoLoteRps)).ToString());
                            Functions.GravaTxtXml(oXmlGravar, tipo + NFe.Components.Servicos.NFSeRecepcionarLoteRps.ToString(), (!string.IsNullOrEmpty(item.RecepcionarLoteRps)).ToString());
                            Functions.GravaTxtXml(oXmlGravar, tipo + NFe.Components.Servicos.NFSeConsultarURL.ToString(), (!string.IsNullOrEmpty(item.ConsultarURLNfse)).ToString());
                            break;

                        default:
                            if (Empresas.Configuracoes[emp].Servico == TipoAplicativo.NFCe ||
                                Empresas.Configuracoes[emp].Servico == TipoAplicativo.Nfe ||
                                Empresas.Configuracoes[emp].Servico == TipoAplicativo.Todos)
                            {
                                Functions.GravaTxtXml(oXmlGravar, tipo + "NFeConsulta", (!string.IsNullOrEmpty(item.NFeConsulta)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + "NFeRecepcao", (!string.IsNullOrEmpty(item.NFeRecepcao)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + "NFeRecepcaoEvento", (!string.IsNullOrEmpty(item.NFeRecepcaoEvento)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + "NFeConsultaCadastro", (!string.IsNullOrEmpty(item.NFeConsultaCadastro)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + Servicos.NFeDownload.ToString(), (!string.IsNullOrEmpty(item.NFeDownload)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + "NFeInutilizacao", (!string.IsNullOrEmpty(item.NFeInutilizacao)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + "NFeManifDest", (!string.IsNullOrEmpty(item.NFeManifDest)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + "NFeStatusServico", (!string.IsNullOrEmpty(item.NFeStatusServico)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + "NFeAutorizacao", (!string.IsNullOrEmpty(item.NFeAutorizacao)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + "NFeRetAutorizacao", (!string.IsNullOrEmpty(item.NFeRetAutorizacao)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + "DFeRecepcao", (!string.IsNullOrEmpty(item.DFeRecepcao)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + NFe.Components.Servicos.LMCAutorizacao.ToString(), (!string.IsNullOrEmpty(item.LMCAutorizacao)).ToString());
                            }
                            if (Empresas.Configuracoes[emp].Servico == TipoAplicativo.MDFe ||
                                Empresas.Configuracoes[emp].Servico == TipoAplicativo.Todos)
                            {
                                Functions.GravaTxtXml(oXmlGravar, tipo + "MDFeRecepcao", (!string.IsNullOrEmpty(item.MDFeRecepcao)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + "MDFeRetRecepcao", (!string.IsNullOrEmpty(item.MDFeRetRecepcao)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + "MDFeConsulta", (!string.IsNullOrEmpty(item.MDFeConsulta)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + "MDFeStatusServico", (!string.IsNullOrEmpty(item.MDFeStatusServico)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + NFe.Components.Servicos.MDFeRecepcaoEvento.ToString(), (!string.IsNullOrEmpty(item.MDFeRecepcaoEvento)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + NFe.Components.Servicos.MDFeConsultaNaoEncerrado.ToString(), (!string.IsNullOrEmpty(item.MDFeNaoEncerrado)).ToString());
                            }
                            if (Empresas.Configuracoes[emp].Servico == TipoAplicativo.Cte ||
                                Empresas.Configuracoes[emp].Servico == TipoAplicativo.Todos)
                            {
                                Functions.GravaTxtXml(oXmlGravar, tipo + NFe.Components.Servicos.CTeRecepcaoEvento.ToString(), (!string.IsNullOrEmpty(item.CTeRecepcaoEvento)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + "CTeConsultaCadastro", (!string.IsNullOrEmpty(item.CTeConsultaCadastro)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + "CTeInutilizacao", (!string.IsNullOrEmpty(item.CTeInutilizacao)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + "CTeStatusServico", (!string.IsNullOrEmpty(item.CTeStatusServico)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + "CTeDistribuicaoDFe", (!string.IsNullOrEmpty(item.CTeDistribuicaoDFe)).ToString());
                            }

                            break;
                        }
                        if (isXml)
                        {
                            ((XmlWriter)oXmlGravar).WriteEndElement();   //Ambiente
                            ((XmlWriter)oXmlGravar).WriteEndElement();   //list.UF
                        }
                    }
                }
                //Finalizar o XML
                if (isXml)
                {
                    ((XmlWriter)oXmlGravar).WriteEndElement(); //nfe_configuracoes
                    ((XmlWriter)oXmlGravar).WriteEndElement(); //retConsInf
                    ((XmlWriter)oXmlGravar).WriteEndDocument();
                    ((XmlWriter)oXmlGravar).Flush();
                    ((XmlWriter)oXmlGravar).Close();
                }
                else
                {
                    ((StringWriter)oXmlGravar).Flush();
                    File.WriteAllText(sArquivo, ((StringWriter)oXmlGravar).GetStringBuilder().ToString());
                    ((StringWriter)oXmlGravar).Close();
                }
            }
            catch (Exception ex)
            {
                Functions.DeletarArquivo(sArquivo);
                ///
                /// danasa 8-2009
                ///
                Auxiliar oAux = new Auxiliar();
                oAux.GravarArqErroERP(Path.GetFileNameWithoutExtension(sArquivo) + ".err", ex.Message);
            }
        }
예제 #41
0
        /// <summary>
        /// Does atomic 1)Gets DCB document 2) Generate xml 3) Update xml file to database.
        /// </summary>
        /// <param name="task">ConvertDCBLinkTaskBusinessEntityObject</param>
        /// <param name="jobParameters">Job business entity</param>
        /// <returns></returns>
        protected override bool DoAtomicWork(ConvertDCBLinkTaskBusinessEntityObject task, BaseJobBEO jobParameters)
        {
            bool StatusFlag = true;// Function return status.

            try
            {
                EvLog.WriteEntry(Constants.JobTypeName + " - " + jobParameters.JobRunId.ToString(CultureInfo.InvariantCulture), Constants.Event_Job_DoAtomicWork_Start, EventLogEntryType.Information);
                // Perform Atomic Task
                DCBLinkCollectionBEO  dcbLinks = new DCBLinkCollectionBEO();
                DCBLinkBEO            dcbLink;
                ReviewerSearchResults searchResults = null;
                if (_documentCount > 0)
                {
                    DocumentQueryEntity documentQueryEntity = GetDocumentQueryEntity(task.DatasetId.ToString(CultureInfo.InvariantCulture), _query, _documentCount.ToString(CultureInfo.InvariantCulture));
                    documentQueryEntity.TransactionName = "ConvertDCBLinksToCaseMap - DoAtomicWork";
                    searchResults = JobSearchHandler.GetSearchResults(documentQueryEntity);
                }
                List <DCBLinkBEO> linkList = new List <DCBLinkBEO>();
                string            uuid     = string.Empty;
                int count = 0;
                foreach (DocumentResult document in searchResults.ResultDocuments)
                {
                    dcbLink = new DCBLinkBEO();
                    DocumentIdentifierBEO docIdentifier = new DocumentIdentifierBEO(document.MatterID.ToString(CultureInfo.InvariantCulture), document.CollectionID, document.DocumentID);
                    if (count == 0)
                    {
                        uuid = docIdentifier.UniqueIdentifier.Replace(docIdentifier.DocumentId, string.Empty);
                    }
                    dcbLink.NewDocumentId = docIdentifier.DocumentId;

                    List <FieldResult> fieldValues = document.Fields.Where(f => System.String.Compare(f.Name, EVSystemFields.DcbId, System.StringComparison.OrdinalIgnoreCase) == 0).ToList();
                    dcbLink.OldDocumentId = fieldValues.Any() ? fieldValues.First().Value.Replace("[", "(").Replace("]", ")") : string.Empty;
                    linkList.Add(dcbLink);
                    dcbLink.CollectionId = docIdentifier.CollectionId;
                    dcbLink.DCN          = docIdentifier.DCN;
                    if (docIdentifier.MatterId != null)
                    {
                        dcbLink.MatterId = long.Parse(docIdentifier.MatterId);
                    }

                    count++;
                }
                linkList.SafeForEach(l => dcbLinks.Links.Add(l));
                dcbLinks.UrlApplicationLink = task.LinkBackUrl;

                string        xml         = DocumentFactBusinessObject.GenerateDcbLinksXml(dcbLinks, uuid);
                UTF8Encoding  encoding    = new UTF8Encoding();
                byte[]        content     = encoding.GetBytes(xml);
                StringBuilder nameBuilder = new StringBuilder();
                nameBuilder.Append(Constants.TaskName);
                nameBuilder.Append(Constants.OnDate);
                nameBuilder.Append(startedTime.ConvertToUserTime());
                string requestName = nameBuilder.ToString();

                nameBuilder = new StringBuilder();
                nameBuilder.Append(Constants.TaskName);
                _requestDescription = nameBuilder.ToString();

                string fileType = ApplicationConfigurationManager.GetValue(Constants.FileType);
                _conversionId = CaseMapDAO.SaveConversionResults(jobParameters.JobRunId, requestName, _requestDescription, content, fileType, _createdByUserGuid);
                StatusFlag    = true;
                EvLog.WriteEntry(Constants.JobTypeName + " - " + jobParameters.JobRunId.ToString(CultureInfo.InvariantCulture), Constants.Event_Job_DoAtomicWork_Success, EventLogEntryType.Information);
                TaskLogInfo.AddParameters(Constants.DataSetName, task.DatasetName);
            }
            catch (EVTaskException ex)
            {
                _isJobFailed = true;
                EvLog.WriteEntry(Constants.JobTypeName + MethodInfo.GetCurrentMethod().Name, ex.Message, EventLogEntryType.Error);
                throw;
            }
            catch (Exception ex)
            {
                _isJobFailed = true;
                // Handle exception in Generate Tasks
                EvLog.WriteEntry(Constants.JobTypeName + MethodInfo.GetCurrentMethod().Name, ex.Message, EventLogEntryType.Error);
                EVTaskException jobException = new EVTaskException(ErrorCodes.DoAtomicError, ex);
                TaskLogInfo.StackTrace = ex.Message + Constants.LineBreak + ex.StackTrace;
                TaskLogInfo.AddParameters(Constants.DataSetId, task.DatasetId.ToString(CultureInfo.InvariantCulture));
                TaskLogInfo.AddParameters(Constants.DataSetName, task.DatasetName);
                TaskLogInfo.TaskKey    = Constants.DataSetName + ":" + task.DatasetName;
                jobException.LogMessge = TaskLogInfo;
                throw (jobException);
            }
            return(StatusFlag);
        }
예제 #42
0
        public void AddItem(LogItem item)
        {
            if (LogLevel == LogLevel.None || item == null || string.IsNullOrWhiteSpace(item.Exception.ToString()))
            {
                return;
            }

            try
            {
                var uniqueValue = (item.Exception + AdditionalData.ToDebugString()).Trim();
                if (!_unique.Contains(uniqueValue))
                {
                    OnItemAdded.RaiseEvent(item, new EventArgs());
                    _unique.Add(uniqueValue);

                    var file = Path.Combine(
                        LogDir,
                        string.Format(
                            _fileName, DateTime.Now.ToString("yyyy_MM_dd"), LogLevel.ToString().ToLower(),
                            (item.Exception + AdditionalData.ToDebugString()).ToMd5Hash()));

                    if (File.Exists(file))
                    {
                        return;
                    }

                    AddData(item.Exception);

                    if (OutputConsole)
                    {
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine(item.Exception);
                        Console.ResetColor();
                    }

                    using (
                        var fileStream = new FileStream(
                            file, FileMode.CreateNew, FileAccess.Write, FileShare.None, 4096, true))
                    {
                        using (Stream gzStream = new GZipStream(fileStream, CompressionMode.Compress, false))
                        {
                            var text = item.Exception.ToString();
                            text = item.Exception.Data.Cast <DictionaryEntry>()
                                   .Aggregate(
                                text,
                                (current, entry) =>
                                current +
                                string.Format("{0}{1}: {2}", Environment.NewLine, entry.Key, entry.Value));

                            if (string.IsNullOrWhiteSpace(text.Trim()))
                            {
                                return;
                            }

                            var logByte = new UTF8Encoding(true).GetBytes(text);

                            if (Compression)
                            {
                                gzStream.Write(logByte, 0, logByte.Length);
                            }
                            else
                            {
                                fileStream.Write(logByte, 0, logByte.Length);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
예제 #43
0
        private BuddyUploadResponse UploadBuddyData(string postData, string url, bool forced = false)
        {
            if (_uploadCooldown.IsOnCooldown && !forced)
            {
                Logger.Info("Buddy data not uploaded, still on cooldown..");
                return(null);
            }


            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

            if (request == null)
            {
                Logger.Warn("Could not create HttpWebRequest");
                return(null);
            }
            var encoding = new UTF8Encoding();

            byte[] data = encoding.GetBytes(postData);

            request.Method = "POST";
            request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
            request.Headers.Add(HttpRequestHeader.ContentEncoding, "gzip");
            request.ContentType = "application/x-www-form-urlencoded";
            //request.ContentLength = data.Length;

            try {
                using (Stream stream = request.GetRequestStream()) {
                    stream.Write(data, 0, data.Length);
                }
                // threshold
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        Logger.Info("Failed to upload buddy item data.");
                        return(new BuddyUploadResponse {
                            Status = (int)response.StatusCode
                        });
                    }

                    string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

                    Logger.Debug(responseString);
                    Logger.Info("Uploaded buddy item data.");

                    _uploadCooldown.Reset();
                    return(new BuddyUploadResponse {
                        Content = responseString,
                        Status = 200
                    });
                }
            }
            catch (WebException ex) {
                Logger.Info("Failed to upload buddy item data.");

                using (WebResponse response = ex.Response) {
                    HttpWebResponse httpResponse = (HttpWebResponse)response;
                    if (httpResponse.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        return(new BuddyUploadResponse {
                            Status = (int)httpResponse.StatusCode
                        });
                    }
                }

                if (ex.Status != WebExceptionStatus.NameResolutionFailure && ex.Status != WebExceptionStatus.Timeout)
                {
                    Logger.Warn(ex.Message);
                    Logger.Warn(ex.StackTrace);
                    ExceptionReporter.ReportException(ex);
                }
                else
                {
                    Logger.Info("Could not resolve DNS for buddy server, skipping upload.");
                }
            }
            catch (IOException ex) {
                Logger.Warn(ex.Message);
                Logger.Warn(ex.StackTrace);
            }
            catch (Exception ex) {
                Logger.Error(ex.Message);
                Logger.Error(ex.StackTrace);
                ExceptionReporter.ReportException(ex);
            }

            return(null);
        }
예제 #44
0
파일: MCfdi.cs 프로젝트: IsraelBV/SUN
        /// <summary>
        /// Metodo donde ser realizaron varias formas para obtener el Sello a SHA256
        /// </summary>
        /// <param name="noCertificado"></param>
        /// <param name="certificadoB64"></param>
        /// <param name="cadenaOriginal"></param>
        /// <param name="datos"></param>
        /// <returns></returns>
        public static string GetSelloDigitalEmisor33123(ref string noCertificado, ref string certificadoB64,
                                                        string cadenaOriginal, PathsCertificado datos)
        {
            string selloDigital = "";

            CertificadoDigital cert = GetCertificadoDigital(datos.PathArchivoCer);

            noCertificado  = cert.NoCertificado;
            certificadoB64 = cert.CertificadoBase64;


            //Metodo 1
            SecureString identidad = new SecureString();

            identidad.Clear();

            foreach (var c in datos.Password.ToCharArray())
            {
                identidad.AppendChar(c);
            }

            byte[] llavePrivadaBytes = File.ReadAllBytes(datos.PathArchivoKey);
            var    data = Encoding.UTF8.GetBytes(cadenaOriginal);

            //METODO SHA1
            RSACryptoServiceProvider  lrsa0   = opensslkey.DecodeEncryptedPrivateKeyInfo(llavePrivadaBytes, identidad);
            SHA1CryptoServiceProvider hasher0 = new SHA1CryptoServiceProvider();

            byte[] bytesFirmados0 = lrsa0.SignData(Encoding.UTF8.GetBytes(cadenaOriginal), hasher0);

            var selloDigital0 = Convert.ToBase64String(bytesFirmados0);


            #region METODO 1
            RSACryptoServiceProvider    lrsa1   = opensslkey.DecodeEncryptedPrivateKeyInfo(llavePrivadaBytes, identidad);
            SHA256CryptoServiceProvider hasher1 = new SHA256CryptoServiceProvider();

            byte[] bytesFirmados1 = lrsa1.SignData(data, hasher1);

            //byte[] bytesFirmados11 = lrsa1.SignData(data, "sha256");

            bool isValid = lrsa1.VerifyData(data, hasher1, bytesFirmados1);

            //byte[] bytesFirmados111 = lrsa1.SignData(data, HashAlgorithmName.SHA256);

            //var selloDigital11 = Convert.ToBase64String(bytesFirmados11);
            //var selloDigital111 = Convert.ToBase64String(bytesFirmados111);

            selloDigital = Convert.ToBase64String(bytesFirmados1);

            #endregion

            #region METODO 2

            RSACryptoServiceProvider lrsa2 = opensslkey.DecodeEncryptedPrivateKeyInfo(llavePrivadaBytes, identidad);
            SHA256 sha256 = SHA256Managed.Create();

            byte[] bytes2 = Encoding.UTF8.GetBytes(cadenaOriginal);
            byte[] hash   = sha256.ComputeHash(bytes2);
            //return GetStringFromHash(hash);
            //CryptoConfig.CreateFromName("SHA256");
            byte[] bytesFirmados2 = lrsa2.SignData(data, sha256);

            var selloDigital2 = Convert.ToBase64String(bytesFirmados2);

            #endregion

            #region METODO 3

            RSACryptoServiceProvider lrsa3 = opensslkey.DecodeEncryptedPrivateKeyInfo(llavePrivadaBytes, identidad);
            Byte[] inputBytes = Encoding.UTF8.GetBytes(cadenaOriginal);
            SHA256CryptoServiceProvider sha3 = new SHA256CryptoServiceProvider();

            Byte[] hashedBytes = sha3.ComputeHash(inputBytes);

            byte[] bytesFirmados3 = lrsa3.SignData(data, sha3);

            var selloDigital3 = Convert.ToBase64String(bytesFirmados3);

            #endregion

            #region METODO 4

            string strSello = string.Empty;

            RSACryptoServiceProvider rsa4 = opensslkey.DecodeEncryptedPrivateKeyInfo(llavePrivadaBytes, identidad);

            SHA256Managed sha      = new SHA256Managed();
            UTF8Encoding  encoding = new UTF8Encoding();
            byte[]        bytes    = encoding.GetBytes(cadenaOriginal);
            byte[]        digest   = sha.ComputeHash(bytes);

            RSAPKCS1SignatureFormatter rsaFormatter = new RSAPKCS1SignatureFormatter(rsa4);
            rsaFormatter.SetHashAlgorithm("SHA256");
            byte[] signedHashValue4 = rsaFormatter.CreateSignature(digest);

            SHA256CryptoServiceProvider hasher4 = new SHA256CryptoServiceProvider();

            byte[] bytesFirmados4 = rsa4.SignData(System.Text.Encoding.UTF8.GetBytes(cadenaOriginal), hasher4);

            strSello = Convert.ToBase64String(bytesFirmados4);             // Y aquí está el sello
            string strSello256 = Convert.ToBase64String(signedHashValue4); // Y aquí está el sello 2

            #endregion

            #region METODO 5
            //X509Certificate2 miCertificado5 = new X509Certificate2(datos.PathArchivoCer, datos.Password);

            //RSACryptoServiceProvider rsa5 = (RSACryptoServiceProvider)miCertificado5.PrivateKey;
            //SHA256CryptoServiceProvider hasher5 = new SHA256CryptoServiceProvider();
            //UTF8Encoding e = new UTF8Encoding(true);

            ////byte[] signature = RSA1.SignHash(hasher5, CryptoConfig.MapNameToOID("SHA256"));

            //byte[] bytesFirmados5 = rsa5.SignData(e.GetBytes(cadenaOriginal), hasher5);
            //var selloDigital5 = Convert.ToBase64String(bytesFirmados5);

            #endregion

            #region METODO 6
            //System.Security.Cryptography.X509Certificates.X509Certificate2 miCertificado6 = new System.Security.Cryptography.X509Certificates.X509Certificate2(datos.PathArchivoCer, datos.Password);

            // GetRSAPrivateKey returns an object with an independent lifetime, so it should be
            // handled via a using statement.
            //using (RSA rsa6 = miCertificado6.GetRSAPrivateKey())
            //{
            // RSA now exposes SignData, and the hash algorithm parameter takes a strong type,
            // which allows for IntelliSense hints.
            //var bytesFirmados6 = rsa6.SignData(data, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);

            //var selloDigital6 = Convert.ToBase64String(bytesFirmados6);
            //}



            #endregion



            return(selloDigital);
        }
예제 #45
0
        private void BtnOpen_Click(object sender, EventArgs e)
        {
            string        root                = Application.StartupPath;
            string        tempDir             = Path.Combine(root, @"Temp");
            string        templateDir         = Path.Combine(root, @"Template");
            string        outputDir           = Path.Combine(root, @"Output");
            string        handBreakeTemplate  = Path.Combine(templateDir, @"job.json");
            string        vapourSynthTemplate = Path.Combine(templateDir, @"waifu2x.vpy");
            string        handBreakeParams    = Path.Combine(templateDir, @"HandBrakeParams.json");
            string        workBat             = Path.Combine(root, @"work.bat");
            List <string> tempFiles           = new List <string> {
                workBat
            };
            List <MediaFile> files = new List <MediaFile>();
            StringBuilder    build = new StringBuilder();

            OpenFileDialog dlg = new OpenFileDialog {
                Multiselect = true, Filter = @"MP4文件|*.mp4"
            };

            if (DialogResult.OK == dlg.ShowDialog())
            {
                // 删除临时文件
                if (Directory.Exists(tempDir))
                {
                    Directory.Delete(tempDir, true);
                }
                Directory.CreateDirectory(tempDir);

                files.AddRange(dlg.FileNames.Select(file => new MediaFile {
                    Path = file
                }));
                int idx = 0;
                foreach (MediaFile file in files)
                {
                    // 编号
                    file.JobIndex = idx;

                    // 源
                    string srcFile = Path.Combine(tempDir, string.Format($@"src{idx}.mp4"));
                    File.Copy(file.Path, srcFile);

                    // 抽取
                    string srcV = Path.Combine(tempDir, string.Format($@"V{idx}.mp4"));
                    string srcA = Path.Combine(tempDir, string.Format($@"V{idx}.aac"));
                    tempFiles.Add(srcV);
                    tempFiles.Add(srcA);
                    build.AppendLine(CMD_ExtractMp4_Video.Replace(INPUT, srcFile).Replace(OUTPUT, srcV));
                    build.AppendLine(CMD_ExtractMp4_Audio.Replace(INPUT, srcFile).Replace(OUTPUT, srcA));

                    // HandBrake配置文件生成
                    UTF8Encoding utf8NoBOM      = new UTF8Encoding(false); // 微软默认含有BOM头,要去掉否则HandBreak不能识别
                    string       fixedV         = Path.Combine(tempDir, string.Format($@"V{idx}_fixed.mp4"));
                    string       handBreakeFile = Path.Combine(tempDir, string.Format($@"job{idx}.json"));
                    tempFiles.Add(fixedV);
                    tempFiles.Add(handBreakeFile);
                    string handBreakeScript = FileTool.OpenAndReadAllText(handBreakeTemplate, utf8NoBOM).Replace(INPUT, srcV).Replace(OUTPUT, fixedV).Replace(@"\", @"\\");
                    FileTool.CreateAndWriteText(handBreakeFile, handBreakeScript, utf8NoBOM);

                    // 执行HandBrake
                    build.AppendLine(CMD_HandBrake.Replace(PRESET, handBreakeParams).Replace(INPUT, handBreakeFile));

                    // VapourSynth脚本生成
                    string vpyFile  = Path.Combine(tempDir, string.Format($@"vpy{idx}.vpy"));
                    string waifu2xV = Path.Combine(tempDir, string.Format($@"V{idx}_waifu2x.hevc"));
                    tempFiles.Add(vpyFile);
                    tempFiles.Add(waifu2xV);
                    string vpyScript = FileTool.OpenAndReadAllText(vapourSynthTemplate, Encoding.UTF8).Replace(INPUT, fixedV);
                    FileTool.CreateAndWriteText(vpyFile, vpyScript, Encoding.UTF8);

                    // 执行VapourSynth和x265
                    build.AppendLine(CMD_VapourSynthAndX265.Replace(INPUT, vpyFile).Replace(OUTPUT, waifu2xV));

                    // 封装MKV
                    string output = Path.Combine(outputDir, string.Format($@"out{idx}.mkv"));
                    build.AppendLine(CMD_MergeMKV.Replace(OUTPUT, output).Replace(V_INPUT, waifu2xV).Replace(A_INPUT, srcA));

                    idx++;
                }

                // 生成BAT文件
                FileTool.CreateAndWriteText(workBat, build.ToString(), Encoding.Default);
                if (chkExecuteWhenDone.Checked)
                {
                    Process.Start(workBat);
                }

                // 等待执行并删除临时文件

                // 重命名输出文件
            }
        }
예제 #46
0
    public string DeserializeString()
    {
        UTF8Encoding pEncoder = new UTF8Encoding();

        return(pEncoder.GetString(DeserializeByteArray()));
    }
예제 #47
0
 public static byte[] WriteStringToByte(string str, FileStream fs)
 {
     byte[] info = new UTF8Encoding(true).GetBytes(str);
     fs.Write(info, 0, info.Length);
     return(info);
 }
예제 #48
0
        public static byte[] Encode(string format, params object[] value)
        {
            if (format == null)
            {
                throw new ArgumentNullException(nameof(format));
            }

            // no need to turn on invalid encoding detection as we just do string->byte[] conversion.
            UTF8Encoding utf8Encoder = new UTF8Encoding();

            byte[] encodingResult = null;
            // value is allowed to be null in certain scenario, so if it is null, just set it to empty array.
            if (value == null)
            {
                value = Array.Empty <object>();
            }

            Debug.WriteLine("Begin encoding\n");

            // allocate the berelement
            SafeBerHandle berElement = new SafeBerHandle();

            int valueCount = 0;
            int error      = 0;

            for (int formatCount = 0; formatCount < format.Length; formatCount++)
            {
                char fmt = format[formatCount];
                if (fmt == '{' || fmt == '}' || fmt == '[' || fmt == ']' || fmt == 'n')
                {
                    // no argument needed
                    error = BerPal.PrintEmptyArgument(berElement, new string(fmt, 1));
                }
                else if (fmt == 't' || fmt == 'i' || fmt == 'e')
                {
                    if (valueCount >= value.Length)
                    {
                        // we don't have enough argument for the format string
                        Debug.WriteLine("value argument is not valid, valueCount >= value.Length\n");
                        throw new ArgumentException(SR.BerConverterNotMatch);
                    }

                    if (!(value[valueCount] is int))
                    {
                        // argument is wrong
                        Debug.WriteLine("type should be int\n");
                        throw new ArgumentException(SR.BerConverterNotMatch);
                    }

                    // one int argument
                    error = BerPal.PrintInt(berElement, new string(fmt, 1), (int)value[valueCount]);

                    // increase the value count
                    valueCount++;
                }
                else if (fmt == 'b')
                {
                    if (valueCount >= value.Length)
                    {
                        // we don't have enough argument for the format string
                        Debug.WriteLine("value argument is not valid, valueCount >= value.Length\n");
                        throw new ArgumentException(SR.BerConverterNotMatch);
                    }

                    if (!(value[valueCount] is bool))
                    {
                        // argument is wrong
                        Debug.WriteLine("type should be boolean\n");
                        throw new ArgumentException(SR.BerConverterNotMatch);
                    }

                    // one int argument
                    error = BerPal.PrintInt(berElement, new string(fmt, 1), (bool)value[valueCount] ? 1 : 0);

                    // increase the value count
                    valueCount++;
                }
                else if (fmt == 's')
                {
                    if (valueCount >= value.Length)
                    {
                        // we don't have enough argument for the format string
                        Debug.WriteLine("value argument is not valid, valueCount >= value.Length\n");
                        throw new ArgumentException(SR.BerConverterNotMatch);
                    }

                    if (value[valueCount] != null && !(value[valueCount] is string))
                    {
                        // argument is wrong
                        Debug.WriteLine("type should be string, but receiving value has type of ");
                        Debug.WriteLine(value[valueCount].GetType());
                        throw new ArgumentException(SR.BerConverterNotMatch);
                    }

                    // one string argument
                    byte[] tempValue = null;
                    if (value[valueCount] != null)
                    {
                        tempValue = utf8Encoder.GetBytes((string)value[valueCount]);
                    }
                    error = EncodingByteArrayHelper(berElement, tempValue, 'o');

                    // increase the value count
                    valueCount++;
                }
                else if (fmt == 'o' || fmt == 'X')
                {
                    // we need to have one arguments
                    if (valueCount >= value.Length)
                    {
                        // we don't have enough argument for the format string
                        Debug.WriteLine("value argument is not valid, valueCount >= value.Length\n");
                        throw new ArgumentException(SR.BerConverterNotMatch);
                    }

                    if (value[valueCount] != null && !(value[valueCount] is byte[]))
                    {
                        // argument is wrong
                        Debug.WriteLine("type should be byte[], but receiving value has type of ");
                        Debug.WriteLine(value[valueCount].GetType());
                        throw new ArgumentException(SR.BerConverterNotMatch);
                    }

                    byte[] tempValue = (byte[])value[valueCount];
                    error = EncodingByteArrayHelper(berElement, tempValue, fmt);

                    valueCount++;
                }
                else if (fmt == 'v')
                {
                    // we need to have one arguments
                    if (valueCount >= value.Length)
                    {
                        // we don't have enough argument for the format string
                        Debug.WriteLine("value argument is not valid, valueCount >= value.Length\n");
                        throw new ArgumentException(SR.BerConverterNotMatch);
                    }

                    if (value[valueCount] != null && !(value[valueCount] is string[]))
                    {
                        // argument is wrong
                        Debug.WriteLine("type should be string[], but receiving value has type of ");
                        Debug.WriteLine(value[valueCount].GetType());
                        throw new ArgumentException(SR.BerConverterNotMatch);
                    }

                    string[] stringValues = (string[])value[valueCount];
                    byte[][] tempValues   = null;
                    if (stringValues != null)
                    {
                        tempValues = new byte[stringValues.Length][];
                        for (int i = 0; i < stringValues.Length; i++)
                        {
                            string s = stringValues[i];
                            if (s == null)
                            {
                                tempValues[i] = null;
                            }
                            else
                            {
                                tempValues[i] = utf8Encoder.GetBytes(s);
                            }
                        }
                    }

                    error = EncodingMultiByteArrayHelper(berElement, tempValues, 'V');

                    valueCount++;
                }
                else if (fmt == 'V')
                {
                    // we need to have one arguments
                    if (valueCount >= value.Length)
                    {
                        // we don't have enough argument for the format string
                        Debug.WriteLine("value argument is not valid, valueCount >= value.Length\n");
                        throw new ArgumentException(SR.BerConverterNotMatch);
                    }

                    if (value[valueCount] != null && !(value[valueCount] is byte[][]))
                    {
                        // argument is wrong
                        Debug.WriteLine("type should be byte[][], but receiving value has type of ");
                        Debug.WriteLine(value[valueCount].GetType());
                        throw new ArgumentException(SR.BerConverterNotMatch);
                    }

                    byte[][] tempValue = (byte[][])value[valueCount];

                    error = EncodingMultiByteArrayHelper(berElement, tempValue, fmt);

                    valueCount++;
                }
                else
                {
                    Debug.WriteLine("Format string contains undefined character: ");
                    Debug.WriteLine(new string(fmt, 1));
                    throw new ArgumentException(SR.BerConverterUndefineChar);
                }

                // process the return value
                if (error == -1)
                {
                    Debug.WriteLine("ber_printf failed\n");
                    throw new BerConversionException();
                }
            }

            // get the binary value back
            berval binaryValue = new berval();
            IntPtr flattenptr  = IntPtr.Zero;

            try
            {
                // can't use SafeBerval here as CLR creates a SafeBerval which points to a different memory location, but when doing memory
                // deallocation, wldap has special check. So have to use IntPtr directly here.
                error = BerPal.FlattenBerElement(berElement, ref flattenptr);

                if (error == -1)
                {
                    Debug.WriteLine("ber_flatten failed\n");
                    throw new BerConversionException();
                }

                if (flattenptr != IntPtr.Zero)
                {
                    Marshal.PtrToStructure(flattenptr, binaryValue);
                }

                if (binaryValue == null || binaryValue.bv_len == 0)
                {
                    encodingResult = Array.Empty <byte>();
                }
                else
                {
                    encodingResult = new byte[binaryValue.bv_len];

                    Marshal.Copy(binaryValue.bv_val, encodingResult, 0, binaryValue.bv_len);
                }
            }
            finally
            {
                if (flattenptr != IntPtr.Zero)
                {
                    BerPal.FreeBerval(flattenptr);
                }
            }

            return(encodingResult);
        }
예제 #49
0
    // 인터페이스 : string
    public void Serialize(string strValue)
    {
        UTF8Encoding pEncoder = new UTF8Encoding();

        Serialize(pEncoder.GetBytes(strValue));
    }
예제 #50
0
        internal static object[] TryDecode(string format, byte[] value, out bool decodeSucceeded)
        {
            if (format == null)
            {
                throw new ArgumentNullException(nameof(format));
            }

            Debug.WriteLine("Begin decoding\n");

            UTF8Encoding  utf8Encoder = new UTF8Encoding(false, true);
            berval        berValue    = new berval();
            ArrayList     resultList  = new ArrayList();
            SafeBerHandle berElement  = null;

            object[] decodeResult = null;
            decodeSucceeded = false;

            if (value == null)
            {
                berValue.bv_len = 0;
                berValue.bv_val = IntPtr.Zero;
            }
            else
            {
                berValue.bv_len = value.Length;
                berValue.bv_val = Marshal.AllocHGlobal(value.Length);
                Marshal.Copy(value, 0, berValue.bv_val, value.Length);
            }

            try
            {
                berElement = new SafeBerHandle(berValue);
            }
            finally
            {
                if (berValue.bv_val != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(berValue.bv_val);
                }
            }

            int error = 0;

            for (int formatCount = 0; formatCount < format.Length; formatCount++)
            {
                char fmt = format[formatCount];
                if (fmt == '{' || fmt == '}' || fmt == '[' || fmt == ']' || fmt == 'n' || fmt == 'x')
                {
                    error = BerPal.ScanNext(berElement, new string(fmt, 1));

                    if (BerPal.IsBerDecodeError(error))
                    {
                        Debug.WriteLine("ber_scanf for {, }, [, ], n or x failed");
                    }
                }
                else if (fmt == 'i' || fmt == 'e' || fmt == 'b')
                {
                    int result = 0;
                    error = BerPal.ScanNextInt(berElement, new string(fmt, 1), ref result);

                    if (!BerPal.IsBerDecodeError(error))
                    {
                        if (fmt == 'b')
                        {
                            // should return a bool
                            bool boolResult = false;
                            if (result == 0)
                            {
                                boolResult = false;
                            }
                            else
                            {
                                boolResult = true;
                            }
                            resultList.Add(boolResult);
                        }
                        else
                        {
                            resultList.Add(result);
                        }
                    }
                    else
                    {
                        Debug.WriteLine("ber_scanf for format character 'i', 'e' or 'b' failed");
                    }
                }
                else if (fmt == 'a')
                {
                    // return a string
                    byte[] byteArray = DecodingByteArrayHelper(berElement, 'O', ref error);
                    if (!BerPal.IsBerDecodeError(error))
                    {
                        string s = null;
                        if (byteArray != null)
                        {
                            s = utf8Encoder.GetString(byteArray);
                        }

                        resultList.Add(s);
                    }
                }
                else if (fmt == 'O')
                {
                    // return berval
                    byte[] byteArray = DecodingByteArrayHelper(berElement, fmt, ref error);
                    if (!BerPal.IsBerDecodeError(error))
                    {
                        // add result to the list
                        resultList.Add(byteArray);
                    }
                }
                else if (fmt == 'B')
                {
                    error = DecodeBitStringHelper(resultList, berElement);
                }
                else if (fmt == 'v')
                {
                    //null terminate strings
                    byte[][] byteArrayresult = null;
                    string[] stringArray     = null;

                    byteArrayresult = DecodingMultiByteArrayHelper(berElement, 'V', ref error);
                    if (!BerPal.IsBerDecodeError(error))
                    {
                        if (byteArrayresult != null)
                        {
                            stringArray = new string[byteArrayresult.Length];
                            for (int i = 0; i < byteArrayresult.Length; i++)
                            {
                                if (byteArrayresult[i] == null)
                                {
                                    stringArray[i] = null;
                                }
                                else
                                {
                                    stringArray[i] = utf8Encoder.GetString(byteArrayresult[i]);
                                }
                            }
                        }

                        resultList.Add(stringArray);
                    }
                }
                else if (fmt == 'V')
                {
                    byte[][] result = null;

                    result = DecodingMultiByteArrayHelper(berElement, fmt, ref error);
                    if (!BerPal.IsBerDecodeError(error))
                    {
                        resultList.Add(result);
                    }
                }
                else
                {
                    Debug.WriteLine("Format string contains undefined character\n");
                    throw new ArgumentException(SR.BerConverterUndefineChar);
                }

                if (BerPal.IsBerDecodeError(error))
                {
                    // decode failed, just return
                    return(decodeResult);
                }
            }

            decodeResult = new object[resultList.Count];
            for (int count = 0; count < resultList.Count; count++)
            {
                decodeResult[count] = resultList[count];
            }

            decodeSucceeded = true;
            return(decodeResult);
        }
예제 #51
0
 public RaynReader(byte[] buffer)
 {
     _buffer   = buffer;
     _encoding = new UTF8Encoding();
 }
예제 #52
0
        public void LoadXmlFromBase64(string response)
        {
            UTF8Encoding enc = new UTF8Encoding();

            LoadXml(enc.GetString(Convert.FromBase64String(response)));
        }
 public PageController(IHostingEnvironment envrnmt) : base(envrnmt)
 {
     _Encoding = new System.Text.UTF8Encoding();
 }
예제 #54
0
        protected void handleClient(TcpClient client)
        {
            NetworkStream stream = client.GetStream();

            try
            {
                byte[] data          = new byte[client.ReceiveBufferSize];
                int    numBytesRead  = stream.Read(data, 0, client.ReceiveBufferSize);
                string requestString = new UTF8Encoding().GetString(data, 0, numBytesRead);

                CustomHttpRequest httpRequest      = CustomHttpRequest.Parse(requestString);
                WebServerRequest  webServerRequest = new WebServerRequest();
                webServerRequest.Cookies = httpRequest.Cookies;
                webServerRequest.Body    = httpRequest.Body;
                webServerRequest.Path    = httpRequest.RequestTarget.LocalPath;

                //Parse additional data
                Dictionary <string, List <string> > queryParts = ParseQuery(httpRequest.RequestTarget.Query);
                object additionalData = null;
                if (httpRequest.Method == "POST")
                {
                    if (httpRequest.PostData.ContainsKey(dataKey))
                    {
                        additionalData = httpRequest.PostData[dataKey];
                    }
                    else
                    {
                        additionalData = httpRequest.PostData;
                    }
                }
                else
                {
                    if (queryParts.ContainsKey(dataKey) && queryParts[dataKey].Count > 0)
                    {
                        additionalData = queryParts[dataKey].First();
                    }
                }
                webServerRequest.Data = additionalData;

                CustomHttpResponse response = new CustomHttpResponse(generateResponse(webServerRequest));
                response.ToStream(stream);
            }
            catch (System.Web.HttpException ex)
            {
                new CustomHttpResponse(ex).ToStream(stream);
            }
            catch
            {
                if (client.Connected)
                {
                    try
                    {
                        CustomHttpResponse response = new CustomHttpResponse();
                        response.StatusCode = "500 Internal Server Error";
                        response.ToStream(stream);
                    }
                    catch { }
                }
            }

            client.Close();
        }
예제 #55
0
 private static void AddText(FileStream fs, string value)
 {
     byte[] info = new UTF8Encoding(true).GetBytes(value);
     fs.Write(info, 0, info.Length);
 }
예제 #56
0
        private static byte[] CUTF8String2Array(string strIn)
        {
            UTF8Encoding enc = new UTF8Encoding();

            return(enc.GetBytes(strIn));
        }
예제 #57
0
        private void ShowMessage(LocalMail message)
        {
            if (message == null)
            {
                SetHeader("");
                MessageBody.Clear();

                return;
            }


            string content = "<b><font size=2>" + message.Info.Subject + "</font></b> from " +
                             Core.GetName(message.Header.SourceID) + ", sent " +
                             Utilities.FormatTime(message.Info.Date) + @"<br> 
                              <b>To:</b> " + Mail.GetNames(message.To) + "<br>";

            if (message.CC.Count > 0)
            {
                content += "<b>CC:</b> " + Mail.GetNames(message.CC) + "<br>";
            }

            if (message.Attached.Count > 1)
            {
                string attachHtml = "";

                for (int i = 0; i < message.Attached.Count; i++)
                {
                    if (message.Attached[i].Name == "body")
                    {
                        continue;
                    }

                    attachHtml += "<a href='http://attach/" + i.ToString() + "'>" + message.Attached[i].Name + "</a> (" + Utilities.ByteSizetoString(message.Attached[i].Size) + "), ";
                }

                attachHtml = attachHtml.TrimEnd(new char[] { ' ', ',' });

                content += "<b>Attachments: </b> " + attachHtml;
            }

            content += "<br>";

            string actions = "";

            if (message.Header.TargetID == Core.UserID)
            {
                actions += @"<a href='http://reply" + "'>Reply</a>";
            }

            actions += @", <a href='http://forward'>Forward</a>";
            actions += @", <a href='http://delete'>Delete</a>";

            content += "<b>Actions: </b>" + actions.Trim(',', ' ');

            SetHeader(content);

            // body

            try
            {
                using (TaggedStream stream = new TaggedStream(Mail.GetLocalPath(message.Header), Core.GuiProtocol))
                    using (CryptoStream crypto = IVCryptoStream.Load(stream, message.Header.LocalKey))
                    {
                        int    buffSize  = 4096;
                        byte[] buffer    = new byte[4096];
                        long   bytesLeft = message.Header.FileStart;
                        while (bytesLeft > 0)
                        {
                            int readSize = (bytesLeft > buffSize) ? buffSize : (int)bytesLeft;
                            int read     = crypto.Read(buffer, 0, readSize);
                            bytesLeft -= read;
                        }

                        // load file
                        foreach (MailFile file in message.Attached)
                        {
                            if (file.Name == "body")
                            {
                                byte[] msgBytes = new byte[file.Size];
                                crypto.Read(msgBytes, 0, (int)file.Size);

                                UTF8Encoding utf = new UTF8Encoding();

                                MessageBody.Clear();
                                MessageBody.SelectionFont  = new Font("Tahoma", 9.75f);
                                MessageBody.SelectionColor = Color.Black;

                                if (message.Info.Format == TextFormat.RTF)
                                {
                                    MessageBody.Rtf = utf.GetString(msgBytes);
                                }
                                else
                                {
                                    MessageBody.Text = utf.GetString(msgBytes);
                                }

                                MessageBody.DetectLinksDefault();
                            }
                        }
                    }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "Error Opening Mail: " + ex.Message);
            }

            if (message.Header.Read == false)
            {
                message.Header.Read = true;

                Mail.SaveMailbox = true;

                if (MessageView.SelectedNodes.Count > 0)
                {
                    ((MessageNode)MessageView.SelectedNodes[0]).UpdateRow();
                }
            }
        }
예제 #58
0
        public IActionResult Index(FacturaViewModel facturaViewModel)
        {
            /***** Generar Factura *****
             * 1. Datos de venta
             * 2. Certificados
             * 3. Cadena Original
             * 4. Sello Digital
             * 5. XML
             * 6. PDF
             * 7. QR
             */

            Facturas Factura = new Facturas();

            //Asociar a la factura con la venta que se acaba de realizar
            Factura.Ventas = facturaViewModel.Venta;

            Factura.VentaId = Factura.Ventas.Id;

            Factura.Clientes = facturaViewModel.Cliente;

            Factura.ClienteID = Factura.Clientes.Id;

            Factura.FechaExpedicion = DateTime.Now.ToUniversalTime();

            Factura.TipoDeComprobante = SD.TipoDeComprobante;

            //Traer las transacciones asociadas a la factura
            List <Transacciones> transacciones = new List <Transacciones>();

            transacciones = _context.Transacciones.Where(x => x.VentaId == Factura.VentaId).ToList();


            //**** Certificados ****//
            X509Certificate2 certEmisor = new X509Certificate2(); // Generas un objeto del tipo de certificado

            FileStream f    = new FileStream("C:/Users/Xochipilli/Desktop/CSDAAA010101AAA/CSD01_AAA010101AAA.cer", FileMode.Open, FileAccess.Read);
            int        size = (int)f.Length;

            byte[] data = new byte[size];
            size = f.Read(data, 0, size);
            f.Close();
            var strCertificado = data;

            byte[] byteCertData = strCertificado; // Manda llamar la funcion Readfile para cargar el archivo .cer

            certEmisor.Import(byteCertData);      // Importa los datos del certificado qeu acabas d

            //Recuperar numero de serie de certificado
            Factura.NoCertificado = System.Text.ASCIIEncoding.ASCII.GetString(certEmisor.GetSerialNumber());

            //Convertir certificado a base 64
            Factura.Certificado = Convert.ToBase64String(certEmisor.GetRawCertData());


            //**** Cadena Original ****//
            string CadenaOriginal = "||" + SD.Version + "|" + Factura.FechaExpedicion + "|" + SD.TipoDeComprobante + "|" + Factura.Ventas.FormasPago.Clave + "|";

            if (Factura.Ventas.CondicionesDePago != null)
            {
                CadenaOriginal = CadenaOriginal + Factura.Ventas.CondicionesDePago + "|";
            }
            CadenaOriginal = CadenaOriginal + Factura.Ventas.SubTotal + "|";
            if (!Double.IsNaN(Factura.Ventas.DescuentoTotal))
            {
                CadenaOriginal = CadenaOriginal + Factura.Ventas.DescuentoTotal + "|";
            }
            if (!Double.IsNaN(Factura.Ventas.TipoCambio))
            {
                CadenaOriginal = CadenaOriginal + Factura.Ventas.TipoCambio + "|";
            }
            CadenaOriginal = CadenaOriginal + Factura.Ventas.Moneda.Clave + "|" + Factura.Ventas.Total + "|" + Factura.Ventas.MetodosPago.Clave + "|" + SD.LugarExpedicion + "|";
            CadenaOriginal = CadenaOriginal + SD.RFCEmisor + "|" + SD.NombreEmisor + "|" + SD.DomicilioFiscalCalle + "|" + SD.DomicilioFiscalNoExterior + "|" + SD.DomicilioFiscalColonia + "|" + SD.DomicilioFiscalMunicipio + "|" + SD.DomicilioFiscalEstado + "|" + SD.DomicilioFiscalCodigoPostal + "|";
            CadenaOriginal = CadenaOriginal + SD.RegimenFiscalEmisor + "|" + Factura.Clientes.RFC + "|" + Factura.Clientes.Nombre + "|";
            foreach (var item in transacciones)
            {
                CadenaOriginal = CadenaOriginal + item.CantidadVendida + "|" + item.Productos.ClaveUnidad.Clave + "|" + item.Productos.Descripcion + "|" + item.Productos.ValorUnitario + "|" + item.SubTotal + "|";
            }
            double acumuladorImpuestos = 0;

            foreach (var item in transacciones)
            {
                acumuladorImpuestos = acumuladorImpuestos + item.ImpuestosRetenidos;
                CadenaOriginal      = CadenaOriginal + SD.Impuesto + "|" + item.ImpuestosRetenidos + "|";
            }
            CadenaOriginal = CadenaOriginal + acumuladorImpuestos + "||";


            //**** Sello Digital ****//
            string strSello     = string.Empty;
            string strPathLlave = "C:/Users/Xochipilli/Desktop/CSDAAA010101AAA/CSD01_AAA010101AAA.key";
            string strLlavePwd  = "12345678a";

            System.Security.SecureString passwordSeguro = new System.Security.SecureString();
            passwordSeguro.Clear();

            foreach (char c in strLlavePwd.ToCharArray())
            {
                passwordSeguro.AppendChar(c);
            }

            byte[] llavePrivadaBytes     = System.IO.File.ReadAllBytes(strPathLlave);
            RSACryptoServiceProvider rsa = opensslkey.DecodeEncryptedPrivateKeyInfo(llavePrivadaBytes, passwordSeguro);

            SHA1Managed  sha      = new SHA1Managed();
            UTF8Encoding encoding = new UTF8Encoding();

            byte[] bytes  = encoding.GetBytes(CadenaOriginal);
            byte[] digest = sha.ComputeHash(bytes);

            RSAPKCS1SignatureFormatter RSAFormatter = new RSAPKCS1SignatureFormatter(rsa);

            RSAFormatter.SetHashAlgorithm("SHA1");
            byte[] SignedHashValue = RSAFormatter.CreateSignature(digest);

            SHA1CryptoServiceProvider hasher = new SHA1CryptoServiceProvider();

            byte[] bytesFirmados = rsa.SignData(System.Text.Encoding.UTF8.GetBytes(CadenaOriginal), hasher);
            strSello = Convert.ToBase64String(bytesFirmados);  // Y aquí está el sello


            //**** XML ****//
            XmlWriter xmlWriter = XmlWriter.Create("Factura.xml");

            xmlWriter.WriteStartDocument();

            //** Comprobante **//
            xmlWriter.WriteStartElement("cfdi:Comrpobante");
            xmlWriter.WriteAttributeString("Version", SD.Version);
            xmlWriter.WriteAttributeString("Fecha", Factura.FechaExpedicion.ToString());
            xmlWriter.WriteAttributeString("Sello", strSello);
            xmlWriter.WriteAttributeString("FormaPago", Factura.Ventas.FormasPago.Clave.ToString());
            xmlWriter.WriteAttributeString("NoCertificado", Factura.NoCertificado);
            xmlWriter.WriteAttributeString("Certificado", Factura.Certificado);
            xmlWriter.WriteAttributeString("Certificado", Factura.Certificado);
            if (Factura.Ventas.CondicionesDePago != null)
            {
                xmlWriter.WriteAttributeString("CondicionesDePago", Factura.Ventas.CondicionesDePago);
            }
            xmlWriter.WriteAttributeString("SubTotal", Factura.Ventas.SubTotal.ToString());
            if (!Double.IsNaN(Factura.Ventas.DescuentoTotal))
            {
                xmlWriter.WriteAttributeString("Descuento", Factura.Ventas.DescuentoTotal.ToString());
            }
            xmlWriter.WriteAttributeString("Moneda", Factura.Ventas.Moneda.Clave);
            if (!Double.IsNaN(Factura.Ventas.TipoCambio))
            {
                xmlWriter.WriteAttributeString("TipoCambio", Factura.Ventas.TipoCambio.ToString());
            }
            xmlWriter.WriteAttributeString("Total", Factura.Ventas.Total.ToString());
            xmlWriter.WriteAttributeString("TipoDeComprobante", SD.TipoDeComprobante);
            xmlWriter.WriteAttributeString("MetodoPago", Factura.Ventas.MetodosPago.Clave);
            xmlWriter.WriteAttributeString("LugarExpedicion", SD.LugarExpedicion);

            //** Emisor **//
            xmlWriter.WriteStartElement("cfdi:Emisor");
            xmlWriter.WriteAttributeString("Rfc", SD.RFCEmisor);
            xmlWriter.WriteAttributeString("Nombre", SD.NombreEmisor);
            xmlWriter.WriteAttributeString("RegimenFiscal", SD.RegimenFiscalEmisor);
            xmlWriter.WriteEndElement();

            //** Receptor **//
            xmlWriter.WriteStartElement("cfdi:Receptor");
            xmlWriter.WriteAttributeString("Rfc", Factura.Clientes.RFC);
            xmlWriter.WriteAttributeString("Nombre", Factura.Clientes.Nombre);
            xmlWriter.WriteAttributeString("UsoCFDI", SD.UsoCFDI);
            xmlWriter.WriteEndElement();

            //** Conceptos **//
            xmlWriter.WriteStartElement("cfdi:Conceptos");
            xmlWriter.WriteAttributeString("Rfc", Factura.Clientes.RFC);
            xmlWriter.WriteAttributeString("Nombre", Factura.Clientes.Nombre);
            xmlWriter.WriteAttributeString("UsoCFDI", SD.UsoCFDI);

            //** Concepto **//
            foreach (var item in transacciones)
            {
                xmlWriter.WriteStartElement("cfdi:Concepto");
                xmlWriter.WriteAttributeString("ClaveProdServ", item.Productos.ClaveProdServ.Clave.ToString());
                xmlWriter.WriteAttributeString("Cantidad", item.CantidadVendida.ToString());
                xmlWriter.WriteAttributeString("ClaveUnidad", item.Productos.ClaveUnidad.Clave);
                xmlWriter.WriteAttributeString("Unidad", item.Productos.ClaveUnidad.Descripcion);
                xmlWriter.WriteAttributeString("Descripcion", item.Productos.Descripcion);
                xmlWriter.WriteAttributeString("ValorUnitario", item.Productos.ValorUnitario.ToString());
                xmlWriter.WriteAttributeString("Importe", item.SubTotal.ToString());
                if (!Double.IsNaN(item.Descuento))
                {
                    xmlWriter.WriteAttributeString("Descuento", item.Descuento.ToString());
                }
                xmlWriter.WriteEndElement();
            }

            xmlWriter.WriteEndElement();

            //** Impuestos **//
            xmlWriter.WriteStartElement("cfdi:Impuestos");
            xmlWriter.WriteAttributeString("TotalImpuestosRetenidos", acumuladorImpuestos.ToString());
            //** Retenciones **//
            xmlWriter.WriteStartElement("cfdi:Retenciones");
            //** Retencion **//
            foreach (var item in transacciones)
            {
                xmlWriter.WriteStartElement("cfdi:Retencion");
                xmlWriter.WriteAttributeString("Impuesto", SD.Impuesto);
                xmlWriter.WriteAttributeString("Impuesto", SD.TipoFactor);
                xmlWriter.WriteAttributeString("TasaOCuota", SD.TasaOCuota);
                xmlWriter.WriteAttributeString("Importe", item.ImpuestosRetenidos.ToString());
                xmlWriter.WriteEndElement();
            }
            xmlWriter.WriteEndElement();
            xmlWriter.WriteEndElement();

            xmlWriter.WriteEndElement();
            xmlWriter.WriteEndDocument();
            xmlWriter.Close();

            return(View(Factura));
        }
예제 #59
0
        private void StartButton_Click(object sender, EventArgs e)
        {
            IPAddress address;

            if (IPAddress.TryParse(textBox1.Text, out address))
            {
                Ping      pingSender = new Ping();
                PingReply reply      = pingSender.Send(address);
                if (reply.Status != IPStatus.Success)
                {
                    MessageBox.Show("Indirizzo IP non raggiungibile.");
                }
                else
                {
                    if (File.Exists(@"\\" + textBox1.Text + HostfileName))
                    {
                        using (FileStream fs = File.Create(@"\\" + textBox1.Text + ClientfileName))
                        {
                            byte[] text;
                            text = new UTF8Encoding(true).GetBytes(textBox2.Text);
                            fs.Write(text, 0, text.Length);
                        }
                        const Int32 BufferSize = 128;
                        using (var fileStream = File.OpenRead(@"\\" + textBox1.Text + HostfileName))
                            using (var streamReader = new StreamReader(fileStream, Encoding.UTF8, true, BufferSize))
                            {
                                string line;
                                int    cnt = 0;
                                while ((line = streamReader.ReadLine()) != null)
                                {
                                    if (cnt == 0)
                                    {
                                        int.TryParse(line, out dim);
                                    }
                                    if (cnt == 1)
                                    {
                                        opponentName = line;
                                    }
                                }
                            }
                        IP = @"\\" + textBox1.Text;
                        Game game = new Game();
                        this.Hide();
                        Status = game.ShowDialog(this);
                        if (Status == DialogResult.OK)
                        {
                            this.Show();
                        }
                        if (Status == DialogResult.Abort)
                        {
                            if (File.Exists(@"\\" + textBox1.Text + ClientfileName))
                            {
                                File.Delete(@"\\" + textBox1.Text + ClientfileName);
                            }
                            this.DialogResult = DialogResult.Abort;
                            game.Dispose();
                            this.Close();
                        }
                    }
                    else
                    {
                        MessageBox.Show("Server non valido o non raggiungibile.");
                    }
                }
            }
            else
            {
                MessageBox.Show("Indirizzo IP non valido.");
            }
        }
예제 #60
-1
    public static string EncryptRijndael(string original)
    {
        byte[] encrypted;

        byte[] toEncrypt;

        UTF8Encoding utf8Converter = new UTF8Encoding();

        toEncrypt = utf8Converter.GetBytes(original);

        RijndaelManaged myRijndael = new RijndaelManaged();

        MemoryStream ms = new MemoryStream();

        ICryptoTransform encryptor = myRijndael.CreateEncryptor(Key, IV);

        CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write);

        cs.Write(toEncrypt, 0, toEncrypt.Length);

        cs.FlushFinalBlock();

        encrypted = ms.ToArray();

        string encryptedString = Convert.ToBase64String(encrypted);

        return encryptedString;
    }