GetByteCount() private method

private GetByteCount ( char chars, int count ) : int
chars char
count int
return int
        public static string HashPassword(string password, string saltValue)
        {
            if (String.IsNullOrEmpty(password)) throw new ArgumentException("Password is null");

            var encoding = new UnicodeEncoding();
            var hash = new SHA256CryptoServiceProvider();

            if (saltValue == null)
            {
                saltValue = GenerateSaltValue();
            }

            byte[] binarySaltValue = Convert.FromBase64String(saltValue);
            byte[] valueToHash = new byte[SaltValueSize + encoding.GetByteCount(password)];
            byte[] binaryPassword = encoding.GetBytes(password);

            binarySaltValue.CopyTo(valueToHash, 0);
            binaryPassword.CopyTo(valueToHash, SaltValueSize);

            byte[] hashValue = hash.ComputeHash(valueToHash);
            var hashedPassword = String.Empty;
            foreach (byte hexdigit in hashValue)
            {
                hashedPassword += hexdigit.ToString("X2", CultureInfo.InvariantCulture.NumberFormat);
            }

            return hashedPassword;
        }
示例#2
0
        static void Main(string[] args)
        {
            Stopwatch start = Stopwatch.StartNew();
            FileStream fs;
            UnicodeEncoding uni = new UnicodeEncoding();
            //string stime = "";
            fs = new FileStream("./solution3.log", FileMode.Create);

            // for (int j = 1; j <= 50; j++)
            // {
            //int totalReset = 0;
            for (int i = 0; i < 50; i++)
            {
                start.Restart();
                Solver s = new Solver(3, @"C:\ULAVAL\IFT-4102\TP1\Question2\sudoku\base.txt", 810, 0.5, 0.8);
                string solution = s.Solve();
                //totalReset += reset;
                start.Stop();
                string stime = "Temps : " + start.ElapsedMilliseconds + "ms" + Environment.NewLine + solution + Environment.NewLine;
                Console.Write(stime);// + solution );
                fs.Write(uni.GetBytes(stime), 0, uni.GetByteCount(stime));
                // }
                // long total = start.ElapsedMilliseconds;
                // string timeTotal = total + "ms";
                // string timeMoyen = (total / 20.0) + "ms";
                // //stime = "With comparaison : " + (1 - 0.02 * j) + " took a total of " + timeTotal + " Moyen : " + timeMoyen + " and moyenReset " + totalReset / 20 + Environment.NewLine;
                // Console.Write(stime);
                //fs.Write(uni.GetBytes(stime), 0, uni.GetByteCount(stime));
            }

        }
示例#3
0
 private void DoExportForHishop(string csvFilename, string imagePath, System.Collections.Generic.List <ExportToLocal.ProductDetail> list)
 {
     using (System.IO.FileStream fileStream = new System.IO.FileStream(csvFilename, System.IO.FileMode.Create, System.IO.FileAccess.Write))
     {
         string productCSVForEcdev = this.GetProductCSVForHishop(imagePath, list);
         System.Text.UnicodeEncoding unicodeEncoding = new System.Text.UnicodeEncoding();
         //UTF8Encoding unicodeEncoding = new UTF8Encoding();
         int    byteCount = unicodeEncoding.GetByteCount(productCSVForEcdev);
         byte[] preamble  = unicodeEncoding.GetPreamble();
         byte[] array     = new byte[preamble.Length + byteCount];
         System.Buffer.BlockCopy(preamble, 0, array, 0, preamble.Length);
         unicodeEncoding.GetBytes(productCSVForEcdev.ToCharArray(), 0, productCSVForEcdev.Length, array, preamble.Length);
         fileStream.Write(array, 0, array.Length);
     }
     using (ZipFile zipFile = new ZipFile(System.Text.Encoding.Default))
     {
         System.IO.DirectoryInfo directoryInfo = new System.IO.DirectoryInfo(imagePath);
         zipFile.CompressionLevel = CompressionLevel.Default;
         zipFile.AddFile(csvFilename, "");
         zipFile.AddDirectory(directoryInfo.FullName, directoryInfo.Name);
         System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
         response.ContentType     = "application/x-zip-compressed";
         response.ContentEncoding = this._encoding;
         response.AddHeader("Content-Disposition", "attachment; filename=" + directoryInfo.Name + ".zip");
         response.Clear();
         zipFile.Save(response.OutputStream);
         this._workDir.Delete(true);
         response.Flush();
         response.Close();
     }
 }
 public void PosTest1()
 {
     UnicodeEncoding uEncoding = new UnicodeEncoding();
     int actualValue;
     actualValue = uEncoding.GetByteCount("");
     Assert.Equal(0, actualValue);
 }
示例#5
0
        //4 Add - StringUTF16
        public void AddStringUTF16(string val)
        {
            int len = UTF16.GetByteCount(val);

            CheckBuffer(len + 5);
            WriteValueType(StringUTF16Type);
            WriteUnicodeString(val);
        }
 private void WriteToStream(Stream stream, string msg)
 {
     if (stream != null)
     {
         stream.Write(uniEncoding.GetBytes(msg),
                      0, uniEncoding.GetByteCount(msg));
     }
 }
 public void PosTest1()
 {
     Char[] chars = new Char[] { };
     UnicodeEncoding uEncoding = new UnicodeEncoding();
     int actualValue;
     actualValue = uEncoding.GetByteCount(chars, 0, 0);
     Assert.Equal(0, actualValue);
 }
 public void PosTest3()
 {
     String str = GetString(1);
     UnicodeEncoding uEncoding = new UnicodeEncoding();
     int actualValue;
     actualValue = uEncoding.GetByteCount(str);
     Assert.Equal(2, actualValue);
 }
 public void NegTest1()
 {
     UnicodeEncoding uEncoding = new UnicodeEncoding();
     int actualValue;
     Assert.Throws<ArgumentNullException>(() =>
     {
         actualValue = uEncoding.GetByteCount(null, 0, 0);
     });
 }
        public void PosTest3()
        {
            Char[] chars = GetCharArray(1);
            UnicodeEncoding uEncoding = new UnicodeEncoding();
            int actualValue;

            actualValue = uEncoding.GetByteCount(chars, 0, 1);
            Assert.Equal(2, actualValue);
        }
示例#11
0
        public static void TestMailSlot()
        {
            //int i = 0;
            MailSlotTransport transport = new MailSlotTransport();
            //StringBuilder sb = new StringBuilder();
            //while (true)
            //{
            //    if (transport.Ready)
            //    {
            //        sb.Append("|" + sb.Length);
            //        bool retval = transport.Send("csharp.test.mailslot:1|c|" + sb.ToString());
            //        Console.WriteLine("return " + retval);
            //    }
            //}
            string SLOTNAME = @"\\.\mailslot\afcollectorapi";
            SafeFileHandle slotHandle = NativeMailSlot.CreateFile(SLOTNAME,
                            (uint)FileAccess.Write,
                            (uint)FileShare.ReadWrite,
                            0,
                            (uint)FileMode.Open,
                            (uint)FileAttributes.Normal,
                            0);
            FileStream fs = new FileStream(slotHandle, FileAccess.Write);

            UnicodeEncoding encoding = new UnicodeEncoding();
            string data_string = string.Format("{0}:{1}:{2}", Process.GetCurrentProcess().Id, 3, "csharp.test.mailslot:1|c");
            byte[] data_bytes = encoding.GetBytes(data_string);
            int byteCount = encoding.GetByteCount(data_string);
            fs.Write(data_bytes, 0, byteCount);
            fs.Flush();

            int size = 0, nextsize = 0, count = 0, timeout = 0;
            bool succeeded = false;
            if (slotHandle.IsInvalid)
            {
                Console.WriteLine("MailSlot handle is invalid");
                return;
            }
            try
            {
                succeeded = NativeMailSlot.GetMailslotInfo(slotHandle, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
            }
            if (succeeded)
            {
                Console.WriteLine(String.Format("size {0}, nextsize {1}, count {2}, timeout {3}",
                    size, nextsize, count, timeout));
            }
            else
            {
                Console.WriteLine(String.Format("can't get mailslot info {0:d}", Marshal.GetLastWin32Error()));
            }
        }
 public void NegTest3()
 {
     Char[] chars = GetCharArray(10);
     UnicodeEncoding uEncoding = new UnicodeEncoding();
     int actualValue;
     Assert.Throws<ArgumentOutOfRangeException>(() =>
     {
         actualValue = uEncoding.GetByteCount(chars, 5, -1);
     });
 }
示例#13
0
        public String Md5Encryption(String src)
        {
            System.Text.UnicodeEncoding encode = new System.Text.UnicodeEncoding();
            System.Text.Decoder         decode = encode.GetDecoder();
            MD5 md5 = new MD5CryptoServiceProvider();

            byte[] password      = new byte[encode.GetByteCount(src)];
            char[] char_password = new char[encode.GetCharCount(password)];
            password = encode.GetBytes(src);
            password = md5.ComputeHash(password);
            int length = encode.GetByteCount(src);

            if (length > 16)
            {
                length = 16;
            }
            decode.GetChars(password, 0, length, char_password, 0);
            return(new String(char_password));
        }
        public void PosTest2()
        {
            String str = GetString(10);
            UnicodeEncoding uEncoding = new UnicodeEncoding();
            int actualValue;

            String temp = ToString(str);
            actualValue = uEncoding.GetByteCount(str);
            Assert.Equal(20, actualValue);
        }
示例#15
0
		internal static uint GetCrc(string sResult)
		{
			UnicodeEncoding enc = new UnicodeEncoding();
			int iCount = enc.GetByteCount(sResult);
			using (CrcStream crc = new CrcStream(iCount))
			{
				crc.Write(enc.GetBytes(sResult), 0, iCount);
				return crc.WriteCrc;
				// Closed in the Dispose of 'crc'.
			}
		}
示例#16
0
        private static string HashPassword(string clearData, string saltValue, HashAlgorithm hash)
        {
            UnicodeEncoding encoding = new UnicodeEncoding();

            if (clearData != null && hash != null && encoding != null)
            {
                // If the salt string is null or the length is invalid then
                // create a new valid salt value.

                if (saltValue == null)
                {
                    // Generate a salt string.
                    saltValue = GenerateSaltValue();
                }

                // Convert the salt string and the password string to a single
                // array of bytes. Note that the password string is Unicode and
                // therefore may or may not have a zero in every other byte.

                byte[] binarySaltValue = new byte[SaltValueSize];

                binarySaltValue[0] = byte.Parse(saltValue.Substring(0, 2), System.Globalization.NumberStyles.HexNumber, CultureInfo.InvariantCulture.NumberFormat);
                binarySaltValue[1] = byte.Parse(saltValue.Substring(2, 2), System.Globalization.NumberStyles.HexNumber, CultureInfo.InvariantCulture.NumberFormat);
                binarySaltValue[2] = byte.Parse(saltValue.Substring(4, 2), System.Globalization.NumberStyles.HexNumber, CultureInfo.InvariantCulture.NumberFormat);
                binarySaltValue[3] = byte.Parse(saltValue.Substring(6, 2), System.Globalization.NumberStyles.HexNumber, CultureInfo.InvariantCulture.NumberFormat);

                byte[] valueToHash = new byte[SaltValueSize + encoding.GetByteCount(clearData)];
                byte[] binaryPassword = encoding.GetBytes(clearData);

                // Copy the salt value and the password to the hash buffer.

                binarySaltValue.CopyTo(valueToHash, 0);
                binaryPassword.CopyTo(valueToHash, SaltValueSize);

                byte[] hashValue = hash.ComputeHash(valueToHash);

                // The hashed password is the salt plus the hash value (as a string).

                string hashedPassword = saltValue;

                foreach (byte hexdigit in hashValue)
                {
                    hashedPassword += hexdigit.ToString("X2", CultureInfo.InvariantCulture.NumberFormat);
                }

                // Return the hashed password as a string.

                return hashedPassword;
            }

            return null;
        }
 static public int GetByteCount__A_Char(IntPtr l)
 {
     try {
         System.Text.UnicodeEncoding self = (System.Text.UnicodeEncoding)checkSelf(l);
         System.Char[] a1;
         checkArray(l, 2, out a1);
         var ret = self.GetByteCount(a1);
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
示例#18
0
        /// <summary>
        /// Encodes the password using the <see cref="SHA256Managed"/> <see cref="HashAlgorithm"/>.
        /// </summary>
        /// <param name="password">The password.</param>
        /// <param name="saltValue">The salt value. Null if no salt value.</param>
        /// <returns>The Base64 encoding <see cref="String"/> of the hashed password.</returns>
        public static string HashPassword(string password, string saltValue = null)
        {
            var encoding = new UnicodeEncoding();
            var builder = new StringBuilder();
            var salt = saltValue == null ? GenerateSalt() : GetSaltFromString(saltValue);
            var dataBuffer = new byte[encoding.GetByteCount(password) + SaltValueSize];
            var stringToHashBytes = encoding.GetBytes(password);

            salt.CopyTo(dataBuffer, 0);
            stringToHashBytes.CopyTo(dataBuffer, SaltValueSize);

            HashAlgorithm hashAlgorithm = new SHA256Managed();

            var hashedBytes = hashAlgorithm.ComputeHash(dataBuffer);

            foreach (var outputByte in salt) builder.Append(outputByte.ToString("x2").ToUpper());
            foreach (var outputByte in hashedBytes) builder.Append(outputByte.ToString("x2").ToUpper());

            return builder.ToString();
        }
示例#19
0
文件: typedval.cs 项目: hol353/ApsimX
        //======================================================================
        /// <summary>
        /// Sets the value for this scalar.
        /// </summary>
        /// <param name="value">The value to set this scalar to.</param>
        /// <returns>True if successful.</returns>
        //======================================================================
        public Boolean setValue(String value)
        {
            bool result = false;

            if (FIsScalar)
            {
                switch (FBaseType)
                {
                    case TBaseType.ITYPE_BOOL:
                        {
                            if ((value.Length > 0) && (Char.ToLower(value[0]) == 't'))
                                setValue(true);
                            else setValue(false);
                        } break;
                    case TBaseType.ITYPE_INT1:
                    case TBaseType.ITYPE_INT2:
                    case TBaseType.ITYPE_INT4:
                    case TBaseType.ITYPE_INT8:
                        if (value.Length > 0)
                            setValue(Convert.ToInt64(value)); break;
                    case TBaseType.ITYPE_SINGLE:
                    case TBaseType.ITYPE_DOUBLE:
                        {
                            if (value.Length > 0)
                                setValue(Convert.ToDouble(value));
                            else
                                setValue(0);
                        } break;
                    case TBaseType.ITYPE_CHAR:
                    case TBaseType.ITYPE_WCHAR: setValue(value[0]); break;
                    case TBaseType.ITYPE_STR:
                        {    //single byte characters
                            uint byteCount = (uint)value.Length;
                            FDataSize = INTSIZE + byteCount;
                            FData = new Byte[FDataSize];
                            FData[0] = (Byte)((uint)value.Length);
                            FData[1] = (Byte)(((uint)value.Length) >> 8);
                            FData[2] = (Byte)(((uint)value.Length) >> 16);
                            FData[3] = (Byte)(((uint)value.Length) >> 24);

                            ascii.GetBytes(value, 0, value.Length, FData, 4); //copy the unicode chars to single bytes
                        } break;
                    case TBaseType.ITYPE_WSTR:
                        {    //double byte unicode characters
                            System.Text.UnicodeEncoding uni = new System.Text.UnicodeEncoding();
                            uint byteCount = (uint)uni.GetByteCount(value);
                            FDataSize = INTSIZE + byteCount;
                            FData = new Byte[FDataSize];
                            FData[0] = (Byte)((uint)value.Length);
                            FData[1] = (Byte)(((uint)value.Length) >> 8);
                            FData[2] = (Byte)(((uint)value.Length) >> 16);
                            FData[3] = (Byte)(((uint)value.Length) >> 24);

                            uni.GetBytes(value, 0, value.Length, FData, 4); //copy the unicode chars to double bytes
                        } break;
                }
                result = true;
            }

            return result;
        }
示例#20
0
        public bool Send(string mail)
        {
            try
            {
                UnicodeEncoding encoding = new UnicodeEncoding();
                string data_string = string.Format("{0}:{1}:{2}", Process.GetCurrentProcess().Id, 3, mail);
                byte[] data_bytes = encoding.GetBytes(data_string);
                int byteCount = encoding.GetByteCount(data_string);

                mailSlot.Write(data_bytes, 0, byteCount);
                mailSlot.Flush();

                Debug.WriteLine("sending " + data_string);
            }
            catch (IOException ioe)
            {
                Debug.WriteLine(String.Format("{0} Exception caught.", ioe));
            }

            return true;
        }
示例#21
0
            const int OKTO_VM_NAME_MAX_CHARS = (OKTO_VM_NAME_BUFF_WCZ_MAX - 1); // Allow NULL terminator.

            #endregion Fields

            #region Methods

            public static unsafe uint Request(
                SafeFileHandle hPort,
                uint tenantId,
                uint flowId,
                string accountName,
                SecurityIdentifier sid,
                string shareName)
            {
                uint HRESULT = 0;
                uint lpBytesReturned = 0;
                UnicodeEncoding enc = new UnicodeEncoding();
                OKTOPUS_CREATE_RAP_REQUEST Request = new OKTOPUS_CREATE_RAP_REQUEST();
                OKTOPUS_CREATE_RAP_REPLY Reply = new OKTOPUS_CREATE_RAP_REPLY();

                if (accountName.Length + 1 > OKTO_VM_NAME_MAX_CHARS)
                    throw new ExceptionIoFlow(DecodeOktoResult((uint)RESULTCODES.OKTO_VM_NAME_TOO_LONG));
                if (shareName.Length + 1 > OKTO_SHARE_NAME_MAX_CHARS)
                    throw new ExceptionIoFlow(DecodeOktoResult((uint)RESULTCODES.OKTO_SHARE_NAME_TOO_LONG));
                if (sid.BinaryLength > OKTO_SID_BUFF_BYTE_LEN)
                    throw new ExceptionIoFlow(DecodeOktoResult((uint)RESULTCODES.OKTO_VM_SID_TOO_LONG));

                //
                // Format request buffer.
                //
                Request.OpCode = (ulong)IOFLOWUSER_OPCODE.OpCodeCreateRap;
                Request.TenantId = tenantId;
                Request.FlowId = flowId;
                Request.MaxStatsArraySize = MAX_STATS_ARRAY_SIZE;
                Request.Result = 0;
                Request.VmNameWCharLen = ((uint)enc.GetByteCount(accountName) / 2) + 1;
                byte[] encVmNameBuff = new byte[OKTO_VM_NAME_BUFF_WCZ_MAX * 2];
                enc.GetBytes(accountName, 0, accountName.Length, encVmNameBuff, 0);
                for (int i = 0; i < OKTO_VM_NAME_BUFF_WCZ_MAX * 2; i++)
                    Request.VmNameBuff[i] = encVmNameBuff[i];
                Request.ShareNameWCharZLen = ((uint)enc.GetByteCount(shareName) / 2) + 1;
                byte[] encShareNameBuff = new byte[OKTO_SHARE_NAME_BUFF_WCZ_MAX * 2];
                enc.GetBytes(shareName, 0, shareName.Length, encShareNameBuff, 0);
                for (int i = 0; i < OKTO_SHARE_NAME_BUFF_WCZ_MAX * 2; i++)
                    Request.ShareNameBuff[i] = encShareNameBuff[i];
                Request.SidLength = (uint)sid.BinaryLength;
                byte[] sidBuff = new byte[sid.BinaryLength];
                sid.GetBinaryForm(sidBuff, 0);
                for (int i = 0; i < sid.BinaryLength; i++)
                    Request.Sid[i] = sidBuff[i];
                Request.PID = 0;
                Request.i_index = 0;
                Request.j_index = 0;

                Reply.Result = 0;

                // Pin buffers for duration of synchronous call to FilterSendMessage.
                GCHandle gchRequest = GCHandle.Alloc(Request, GCHandleType.Pinned);
                GCHandle gchReply = GCHandle.Alloc(Reply, GCHandleType.Pinned);

                // FilterSendMessage() ref http://msdn.microsoft.com/en-us/library/windows/hardware/ff541513(v=vs.85).aspx
                HRESULT = FilterSendMessage(hPort,                           // HANDLE hPort,
                                            gchRequest.AddrOfPinnedObject(), // LPVOID lpInBuffer,
                                            (uint)Marshal.SizeOf(Request),   // DWORD dwInBufferSize,
                                            gchReply.AddrOfPinnedObject(),   // LPVOID lpOutBuffer,
                                            (uint)Marshal.SizeOf(Reply),     // DWORD dwOutBufferSize,
                                            out lpBytesReturned);            // LPDWORD lpBytesReturned

                if (HRESULT != S_OK)
                {
                    Marshal.ThrowExceptionForHR((int)HRESULT);
                }

                if (Reply.Result != (uint)RESULTCODES.OKTO_RESULT_SUCCESS)
                {
                    throw new ExceptionIoFlow(DecodeOktoResult(Reply.Result));
                }

                gchRequest.Free();
                gchReply.Free();

                return HRESULT;
            }
示例#22
0
文件: Utils.cs 项目: BraZee/IgniteMe
        /// <summary>
        /// 
        /// </summary>
        /// <param name="clearProperty"></param>
        /// <param name="saltValue">8 lenght hexadecimal string</param>
        /// <returns></returns>
        internal static string HashProperty(string clearProperty, string saltValue)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            UnicodeEncoding encoding = new UnicodeEncoding();            

            byte[] binarySaltValue = new byte[saltValueSize];

            binarySaltValue[0] = byte.Parse(saltValue.Substring(0, 2), System.Globalization.NumberStyles.HexNumber);
            binarySaltValue[1] = byte.Parse(saltValue.Substring(2, 2), System.Globalization.NumberStyles.HexNumber);
            binarySaltValue[2] = byte.Parse(saltValue.Substring(4, 2), System.Globalization.NumberStyles.HexNumber);
            binarySaltValue[3] = byte.Parse(saltValue.Substring(6, 2), System.Globalization.NumberStyles.HexNumber);

            byte[] valueToHash = new byte[saltValueSize + encoding.GetByteCount(clearProperty)];
            byte[] binaryProperty = encoding.GetBytes(clearProperty);

            binarySaltValue.CopyTo(valueToHash, 0);
            binaryProperty.CopyTo(valueToHash, saltValueSize);

            byte[] hashValue = md5.ComputeHash(valueToHash);

            string hashedProperty = saltValue;

            foreach (byte hexDigit in hashValue)
            {
                hashedProperty += hexDigit.ToString("X2");
            }

            return hashedProperty;
        }
        public override void doIt(MArgList args)
        {
            // parse args to get the file name from the command-line
            //
            parseArgs(args);
            uint count = 0;

            // Iterate through graph and search for skinCluster nodes
            //
            MItDependencyNodes iter = new MItDependencyNodes( MFn.Type.kInvalid);
            for ( ; !iter.isDone; iter.next() )
            {
                MObject obj = iter.item;
                if (obj.apiType == MFn.Type.kSkinClusterFilter)
                {
                    count++;

                    // For each skinCluster node, get the list of influence objects
                    //
                    MFnSkinCluster skinCluster = new MFnSkinCluster(obj);
                    MDagPathArray infs = new MDagPathArray();
                    uint nInfs;
                    try
                    {
                        nInfs = skinCluster.influenceObjects(infs);
                    }
                    catch (Exception)
                    {
                        MGlobal.displayInfo("Error getting influence objects.");
                        continue;
                    }
                    if (0 == nInfs)
                    {
                        MGlobal.displayInfo("Error: No influence objects found.");
                        continue;
                    }

                    // loop through the geometries affected by this cluster
                    //
                    uint nGeoms = skinCluster.numOutputConnections;
                    for (uint ii = 0; ii < nGeoms; ++ii)
                    {
                        uint index;
                        try
                        {
                            index = skinCluster.indexForOutputConnection(ii);
                        }
                        catch (Exception)
                        {
                            MGlobal.displayInfo("Error getting geometry index.");
                            continue;
                        }

                        // get the dag path of the ii'th geometry
                        //
                        MDagPath skinPath = new MDagPath();
                        try{
                        skinCluster.getPathAtIndex(index,skinPath);
                        }
                        catch (Exception)
                        {
                            MGlobal.displayInfo("Error getting geometry path.");
                            continue;
                        }

                        // iterate through the components of this geometry
                        //
                        MItGeometry gIter = new MItGeometry(skinPath);

                        // print out the path name of the skin, vertexCount & influenceCount
                        //
                        UnicodeEncoding uniEncoding = new UnicodeEncoding();
                        string res = String.Format("{0} {1} {2}\n",skinPath.partialPathName,gIter.count,nInfs);
                        file.Write(uniEncoding.GetBytes(res),0,uniEncoding.GetByteCount(res));

                        // print out the influence objects
                        //
                        for (int kk = 0; kk < nInfs; ++kk)
                        {
                            res = String.Format("{0} ", infs[kk].partialPathName);
                            file.Write(uniEncoding.GetBytes(res),0,uniEncoding.GetByteCount(res));
                        }
                        res = "\n";
                        file.Write(uniEncoding.GetBytes(res), 0, uniEncoding.GetByteCount(res));

                        for ( /* nothing */ ; !gIter.isDone; gIter.next() ) {
                            MObject comp;
                            try
                            {
                                comp = gIter.component;
                            }
                            catch (Exception)
                            {
                                MGlobal.displayInfo("Error getting geometry path.");
                                continue;
                            }

                            // Get the weights for this vertex (one per influence object)
                            //
                            MDoubleArray wts = new MDoubleArray();
                            uint infCount = 0;
                            try
                            {
                                skinCluster.getWeights(skinPath, comp, wts, ref infCount);
                            }
                            catch (Exception)
                            {
                                displayError("Error getting weights.");
                                continue;
                            }
                            if (0 == infCount)
                            {
                                displayError("Error: 0 influence objects.");
                            }

                            // Output the weight data for this vertex
                            //
                            res = String.Format("{0} ",gIter.index);
                            file.Write(uniEncoding.GetBytes(res), 0, uniEncoding.GetByteCount(res));
                            for (int jj = 0; jj < infCount ; ++jj )
                            {
                                res = String.Format("{0} ", wts[jj]);
                                file.Write(uniEncoding.GetBytes(res), 0, uniEncoding.GetByteCount(res));
                            }
                            file.Write(uniEncoding.GetBytes("\n"), 0, uniEncoding.GetByteCount("\n"));
                        }
                    }
                }
            }

            if (0 == count)
            {
                displayError("No skinClusters found in this scene.");
            }
            file.Close();
            return;
        }
        /// <summary>
        /// Exports database to a CSV file
        /// </summary>
        public override void ExportAsCsv()
        {
            var csvString = "Id,Ranking,Date\n";

            var query = "SELECT * FROM " + _table;
            var command = new SQLiteCommand(query, _dbConnection);
            var reader = command.ExecuteReader();

            while (reader.Read())
            {
                var id = (long)reader["Id"];
                var rank = (int)reader["Rank"];
                var date = (DateTime)reader["Date"];
                csvString += id + "," + rank + "," + date + "\n";
            }

            //Save File
            var csvFileDialog = new SaveFileDialog
            {
                Filter = "CSV file|*.csv",
                Title = "Save CSV File"
            };
            csvFileDialog.ShowDialog();

            if (csvFileDialog.FileName != "")
            {
                //Create Unicode converter
                UnicodeEncoding uniEncoding = new UnicodeEncoding();

                //Get Filestream
                try
                {
                    FileStream fs = (FileStream)csvFileDialog.OpenFile();

                    //Write to file
                    fs.Write(uniEncoding.GetBytes(csvString), 0, uniEncoding.GetByteCount(csvString));

                    fs.Close();
                }
                catch (IOException)
                {
                    MessageBox.Show("The program can't write to the file!\nPlease close any other program that has the file open.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
示例#25
0
		public void ZeroLengthArrays ()
		{
			UnicodeEncoding encoding = new UnicodeEncoding ();
			encoding.GetCharCount (new byte [0]);
			encoding.GetChars (new byte [0]);
			encoding.GetCharCount (new byte [0], 0, 0);
			encoding.GetChars (new byte [0], 0, 0);
			encoding.GetChars (new byte [0], 0, 0, new char [0], 0);
			encoding.GetByteCount (new char [0]);
			encoding.GetBytes (new char [0]);
			encoding.GetByteCount (new char [0], 0, 0);
			encoding.GetBytes (new char [0], 0, 0);
			encoding.GetBytes (new char [0], 0, 0, new byte [0], 0);
			encoding.GetByteCount ("");
			encoding.GetBytes ("");
		}
示例#26
0
        //hashes a specific string (clearData) with a salt value (saltValue) and a definied Hashalgorithm (hash)
        public static string HashPassword(string clearData, string saltValue, HashAlgorithm hash)
        {
            UnicodeEncoding encoding = new UnicodeEncoding();

            if (clearData != null && hash != null && encoding != null)
            {

                //if salt value is null generate new salt value
                if (saltValue == null)
                {
                    saltValue = GenerateSaltValue();
                }

                // Convert the salt string and the password string to a single array of bytes.

                byte[] binarySaltValue = new byte[6];
                byte[] valueToHash = new byte[6 + encoding.GetByteCount(clearData)];
                byte[] binaryPassword = encoding.GetBytes(clearData);

                // Copy the salt value and the password to the hash buffer.

                binarySaltValue.CopyTo(valueToHash, 0);
                binaryPassword.CopyTo(valueToHash, 6);

                byte[] hashValue = hash.ComputeHash(valueToHash);

                // The hashed password is the salt plus the hash value (as a string).

                string hashedPassword = saltValue;

                foreach (byte hexdigit in hashValue)
                {
                    hashedPassword += hexdigit.ToString("X2", CultureInfo.InvariantCulture.NumberFormat);
                }

                // Return the hashed password as a string.

                return hashedPassword;
            }

            return null;
        }
示例#27
0
        /// <summary>
        /// Computes the hash. Given the salt value (if any) and the provided hash algorithm.
        /// </summary>
        /// <returns>The hash string.</returns>
        /// <param name="stringToHash">The string to hash.</param>
        /// <param name="saltValue">A salt value.</param>
        /// <param name="hashAlgorithm">The hash algorithm to use.</param>
        private string ComputeHash(string stringToHash, string saltValue, HashAlgorithm hashAlgorithm)
        {
            UnicodeEncoding encoding = new UnicodeEncoding();
            byte[] hashedBytes;
            byte[] salt = null;
            byte[] dataBuffer;
            byte[] stringToHashBytes;
            StringBuilder builder = new StringBuilder();

            if (saltValue == null)
                salt = GenerateSalt();
            else
                salt = GetSaltFromString(saltValue);

            dataBuffer = new byte[encoding.GetByteCount(stringToHash) + SaltValueSize];
            stringToHashBytes = encoding.GetBytes(stringToHash);

            salt.CopyTo(dataBuffer, 0);
            stringToHashBytes.CopyTo(dataBuffer, SaltValueSize);

            hashedBytes = hashAlgorithm.ComputeHash(dataBuffer);

            foreach (byte outputByte in salt)
                builder.Append(outputByte.ToString("x2").ToUpper());
            foreach (byte outputByte in hashedBytes)
                builder.Append(outputByte.ToString("x2").ToUpper());

            return builder.ToString();
        }
示例#28
0
 public override void DoExport()
 {
     this._workDir = this._baseDir.CreateSubdirectory(this._flag);
     this._productImagesDir = this._workDir.CreateSubdirectory("products");
     string path = Path.Combine(this._workDir.FullName, "products.csv");
     using (FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write))
     {
         string productCSV = this.GetProductCSV();
         UnicodeEncoding encoding = new UnicodeEncoding();
         int byteCount = encoding.GetByteCount(productCSV);
         byte[] preamble = encoding.GetPreamble();
         byte[] dst = new byte[preamble.Length + byteCount];
         Buffer.BlockCopy(preamble, 0, dst, 0, preamble.Length);
         encoding.GetBytes(productCSV.ToCharArray(), 0, productCSV.Length, dst, preamble.Length);
         stream.Write(dst, 0, dst.Length);
     }
     using (ZipFile file = new ZipFile())
     {
         file.CompressionLevel = CompressionLevel.Default;
         file.AddFile(path, "");
         file.AddDirectory(this._productImagesDir.FullName, this._productImagesDir.Name);
         HttpResponse response = HttpContext.Current.Response;
         response.ContentType = "application/x-zip-compressed";
         response.ContentEncoding = this._encoding;
         response.AddHeader("Content-Disposition", "attachment; filename=" + this._zipFilename);
         response.Clear();
         file.Save(response.OutputStream);
         this._workDir.Delete(true);
         response.Flush();
         response.Close();
     }
 }
示例#29
0
        protected bool SendByMailSlot(string stat)
        {
            if (!slotHandle.IsClosed)
            {
                if (fs == null)
                    fs = new FileStream(slotHandle, FileAccess.Write);

                System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding();
                string data_string = String.Format("{0}:{1}:{2}", Process.GetCurrentProcess().Id, 3, stat);
                byte[] data_bytes = encoding.GetBytes(data_string);
                int byteCount = encoding.GetByteCount(data_string);

                fs.Write(data_bytes, 0, byteCount);
                fs.Flush();
            }

            return true;
        }
示例#30
0
            public bool setTypeface( string sTypeface )
            {
                bool bResult = true;

                UnicodeEncoding ue = new UnicodeEncoding();

                if( ue.GetByteCount( sTypeface ) != 6 )
                {
                    bResult = false;
                    throw new ArrayTypeMismatchException( "Typeface should have a length of 16 characters." );
                }

                m_Typeface = ue.GetBytes( sTypeface );

                return bResult;
            }
示例#31
0
            public bool setFileName( string sFileName )
            {
                bool bResult = true;

                UnicodeEncoding ue = new UnicodeEncoding();

                if( ue.GetByteCount( sFileName ) != 6 )
                {
                    bResult = false;
                    throw new ArrayTypeMismatchException( "FileName is should have a length of 6 characters." );
                }

                m_FileName = ue.GetBytes( sFileName );

                return bResult;
            }
示例#32
0
            public bool setCharacterComplement( string sCharacterComplement )
            {
                bool bResult = true;

                UnicodeEncoding ue = new UnicodeEncoding();

                if( ue.GetByteCount( sCharacterComplement ) != 8 )
                {
                    bResult = false;
                    throw new ArrayTypeMismatchException( "CharacterComplement should have a length of 8 characters." );
                }

                m_CharacterComplement = ue.GetBytes( sCharacterComplement );

                return bResult;
            }
示例#33
0
        public string HashPassword(string password, string valorSal = null)
        {
            try
            {

                UnicodeEncoding encoding = new UnicodeEncoding();
                HashAlgorithm hash = HashAlgorithm.Create("SHA256");

                if (password != null && hash != null && encoding != null)
                {

                    if (valorSal == null)
                    {
                        valorSal = GenerarValorSal();
                    }

                    byte[] bytesValorSal = new byte[tamañoValorSal];

                    bytesValorSal = Encoding.Unicode.GetBytes(valorSal);

                    byte[] bytesDatos = new byte[tamañoValorSal + encoding.GetByteCount(password)];
                    byte[] bytesPassword = encoding.GetBytes(password);

                    bytesValorSal.CopyTo(bytesDatos, 0);
                    bytesPassword.CopyTo(bytesDatos, tamañoValorSal);

                    byte[] bytesHash = hash.ComputeHash(bytesDatos);

                    string passwordHasheado = valorSal;

                    foreach (byte hexa in bytesHash)
                    {
                        passwordHasheado += hexa.ToString("X2", CultureInfo.InvariantCulture.NumberFormat);
                    }

                    return passwordHasheado;
                }

                return null;

            }
            catch (Exception ex)
            {
                throw new GestorHashException("HashPassword", "General: " + ex.GetType().ToString(), ex.Message, ex);
            }
        }