Exemplo n.º 1
0
        private static unsafe void HandleSessionError(IntPtr sessionHandlePtr, ErrorCode errorCode, byte *messageBuffer, IntPtr messageLength, IntPtr userInfoPairs, int userInfoPairsLength, bool isClientReset)
        {
            try
            {
                var handle  = new SessionHandle(sessionHandlePtr);
                var session = new Session(handle);
                var message = Encoding.UTF8.GetString(messageBuffer, (int)messageLength);

                SessionException exception;

                if (isClientReset)
                {
                    var userInfo = StringStringPair.UnmarshalDictionary(userInfoPairs, userInfoPairsLength);
                    exception = new ClientResetException(session.User.App, message, userInfo);
                }
                else if (errorCode == ErrorCode.PermissionDenied)
                {
                    var userInfo = StringStringPair.UnmarshalDictionary(userInfoPairs, userInfoPairsLength);
                    exception = new PermissionDeniedException(session.User.App, message, userInfo);
                }
                else
                {
                    exception = new SessionException(message, errorCode);
                }

                Session.RaiseError(session, exception);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Exemplo n.º 2
0
        public void CopyToEmpty()
        {
            _tree.Clear();
            var array = new StringStringPair[0];

            _tree.CopyTo(array, 0);
        }
Exemplo n.º 3
0
        public void AsReadOnly()
        {
            Assert.IsTrue(_list.Equals(_readOnly));

            _list[2] = new StringStringPair("two", "foo value");
            Assert.IsTrue(_list.Equals(_readOnly));

            _list[2] = new StringStringPair("two", "second value");
            Assert.IsTrue(_list.Equals(_readOnly));
        }
        public void CopyTo()
        {
            StringStringPair[] array = new StringStringPair[4];
            Assert.Throws <ArgumentException>(() => _dictionary.CopyTo(array, 3));

            _dictionary.CopyTo(array, 0);
            for (int i = 0; i < _dictionary.Count; i++)
            {
                Assert.IsTrue(_dictionary.Contains(array[i]));
            }

            _dictionary.CopyTo(array, 1);
            for (int i = 0; i < _dictionary.Count; i++)
            {
                Assert.IsTrue(_dictionary.Contains(array[i + 1]));
            }
        }
Exemplo n.º 5
0
        public void Constructor()
        {
            StringStringList list = new StringStringList(567);

            list.Add("foo", "foo value");
            list.Add("bar", "bar value");
            Assert.AreEqual(567, list.Capacity);
            Assert.AreEqual(2, list.Count);

            StringStringPair[] array = new StringStringPair[4] {
                new StringStringPair("a", "a value"),
                new StringStringPair("b", "b value"),
                new StringStringPair("c", "c value"),
                new StringStringPair("d", "d value")
            };

            list = new StringStringList(array);
            Assert.AreEqual(4, list.Capacity);
            Assert.AreEqual(4, list.Count);
        }
 public void CopyToEmpty()
 {
     _dictionary.Clear();
     StringStringPair[] array = new StringStringPair[0];
     _dictionary.CopyTo(array, 0);
 }
        public static int ConvertAddressBook(string database, string targetFolder, bool singleFile)
        {
            var vCards = 0;

            StreamWriter file = null;

            if (singleFile)
            {
                file = File.CreateText(Path.Combine(targetFolder, "Contacts.vcf"));
            }

            SQLiteConnection con = new SQLiteConnection("Data Source=" + database);

            con.Open();

            var multiValueLabels = AddressBookValueLabels(con);
            var addressLabels    = AddressBookAddressValueLabels(con);

            SQLiteCommand command = new SQLiteCommand("SELECT ROWID, First, Last, Middle, Organization, Department, Note, Birthday, JobTitle, Prefix, Suffix FROM ABPerson;", con);

            SQLiteDataReader reader = command.ExecuteReader();

            while (reader.Read())
            {
                vCards++;
                var row          = reader[0].ToString();
                var firstName    = reader[1].ToString();
                var middleName   = reader[3].ToString();
                var lastName     = reader[2].ToString();
                var organization = reader[4].ToString();
                var department   = reader[5].ToString();
                var note         = reader[6].ToString();
                var birthday     = DateTime.MinValue;
                var bday         = reader[7].ToString().Split('.')[0];
                int bdayseconds;
                if (int.TryParse(bday, out bdayseconds))
                {
                    birthday = new DateTime(2001, 1, 1).AddSeconds(bdayseconds);
                }
                var jobtitle = reader[8].ToString();
                var prefix   = reader[9].ToString();
                var suffix   = reader[10].ToString();

                List <StringStringPair> additionalEntries = new List <StringStringPair>();

                List <StringStringPair> phoneNumber = new List <StringStringPair>(); //phone number
                List <StringStringPair> email       = new List <StringStringPair>();
                List <Address>          address     = new List <Address>();

                SQLiteCommand multiValueCommand = new SQLiteCommand("SELECT property, label, value, UID FROM ABMultiValue WHERE record_id=" + row + ";", con);

                var multiValueReader = multiValueCommand.ExecuteReader();
                while (multiValueReader.Read())
                {
                    var prop = multiValueReader[0].ToString();
                    var lab  = multiValueReader[1].ToString();

                    var property = int.Parse(string.IsNullOrEmpty(prop) ? "0" : prop);
                    var label    = int.Parse(string.IsNullOrEmpty(lab) ? "0" : lab);
                    var value    = multiValueReader[2].ToString();
                    var uid      = multiValueReader[3].ToString();
                    switch (property)
                    {
                    case 3:     //seems to be phone number
                        StringStringPair p = new StringStringPair {
                            Key = value, Value = multiValueLabels[label]
                        };
                        phoneNumber.Add(p);
                        break;

                    case 4:     //seems to be email
                        StringStringPair e = new StringStringPair {
                            Key = value, Value = multiValueLabels[label]
                        };
                        email.Add(e);
                        break;

                    case 5:     //address...
                        SQLiteCommand addressCommand =
                            new SQLiteCommand(
                                "SELECT key, value FROM ABMultiValueEntry WHERE parent_id=" + uid + ";", con);

                        Address a = new Address {
                            Key = multiValueLabels[label]
                        };
                        var addressReader = addressCommand.ExecuteReader();
                        while (addressReader.Read())
                        {
                            var k              = addressReader[0].ToString();
                            var key            = int.Parse(string.IsNullOrEmpty(k) ? "0" : k);
                            var avalue         = addressReader[1].ToString();
                            StringStringPair s = new StringStringPair {
                                Key = addressLabels[key], Value = avalue
                            };
                            a.AddressData.Add(s);
                        }
                        address.Add(a);
                        break;

                    case 22:     //seems to be additional entry
                        StringStringPair b = new StringStringPair {
                            Key = multiValueLabels[label], Value = value
                        };
                        additionalEntries.Add(b);
                        break;
                    }
                }
                multiValueReader.Close();
                multiValueReader.Dispose();
                multiValueCommand.Dispose();

                StringBuilder sb = new StringBuilder();
                sb.AppendLine("BEGIN:VCARD");
                sb.AppendLine("VERSION:3.0");
                sb.AppendLine("FN;CHARSET=utf-8;ENCODING=QUOTED-PRINTABLE:");
                sb.AppendLine("N;CHARSET=utf-8;ENCODING=QUOTED-PRINTABLE:" + lastName + ";" + firstName + ";" + middleName + ";" + prefix + ";" + suffix);

                if (birthday != DateTime.MinValue)
                {
                    sb.AppendLine("BDAY:" + birthday.ToString("yyyyMMdd"));
                }

                foreach (var p in phoneNumber)
                {
                    sb.AppendLine("TEL;TYPE=" + p.Value + ":" + p.Key);
                }

                foreach (var a in address)
                {
                    var country    = "";
                    var locality   = "";
                    var postalCode = "";
                    var street     = "";

                    foreach (var s in a.AddressData)
                    {
                        var key = s.Key.ToLower();

                        if (key.Contains("zip"))
                        {
                            postalCode = s.Value; continue;
                        }
                        if (key.Contains("city"))
                        {
                            locality = s.Value; continue;
                        }
                        if (key.Contains("countrycode"))
                        {
                            continue;
                        }
                        if (key.Contains("country"))
                        {
                            country = s.Value; continue;
                        }
                        if (key.Contains("street"))
                        {
                            street = s.Value; continue;
                        }
                    }

                    sb.AppendLine("ADR;CHARSET=utf-8;ENCODING=QUOTED-PRINTABLE;" + a.Key + ":;;"
                                  + street + ";" + locality + ";;" +
                                  postalCode + ";" + country);
                }

                foreach (var e in email)
                {
                    sb.AppendLine("EMAIL; INTERNET:" + e.Key);
                }


                sb.AppendLine("NOTE;CHARSET=utf-8;ENCODING=QUOTED-PRINTABLE:" + note);
                sb.AppendLine("ORG;CHARSET=utf-8;ENCODING=QUOTED-PRINTABLE:" + organization);
                sb.AppendLine("ROLE;CHARSET=utf-8;ENCODING=QUOTED-PRINTABLE:" + department);
                sb.AppendLine("TITLE;CHARSET=utf-8;ENCODING=QUOTED-PRINTABLE:" + jobtitle);
                sb.AppendLine("END:VCARD");

                if (!singleFile)
                {
                    file = File.CreateText(Path.Combine(targetFolder, RemoveIllegalCharsInFileName(firstName + " " + lastName + ".vcf")));
                }
                file.Write(sb.ToString());
                if (!singleFile)
                {
                    file.Close();
                }
            }

            if (singleFile)
            {
                file.Close();
            }

            reader.Close();
            reader.Dispose();
            command.Dispose();
            con.Close();
            return(vCards);
        }
        private static async void ExecuteRequest(HttpClientRequest request, IntPtr callback)
        {
            try
            {
                try
                {
                    using var message = new HttpRequestMessage(request.method.ToHttpMethod(), request.Url);
                    foreach (var header in StringStringPair.UnmarshalDictionary(request.headers, request.headers_len))
                    {
                        message.Headers.TryAddWithoutValidation(header.Key, header.Value);
                    }

                    if (request.method != NativeHttpMethod.get)
                    {
                        message.Content = new StringContent(request.Body, Encoding.UTF8, "application/json");
                    }

                    using var cts = new CancellationTokenSource();
                    cts.CancelAfter((int)request.timeout_ms);

                    var response = await _httpClient.SendAsync(message, cts.Token);

                    var headers = new List <StringStringPair>(response.Headers.Count());
                    foreach (var header in response.Headers)
                    {
                        headers.Add(new StringStringPair
                        {
                            Key   = header.Key,
                            Value = header.Value.FirstOrDefault()
                        });
                    }

                    foreach (var header in response.Content.Headers)
                    {
                        headers.Add(new StringStringPair
                        {
                            Key   = header.Key,
                            Value = header.Value.FirstOrDefault()
                        });
                    }

                    var nativeResponse = new HttpClientResponse
                    {
                        http_status_code = (int)response.StatusCode,
                        Body             = await response.Content.ReadAsStringAsync(),
                    };

                    respond(nativeResponse, headers.ToArray(), headers.Count, callback);
                }
                catch (HttpRequestException rex)
                {
                    var sb = new StringBuilder("An unexpected error occurred while sending the request");

                    // We're doing this because the message for the top-level exception is usually pretty useless.
                    // If there's inner exception, we want to skip it and directly go for the more specific messages.
                    var innerEx = rex.InnerException ?? rex;
                    while (innerEx != null)
                    {
                        sb.Append($": {innerEx.Message}");
                        innerEx = innerEx.InnerException;
                    }

                    var nativeResponse = new HttpClientResponse
                    {
                        custom_status_code = CustomErrorCode.UnknownHttp,
                        Body = sb.ToString(),
                    };

                    respond(nativeResponse, null, 0, callback);
                }
                catch (TaskCanceledException)
                {
                    var nativeResponse = new HttpClientResponse
                    {
                        custom_status_code = CustomErrorCode.Timeout,
                        Body = $"Operation failed to complete within {request.timeout_ms} ms.",
                    };

                    respond(nativeResponse, null, 0, callback);
                }
                catch (Exception ex)
                {
                    var nativeResponse = new HttpClientResponse
                    {
                        custom_status_code = CustomErrorCode.Unknown,
                        Body = ex.Message,
                    };

                    respond(nativeResponse, null, 0, callback);
                }
            }
            catch (Exception outerEx)
            {
                Debug.WriteLine($"Unexpected error occurred while trying to respond to a request: {outerEx}");
            }
        }