コード例 #1
0
ファイル: CustomId.cs プロジェクト: DDROrg/MyCommunity
        public static string ToFriendlyId(this Guid guid)
        {
            if (guid == Guid.Empty)
            {
                return("No GUID supplied for friendly ID");
            }

            string str = Base36.Encode(BitConverter.ToUInt64(guid.ToByteArray(), 8));

            if (string.IsNullOrEmpty(str))
            {
                return("Problem getting friendly name from GUID");
            }
            string part3 = str.Length > 8
                ? str.Substring(8, str.Length - 8).PadRight(4, '0')
                : 0.ToString().PadRight(4, '0');

            string part2 = str.Length > 4
                ? str.Length < 8
                    ? str.Substring(4, str.Length - 4).PadRight(4, '0')
                    : str.Substring(4, 4)
                : 0.ToString().PadRight(4, '0');

            string part1 = str.Length < 4
                ? str.Substring(0, str.Length).PadRight(4, '0')
                : str.Substring(0, 4);

            string resultID = string.Format("{0}-{1}-{2}", part1, part2, part3);

            return(resultID);
        }
コード例 #2
0
ファイル: Base36Tests.cs プロジェクト: devopskartik/ndc-bingo
        public void EncodesAndDecodes(long expected)
        {
            var code   = Base36.Encode(expected);
            var actual = Base36.Decode(code);

            Assert.Equal(expected, actual);
        }
コード例 #3
0
        public void Encode_100000_255S()
        {
            const long input  = 100000L;
            string     result = Base36.Encode(input);

            Assert.AreEqual("255S", result, true);
        }
コード例 #4
0
ファイル: MinifyRec.cs プロジェクト: lapierj01/project8765
    /// <summary>
    /// Insert new URL in NOSQL DB
    /// </summary>
    /// <param name="strUrlIn"></param>
    /// <returns>Base36 string ID</returns>
    public static string putUrl(string strUrlIn)
    {
        try
        {
            // Open database (or create if not exits)
            using (var db = new LiteDatabase(HttpContext.Current.Server.MapPath("~/") + @"Minify.db"))
            {
                // Get Minify Rec collection
                var col = db.GetCollection <MinifyRec>("MinifyRec");

                // Create your new Minify Rec instance
                var MinifyRecIn = new MinifyRec
                {
                    Url    = strUrlIn,
                    Visits = 0
                };

                // Insert new customer document (Id will be auto-incremented)
                col.Insert(MinifyRecIn);
                return(Base36.Encode(MinifyRecIn.Id));
            }
        }
        catch
        {
            return("");
        }
    }
コード例 #5
0
        public void Encode_0_ReturnsZero()
        {
            string expected = "0";

            string actual = Base36.Encode(0);

            Assert.That(actual, Is.EqualTo(expected));
        }
コード例 #6
0
        public void Encode_1_Returns1()
        {
            string expected = "1";

            string actual = Base36.Encode(1);

            Assert.That(actual, Is.EqualTo(expected));
        }
コード例 #7
0
        public void Encode_35_ReturnsZ()
        {
            string expected = "z";

            string actual = Base36.Encode(35);

            Assert.That(actual, Is.EqualTo(expected));
        }
コード例 #8
0
        public async Task SetShortUrlToProduct(int productId)
        {
            var productForAddShortUrl = await GetProductById(productId);

            productForAddShortUrl.ShortUrl = Base36.Encode(productId);
            await UpdateNormal(productForAddShortUrl);
            await SaveChangeAsync();
        }
コード例 #9
0
        public void Encode_10000_Returns7ps()
        {
            string expected = "7ps";

            string actual = Base36.Encode(10000);

            Assert.That(actual, Is.EqualTo(expected));
        }
コード例 #10
0
ファイル: PostService.cs プロジェクト: behnix/ShopCore
        public async Task SetShortUrlToPost(int postId)
        {
            var postForAddShortUrl = await GetPostById(postId);

            postForAddShortUrl.ShortUrl = Base36.Encode(postId);
            await UpdateNormal(postForAddShortUrl);
            await SaveChangeAsync();
        }
コード例 #11
0
        public void Static_Encoding_IsCorrect()
        {
            const ulong  input  = 292_756_934_830;
            const string output = "3QHNX4MM";

            var result = Base36.Encode(input);

            Assert.Equal(output, result);
        }
コード例 #12
0
        public override string ContentsOf(Cell cell)
        {
            if (Distances != null && Distances.ContainsKey(cell))
            {
                return(Base36.Encode(Distances[cell]));
            }

            return(" ");
        }
コード例 #13
0
ファイル: PageService.cs プロジェクト: behnix/ShopCore
        public async Task SetShortUrlToPost(int postId)
        {
            var postForAddShortUrl = await GetPageById(postId);

            postForAddShortUrl.PageShortUrl = Base36.Encode(postId);
            await UpdatePage(postForAddShortUrl);

            await _context.SaveChangesAsync();
        }
コード例 #14
0
        public void Encode_minus12345678_ArgumentOutOfRangeException()
        {
            // Arrange
            int data = -12345678;

            // Act

            // Assert
            Assert.ThrowsException <ArgumentOutOfRangeException>(() => Base36.Encode(data));
        }
コード例 #15
0
        public void Encode_12345678_7CLZI()
        {
            // Arrange
            string expected = "7CLZI";
            int    data     = 12345678;

            // Act
            var result = Base36.Encode(data);

            // Assert
            Assert.AreEqual(expected, result);
        }
コード例 #16
0
ファイル: Converter.cs プロジェクト: dsdude123/CosmosRIF
        private void convert()
        {
            ArrayList imageData = new ArrayList();
            int       h         = (int)image.Width;

            int v = (int)image.Height;

            progressBar1.Maximum = (h * v);
            progressBar1.Step    = 1;

            //outputRIF.AutoFlush = true;

            writeHelper(Base36.Encode(h));
            writeHelper("|");
            writeHelper(Base36.Encode(v));
            writeHelper("|");
            outputRIF.Flush();
            int i;

            for (i = 0; i < v; i++)
            {
                for (int j = 0; j < h; j++)
                {
                    Color pixel = image.GetPixel(j, i);
                    if (imageData.Contains(pixel.ToArgb().ToString()))
                    {
                        int idx = imageData.IndexOf(pixel.ToArgb().ToString());
                        writeHelper("&" + Base36.Encode(idx));
                    }
                    else
                    {
                        imageData.Add(pixel.ToArgb().ToString());
                        string sub = pixel.ToArgb().ToString();
                        if (pixel.ToArgb() < 0)
                        {
                            sub = sub.Substring(1);
                            writeHelper(Base36.Encode(int.Parse(sub)));
                        }
                        else
                        {
                            writeHelper("+" + Base36.Encode(int.Parse(sub)));
                        }
                    }
                    writeHelper("|");
                    outputRIF.Flush();
                    progressBar1.PerformStep();
                }
            }
            outputRIF.Close();
            MessageBox.Show("RIF sucessfully created.");
            this.Close();
        }
コード例 #17
0
ファイル: ChunkLoader.cs プロジェクト: AlphaDelta/SharpBukkit
        private string ChunkFileForXZ(int i, int j)
        {
            string s    = (new java.lang.StringBuilder()).Append("c.").Append(Base36.Encode(i)).Append(".").Append(Base36.Encode(j)).Append(".dat").ToString();
            string s1   = Base36.Encode(i & 0x3f);
            string s2   = Base36.Encode(j & 0x3f);
            string file = System.IO.Path.Combine(saveDir, s1);

            if (!System.IO.File.Exists(file))
            {
                if (createIfNecessary)
                {
                    System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(file));
                    //file.Mkdir();
                }
                else
                {
                    return(null);
                }
            }
            file = System.IO.Path.Combine(file, s2);
            if (!System.IO.File.Exists(file))
            {
                if (createIfNecessary)
                {
                    System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(file));
                }
                else
                {
                    return(null);
                }
            }
            file = System.IO.Path.Combine(file, s);
            if (!System.IO.File.Exists(file) && !createIfNecessary)
            {
                return(null);
            }
            else
            {
                return(file);
            }
        }
コード例 #18
0
ファイル: IDGenerator.cs プロジェクト: AndreAbrantes/Comet
        private static void PopulatePrefix()
        {
            var machineHash    = Math.Abs(Environment.MachineName.GetHashCode());
            var machineEncoded = Base36.Encode(machineHash);

            var i = _prefix.Length - 1;
            var j = 0;

            while (i >= 0)
            {
                if (j < machineEncoded.Length)
                {
                    _prefix[i] = machineEncoded[j];
                    j++;
                }
                else
                {
                    _prefix[i] = '0';
                }
                i--;
            }
        }
コード例 #19
0
ファイル: RsmqCsharp.cs プロジェクト: tontonrally/rsmqCsharp
        private async Task <RsmqQueue> GetQueue(string queueName, bool uid = false)
        {
            var transaction = RedisClient.CreateTransaction();

            var queueAttrTask = transaction.HashGetAllAsync($"{this._options.Namespace}:{queueName}:Q");
            var time          = await GetServerTime();

            if (await transaction.ExecuteAsync())
            {
                var queueAttr = await queueAttrTask;

                if (queueAttr.Length == 0)
                {
                    throw new QueueNotFoundException();
                }

                var props = Utils.ExtractPropsFromRedisHashEntries(queueAttr, new string[] { "vt", "delay", "maxsize" });

                var q = new RsmqQueue
                {
                    VisibilityTimer = int.Parse(props["vt"]),
                    Delay           = int.Parse(props["delay"]),
                    MaxSize         = int.Parse(props["maxsize"]),
                    Timestamp       = ((DateTimeOffset)time).ToUnixTimeMilliseconds()
                };

                if (uid)
                {
                    var us = time.ToString("ffffff");

                    var b36Id = Base36.Encode(long.Parse($"{((DateTimeOffset)time).ToUnixTimeSeconds()}{us}"));
                    q.Uid = $"{b36Id}{Utils.MakeId(22)}";
                }

                return(q);
            }

            return(null);
        }
コード例 #20
0
        public static string CalcSqlSchemaName(this BaseDoc _BaseDoc)
        {
            return(CacheMan.Cache(() =>
            {
                int checksum = 0;
                foreach (var t in _BaseDoc.ListRelatedEntities()
                         .Select(m => new
                {
                    TablePocoType = m,
                    TableName = m.Name.ToLower()
                })
                         .OrderBy(m => m.TableName))
                {
                    checksum ^= t.TableName.GetHashCode();

                    foreach (var p in t
                             .TablePocoType
                             .GetProperties()
                             .Select(p =>
                                     new
                    {
                        ColumnAttribute = p.GetCustomAttributes(true).OfType <ColumnAttribute>().FirstOrDefault(),
                        DataTypeName = p.PropertyType.Name
                    }).Where(m =>
                             m.ColumnAttribute != null &&
                             !string.IsNullOrWhiteSpace(m.ColumnAttribute.Name))
                             .OrderBy(m => m.ColumnAttribute.Name.ToLower()))
                    {
                        checksum ^= p.ColumnAttribute.Name.ToLower().GetHashCode() ^ p.DataTypeName.GetHashCode();
                    }
                }

                return string.Format(
                    "{0}_{1}",
                    _BaseDoc.DocTypeName,
                    Base36.Encode(Math.Abs(checksum)));
            }, false, _BaseDoc.GetType().FullName));
        }
コード例 #21
0
        public ActionResult Index()
        {
            ViewBag.SessionKey = Base36.Encode((ulong)DateTime.Now.Ticks);

            return(View());
        }
コード例 #22
0
 public void Base36EncodeTest()
 {
     Assert.AreEqual("2Z", Base36.Encode(107));
 }
コード例 #23
0
ファイル: Runtime.cs プロジェクト: superbee66/dcForm
        /// <summary>
        /// </summary>
        /// <param name="cSharpCode"></param>
        /// <param name="TempFileFolderName">Define this for debugging purposes</param>
        /// <returns></returns>
        internal static Assembly CompileCSharpCode(string cSharpCode, params string[] DebuggingTempFileDirectoryNameParts)
        {
            bool IncludeDebugInformation =
#if DEBUG
                true;
#else
                false;
#endif
            int key = Math.Abs(cSharpCode.GetHashCode()
                               ^ IncludeDebugInformation.GetHashCode()
                               ^ typeof(Runtime).Assembly.FullName.GetHashCode()
                               ^ WindowsIdentity.GetCurrent().User.Value.GetHashCode() // just incase the user changes due to an apppool change
                               );

            if (!CompileCSharpCodeAssemblies.ContainsKey(key))
            {
                CompilerParameters _CompilerParameters = new CompilerParameters
                {
                    IncludeDebugInformation = IncludeDebugInformation,
                    GenerateExecutable      = false,
                    GenerateInMemory        = false,
                    WarningLevel            = 0
                };

                // it was unknown at them time of this writting
                if (!string.IsNullOrWhiteSpace(CompileCSharpCodeDefaultOutDirectory))
                {
                    _CompilerParameters.OutputAssembly = CompileCSharpCodeDefaultOutDirectory + "\\" + Base36.Encode(key) + ".dll";
                }

                if (File.Exists(_CompilerParameters.OutputAssembly))
                {
                    CompileCSharpCodeAssemblies[key] = Assembly.LoadFile(_CompilerParameters.OutputAssembly);
                }
                else
                {
                    // Combine & normalize (different paths that load to the same dll) lists of referenced assemblies. Consider our custom list (UsingNamespaces.Values) & whatever is currently loaded into the AppDomain.This ensures the newly compiled object will have everything it needs.
                    Dictionary <string, string> ReferenceAssembliesDic = new Dictionary <string, string>();
                    foreach (string AppDomainAssemFileName in
                             AppDomain.CurrentDomain.GetAssemblies().Where(m => !m.IsDynamic).Select(m => m.Location))
                    {
                        if (File.Exists(AppDomainAssemFileName))
                        {
                            foreach (
                                string DirectoryName in
                                new[]
                            {
                                new FileInfo(AppDomainAssemFileName).DirectoryName,
                                @".",
                                @".\bin",
                                @".\bin\debug",
                                @".\bin\release"
                            })
                            {
                                if (Directory.Exists(DirectoryName))
                                {
                                    foreach (FileInfo _FileInfo in USING_NAMESPACES
                                             .Values
                                             .Select(FileName => String.Format(@"{0}\\{1}", DirectoryName, FileName))
                                             .Where(FilePath => File.Exists(FilePath))
                                             .Select(FilePath => new FileInfo(FilePath))
                                             .Where(_FileInfo => !ReferenceAssembliesDic.ContainsKey(_FileInfo.Name.ToLower())))
                                    {
                                        ReferenceAssembliesDic[_FileInfo.Name.ToLower()] = _FileInfo.FullName;
                                    }
                                }
                            }
                        }
                    }

                    _CompilerParameters.ReferencedAssemblies.AddRange(ReferenceAssembliesDic.Values.ToArray());

                    CompilerResults _CompilerResults = CSharpCodeProvider.CompileAssemblyFromSource(_CompilerParameters, cSharpCode);

                    if (_CompilerResults.Errors.Count == 0)
                    {
                        CompileCSharpCodeDefaultOutDirectory = Path.GetDirectoryName(_CompilerResults.PathToAssembly);
                        CompileCSharpCodeAssemblies[key]     = _CompilerResults.CompiledAssembly;
                    }
                    else
                    {
                        new DirectoryInfo(RequestPaths.GetPhysicalApplicationPath(FOLDER_FOR_COMPILE_TEMPORARY_FILES)).mkdir().Attributes = FileAttributes.Hidden;

                        if (DebuggingTempFileDirectoryNameParts != null && DebuggingTempFileDirectoryNameParts.Length > 0)
                        {
                            int           i = 0;
                            DirectoryInfo _DirectoryInfo = null;


                            // often there are processes that just won't let there handles go off previous files generated
                            // now we try delete those directories or create a new one with an auto-incremented number when the previous can't be removed
                            do
                            {
                                _DirectoryInfo = new DirectoryInfo(
                                    RequestPaths
                                    .GetPhysicalApplicationPath(
                                        new[] { FOLDER_FOR_COMPILE_TEMPORARY_FILES, StringTransform.SafeIdentifier(string.Join(" ", DebuggingTempFileDirectoryNameParts.Union(new[] { string.Format("{0}", i++) }))) }
                                        .ToArray()));

                                try { _DirectoryInfo.rmdir(); } catch (Exception) { }
                            } while (_DirectoryInfo.Exists);

                            _DirectoryInfo.mkdir();

                            _CompilerParameters.GenerateInMemory        = false;
                            _CompilerParameters.IncludeDebugInformation = true;
                            _CompilerParameters.TempFiles             = new TempFileCollection(_DirectoryInfo.FullName, true);
                            _CompilerParameters.TreatWarningsAsErrors = true;

                            CSharpCodeProvider.CompileAssemblyFromSource(_CompilerParameters, cSharpCode);

                            throw new Exception(string.Format("\"{0}\" Contains runtime the intermediate files of a runtime build (compile) that failed.", _DirectoryInfo.FullName));
                        }
                    }
                }
            }
            return(CompileCSharpCodeAssemblies[key]);
        }
コード例 #24
0
ファイル: Runtime.cs プロジェクト: progablab/rudine
        public static Assembly CompileCSharpCode(Func <string> cSharpCodeFactory, string OutputName = default(string))
        {
            // can't be null as it will be used in calc later
            OutputName = OutputName ?? string.Empty;

            string cSharpCode = string.IsNullOrWhiteSpace(OutputName)
                                    ? cSharpCodeFactory.Invoke()
                                    : string.Empty;

            bool IncludeDebugInformation =
#if DEBUG
                true;
#else
                false;
#endif
            int key = Math.Abs(cSharpCode.GetHashCode()
                               ^ OutputName.GetHashCode()
                               ^ IncludeDebugInformation.GetHashCode()
                               ^ typeof(Runtime).Assembly.FullName.GetHashCode()
                               ^ WindowsIdentity.GetCurrent()
                               .User.Value.GetHashCode()                  // just incase the user changes due to an apppool change
                               );

            if (!CompileCSharpCodeAssemblies.ContainsKey(key))
            {
                CompilerParameters _CompilerParameters = new CompilerParameters
                {
                    IncludeDebugInformation = IncludeDebugInformation,
                    GenerateExecutable      = false,
                    GenerateInMemory        = false,
                    WarningLevel            = 0,
                    TreatWarningsAsErrors   = false
                };

                // it was unknown at them time of this writing
                if (!string.IsNullOrWhiteSpace(CompileCSharpCodeDefaultOutDirectory))
                {
                    _CompilerParameters.OutputAssembly = string.Format(
                        "{0}\\{1}{2}.dll",
                        CompileCSharpCodeDefaultOutDirectory,
                        string.IsNullOrWhiteSpace(OutputName)
                            ? string.Empty
                            : string.Format("{0}.", FileSystem.CleanFileName(OutputName)),
                        Base36.Encode(key));

                    if (_CompilerParameters.OutputAssembly.Length > 250)
                    {
                        _CompilerParameters.OutputAssembly = string.Format("{0}\\{1}{2}.dll", CompileCSharpCodeDefaultOutDirectory, string.Empty, Base36.Encode(key));
                    }
                }

                if (File.Exists(_CompilerParameters.OutputAssembly))
                {
                    CompileCSharpCodeAssemblies[key] = Assembly.LoadFile(_CompilerParameters.OutputAssembly);
                }
                else
                {
                    // naming parts where specified above so the cSharpCode was no needed right away to calculate the base36 filename, now we actually need to cSharp code for it's primary purpose (to compile it)
                    if (string.IsNullOrWhiteSpace(cSharpCode))
                    {
                        cSharpCode = cSharpCodeFactory.Invoke();
                    }

                    lock (CSharpCodeProvider)
                    {
                        // Combine & normalize (different paths that load to the same dll) lists of referenced assemblies.
                        // Consider our custom list (UsingNamespaces.Values) & whatever is currently loaded into the AppDomain.
                        // This ensures the newly compiled object will have everything it needs.
                        Dictionary <string, string> ReferenceAssembliesDic = new Dictionary <string, string>();
                        foreach (string AppDomainAssemFileName in
                                 AppDomain.CurrentDomain.GetAssemblies()
                                 .Where(m => !m.IsDynamic)
                                 .Select(m => m.Location))
                        {
                            if (File.Exists(AppDomainAssemFileName))
                            {
                                foreach (
                                    string DirectoryName in
                                    new[] {
                                    new FileInfo(AppDomainAssemFileName).DirectoryName,
                                    @".",
                                    @".\bin",
                                    @".\bin\debug",
                                    @".\bin\release"
                                })
                                {
                                    if (Directory.Exists(DirectoryName))
                                    {
                                        foreach (FileInfo _FileInfo in USING_NAMESPACES
                                                 .Values
                                                 .Select(FileName => String.Format(@"{0}\\{1}", DirectoryName, FileName))
                                                 .Where(FilePath => File.Exists(FilePath))
                                                 .Select(FilePath => new FileInfo(FilePath))
                                                 .Where(_FileInfo => !ReferenceAssembliesDic.ContainsKey(_FileInfo.Name.ToLower())))
                                        {
                                            ReferenceAssembliesDic[_FileInfo.Name.ToLower()] = _FileInfo.FullName;
                                        }
                                    }
                                }
                            }
                        }

                        _CompilerParameters.ReferencedAssemblies.AddRange(ReferenceAssembliesDic.Values.ToArray());

                        CompilerResults _CompilerResults = CSharpCodeProvider.CompileAssemblyFromSource(_CompilerParameters, cSharpCode);

                        if (_CompilerResults.Errors.Count == 0)
                        {
                            CompileCSharpCodeDefaultOutDirectory = Path.GetDirectoryName(_CompilerResults.PathToAssembly);
                            CompileCSharpCodeAssemblies[key]     = _CompilerResults.CompiledAssembly;
                        }
                        else
                        {
                            new DirectoryInfo(RequestPaths.GetPhysicalApplicationPath(FOLDER_FOR_COMPILE_TEMPORARY_FILES)).mkdir()
                            .Attributes = FileAttributes.Hidden;

                            int           i = 0;
                            DirectoryInfo _DirectoryInfo = null;

                            // often there are processes that just won't let there handles go off previous files generated
                            // now we try delete those directories or create a new one with an auto-incremented number when the previous can't be removed
                            do
                            {
                                _DirectoryInfo = new DirectoryInfo(
                                    RequestPaths
                                    .GetPhysicalApplicationPath(FOLDER_FOR_COMPILE_TEMPORARY_FILES, string.Format("{0}_{1}", Base36.Encode(key), i++)));

                                try
                                {
                                    _DirectoryInfo.rmdir();
                                }
                                catch (Exception) { }
                            }while (_DirectoryInfo.Exists);

                            _DirectoryInfo.mkdir();

                            _CompilerParameters.GenerateInMemory        = false;
                            _CompilerParameters.IncludeDebugInformation = true;
                            _CompilerParameters.TempFiles             = new TempFileCollection(_DirectoryInfo.FullName, true);
                            _CompilerParameters.TreatWarningsAsErrors = true;

                            CSharpCodeProvider.CompileAssemblyFromSource(_CompilerParameters, cSharpCode);

                            throw new Exception(string.Format("\"{0}\" Contains runtime the intermediate files of a runtime build (compile) that failed.", _DirectoryInfo.FullName));
                        }
                    }
                }
            }
            return(CompileCSharpCodeAssemblies[key]);
        }
コード例 #25
0
        public IHttpActionResult newstuff(ACC011AZ1 newMember, string leaderID)
        {
            #region member
            var utcDate     = DateTime.UtcNow;
            var morDateTime = utcDate.AddHours(1);
            var morDate     = morDateTime.ToString("yyy-MM-dd");
            var morTime     = morDateTime.ToString("HH:mm:ss");
            //ACC011AZ1 mem = new ACC011AZ1();
            //the "10" can be replaced by any starting value
            string maxIDplus = _ctx.Member.Where(w => w.DISTR_ID.StartsWith("06")).Max(q => q.DISTR_ID);
            string distr_sub = maxIDplus.Substring(2, maxIDplus.Length - 2);

            int zeroCount = 0;
            for (int i = 0; i < distr_sub.Length; i++)
            {
                if (distr_sub[i] == '0')
                {
                    zeroCount++;
                }
                else
                {
                    break;
                }
            }

            int int_distr_sub = 0;

            if (int.TryParse(distr_sub, out int_distr_sub))
            {
                int_distr_sub++;
                maxIDplus = int_distr_sub.ToString();
                maxIDplus = maxIDplus.PadLeft(distr_sub.Length, '0');
                maxIDplus = maxIDplus.Insert(0, "06");
            }

            newMember.DISTR_ID = maxIDplus;
            newMember.DETAILED = "1";
            //sponsor_id gy mn el user
            //to calculate icode
            string sponsorID    = newMember.SPONSOR_ID;
            var    sponsorIcode = _ctx.Member.Where(x => x.DISTR_ID == sponsorID).Select(w => w.ICODE).SingleOrDefault();
            newMember.DISTR_ORDER = _ctx.Member.Where(w => w.ICODE.StartsWith(sponsorIcode) && w.ICODE.Length == sponsorIcode.Length + 5).Max(l => l.DISTR_ORDER);

            if (newMember.DISTR_ORDER == null)
            {
                newMember.DISTR_ORDER = 1;
            }
            else
            {
                newMember.DISTR_ORDER++;
            }

            newMember.ICODE = sponsorIcode;
            string temp        = "";
            string distr_index = newMember.DISTR_ID.Substring(0, 2);

            int int_index = int.Parse(distr_index);
            temp            = Base36.Encode(int_index);
            temp            = temp.PadLeft(2, '0');
            newMember.ICODE = newMember.ICODE + temp;
            temp            = Base36.Encode(newMember.DISTR_ORDER);
            temp            = temp.PadLeft(3, '0');

            newMember.ICODE       = newMember.ICODE + temp;
            newMember.DISTR_LEVEL = newMember.ICODE.Length / 5;

            newMember.DETAILED = "1";
            newMember.SHIFT_ID = "012";
            //02
            newMember.SERVICE_CENTER        = "06";
            newMember.JOIN_DATE             = morDate; //DateTime.Now.ToString("yyy-MM-dd");
            newMember.CURRENT_DISTR_TYPE_ID = "00";
            newMember.DIRECTOR_ID           = "00000000";
            newMember.YEAR_DISTR_TYPE       = "";
            newMember.IDENT_LPLACE          = "";
            newMember.DUE_DAYS   = 0;
            newMember.SM_ID      = "00";
            newMember.GROUP_ID   = "00/000";
            newMember.CRE_LIMIT  = 0;
            newMember.MODULE_ID  = "SA";
            newMember.COMP_ID    = "001";
            newMember.SENT       = "0";
            newMember.CR_LMT_TYP = null;
            newMember.AR_AC_ID   = "00000000";
            newMember.ADD_DATE   = newMember.LAST_DATE = newMember.JOIN_DATE;
            newMember.LAST_USER  = newMember.USER_ID = "006";
            newMember.S_AUTO_KEY = 0;
            newMember.ADD_TIME   = morTime;//DateTime.Now.ToString("HH:mm:ss");
            //s_serial empty string
            newMember.S_SERIAL          = "TEST";
            newMember.REG_FEES          = 30;
            newMember.PAID_FEES         = 0;
            newMember.FEES_TYPE         = "1";
            newMember.YEAR_STATUS       = "999999999999";
            newMember.LAST_RENEWAL_DATE = morDate;//DateTime.Now.ToString("yyy-MM-dd");
            newMember.FAX = "";
            var dupe = _ctx.Member.Select(w => w.DISTR_IDENT).ToList();

            if (dupe.Contains(newMember.DISTR_IDENT))
            {
                return(Content(HttpStatusCode.Conflict, "User Identity Already Exists. Please try again."));
            }

            _ctx.Member.Add(newMember);
            _ctx.SaveChanges();
            #endregion
            string vouIDplusApAq = _ctx.APM.Where(w => w.DOC_ID.StartsWith("06")).Max(q => q.DOC_ID);
            string vouSub        = vouIDplusApAq.Substring(2, vouIDplusApAq.Length - 2);
            int    vouSubInt     = 0;
            if (int.TryParse(vouSub, out vouSubInt))
            {
                vouSubInt++;
                vouIDplusApAq = vouSubInt.ToString();
                vouIDplusApAq = vouIDplusApAq.PadLeft(vouSub.Length, '0');
                vouIDplusApAq = vouIDplusApAq.Insert(0, "06");
            }

            string vouIDplus  = _ctx.A9M.Where(w => w.VOU_ID.StartsWith("06")).Where(x => x.TRANS_TYPE == "ST_RS_RSO_O").Max(q => q.VOU_ID);
            string vouSub1    = vouIDplus.Substring(2, vouIDplus.Length - 2);
            int    vouSubInt1 = 0;
            if (int.TryParse(vouSub1, out vouSubInt1))
            {
                vouSubInt1++;
                vouIDplus = vouSubInt1.ToString();
                vouIDplus = vouIDplus.PadLeft(vouSub1.Length, '0');
                vouIDplus = vouIDplus.Insert(0, "06");
            }
            var pn = Convert.ToDouble(_ctx.Periods.Where(w => w.MODULE_ID == "SA").Select(x => x.LAST_OPEN).SingleOrDefault());
            MemberInvoiceDTO memberInvoiceDTO = new MemberInvoiceDTO
            {
                apmaster = new ACC011AP
                {
                    USER_ID       = leaderID,
                    DOC_ID        = vouIDplusApAq,
                    DISTR_ID      = newMember.DISTR_ID,
                    S_SERIAL      = newMember.DISTR_ID + vouIDplusApAq,
                    NET_TOTAL     = 30,
                    QUOT_ID       = vouIDplus,
                    DOC_DATE      = morDate,//DateTime.UtcNow.ToString("yyy-MM-dd"),
                    SM_ID         = "00",
                    SA_ID         = "02",
                    SL_LOC_ID     = "02",
                    DISC_RATIO    = 0,
                    DISC_VAL      = 0,
                    ADDED_TAX     = 0,
                    DED_TAX       = 0,
                    NET_AFTER_TAX = 0,
                    LDELIVERY     = "0000000000",
                    // AREMARKS = "",
                    // LREMARKS = "",
                    IS_TEMPLATE = "0",
                    CLOSEDFLAG  = "0",
                    ADD_TIME    = morTime, //DateTime.Now.ToString("HH:mm:ss"),
                    ADD_DATE    = morDate, //DateTime.Now.ToString("yyy-MM-dd"),
                    LAST_DATE   = morDate, //DateTime.Now.ToString("yyy-MM-dd"),
                    SENT        = "0",
                    OWNER       = null,
                    MODULE_ID   = "SA",
                    HELD        = "0",
                    PRJ_ID      = null,
                    COMP_ID     = "001",
                    DS_SHIPMENT = "023000000000",
                    AREMARKS    = "عضوية جديدة"
                },
                aqdetail = new ACC011AQ
                {
                    DOC_ID = vouIDplusApAq,

                    COUNTER    = "0001",
                    ITEM_ID    = "99m",
                    UNIT       = "",
                    QTY_REQ    = 1,
                    UNIT_PRICE = 30,
                    TOT_PRICE  = 30,
                    ITEM_BP    = 0,
                    ITEM_BV    = 0,
                    //unit_price
                    DISC_RATIO = 0,
                    DISC_VAL   = 0,
                    NET_PRICE  = 30,

                    //net_price
                    //tot_price
                    SENT       = "0",
                    MODULE_ID  = "SA",
                    PACK_UNITS = 0,
                    COMP_ID    = "001",
                    ADD_DATE   = morDate, //DateTime.Now.ToString("yyy-MM-dd"),
                    LAST_DATE  = morDate, //DateTime.Now.ToString("yyy-MM-dd"),
                    USER_ID    = leaderID,
                    LAST_USER  = "******",
                    ADD_TIME   = morTime,//DateTime.Now.ToString("HH:mm:ss"),
                    S_SERIAL   = vouIDplusApAq + "99m" + "0001",
                },
                a9master = new ACC011A9
                {
                    VOU_ID     = vouIDplus,
                    TRANS_TYPE = "ST_RS_RSO_O",
                    VOU_DATE   = morDate, //DateTime.Now.ToString("yyy-MM-dd"),
                    ADD_DATE   = morDate, //DateTime.Now.ToString("yyy-MM-dd"),
                    LAST_DATE  = morDate, //DateTime.Now.ToString("yyy-MM-dd"),
                    CUS_VEN_ID = newMember.DISTR_ID,

                    //adescr is ""
                    ADESCR = "",
                    LDESCR = "",
                    PRJ_ID = "00",
                    //make sure it's 06
                    STORE_ID = "02",
                    TO_ST_ID = "",
                    // CUS_VEN_ID distr_id .. input
                    BRANCH_ID  = "02",
                    DOC_ID     = "",
                    USE_RSRV   = "0",
                    PERIOD_NO  = pn,
                    TOTAL_COST = 30,
                    POSTED     = "0",
                    NO_MODIFY  = "0",

                    SENT      = "0",
                    MODULE_ID = "SA",
                    USER_ID   = leaderID,
                    // USER_ID =  LAST_USER = "******",
                    COMP_ID     = "001",
                    S_AUTO_KEY  = 1,
                    V_DISTR_ID  = "0000",
                    ADD_TIME    = morTime,// DateTime.UtcNow.ToString("HH:mm:ss"),//AddHours(1).ToString("HH:mm:ss"),//+ DateTime.Parse("01:00:00"),//DateTime.Now.ToString("HH:mm:ss"),
                    S_SERIAL    = "SA0053A2LIZQH00",
                    REC_OWNER   = "U",
                    DS_SHIPMENT = "023000000000"
                                  //AREMARKS = "عضوية جديدة"
                },
                aadetail = new ACC011AA
                {
                    // DOC_ID = vouIDplus,

                    TRANS_TYPE = "ST_RS_RSO_O",
                    VOU_ID     = vouIDplus,
                    ITEM_ID    = "99m",
                    COUNTER    = "0001",
                    VOU_DATE   = morDate, //DateTime.Now.ToString("yyy-MM-dd"),
                    ADD_DATE   = morDate, //DateTime.Now.ToString("yyy-MM-dd"),
                    LAST_DATE  = morDate, //DateTime.Now.ToString("yyy-MM-dd"),
                    STORE_ID   = "02",
                    BATCH_ID   = "",
                    EXP_DATE   = "",
                    C_C_ID     = "00/00",
                    PACK_UNITS = 1,
                    //qty, item_id, ratio,
                    TOTAL_COST = 0,
                    ITEM_COST  = 0,
                    RATIO      = 0,
                    REL_ID     = "",
                    PERIOD_NO  = pn,
                    DLV_QTY    = 0,
                    NEW_COST   = 0,
                    COMP_ID    = "001",
                    USER_ID    = leaderID,
                    LAST_USER  = "******",
                    QTY        = 1,
                    S_AUTO_KEY = 0,
                    ADD_TIME   = morTime,//DateTime.Now.ToString("HH:mm:ss"),
                    SENT       = "0",
                    S_SERIAL   = "SA005672TP83L19",
                    VOU_SIGN   = 0,
                    V_DISTR_ID = "0000",
                    ST_LOC_ID  = "",
                    // VOU_SIGN = -1,
                    QTY2 = 0,
                }
            };
            _ctx.APM.Add(memberInvoiceDTO.apmaster);
            //_ctx.SaveChanges();
            _ctx.AQD.Add(memberInvoiceDTO.aqdetail);
            //_ctx.SaveChanges();

            _ctx.AAD.Add(memberInvoiceDTO.aadetail);
            //_ctx.SaveChanges();
            _ctx.A9M.Add(memberInvoiceDTO.a9master);
            _ctx.SaveChanges();
            return(Created(new Uri(Request.RequestUri + "/" + newMember.DISTR_ID), new { id = newMember.DISTR_ID }));
        }
コード例 #26
0
 private string GetSoundEntryLabel()
 {
     return(Base36.Encode(this.SoundID));
 }
コード例 #27
0
 public void When_encoding() => Base36.Encode(10).ShouldBe("A");
コード例 #28
0
ファイル: SmartScope.cs プロジェクト: xw1998/DeviceInterface
        private void InitializeHardware()
        {
            InitializeMemories();
            try
            {
                //FIXME: I have to do this synchronously here because there's no blocking on the USB traffic
                //but there should be when flashing the FPGA.

                byte[] response = GetPicFirmwareVersion();
                if (response == null)
                {
                    throw new Exception("Failed to read from device");
                }
                Logger.Debug(String.Format("PIC FW Version readout {0}", String.Join(".", response)));

                //Init ROM
                this.rom = new Rom(hardwareInterface);

                //Init FPGA
                LogWait("Starting fpga flashing...", 0);

                this.flashed = false;
                string fwName;
                byte[] firmware = null;

                //Get FW contents
                try
                {
                    LabNation.Common.SerialNumber s = new SerialNumber(this.Serial);
                    fwName   = String.Format("blobs.SmartScope_{0}.bin", Base36.Encode((long)s.model, 3).ToUpper());
                    firmware = Resources.Load(fwName);
                }
                catch (Exception e)
                {
                    throw new ScopeIOException("Opening FPGA FW file failed\n" + e.Message);
                }
                if (firmware == null)
                {
                    throw new ScopeIOException("Failed to read FW");
                }

                Logger.Info("Got firmware of length " + firmware.Length);
                if (!this.hardwareInterface.FlashFpga(firmware))
                {
                    throw new ScopeIOException("failed to flash FPGA");
                }
                if (GetFpgaFirmwareVersion() == FPGA_VERSION_UNFLASHED)
                {
                    throw new ScopeIOException("Got firmware version of unflashed FPGA");
                }
                LogWait("FPGA flashed...");
                this.flashed = true;

                InitializeMemories();
                LogWait("Memories initialized...");

                Logger.Debug(String.Format("FPGA FW version = 0x{0:x}", GetFpgaFirmwareVersion()));

                Configure();
                deviceReady = true;
            }
            catch (ScopeIOException e)
            {
                Logger.Error("Failure while connecting to device: " + e.Message);
                this.hardwareInterface = null;
                this.flashed           = false;
                InitializeMemories();
                throw e;
            }
        }
コード例 #29
0
        /// <summary>
        ///     first response performance critical
        /// </summary>
        /// <returns></returns>
        public override MetadataSet GetGeneratedMetadata()
        {
            ImporterController.TryDocRevImporting();

            int i = 0;
            // let the base build up metadata for the service contracts as these are static
            MetadataSet _MetadataSet = base.GetGeneratedMetadata();

            foreach (DirectoryInfo _DirectoryInfo in Directory
                     .EnumerateDirectories(FilesystemTemplateController.DirectoryPath)
                     .Select(path => new DirectoryInfo(path)))
            {
                // persist the datacontract xml schema for the datacontract to the user's temporary directory
                //TODO:combine this logic and Runtime's that calculates it's dll output location
                int key = Math.Abs(File.ReadAllText(
                                       RequestPaths.GetPhysicalApplicationPath(
                                           "doc",
                                           _DirectoryInfo.Name,
                                           Runtime.MYSCHEMA_XSD_FILE_NAME)).GetHashCode()
                                   ^ WindowsIdentity.GetCurrent().User.Value.GetHashCode()); // just incase the user changes due to an apppool change

                string tempDataContractXsdPath = string.Format("{0}\\{1}.xsd", Path.GetTempPath(), Base36.Encode(key));

                if (!File.Exists(tempDataContractXsdPath))
                {
                    // the datacontracts are the things that are dynamic & change according to what DocTypes are present
                    XsdDataContractExporter _XsdDataContractExporter = new XsdDataContractExporter();
                    Type DocType = Runtime.ActivateBaseDocType(_DirectoryInfo.Name, TemplateController.Instance.TopDocRev(_DirectoryInfo.Name));
                    _XsdDataContractExporter.Export(DocType);
                    // _XsdDataContractExporter.Schemas.CompilationSettings.EnableUpaCheck = true;
                    _XsdDataContractExporter.Schemas.Compile();

                    foreach (XmlSchema _XmlSchema in _XsdDataContractExporter.Schemas.Schemas(_XsdDataContractExporter.GetRootElementName(DocType).Namespace))
                    {
                        using (Stream _Stream = File.OpenWrite(tempDataContractXsdPath))
                        {
                            _MetadataSet.MetadataSections.Add(MetadataSection.CreateFromSchema(_XmlSchema));
                            _XmlSchema.Write(_Stream);
                            break;
                        }
                    }
                }

                using (Stream _Stream = File.OpenRead(tempDataContractXsdPath))
                    _MetadataSet.MetadataSections.Add(MetadataSection.CreateFromSchema(
                                                          XmlSchema.Read(_Stream, (s, o) =>
                    {
                        /*if (o != null && o.Exception != null) throw o.Exception;*/
                    })));
            }

            return(_MetadataSet);
        }
コード例 #30
0
        private bool FlashFpga()
        {
            this.flashed = false;
            int packetSize        = 32;     //hardwareInterface.WriteControlMaxLength ();
            int packetsPerCommand = 64;

            if (packetSize <= 0)
            {
                return(false);
            }

            string fwName;

            try
            {
                LabNation.Common.SerialNumber s = new SerialNumber(this.Serial);
                fwName = String.Format("SmartScope_{0}.bin", Base36.Encode((long)s.model, 3).ToUpper());
            }
            catch (Exception)
            {
                return(false);
            }

            byte []  firmware         = null;
            DateTime firmwareModified = DateTime.Now;
            int      killMeNow        = 2048 / 8;

            //Data to send to keep clock running after all data was sent
            byte [] dummyData = new byte[packetSize];
            for (int i = 0; i < dummyData.Length; i++)
            {
                dummyData [i] = 255;
            }

            //Get FW contents
            try {
                firmware = Resources.Load(fwName);
            } catch (Exception e) {
                Logger.Error("Opening FPGA FW file failed");
                Logger.Error(e.Message);
                return(false);
            }
            if (firmware == null)
            {
                Logger.Error("Failed to read FW");
                return(false);
            }

            Logger.Debug("Got firmware of length " + firmware.Length);

            //Send FW to FPGA
            try {
                Stopwatch flashStopwatch = new Stopwatch();
                flashStopwatch.Start();
                String fwModifiedString = Utils.GetPrettyDate(firmwareModified);
                Logger.Debug("Firmware was created " + fwModifiedString);
                UInt16 commands = (UInt16)(firmware.Length / packetSize + killMeNow);
                //PIC: enter FPGA flashing mode
                byte[] msg = new byte[] {
                    SmartScopeUsbInterfaceHelpers.HEADER_CMD_BYTE,
                    (byte)SmartScopeUsbInterfaceHelpers.PIC_COMMANDS.PROGRAM_FPGA_START,
                    (byte)(commands >> 8),
                    (byte)(commands),
                };
                hardwareInterface.WriteControlBytes(msg, false);

                //FIXME: this sleep is found necessary on android tablets.

                /* The problem occurs when a scope is initialised the *2nd*
                 * time after the app starts, i.e. after replugging it.
                 * A possible explanation is that in the second run, caches
                 * are hit and the time between the PROGRAM_FPGA_START command
                 * and the first bitstream bytes is smaller than on the first run.
                 *
                 * Indeed, if this time is smaller than the time for the INIT bit
                 * (see spartan 6 ug380 fig 2.4) to rise, the first bitstream data
                 * is missed and the configuration fails.
                 */
                System.Threading.Thread.Sleep(10);
                hardwareInterface.FlushDataPipe();

                int bytesSent   = 0;
                int commandSize = packetsPerCommand * packetSize;
                while (bytesSent < firmware.Length)
                {
                    if (bytesSent + commandSize > firmware.Length)
                    {
                        commandSize = firmware.Length - bytesSent;
                    }
                    hardwareInterface.WriteControlBytesBulk(firmware, bytesSent, commandSize, false);
                    bytesSent += commandSize;
                }
                flashStopwatch.Stop();
                for (int j = 0; j < killMeNow; j++)
                {
                    hardwareInterface.WriteControlBytesBulk(dummyData, false);
                }

                //Send finish flashing command
                hardwareInterface.SendCommand(SmartScopeUsbInterfaceHelpers.PIC_COMMANDS.PROGRAM_FPGA_END);
                Logger.Debug(String.Format("Flashed FPGA in {0:0.00}s", (double)flashStopwatch.ElapsedMilliseconds / 1000.0));
                Logger.Debug("Flushing data pipe");
                //Flush whatever might be left in the datapipe
                hardwareInterface.FlushDataPipe();
                if (GetFpgaFirmwareVersion() == FPGA_VERSION_UNFLASHED)
                {
                    Logger.Error("Got firmware version of unflashed FPGA");
                    return(false);
                }
                this.flashed = true;
            } catch (ScopeIOException e) {
                Logger.Error("Flashing FPGA failed failed");
                Logger.Error(e.Message);
                return(false);
            }
            return(true);
        }