예제 #1
0
        public void SaveUserInfo(UserInfo userInfo)
        {
            using (IUserRegistrationUow userRegInfoUow = new UserRegistrationUow())
            {
                BaseConverter<UserInfo, ApplicationUser> viewModelToAppUserModelConv= new BaseConverter<UserInfo, ApplicationUser>();
                var appUserDetails = viewModelToAppUserModelConv.SourceModelToTargetModel(userInfo, new ApplicationUser());
                appUserDetails.LoginId = "test";
                appUserDetails.LoginKey = "1";
                appUserDetails.IsSysGenerated = "Y";
                appUserDetails.RoleId = 1;
                appUserDetails.Email = "*****@*****.**";
                appUserDetails.StatusId = 1;
                appUserDetails.UserTypeId = 1;
                userRegInfoUow.AppUser.Add(appUserDetails);

                BaseConverter<UserInfo, MemberAccount> viewModelToMemAccModelConv = new BaseConverter<UserInfo, MemberAccount>();
                var memAccDetails = viewModelToMemAccModelConv.SourceModelToTargetModel(userInfo, new MemberAccount());
                memAccDetails.CreatedBy = 1;
                memAccDetails.CreatedTime = DateTime.Now;
                memAccDetails.Email = "*****@*****.**";
                userRegInfoUow.MemAccount.Add(memAccDetails);

                userRegInfoUow.Commit();
            }
        }
예제 #2
0
 public void Ctor_ValuesIsNull_ThrowArgumentNullException()
 {
     var convert = new BaseConverter(null);
 }
예제 #3
0
        public static byte[] DecodeBase64(string data)
        {
            var bi = BaseConverter.Parse(data, BaseNAlphabet.Base64_RFC4648);

            return(bi.ToByteArray());
        }
예제 #4
0
        public override void Search()
        {
            Results.Clear();

            byte[]        text = (byte[])Params["text"];
            ProcessHandle phandle;
            int           count = 0;

            int  minsize = (int)BaseConverter.ToNumberParse((string)Params["s_ms"]);
            bool unicode = (bool)Params["unicode"];

            bool opt_priv = (bool)Params["private"];
            bool opt_img  = (bool)Params["image"];
            bool opt_map  = (bool)Params["mapped"];

            try
            {
                phandle = new ProcessHandle(PID, ProcessAccess.QueryInformation | Program.MinProcessReadMemoryRights);
            }
            catch
            {
                CallSearchError("Could not open process: " + Win32.GetLastErrorMessage());
                return;
            }

            phandle.EnumMemory(info =>
            {
                // skip unreadable areas
                if (info.Protect == MemoryProtection.AccessDenied)
                {
                    return(true);
                }
                if (info.State != MemoryState.Commit)
                {
                    return(true);
                }

                if ((!opt_priv) && (info.Type == MemoryType.Private))
                {
                    return(true);
                }

                if ((!opt_img) && (info.Type == MemoryType.Image))
                {
                    return(true);
                }

                if ((!opt_map) && (info.Type == MemoryType.Mapped))
                {
                    return(true);
                }

                byte[] data   = new byte[info.RegionSize.ToInt32()];
                int bytesRead = 0;

                CallSearchProgressChanged(
                    String.Format("Searching 0x{0} ({1} found)...", info.BaseAddress.ToString("x"), count));

                try
                {
                    bytesRead = phandle.ReadMemory(info.BaseAddress, data, data.Length);

                    if (bytesRead == 0)
                    {
                        return(true);
                    }
                }
                catch
                {
                    return(true);
                }

                StringBuilder curstr = new StringBuilder();
                bool isUnicode       = false;
                byte byte2           = 0;
                byte byte1           = 0;

                for (int i = 0; i < bytesRead; i++)
                {
                    bool isChar = IsChar(data[i]);

                    if (unicode && isChar && isUnicode && byte1 != 0)
                    {
                        isUnicode = false;

                        if (curstr.Length > 0)
                        {
                            curstr.Remove(curstr.Length - 1, 1);
                        }

                        curstr.Append((char)data[i]);
                    }
                    else if (isChar)
                    {
                        curstr.Append((char)data[i]);
                    }
                    else if (unicode && data[i] == 0 && IsChar(byte1) && !IsChar(byte2))
                    {
                        // skip null byte
                        isUnicode = true;
                    }
                    else if (unicode &&
                             data[i] == 0 && IsChar(byte1) && IsChar(byte2) && curstr.Length < minsize)
                    {
                        // ... [char] [char] *[null]* ([char] [null] [char] [null]) ...
                        //                   ^ we are here
                        isUnicode = true;
                        curstr    = new StringBuilder();
                        curstr.Append((char)byte1);
                    }
                    else
                    {
                        if (curstr.Length >= minsize)
                        {
                            int length = curstr.Length;

                            if (isUnicode)
                            {
                                length *= 2;
                            }

                            Results.Add(new string[]
                            {
                                Utils.FormatAddress(info.BaseAddress),
                                String.Format("0x{0:x}", i - length), length.ToString(),
                                curstr.ToString()
                            });

                            count++;
                        }

                        isUnicode = false;
                        curstr    = new StringBuilder();
                    }

                    byte2 = byte1;
                    byte1 = data[i];
                }

                return(true);
            });

            phandle.Dispose();

            CallSearchFinished();
        }
예제 #5
0
 public override string ToDecimalString()
 {
     return(BaseConverter.OctalToDecimal(_value));
 }
예제 #6
0
        /// <summary>
        /// Process a request message with HttpClient object.
        /// </summary>
        public async Task <T> ProcessRequest <T>(T content, CancellationToken cancellationToken)
        {
            if (this.BaseUri == null)
            {
                throw new ArgumentException("BaseUri is not defined");
            }

            HttpResponseMessage response = null;
            T dmSetResponse = default(T);

            try
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                }

                var requestUri = new StringBuilder();
                requestUri.Append(this.BaseUri.ToString());
                requestUri.Append(this.BaseUri.ToString().EndsWith("/", StringComparison.CurrentCultureIgnoreCase) ? string.Empty : "/");

                // Add params if any
                if (ScopeParameters != null && ScopeParameters.Count > 0)
                {
                    string prefix = "?";
                    foreach (var kvp in ScopeParameters)
                    {
                        requestUri.AppendFormat("{0}{1}={2}", prefix, Uri.EscapeUriString(kvp.Key),
                                                Uri.EscapeUriString(kvp.Value));
                        if (prefix.Equals("?"))
                        {
                            prefix = "&";
                        }
                    }
                }

                // default handler if no one specified
                HttpClientHandler httpClientHandler = this.Handler ?? new HttpClientHandler();

                // serialize dmSet content to bytearraycontent
                var serializer = BaseConverter <T> .GetConverter(SerializationFormat);

                var binaryData = serializer.Serialize(content);
                ByteArrayContent arrayContent = new ByteArrayContent(binaryData);

                // do not dispose HttpClient for performance issue
                if (client == null)
                {
                    client = new HttpClient(httpClientHandler);
                }

                // add it to the default header
                if (this.Cookie != null)
                {
                    client.DefaultRequestHeaders.Add("Cookie", this.Cookie.ToString());
                }

                HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri.ToString())
                {
                    Content = arrayContent
                };

                if (this.CustomHeaders != null && this.CustomHeaders.Count > 0)
                {
                    foreach (var kvp in this.CustomHeaders)
                    {
                        requestMessage.Headers.Add(kvp.Key, kvp.Value);
                    }
                }

                //request.AddHeader("content-type", "application/json");
                if (SerializationFormat == SerializationFormat.Json && !requestMessage.Content.Headers.Contains("content-type"))
                {
                    requestMessage.Content.Headers.Add("content-type", "application/json");
                }

                response = await client.SendAsync(requestMessage, cancellationToken);

                if (cancellationToken.IsCancellationRequested)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                }

                // get response from server
                if (!response.IsSuccessStatusCode)
                {
                    throw new Exception(response.ReasonPhrase);
                }

                // try to set the cookie for http session
                var headers = response?.Headers;
                if (headers != null)
                {
                    if (headers.TryGetValues("Set-Cookie", out IEnumerable <string> tmpList))
                    {
                        var cookieList = tmpList.ToList();

                        // var cookieList = response.Headers.GetValues("Set-Cookie").ToList();
                        if (cookieList != null && cookieList.Count > 0)
                        {
                            // Get the first cookie
                            this.Cookie = CookieHeaderValue.ParseList(cookieList).FirstOrDefault();
                        }
                    }
                }

                using (var streamResponse = await response.Content.ReadAsStreamAsync())
                    if (streamResponse.CanRead && streamResponse.Length > 0)
                    {
                        dmSetResponse = serializer.Deserialize(streamResponse);
                    }

                return(dmSetResponse);
            }
            catch (Exception e)
            {
                if (response.Content == null)
                {
                    throw e;
                }

                try
                {
                    var exrror = await response.Content.ReadAsStringAsync();

                    WebSyncException webSyncException = JsonConvert.DeserializeObject <WebSyncException>(exrror);

                    if (webSyncException != null)
                    {
                        throw webSyncException;
                    }
                }
                catch (WebSyncException)
                {
                    throw;
                }
                catch (Exception)
                {
                    // no need to do something here, just rethrow the initial error
                }

                throw e;
            }
        }
예제 #7
0
 public string Cambia_64() => BaseConverter.ToBaseN(srcInt, BaseNAlphabet.Base64);
 //creates a new NumericRangeFactory
 //converter - the BaseConverter that defines the number system
 //being used
 //min - the smallest value in an acceptable range
 //length - the number of values in a single range
 public NumericRangeFactory(BaseConverter converter, long min,
                            long length)
 {
     _converter = converter; _min = min; _length = length;
 }
 public NumericRangeFactory(BaseConverter converter, string min,
                            long length) : this(converter.StringToLong(min), length)
 {
 }
예제 #10
0
        private void buttonFilter_Click(object sender, EventArgs e)
        {
            ContextMenu menu = new ContextMenu();

            foreach (ColumnHeader ch in listResults.Columns)
            {
                MenuItem columnMenu = new MenuItem(ch.Text);
                MenuItem item;

                columnMenu.Tag = ch.Index;

                item     = new MenuItem("Contains...", new EventHandler(filterMenuItem_Clicked));
                item.Tag = new Matcher(delegate(string s1, string s2)
                {
                    return(s1.Contains(s2));
                });
                columnMenu.MenuItems.Add(item);

                item     = new MenuItem("Contains (case-insensitive)...", new EventHandler(filterMenuItem_Clicked));
                item.Tag = new Matcher(delegate(string s1, string s2)
                {
                    return(s1.ToUpperInvariant().Contains(s2.ToUpperInvariant()));
                });
                columnMenu.MenuItems.Add(item);

                item     = new MenuItem("Regex...", new EventHandler(filterMenuItem_Clicked));
                item.Tag = new Matcher(delegate(string s1, string s2)
                {
                    try
                    {
                        System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(s2);

                        return(r.IsMatch(s1));
                    }
                    catch
                    {
                        return(false);
                    }
                });
                columnMenu.MenuItems.Add(item);

                item     = new MenuItem("Regex (case-insensitive)...", new EventHandler(filterMenuItem_Clicked));
                item.Tag = new Matcher(delegate(string s1, string s2)
                {
                    try
                    {
                        System.Text.RegularExpressions.Regex r =
                            new System.Text.RegularExpressions.Regex(s2, System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                        return(r.IsMatch(s1));
                    }
                    catch
                    {
                        return(false);
                    }
                });
                columnMenu.MenuItems.Add(item);

                columnMenu.MenuItems.Add(new MenuItem("-"));

                item     = new MenuItem("Numerical relation...", new EventHandler(filterMenuItem_Clicked));
                item.Tag = new Matcher(delegate(string s1, string s2)
                {
                    if (s2.Contains("!="))
                    {
                        decimal n1 = BaseConverter.ToNumberParse(s1);
                        decimal n2 = BaseConverter.ToNumberParse(s2.Split(new string[] { "!=" }, StringSplitOptions.None)[1]);

                        return(n1 != n2);
                    }
                    else if (s2.Contains("<="))
                    {
                        decimal n1 = BaseConverter.ToNumberParse(s1);
                        decimal n2 = BaseConverter.ToNumberParse(s2.Split(new string[] { "<=" }, StringSplitOptions.None)[1]);

                        return(n1 <= n2);
                    }
                    else if (s2.Contains(">="))
                    {
                        decimal n1 = BaseConverter.ToNumberParse(s1);
                        decimal n2 = BaseConverter.ToNumberParse(s2.Split(new string[] { ">=" }, StringSplitOptions.None)[1]);

                        return(n1 >= n2);
                    }
                    else if (s2.Contains("<"))
                    {
                        decimal n1 = BaseConverter.ToNumberParse(s1);
                        decimal n2 = BaseConverter.ToNumberParse(s2.Split(new string[] { "<" }, StringSplitOptions.None)[1]);

                        return(n1 < n2);
                    }
                    else if (s2.Contains(">"))
                    {
                        decimal n1 = BaseConverter.ToNumberParse(s1);
                        decimal n2 = BaseConverter.ToNumberParse(s2.Split(new string[] { ">" }, StringSplitOptions.None)[1]);

                        return(n1 > n2);
                    }
                    else if (s2.Contains("="))
                    {
                        decimal n1 = BaseConverter.ToNumberParse(s1);
                        decimal n2 = BaseConverter.ToNumberParse(s2.Split(new string[] { "=" }, StringSplitOptions.None)[1]);

                        return(n1 == n2);
                    }
                    else
                    {
                        return(false);
                    }
                });
                columnMenu.MenuItems.Add(item);

                menu.MenuItems.Add(columnMenu);
            }

            menu.Show(buttonFilter, new System.Drawing.Point(buttonFilter.Size.Width, 0));
        }
예제 #11
0
        private void readWriteAddressMemoryMenuItem_Click(object sender, EventArgs e)
        {
            PromptBox prompt = new PromptBox();

            if (prompt.ShowDialog() == DialogResult.OK)
            {
                IntPtr address       = new IntPtr(-1);
                IntPtr regionAddress = IntPtr.Zero;
                long   regionSize    = 0;
                bool   found         = false;

                try
                {
                    address = ((long)BaseConverter.ToNumberParse(prompt.Value)).ToIntPtr();
                }
                catch
                {
                    PhUtils.ShowError("You have entered an invalid address.");

                    return;
                }

                List <MemoryItem> items = new List <MemoryItem>();

                foreach (MemoryItem item in _provider.Dictionary.Values)
                {
                    items.Add(item);
                }

                items.Sort((i1, i2) => i1.Address.CompareTo(i2.Address));

                int i = 0;

                foreach (MemoryItem item in items)
                {
                    if (item.Address.CompareTo(address) > 0)
                    {
                        MemoryItem regionItem = items[i - 1];

                        listMemory.Items[regionItem.Address.ToString()].Selected = true;
                        listMemory.Items[regionItem.Address.ToString()].EnsureVisible();
                        regionAddress = regionItem.Address;
                        regionSize    = regionItem.Size;
                        found         = true;

                        break;
                    }

                    i++;
                }

                if (!found)
                {
                    PhUtils.ShowError("Unable to find the memory address.");
                    return;
                }

                MemoryEditor m_e = MemoryEditor.ReadWriteMemory(_pid, regionAddress, (int)regionSize, false,
                                                                new Program.MemoryEditorInvokeAction(delegate(MemoryEditor f) { f.Select(address.Decrement(regionAddress).ToInt64(), 1); }));
            }
        }
예제 #12
0
 protected BaseRepo(BaseMongoService <TM> service
                    , BaseConverter <T, TM> converter)
 {
     this.converter = converter;
     this.service   = service;
 }
예제 #13
0
        private void ValidateCustomTextFields()
        {
            // Get the bases of each field so we can validate them

            if (!int.TryParse(Base1.Text, out int base1))
            {
                base1 = -1;
            }
            if (!int.TryParse(Base2.Text, out int base2))
            {
                base2 = -1;
            }
            if (!int.TryParse(Base3.Text, out int base3))
            {
                base3 = -1;
            }

            // Store the current position of the caret

            int caret1 = Custom1.CaretIndex;
            int caret2 = Custom2.CaretIndex;
            int caret3 = Custom3.CaretIndex;

            // If they entered invalid text, take one away from the caret so it will end up in the same place

            char[] validCharacters = BaseConverter.GetValidCharactersForBase(base1);
            if (!string.IsNullOrEmpty(Base1.Text) && Custom1.Text.ToCharArray().Any(x => !validCharacters.Contains(x)))
            {
                caret1--;
            }

            validCharacters = BaseConverter.GetValidCharactersForBase(base2);
            if (!string.IsNullOrEmpty(Custom2.Text) && Custom2.Text.ToCharArray().Any(x => !validCharacters.Contains(x)))
            {
                caret2--;
            }

            validCharacters = BaseConverter.GetValidCharactersForBase(base3);
            if (!string.IsNullOrEmpty(Custom3.Text) && Custom3.Text.ToCharArray().Any(x => !validCharacters.Contains(x)))
            {
                caret3--;
            }

            // Remove the invalid text

            validCharacters = BaseConverter.GetValidCharactersForBase(base1);
            Custom1.Text    = string.Concat(Custom1.Text.ToCharArray().Where(x => validCharacters.Contains(x)));

            validCharacters = BaseConverter.GetValidCharactersForBase(base2);
            Custom2.Text    = string.Concat(Custom2.Text.ToCharArray().Where(x => validCharacters.Contains(x)));

            validCharacters = BaseConverter.GetValidCharactersForBase(base3);
            Custom3.Text    = string.Concat(Custom3.Text.ToCharArray().Where(x => validCharacters.Contains(x)));

            // Set the position of the caret back to what it was before

            if (caret1 < 1)
            {
                caret1 = 0;
            }
            if (caret2 < 1)
            {
                caret2 = 0;
            }
            if (caret3 < 1)
            {
                caret3 = 0;
            }

            Custom1.CaretIndex = caret1;
            Custom2.CaretIndex = caret2;
            Custom3.CaretIndex = caret3;
        }
예제 #14
0
        void OnSelectButtonClicked(object o, EventArgs args)
        {
            if (dataBook.NPages == 0)
            {
                return;
            }

            DataView dv = ((DataViewDisplay)dataBook.CurrentPageWidget).View;

            long fromOffset = -1;
            long toOffset   = -1;
            int  relative   = 0;

            try {
                fromOffset = BaseConverter.Parse(FromEntry.Text);
            }
            catch (FormatException e) {
                ErrorAlert ea = new ErrorAlert(Catalog.GetString("Error in From Offset Format"), e.Message, null);
                ea.Run();
                ea.Destroy();
                return;
            }

            string toString = ToEntry.Text.Trim();

            if (toString.StartsWith("+"))
            {
                relative = 1;
            }
            else if (toString.StartsWith("-"))
            {
                relative = -1;
            }

            toString = toString.TrimStart(new char[] { '+', '-' });

            try {
                toOffset = BaseConverter.Parse(toString);
            }
            catch (FormatException e) {
                ErrorAlert ea = new ErrorAlert(Catalog.GetString("Error in To Offset Format"), e.Message, null);
                ea.Run();
                ea.Destroy();
                return;
            }

            if (relative != 0)
            {
                toOffset = fromOffset + relative * (toOffset - 1);
            }

            if (toOffset >= 0 && toOffset < dv.Buffer.Size &&
                fromOffset >= 0 && fromOffset < dv.Buffer.Size)
            {
                dv.SetSelection(fromOffset, toOffset);
                dv.Display.MakeOffsetVisible(toOffset, DataViewDisplay.ShowType.Closest);
                // append string to drop-down lists
                ListStore ls = (ListStore)ToEntry.Completion.Model;
                ls.AppendValues(ToEntry.Text);
                ls = (ListStore)FromEntry.Completion.Model;
                ls.AppendValues(FromEntry.Text);
            }
            else
            {
                ErrorAlert ea = new ErrorAlert(Catalog.GetString("Invalid Range"), Catalog.GetString("The range you specified is outside the file's limits."), null);
                ea.Run();
                ea.Destroy();
            }
        }
예제 #15
0
        public void ToBaseN_WhenBaseIs16AndNumberEquals255_ReturnsFF()
        {
            var convert = new BaseConverter(this.base16Values);
            string result = convert.ToBaseN(16, 255, 0, 255);

            Assert.AreEqual("FF", result);
        }
예제 #16
0
        private void button1_Click(object sender, EventArgs e)
        {
            //print
            string[] lines = File.ReadAllLines(label4.Text).Select(t => t.Trim()).Where(t => t != "" && t != "0").ToArray();

            LabelPrinter printer = new LabelPrinter();

            ProgressDialog pgd = new ProgressDialog("Printing Labels");

            pgd.Show();
            pgd.Maximum = lines.Length - 1;

            for (int i = 0; i < lines.Length;)
            {
                pgd.LabelText = "Printing Label " + (i + 1) + " of " + lines.Length;

                if ((i + 1) < lines.Length)
                {
                    printer.PrintTwoLabel(BaseConverter.EncodeFromBase10(Convert.ToUInt64(lines[i])), BaseConverter.EncodeFromBase10(Convert.ToUInt64(lines[i + 1])));
                }
                else
                {
                    printer.PrintLabel(BaseConverter.EncodeFromBase10(Convert.ToUInt64(lines[i])));
                }

                if ((i + 1) < lines.Length)
                {
                    i += 2;
                    pgd.Step();
                    pgd.Step();
                }
                else
                {
                    i++;
                    pgd.Step();
                }
            }
        }
예제 #17
0
        private async void button1_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex == 0)
            {
                List <string> files_to_import = new List <string>();

                using (OpenFileDialog ofd = new OpenFileDialog())
                {
                    ofd.Multiselect      = true;
                    ofd.Filter           = "Supported Extentions (*.db2bak)|*.db2bak";
                    ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                    ofd.FileName         = "";

                    if (ofd.ShowDialog() == DialogResult.OK)
                    {
                        files_to_import.AddRange(ofd.FileNames);
                    }
                }

                if (files_to_import.Count() == 0)
                {
                    return;
                }

                foreach (string path in files_to_import)
                {
                    ImportDB2Bak(path);
                }
            }
            else
            if (listBox1.SelectedIndex == 2) //import nuid set
            {
                List <string> to_import = new List <string>();

                using (OpenFileDialog ofd = new OpenFileDialog())
                {
                    ofd.Multiselect      = true;
                    ofd.Filter           = "Supported Extentions (*.txt)|*.txt";
                    ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                    ofd.FileName         = "";

                    if (ofd.ShowDialog() == DialogResult.OK)
                    {
                        to_import.AddRange(ofd.FileNames);
                    }
                }

                if (to_import.Count() == 0)
                {
                    return;
                }

                using (MySqlConnection sqlconn = new MySqlConnection(MCv2Persistance.Instance.Config.DatabaseConfiguration.DatabaseConnectionProperties.ConnectionString))
                {
                    await sqlconn.OpenAsync();

                    foreach (string path in to_import)
                    {
                        UInt64[] nuids = File.ReadAllLines(path).Where(x => x.Trim() != "").Select(v => Convert.ToUInt64(BaseConverter.DecodeFromString(v.Trim()))).ToArray();
                        foreach (var nuid in nuids)
                        {
                            await DatabaseUtilities.AddCardToDatabase(sqlconn, nuid);
                        }
                    }
                }
            }
            else
            if (listBox1.SelectedIndex == 1)
            {
                foreach (Control c in Controls)
                {
                    c.Enabled = false;
                }

                UseWaitCursor = true;



                List <string> files_to_import = new List <string>();

                using (OpenFileDialog ofd = new OpenFileDialog())
                {
                    ofd.Multiselect      = true;
                    ofd.Filter           = "Supported Extentions (*.xlsx)|*.xlsx";
                    ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                    ofd.FileName         = "";

                    if (ofd.ShowDialog() == DialogResult.OK)
                    {
                        files_to_import.AddRange(ofd.FileNames);
                    }
                }

                if (files_to_import.Count() == 0)
                {
                    return;
                }


                if (listBox1.SelectedIndex == 0) //import database backup
                {
                }
                else
                if (listBox1.SelectedIndex == 1) //import master controller list
                {
                    ProgressDialog pgd = new ProgressDialog("Importing List");
                    pgd.Show(this);

                    pgd.LabelText = "Importing " + files_to_import.Count() + " files.";

                    foreach (string file_name in files_to_import)
                    {
                        //import users

                        //load file

                        pgd.Reset();
                        pgd.LabelText = "Parsing list " + (files_to_import.IndexOf(file_name) + 1) + " of " + files_to_import.Count();

                        List <ListMember> members = (await ListUtilities.GetListMembers(new string[] { file_name })).ToList();

                        pgd.Step();

                        using (MySqlConnection sqlconn = new MySqlConnection(MCv2Persistance.Instance.Config.DatabaseConfiguration.DatabaseConnectionProperties.ConnectionString))
                        {
                            pgd.Reset();
                            pgd.LabelText = "Opening Database Connection";

                            await sqlconn.OpenAsync();

                            pgd.Step();

                            //check to make sure the user table exists
                            List <string> table_names = new List <string>();

                            using (MySqlCommand cmdName = new MySqlCommand("show tables", sqlconn))
                                using (MySqlDataReader reader = cmdName.ExecuteReader())
                                    while (await reader.ReadAsync())
                                    {
                                        table_names.Add(reader.GetString(0));
                                    }

                            if (!table_names.Contains("users"))
                            {
                                string cmdstr = "CREATE TABLE `accesscontrol`.`users` (`user_id` BIGINT UNSIGNED NOT NULL,`name` VARCHAR(255) NOT NULL,`description` VARCHAR(255) NULL,PRIMARY KEY (`user_id`),UNIQUE INDEX `user_id_UNIQUE` (`user_id` ASC));";

                                using (MySqlCommand sqlcmd = new MySqlCommand(cmdstr, sqlconn))
                                    await sqlcmd.ExecuteNonQueryAsync();
                            }

                            //generate subset of listmembers that dont exist in the current user list
                            //this will be based off of name and description matching

                            pgd.Reset();
                            pgd.LabelText = "Generating List of New Users";

                            if (members.Count() > 0)
                            {
                                pgd.Maximum = members.Count() - 1;
                            }

                            List <ListMember> new_users = new List <ListMember>();

                            foreach (ListMember lm in members)
                            {
                                if (lm.Name.Trim() == "")
                                {
                                    pgd.Step();
                                    continue;
                                }

                                string cmd = "SELECT * FROM `users` WHERE name=@name AND description=@description;";

                                using (MySqlCommand sqlcmd = new MySqlCommand(cmd, sqlconn))
                                {
                                    sqlcmd.Parameters.AddWithValue("@name", lm.Name.Trim());
                                    sqlcmd.Parameters.AddWithValue("@description", lm.Description.Trim());

                                    using (MySqlDataReader reader = sqlcmd.ExecuteReader())
                                        if (!(await reader.ReadAsync()))
                                        {
                                            new_users.Add(lm);
                                        }
                                }

                                pgd.Step();
                            }

                            pgd.Reset();
                            pgd.LabelText = "Adding New Users to the Database";

                            if (new_users.Count() > 0)
                            {
                                pgd.Maximum = new_users.Count() - 1;
                            }

                            foreach (ListMember lm in new_users)
                            {
                                using (MySqlCommand sqlcmd = new MySqlCommand("insert into `users` (user_id, name, description) values (@user_id, @name, @description)", sqlconn))
                                {
                                    sqlcmd.Parameters.AddWithValue("@user_id", await DatabaseUtilities.GenerateUniqueUserID(sqlconn));
                                    sqlcmd.Parameters.AddWithValue("@name", lm.Name.Trim());
                                    sqlcmd.Parameters.AddWithValue("@description", lm.Description.Trim());

                                    await sqlcmd.ExecuteNonQueryAsync();
                                }

                                pgd.Step();
                            }

                            //check to see if the cards table exists

                            if (!table_names.Contains("cards"))
                            {
                                string cmd = "CREATE TABLE `accesscontrol`.`cards` (`uid` BIGINT UNSIGNED NOT NULL,`user_id` BIGINT UNSIGNED NULL,PRIMARY KEY (`uid`),UNIQUE INDEX `uid_UNIQUE` (`uid` ASC));";

                                using (MySqlCommand sqlcmd = new MySqlCommand(cmd, sqlconn))
                                    await sqlcmd.ExecuteNonQueryAsync();
                            }

                            //generate a list of new cards that will be added to the database

                            pgd.Reset();
                            pgd.LabelText = "Adding New Cards to the Database";

                            List <ListMember> new_cards = new List <ListMember>();

                            foreach (ListMember lm in members)
                            {
                                if (lm.UID == 0)
                                {
                                    continue;
                                }

                                string cmd = "SELECT uid FROM `cards` WHERE uid=@uid;";

                                using (MySqlCommand sqlcmd = new MySqlCommand(cmd, sqlconn))
                                {
                                    sqlcmd.Parameters.AddWithValue("@uid", lm.UID);

                                    using (MySqlDataReader reader = sqlcmd.ExecuteReader())
                                        if (!(await reader.ReadAsync()))
                                        {
                                            new_cards.Add(lm);
                                        }
                                }
                            }

                            if (new_cards.Count() > 0)
                            {
                                pgd.Maximum = new_cards.Count() - 1;
                            }

                            //add the new cards to the database

                            foreach (ListMember lm in new_cards)
                            {
                                using (MySqlCommand sqlcmd = new MySqlCommand("insert into `cards` (uid, user_id) values (@uid, @user_id)", sqlconn))
                                {
                                    sqlcmd.Parameters.AddWithValue("@uid", lm.UID);
                                    sqlcmd.Parameters.AddWithValue("@user_id", 0);

                                    await sqlcmd.ExecuteNonQueryAsync();
                                }

                                pgd.Step();
                            }

                            //associate card uids with user_ids

                            pgd.Reset();
                            pgd.LabelText = "Associating Cards With Users";
                            pgd.Maximum   = members.Count() - 1;

                            foreach (ListMember lm in members)
                            {
                                if (lm.Name.Trim() == "" || lm.UID == 0)
                                {
                                    pgd.Step();
                                    continue;
                                }

                                //obtain user_id from database

                                UInt64 user_id = 0;

                                string cmd = "SELECT user_id FROM `users` WHERE name=@name AND description=@description;";

                                using (MySqlCommand sqlcmd = new MySqlCommand(cmd, sqlconn))
                                {
                                    sqlcmd.Parameters.AddWithValue("@name", lm.Name.Trim());
                                    sqlcmd.Parameters.AddWithValue("@description", lm.Description.Trim());

                                    using (MySqlDataReader reader = sqlcmd.ExecuteReader())
                                        if (await reader.ReadAsync())
                                        {
                                            user_id = reader.GetUInt64(0);
                                        }
                                }

                                //complete card association

                                using (MySqlCommand sqlcmd = new MySqlCommand("update `cards` set user_id=@user_id where uid=@uid;", sqlconn))
                                {
                                    sqlcmd.Parameters.AddWithValue("@user_id", user_id);
                                    sqlcmd.Parameters.AddWithValue("@uid", lm.UID);

                                    await sqlcmd.ExecuteNonQueryAsync();
                                }

                                pgd.Step();
                            }

                            //generate access control list

                            //check to see if the lists table exists

                            if (!table_names.Contains("lists"))
                            {
                                string cmd = "CREATE TABLE `accesscontrol`.`lists` (`uid` BIGINT UNSIGNED NOT NULL,`alias` VARCHAR(255) NULL,`type` TINYINT UNSIGNED NOT NULL,PRIMARY KEY(`uid`),UNIQUE INDEX `uid_UNIQUE` (`uid` ASC));";

                                using (MySqlCommand sqlcmd = new MySqlCommand(cmd, sqlconn))
                                    await sqlcmd.ExecuteNonQueryAsync();
                            }

                            //create a master list table entry

                            pgd.Reset();
                            pgd.LabelText = "Adding List to Master Table";

                            UInt64 list_uid = await DatabaseUtilities.GenerateUniqueListUID(sqlconn);

                            using (MySqlCommand sqlcmd = new MySqlCommand("insert into `lists` (uid, alias, type) values (@uid, @alias, @type)", sqlconn))
                            {
                                sqlcmd.Parameters.AddWithValue("@uid", list_uid);
                                sqlcmd.Parameters.AddWithValue("@alias", new FileInfo(file_name).Name.Split('.')[0]);
                                sqlcmd.Parameters.AddWithValue("@type", 0);

                                await sqlcmd.ExecuteNonQueryAsync();
                            }

                            pgd.Step();

                            //create list table

                            pgd.Reset();
                            pgd.LabelText = "Creating New List Table";

                            string sqlcmdstr = "CREATE TABLE `accesscontrol`.`" + list_uid + "` (`user_id` BIGINT UNSIGNED NOT NULL,`days` VARCHAR(255) NOT NULL,`times` VARCHAR(255) NOT NULL,`enabled` TINYINT UNSIGNED NOT NULL,PRIMARY KEY(`user_id`),UNIQUE INDEX `user_id_UNIQUE` (`user_id` ASC));";

                            using (MySqlCommand sqlcmd = new MySqlCommand(sqlcmdstr, sqlconn))
                                await sqlcmd.ExecuteNonQueryAsync();

                            pgd.Step();

                            //populate list table

                            pgd.Reset();
                            pgd.LabelText = "Populating New List";
                            pgd.Maximum   = members.Count() - 1;

                            foreach (ListMember lm in members)
                            {
                                if (lm.Name.Trim() == "" || lm.UID == 0 || lm.ActiveDays.Trim() == "" || lm.ActiveTimes.Trim() == "")
                                {
                                    pgd.Step();
                                    continue;
                                }

                                UInt64 user_id = 0;

                                string cmd = "SELECT user_id FROM `users` WHERE name=@name AND description=@description;";

                                using (MySqlCommand sqlcmd = new MySqlCommand(cmd, sqlconn))
                                {
                                    sqlcmd.Parameters.AddWithValue("@name", lm.Name.Trim());
                                    sqlcmd.Parameters.AddWithValue("@description", lm.Description.Trim());

                                    using (MySqlDataReader reader = sqlcmd.ExecuteReader())
                                        if (await reader.ReadAsync())
                                        {
                                            user_id = reader.GetUInt64(0);
                                        }
                                }

                                if (user_id == 0)
                                {
                                    continue;
                                }

                                //check to see if the user is already present in the list and if necessary resolve the contention

                                cmd = "SELECT * FROM `" + list_uid + "` WHERE user_id=@user_id;";

                                bool   contention_detected   = false;
                                string resolved_access_days  = "";
                                string resolved_access_times = "";

                                using (MySqlCommand sqlcmd = new MySqlCommand(cmd, sqlconn))
                                {
                                    sqlcmd.Parameters.AddWithValue("@user_id", user_id);

                                    using (MySqlDataReader reader = sqlcmd.ExecuteReader())
                                        if (await reader.ReadAsync())
                                        {
                                            contention_detected = true;

                                            //there were multiple occurences of the user in the source list. merge the access privileges.

                                            string stored_access_days  = (string)reader["days"];
                                            string stored_access_times = (string)reader["times"];

                                            string contending_access_days  = lm.ActiveDays;
                                            string contending_access_times = lm.ActiveTimes;

                                            //parse entry times
                                            uint stored_start_hour, stored_start_minute, stored_end_hour, stored_end_minute;
                                            uint contending_start_hour, contending_start_minute, contending_end_hour, contending_end_minute;

                                            stored_start_hour   = uint.Parse(stored_access_times.Substring(0, stored_access_times.IndexOf(':')).Trim());
                                            stored_access_times = stored_access_times.Substring(stored_access_times.IndexOf(':') + 1);

                                            stored_start_minute = uint.Parse(stored_access_times.Substring(0, stored_access_times.IndexOf('-')).Trim());
                                            stored_access_times = stored_access_times.Substring(stored_access_times.IndexOf('-') + 1);

                                            stored_end_hour     = uint.Parse(stored_access_times.Substring(0, stored_access_times.IndexOf(':')).Trim());
                                            stored_access_times = stored_access_times.Substring(stored_access_times.IndexOf(':') + 1);

                                            stored_end_minute = uint.Parse(stored_access_times.Trim());

                                            //

                                            contending_start_hour   = uint.Parse(contending_access_times.Substring(0, contending_access_times.IndexOf(':')).Trim());
                                            contending_access_times = contending_access_times.Substring(contending_access_times.IndexOf(':') + 1);

                                            contending_start_minute = uint.Parse(contending_access_times.Substring(0, contending_access_times.IndexOf('-')).Trim());
                                            contending_access_times = contending_access_times.Substring(contending_access_times.IndexOf('-') + 1);

                                            contending_end_hour     = uint.Parse(contending_access_times.Substring(0, contending_access_times.IndexOf(':')).Trim());
                                            contending_access_times = contending_access_times.Substring(contending_access_times.IndexOf(':') + 1);

                                            contending_end_minute = uint.Parse(contending_access_times.Trim());

                                            //complete the time conflict resolution

                                            if (stored_start_hour * 24 + stored_start_minute < contending_start_hour * 24 + contending_start_minute)
                                            {
                                                resolved_access_times += stored_start_hour.ToString("00") + ":" + stored_start_minute.ToString("00") + "-";
                                            }
                                            else
                                            {
                                                resolved_access_times += contending_start_hour.ToString("00") + ":" + contending_start_minute.ToString("00") + "-";
                                            }

                                            if (stored_end_hour * 24 + stored_end_minute > contending_end_hour * 24 + contending_end_minute)
                                            {
                                                resolved_access_times += stored_end_hour.ToString("00") + ":" + stored_end_minute.ToString("00");
                                            }
                                            else
                                            {
                                                resolved_access_times += contending_end_hour.ToString("00") + ":" + contending_end_minute.ToString("00");
                                            }

                                            //begin day of week conflict resolution

                                            byte merged_days = (byte)(ListEntryUtilities.ConvertDaysString(stored_access_days) | ListEntryUtilities.ConvertDaysString(contending_access_days));

                                            List <string> to_merge = new List <string>();

                                            for (int i = 6; i >= 0; i--)
                                            {
                                                if (((byte)(merged_days >> i) & 1) == 1)
                                                {
                                                    to_merge.Add(days_of_the_week[6 - i]);
                                                }
                                            }

                                            for (int i = 0; i < to_merge.Count(); i++)
                                            {
                                                resolved_access_days += to_merge[i];

                                                if (i + 1 != to_merge.Count())
                                                {
                                                    resolved_access_days += ":";
                                                }
                                            }
                                        }
                                }

                                if (contention_detected)
                                {
                                    using (MySqlCommand sqlcmd = new MySqlCommand("update `" + list_uid + "` set days=@days, times=@times where user_id=@user_id;", sqlconn))
                                    {
                                        sqlcmd.Parameters.AddWithValue("@days", resolved_access_days);
                                        sqlcmd.Parameters.AddWithValue("@times", resolved_access_times);
                                        sqlcmd.Parameters.AddWithValue("@user_id", user_id);

                                        await sqlcmd.ExecuteNonQueryAsync();
                                    }
                                }
                                else
                                {
                                    using (MySqlCommand sqlcmd = new MySqlCommand("insert into `" + list_uid + "` (user_id, days, times, enabled) values (@user_id, @days, @times, @enabled)", sqlconn))
                                    {
                                        sqlcmd.Parameters.AddWithValue("@user_id", user_id);
                                        sqlcmd.Parameters.AddWithValue("@days", lm.ActiveDays);
                                        sqlcmd.Parameters.AddWithValue("@times", lm.ActiveTimes);
                                        sqlcmd.Parameters.AddWithValue("@enabled", 1);

                                        await sqlcmd.ExecuteNonQueryAsync();
                                    }
                                }

                                pgd.Step();
                            }
                        }
                    }

                    pgd.Dispose();
                }

                foreach (Control c in Controls)
                {
                    c.Enabled = true;
                }

                UseWaitCursor = false;
                Cursor        = Cursors.Default;

                Refresh();
            }
        }
예제 #18
0
        private async Task CardLookupAndDisplay(List <ulong> user_id, string query, bool force, CancellationTokenSource lcts = null)
        {
            if (lcts == null)
            {
                lcts = new CancellationTokenSource();
            }

            dgv1_cc = false;

            try
            {
                await Task.Run(async() =>
                {
                    //selected index description
                    //0 == unassigned cards
                    //1 == all cards
                    int selected_index = 0;

                    Invoke((MethodInvoker)(() =>
                    {
                        foreach (Control c in card_lookup_controls)
                        {
                            c.Enabled = false;
                        }

                        Refresh();
                    }));

                    if (display_uids_in_short_form)
                    {
                        if (query != "")
                        {
                            if (BaseConverter.TryParseEncodedString(query))
                            {
                                query = BaseConverter.DecodeFromString(query).ToString();
                            }
                        }
                    }

                    var cards = await DatabaseUtilities.GetAllCards(lcts);

                    //unassigned cards filtered by query
                    List <ulong> filtered_uids = cards.Where(x => x.UserAssignment == 0 && (query == "" || x.CardNUID.ToString().Contains(query))).Select(y => y.CardNUID).ToList();
                    filtered_uids.Sort();
                    List <string> formatted_filtered_uids = filtered_uids.Select(x => display_uids_in_short_form ? BaseConverter.EncodeFromBase10(x) : x.ToString()).ToList();

                    //assigned cards filtered by query
                    List <ulong> assigned_uids = new List <ulong>();

                    foreach (var id in user_id)
                    {
                        assigned_uids.AddRange(cards.Where(x => x.UserAssignment == id).Select(y => y.CardNUID));
                    }

                    List <ulong> filtered_assigned_uids = assigned_uids.Where(x => query == "" || x.ToString().Contains(query)).ToList();
                    filtered_assigned_uids.Sort();
                    List <string> formatted_filtered_assigned_uids = filtered_assigned_uids.Select(x => display_uids_in_short_form ? BaseConverter.EncodeFromBase10(x) : x.ToString()).ToList();



                    AutoCompleteStringCollection acsc_a = new AutoCompleteStringCollection();
                    acsc_a.AddRange(formatted_filtered_uids.ToArray());
                    acsc_a.AddRange(formatted_filtered_assigned_uids.ToArray());

                    Invoke((MethodInvoker)(() =>
                    {
                        listBox1.DataSource = formatted_filtered_uids;
                        textBox3.AutoCompleteCustomSource = acsc_a;

                        if (listBox1.Items.Count > 0)
                        {
                            button1.Enabled = true;
                        }

                        /////

                        listBox2.DataSource = formatted_filtered_assigned_uids;

                        if (listBox2.Items.Count > 0)
                        {
                            button2.Enabled = true;
                        }

                        ////

                        foreach (Control c in card_lookup_controls)
                        {
                            if (c.Name != "button1" && c.Name != "button2")
                            {
                                c.Enabled = true;
                            }
                        }

                        Refresh();
                    }));

                    if (formatted_filtered_uids.Count() == 0 && formatted_filtered_assigned_uids.Count() == 0 && query != "" && cards.Select(x => x.CardNUID).Contains(Convert.ToUInt64(query)))
                    {
                        var result = MessageBox.Show("The query had no results but the card was found. It's assigned to a user outside of the query parameters. Would you like to break the association and return the card to the pool?" +
                                                     " To determine the user association use the main search field to lookup the card. Clicking cancel will clear the card lookup field and refresh.", "Warning", MessageBoxButtons.OKCancel);
                        if (result == DialogResult.OK)
                        {
                            var sqlconn = await ARDBConnectionManager.default_manager.CheckOut();

                            using (MySqlCommand cmdName = new MySqlCommand("update `cards` set user_id=@user_id where uid=@uid", sqlconn.Connection))
                            {
                                cmdName.Parameters.AddWithValue("@user_id", 0);
                                cmdName.Parameters.AddWithValue("@uid", Convert.ToUInt64(query));
                                await cmdName.ExecuteNonQueryAsync();
                            }

                            ARDBConnectionManager.default_manager.CheckIn(sqlconn);

                            await CardLookupAndDisplay(user_id, textBox3.Text.Trim(), true, lcts);

                            return;
                        }
                    }
                }, lcts.Token);
            }
            catch (TaskCanceledException tcex) {  }

            dgv1_cc = true;
        }
예제 #19
0
 public WebProxyServerProvider(CoreProvider localProvider, SerializationFormat serializationFormat)
 {
     this.LocalProvider = localProvider;
     this.serializationFormat = serializationFormat;
     this.serializer = BaseConverter<HttpMessage>.GetConverter(this.serializationFormat);
 }
예제 #20
0
        /// <summary>
        /// Call this method to handle requests on the server, sent by the client
        /// </summary>
        public async Task HandleRequestAsync(HttpContext context, Action <SyncMemoryProvider> action, CancellationToken cancellationToken)
        {
            var httpRequest  = context.Request;
            var httpResponse = context.Response;
            var streamArray  = GetBody(httpRequest);

            var serializationFormat = SerializationFormat.Json;

            // Get the serialization format
            if (TryGetHeaderValue(context.Request.Headers, "dotmim-sync-serialization-format", out var vs))
            {
                serializationFormat = vs.ToLowerInvariant() == "json" ? SerializationFormat.Json : SerializationFormat.Binary;
            }

            if (!TryGetHeaderValue(context.Request.Headers, "dotmim-sync-session-id", out var sessionId))
            {
                throw new SyncException($"Can't find any session id in the header");
            }

            SyncMemoryProvider syncMemoryProvider = null;
            var         syncSessionId             = "";
            HttpMessage httpMessage = null;

            try
            {
                var serializer = BaseConverter <HttpMessage> .GetConverter(serializationFormat);

                httpMessage   = serializer.Deserialize(streamArray);
                syncSessionId = httpMessage.SyncContext.SessionId.ToString();

                if (!httpMessage.SyncContext.SessionId.Equals(Guid.Parse(sessionId)))
                {
                    throw new SyncException($"Session id is not matching correctly between header and message");
                }

                // get cached provider instance if not defined byt web proxy server provider
                if (syncMemoryProvider == null)
                {
                    syncMemoryProvider = GetCachedProviderInstance(context, syncSessionId);
                }

                if (syncMemoryProvider == null)
                {
                    syncMemoryProvider = AddNewProviderToCacheFromDI(context, syncSessionId);
                }

                // action from user if available
                action?.Invoke(syncMemoryProvider);

                // get cache manager
                // since we are using memorycache, it's not necessary to handle it here
                //syncMemoryProvider.LocalProvider.CacheManager = GetCacheManagerInstance(context, syncSessionId);

                var httpMessageResponse =
                    await syncMemoryProvider.GetResponseMessageAsync(httpMessage, cancellationToken);

                var binaryData = serializer.Serialize(httpMessageResponse);
                await GetBody(httpResponse).WriteAsync(binaryData, 0, binaryData.Length);
            }
            catch (Exception ex)
            {
                await WriteExceptionAsync(httpResponse, ex, syncMemoryProvider?.LocalProvider?.ProviderTypeName ?? "ServerLocalProvider");
            }
            finally
            {
                if (httpMessage != null && httpMessage.Step == HttpStep.EndSession)
                {
                    Cleanup(context.RequestServices.GetService(typeof(IMemoryCache)), syncSessionId);
                }
            }
        }
예제 #21
0
        private async Task UserLookupAndDisplay_Groups(string query, bool force, CancellationTokenSource lcts = null)
        {
            if (query != previous_search || previous_search == null || force)
            {
                if (lcts == null)
                {
                    lcts = new CancellationTokenSource();
                }

                await Task.Run(async() =>
                {
                    //RemoveDataGridView1Events();

                    Invoke((MethodInvoker)(() =>
                    {
                        dataGridView1.Enabled = false;

                        //dataGridView1.DataSource = null;

                        Refresh();
                    }));

                    //begin a second task. we need to build the autocomplete source.
                    string[] autocomplete_strings     = null;
                    Task auto_complete_source_builder = new Task(async() =>
                    {
                        autocomplete_strings = await DatabaseUtilities.BuildDenseAutocompleteSource(lcts.Token);
                    }, lcts.Token);
                    auto_complete_source_builder.Start();

                    previous_search = query;

                    AutoRefreshDBConnection sqlconn = await ARDBConnectionManager.default_manager.CheckOut();

                    //await DatabaseUtilities.CheckIfUsersTableExistsAndCreateIfNeeded(sqlconn);

                    int selected_index = 0;
                    Invoke((MethodInvoker)(() => { selected_index = comboBox1.SelectedIndex - 1; }));

                    var users_in_group = await GroupDBUtilities.GetUsersInGroup(ULAD_ViewingGroups.ElementAt(selected_index).Key);
                    var comp_str       = "";
                    foreach (var user in users_in_group)
                    {
                        comp_str += user + ", ";
                    }
                    if (comp_str != "")
                    {
                        comp_str = comp_str.Substring(0, comp_str.Length - 2);
                    }

                    if (query == "")
                    {
                        mySqlDataAdapter = new MySqlDataAdapter("select * from users where user_id in (0, " + comp_str + ");", sqlconn.Connection);
                    }
                    else
                    {
                        List <string> substrs = query.Split(' ').ToList();

                        List <string> results = new List <string>();

                        if (cb2_seli == 1)
                        {
                            foreach (var substr in substrs)
                            {
                                if (BaseConverter.TryParseEncodedString(substr))
                                {
                                    results.Add(BaseConverter.DecodeFromString(substr).ToString());
                                }
                            }
                        }

                        //substrs.AddRange(result);

                        //string cmd = "SELECT * FROM `users` WHERE";

                        string cmd = "SELECT a.user_id, a.name, a.description FROM users a LEFT JOIN cards b ON a.user_id=b.user_id WHERE (";

                        foreach (string str in substrs)
                        {
                            string str_l = str;

                            str_l = str_l.Replace("\'", "\\'");

                            ulong res;

                            bool is_int = UInt64.TryParse(str_l, out res);

                            if (cb2_seli == 0)
                            {
                                is_int = false;
                            }

                            cmd += " (";

                            if (is_int)
                            {
                                cmd += " a.user_id=" + str_l + " OR ";
                                cmd += " b.uid=" + str_l + ") AND";
                            }
                            else
                            {
                                cmd += " a.name LIKE " + "'%" + str_l + "%'" + " OR ";
                                cmd += " a.description LIKE " + "'%" + str_l + "%'" + ") AND";
                            }

                            bool is_encoded = false;
                            string dec_str  = "";

                            if (cb2_seli == 1)
                            {
                                if (is_encoded = BaseConverter.TryParseEncodedString(str_l))
                                {
                                    dec_str = BaseConverter.DecodeFromString(str_l).ToString();
                                }
                            }

                            if (is_encoded)
                            {
                                cmd  = cmd.Substring(0, cmd.Length - 4);
                                cmd += " OR (";
                                cmd += " a.user_id=" + dec_str + " OR ";
                                cmd += " b.uid=" + dec_str + ") AND";
                            }
                        }

                        cmd = cmd.Substring(0, cmd.Length - 4);

                        cmd += ") AND a.user_id in (0, " + comp_str + ")" + " GROUP BY a.user_id;";

                        Console.WriteLine(cmd);

                        mySqlDataAdapter = new MySqlDataAdapter(cmd, sqlconn.Connection);
                    }

                    DataSet ds = new DataSet();

                    try
                    {
                        await mySqlDataAdapter.FillAsync(ds);
                    }
                    catch (Exception ex)
                    {
                        //MessageBox.Show("Query Error");
                    }

                    await auto_complete_source_builder;

                    Invoke((MethodInvoker)(() =>
                    {
                        if (autocomplete_strings != null)
                        {
                            AutoCompleteStringCollection acsc = new AutoCompleteStringCollection();
                            acsc.AddRange(autocomplete_strings);
                            textBox1.AutoCompleteCustomSource = acsc;
                        }

                        //dataGridView1.DataSource = null;
                        try
                        {
                            dataGridView1.DataSource = ds.Tables[0];
                        }
                        catch (Exception ex)
                        {
                            dataGridView1.DataSource = null;
                        }

                        dataGridView1.Enabled = true;

                        Refresh();
                    }));

                    ARDBConnectionManager.default_manager.CheckIn(sqlconn);
                }, lcts.Token);
            }

            Invoke((MethodInvoker)(() =>
            {
                refreshToolStripMenuItem.BackColor = SystemColors.Control;
            }));
        }
예제 #22
0
        protected virtual int BuildByte(IBuffer buffer, long offset, BuildBytesInfo info, bool dummy)
        {
            string str;
            int    nwritten = 0;
            byte   b        = 0;

            if (dummy == true || offset >= buffer.Size)
            {
                dummy = true;
            }
            else
            {
                nwritten++;
                b = buffer[offset];
            }

            if (info.Type == 'A')
            {
                // Replace unprintable characters with dots
                if (b < 32 || b >= 127)
                {
                    str = ".";
                }
                else
                {
                    str = System.Text.Encoding.ASCII.GetString(new byte[] { b });
                }
            }
            else
            {
                bool lowercase;
                int  numBase = GetBaseFromArgument(info.Type, out lowercase);
                str = BaseConverter.ConvertToString(b, numBase, false, lowercase, 0);
            }

            if (!dummy && info.Prefix != null)
            {
                BuildPrefix(info.Prefix);
            }
            else
            {
                BuildEmpty(info.Prefix, " ");
            }

            if (!dummy && str != null)
            {
                BuildByteData(str);
            }
            else if (info.Empty != null)
            {
                BuildEmpty(str, info.Empty);
            }
            else
            {
                BuildEmpty(str, " ");
            }

            if (!dummy && info.Suffix != null)
            {
                BuildSuffix(info.Suffix);
            }
            else
            {
                BuildEmpty(info.Suffix, " ");
            }

            return(nwritten);
        }
예제 #23
0
 public override string ToBinaryString()
 {
     return(BaseConverter.OctalToBinary(_value));
 }
예제 #24
0
        private void ParseStructDef(string text, ref int i)
        {
            StructDef def = new StructDef();

            _eatResult = EatWhitespace(text, ref i);
            string structName = EatId(text, ref i);

            if (_eatResult || structName == "")
            {
                throw new ParserException(_fileName, _lineNumber, "Expected identifier (struct name)");
            }

            if (_structs.ContainsKey(structName))
            {
                throw new ParserException(_fileName, _lineNumber, "Struct name '" + structName + "' already used");
            }

            // add it first so that structs can be self-referential
            _structs.Add(structName, null);

            // {
            _eatResult = EatWhitespace(text, ref i);
            string openingBrace = EatSymbol(text, ref i);

            if (_eatResult || openingBrace != "{")
            {
                throw new ParserException(_fileName, _lineNumber, "Expected '{'");
            }

            while (true)
            {
                // }
                _eatResult = EatWhitespace(text, ref i);
                string endBrace = EatSymbol(text, ref i);

                if (_eatResult)
                {
                    throw new ParserException(_fileName, _lineNumber, "Expected type name or '}'");
                }
                if (endBrace == "}")
                {
                    break;
                }
                if (endBrace.Length > 0)
                {
                    throw new ParserException(_fileName, _lineNumber, "Unexpected '" + endBrace + "'");
                }

                // TYPE
                _eatResult = EatWhitespace(text, ref i);
                string typeName = EatId(text, ref i);

                if (_eatResult || typeName == "")
                {
                    throw new ParserException(_fileName, _lineNumber, "Expected type name");
                }

                FieldType type;

                if (_typeDefs.ContainsKey(typeName))
                {
                    type = this.GetType(typeName);
                }
                else
                {
                    type = FieldType.Struct;

                    if (!_structs.ContainsKey(typeName))
                    {
                        throw new ParserException(_fileName, _lineNumber, "Unknown identifier '" + typeName + "' (type or struct name)");
                    }
                }

                // type, without the pointer or array flag
                FieldType justType = type;

                // TYPE*
                // optional asterisk (pointer)
                _eatResult = EatWhitespace(text, ref i);

                if (EatSymbol(text, ref i) == "*")
                {
                    if (this.IsTypePointer(type))
                    {
                        throw new ParserException(_fileName, _lineNumber, "Invalid '*'; type '" + typeName + "' is already a pointer");
                    }

                    type |= FieldType.Pointer;
                }

                // TYPE* FIELDNAME
                _eatResult = EatWhitespace(text, ref i);
                string fieldName = EatId(text, ref i);

                if (_eatResult || fieldName == "")
                {
                    throw new ParserException(_fileName, _lineNumber, "Expected identifier (struct field name)");
                }

                if (def.ContainsField(fieldName))
                {
                    throw new ParserException(_fileName, _lineNumber, "Field name '" + fieldName + "' already used");
                }

                _eatResult = EatWhitespace(text, ref i);
                string leftSqBracket = EatSymbol(text, ref i);
                int    varLength     = 0;

                if (leftSqBracket == "[")
                {
                    _eatResult = EatWhitespace(text, ref i);
                    string fieldRefName  = EatId(text, ref i);
                    string fieldSizeSpec = EatNumber(text, ref i);

                    if (fieldRefName != "")
                    {
                        if (!def.ContainsField(fieldRefName))
                        {
                            throw new ParserException(_fileName, _lineNumber, "Unknown identifier '" + fieldRefName + "' (field name)");
                        }

                        def.GetField(fieldRefName).SetsVarOn = fieldName;

                        // const add/multiply
                        int iSave = i;

                        _eatResult = EatWhitespace(text, ref i);
                        string plusOrMulOrDivSign = EatSymbol(text, ref i);

                        if (plusOrMulOrDivSign == "+")
                        {
                            def.GetField(fieldRefName).SetsVarOnAdd = EatParseInt(text, ref i);
                        }
                        else if (plusOrMulOrDivSign == "*")
                        {
                            def.GetField(fieldRefName).SetsVarOnMultiply = EatParseFloat(text, ref i);

                            int iSave2 = i;
                            _eatResult = EatWhitespace(text, ref i);
                            string plusSign = EatSymbol(text, ref i);

                            if (plusSign == "+")
                            {
                                def.GetField(fieldRefName).SetsVarOnAdd = EatParseInt(text, ref i);
                            }
                            else if (plusSign == "-")
                            {
                                def.GetField(fieldRefName).SetsVarOnAdd = -EatParseInt(text, ref i);
                            }
                            else
                            {
                                i = iSave2;
                            }
                        }
                        else if (plusOrMulOrDivSign == "/")
                        {
                            // here we just set SetsVarOnMultiply to 1 / value
                            def.GetField(fieldRefName).SetsVarOnMultiply = 1 / EatParseFloat(text, ref i);

                            int iSave2 = i;
                            _eatResult = EatWhitespace(text, ref i);
                            string plusSign = EatSymbol(text, ref i);

                            if (plusSign == "+")
                            {
                                def.GetField(fieldRefName).SetsVarOnAdd = EatParseInt(text, ref i);
                            }
                            else if (plusSign == "-")
                            {
                                def.GetField(fieldRefName).SetsVarOnAdd = -EatParseInt(text, ref i);
                            }
                            else
                            {
                                i = iSave2;
                            }
                        }
                        else
                        {
                            // that didn't work; restore the index
                            i = iSave;
                        }
                    }
                    else if (fieldSizeSpec != "")
                    {
                        try
                        {
                            varLength = (int)BaseConverter.ToNumberParse(fieldSizeSpec);
                            varLength = (int)BaseConverter.ToNumberParse(fieldSizeSpec);
                        }
                        catch
                        {
                            throw new ParserException(_fileName, _lineNumber, "Could not parse number '" + fieldSizeSpec + "'");
                        }
                    }
                    else
                    {
                        throw new ParserException(_fileName, _lineNumber, "Number or identifier expected (size specifier)");
                    }

                    // if it's not a string, it's an array
                    if (justType != FieldType.StringASCII && justType != FieldType.StringUTF16)
                    {
                        type |= FieldType.Array;
                    }

                    _eatResult = EatWhitespace(text, ref i);
                    string rightSqBracket = EatSymbol(text, ref i);

                    if (_eatResult || rightSqBracket != "]")
                    {
                        throw new ParserException(_fileName, _lineNumber, "Expected ']'");
                    }

                    // fix up the semicolon
                    _eatResult    = EatWhitespace(text, ref i);
                    leftSqBracket = EatSymbol(text, ref i);
                }

                // TYPE* FIELDNAME;
                string endSemicolon = leftSqBracket;

                if (_eatResult || endSemicolon != ";")
                {
                    throw new ParserException(_fileName, _lineNumber, "Expected ';'");
                }

                StructField field = new StructField(fieldName, type);

                if (field.Type == FieldType.Struct)
                {
                    field.StructName = typeName;
                }

                field.VarArrayLength = varLength;
                field.VarLength      = varLength;

                def.AddField(field);
            }

            _structs[structName] = def;
        }
예제 #25
0
        private void buttonFilter_Click(object sender, EventArgs e)
        {
            ContextMenu menu = new ContextMenu();

            foreach (ColumnHeader ch in listResults.Columns)
            {
                MenuItem columnMenu = new MenuItem(ch.Text)
                {
                    Tag = ch.Index
                };

                MenuItem item = new MenuItem("Contains...", this.filterMenuItem_Clicked)
                {
                    Tag = new Matcher((s1, s2) => s1.Contains(s2, StringComparison.OrdinalIgnoreCase))
                };
                columnMenu.MenuItems.Add(item);

                item = new MenuItem("Contains (case-insensitive)...", this.filterMenuItem_Clicked)
                {
                    Tag = new Matcher((s1, s2) => s1.Contains(s2, StringComparison.OrdinalIgnoreCase))
                };
                columnMenu.MenuItems.Add(item);

                item = new MenuItem("Regex...", this.filterMenuItem_Clicked)
                {
                    Tag = new Matcher((s1, s2) =>
                    {
                        try
                        {
                            System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(s2);

                            return(r.IsMatch(s1));
                        }
                        catch
                        {
                            return(false);
                        }
                    })
                };
                columnMenu.MenuItems.Add(item);

                item = new MenuItem("Regex (case-insensitive)...", this.filterMenuItem_Clicked)
                {
                    Tag = new Matcher((s1, s2) =>
                    {
                        try
                        {
                            System.Text.RegularExpressions.Regex r =
                                new System.Text.RegularExpressions.Regex(s2, System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                            return(r.IsMatch(s1));
                        }
                        catch
                        {
                            return(false);
                        }
                    })
                };
                columnMenu.MenuItems.Add(item);

                columnMenu.MenuItems.Add(new MenuItem("-"));
                item = new MenuItem("Numerical relation...", this.filterMenuItem_Clicked)
                {
                    Tag = new Matcher((s1, s2) =>
                    {
                        if (s2.Contains("!=", StringComparison.OrdinalIgnoreCase))
                        {
                            decimal n1 = BaseConverter.ToNumberParse(s1);
                            decimal n2 = BaseConverter.ToNumberParse(s2.Split(new string[]
                            {
                                "!="
                            }, StringSplitOptions.None)[1]);

                            return(n1 != n2);
                        }

                        if (s2.Contains("<=", StringComparison.OrdinalIgnoreCase))
                        {
                            decimal n1 = BaseConverter.ToNumberParse(s1);
                            decimal n2 = BaseConverter.ToNumberParse(s2.Split(new string[]
                            {
                                "<="
                            }, StringSplitOptions.None)[1]);

                            return(n1 <= n2);
                        }

                        if (s2.Contains(">=", StringComparison.OrdinalIgnoreCase))
                        {
                            decimal n1 = BaseConverter.ToNumberParse(s1);
                            decimal n2 = BaseConverter.ToNumberParse(s2.Split(new string[]
                            {
                                ">="
                            }, StringSplitOptions.None)[1]);

                            return(n1 >= n2);
                        }

                        if (s2.Contains("<", StringComparison.OrdinalIgnoreCase))
                        {
                            decimal n1 = BaseConverter.ToNumberParse(s1);
                            decimal n2 = BaseConverter.ToNumberParse(s2.Split(new string[]
                            {
                                "<"
                            }, StringSplitOptions.None)[1]);

                            return(n1 < n2);
                        }

                        if (s2.Contains(">", StringComparison.OrdinalIgnoreCase))
                        {
                            decimal n1 = BaseConverter.ToNumberParse(s1);
                            decimal n2 = BaseConverter.ToNumberParse(s2.Split(new string[]
                            {
                                ">"
                            }, StringSplitOptions.None)[1]);

                            return(n1 > n2);
                        }

                        if (s2.Contains("=", StringComparison.OrdinalIgnoreCase))
                        {
                            decimal n1 = BaseConverter.ToNumberParse(s1);
                            decimal n2 = BaseConverter.ToNumberParse(s2.Split(new string[]
                            {
                                "="
                            }, StringSplitOptions.None)[1]);

                            return(n1 == n2);
                        }

                        return(false);
                    })
                };
                columnMenu.MenuItems.Add(item);

                menu.MenuItems.Add(columnMenu);
            }

            menu.Show(buttonFilter, new Point(buttonFilter.Size.Width, 0));
        }
예제 #26
0
        public override void Search()
        {
            Results.Clear();

            ProcessHandle phandle;
            int           count = 0;

            bool opt_priv = (bool)Params["private"];
            bool opt_img  = (bool)Params["image"];
            bool opt_map  = (bool)Params["mapped"];

            string structName = (string)Params["struct"];
            int    align      = (int)BaseConverter.ToNumberParse((string)Params["struct_align"]);

            if (!Program.Structs.ContainsKey(structName))
            {
                CallSearchError("Struct '" + structName + "' is not defined.");
                return;
            }

            StructDef structDef = Program.Structs[structName];
            string    structLen = structDef.Size.ToString();

            structDef.IOProvider = new ProcessMemoryIO(PID);

            try
            {
                phandle = new ProcessHandle(PID, ProcessHacker.Native.Security.ProcessAccess.QueryInformation);
            }
            catch
            {
                CallSearchError("Could not open process: " + Win32.GetLastErrorMessage());
                return;
            }

            phandle.EnumMemory(info =>
            {
                // skip unreadable areas
                if (info.Protect == MemoryProtection.AccessDenied)
                {
                    return(true);
                }
                if (info.State != MemoryState.Commit)
                {
                    return(true);
                }

                if ((!opt_priv) && (info.Type == MemoryType.Private))
                {
                    return(true);
                }

                if ((!opt_img) && (info.Type == MemoryType.Image))
                {
                    return(true);
                }

                if ((!opt_map) && (info.Type == MemoryType.Mapped))
                {
                    return(true);
                }

                CallSearchProgressChanged(
                    String.Format("Searching 0x{0} ({1} found)...", info.BaseAddress.ToString("x"), count));

                for (int i = 0; i < info.RegionSize.ToInt32(); i += align)
                {
                    try
                    {
                        structDef.Offset = info.BaseAddress.Increment(i);
                        structDef.Read();

                        // read succeeded, add it to the results
                        Results.Add(new string[]
                        {
                            Utils.FormatAddress(info.BaseAddress),
                            String.Format("0x{0:x}", i), structLen, string.Empty
                        });
                        count++;
                    }
                    catch
                    {
                    }
                }

                return(true);
            });

            phandle.Dispose();

            CallSearchFinished();
        }
예제 #27
0
        public static byte[] DecodeBase32(string data)
        {
            var bi = BaseConverter.Parse(data, Alphabet.Base32Alphabet);

            return(bi.ToByteArray());
        }
예제 #28
0
 public void BaseToObjectException()
 {
     var baseconverter = new BaseConverter("123").ConvertToObject("", CultureInfo.CurrentCulture);
 }
예제 #29
0
 public void Ctor_ValuesIsEmpty_ThrowArgumentException()
 {
     var convert = new BaseConverter(new Dictionary<string, int>());
 }
예제 #30
0
 public void BaseTostringException()
 {
     var baseconverter = new BaseConverter("123").GetString("", CultureInfo.CurrentCulture);
 }
예제 #31
0
 public void ToBaseN_WhenBaseIs10AndNumberIsLessThan0_ThrowsIndexOutOfRangeException()
 {
     var convert = new BaseConverter(this.base10Values);
     string result = convert.ToBaseN(10, -1, 0, 1000);
 }
예제 #32
0
 public string Cambia_36() => BaseConverter.ToBaseN(srcInt, BaseNAlphabet.Base36);
예제 #33
0
        public void ToBaseN_WhenBaseIs2AndNumberEquals1_Returns1()
        {
            var convert = new BaseConverter(this.base2Values);
            string result = convert.ToBaseN(2, 1, 0, 512);

            Assert.AreEqual("1", result);
        }
예제 #34
0
 public override string ToOctalString()
 {
     return(BaseConverter.BinaryToOctal(_value));
 }