/// <summary> /// Tracks the entity. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">The key.</param> /// <param name="document">The document.</param> /// <param name="metadata">The metadata.</param> /// <returns></returns> public T TrackEntity <T>(string key, RavenJObject document, RavenJObject metadata) { document.Remove("@metadata"); object entity; if (entitiesByKey.TryGetValue(key, out entity) == false) { entity = ConvertToEntity <T>(key, document, metadata); } else { // the local instance may have been changed, we adhere to the current Unit of Work // instance, and return that, ignoring anything new. return((T)entity); } var etag = metadata.Value <string>("@etag"); if (metadata.Value <bool>("Non-Authoritative-Information") && AllowNonAuthoritativeInformation == false) { throw new NonAuthoritativeInformationException("Document " + key + " returned Non Authoritative Information (probably modified by a transaction in progress) and AllowNonAuthoritativeInformation is set to false"); } entitiesAndMetadata[entity] = new DocumentMetadata { OriginalValue = document, Metadata = metadata, OriginalMetadata = (RavenJObject)metadata.CloneToken(), ETag = HttpExtensions.EtagHeaderToGuid(etag), Key = key }; entitiesByKey[key] = entity; return((T)entity); }
private void ButtonSearch_Click(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(TextBoxTitleID.Text)) { XtraMessageBox.Show("You haven't specified a title ID.", "Empty Field", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } SetStatus("Searching for game updates..."); Titlepatch gameUpdates = HttpExtensions.GetGameUpdatesFromTitleID(TextBoxTitleID.Text); switch (gameUpdates) { case null: XtraMessageBox.Show("Unable to find details for this title ID.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); break; default: { GridGameUpdates.DataSource = null; DataTable gameUpdateFiles = DataExtensions.CreateDataTable(new List <DataColumn> { new("File URL", typeof(string)), new("File SHA1", typeof(string)), new("File Name", typeof(string)), new("File Version", typeof(string)), new("File Size", typeof(string)), new("System Version", typeof(string)) }); string gameTitle = Regex.Replace(gameUpdates.Tag.Package.Last().Paramsfo.TITLE, @"\(.*?\)", "").Trim().Replace("®", "®"); gameUpdates.Tag.Package.Reverse(); foreach (Package update in gameUpdates.Tag.Package) { gameUpdateFiles.Rows.Add( update.Url, update.Sha1sum, gameTitle, "v" + update.Version.RemoveFirstInstanceOfString("0"), MainWindow.Settings.UseFormattedFileSizes ? long.Parse(update.Size).Bytes().Humanize("#") : update.Size + " Bytes", "v" + update.Ps3_system_ver.RemoveFirstInstanceOfString("0").Replace("000", "00")); } GridGameUpdates.DataSource = gameUpdateFiles; GridViewGameUpdates.Columns[0].Visible = false; GridViewGameUpdates.Columns[1].Visible = false; //GridViewGameUpdates.Columns[2].Width = 325; GridViewGameUpdates.Columns[3].Width = 52; GridViewGameUpdates.Columns[4].Width = 85; GridViewGameUpdates.Columns[5].Width = 55; break; }
/// <summary> /// Check application for update. Installs the latest installer and runs the file before closing this instance /// </summary> public static void CheckUpdate() { try { Program.Log.Info("Checking for update"); using (var sr = new StreamReader(HttpExtensions.GetStream(AppExtensions.VersionUrl))) { var newVersion = new Version(sr.ReadToEnd()); var curVersion = Assembly.GetExecutingAssembly().GetName().Version; if (curVersion.CompareTo(newVersion) < 0) { RunLatestInstaller(newVersion); } else { Program.Log.InfoFormat("Up to date. Version: {0}", newVersion); } } } catch (Exception ex) { Program.Log.Error("Failed: ", ex); Application.Exit(); } }
public async Task DeleteDevice(Device device) { var id = device is PacketDevice cast ? cast.Id : device.Id; var results = await _client.DeleteAsync($"/devices/{id}"); await HttpExtensions.SuccessOrThrow <object>(results); }
private void ButtonSearch_Click(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(TextBoxTitleID.Text)) { XtraMessageBox.Show("You haven't specified a title ID.", "Empty Field", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } string gameTitle = HttpExtensions.GetGameTitleFromTitleID(TextBoxTitleID.Text); Models.Game_Updates.Titlepatch gameUpdates = HttpExtensions.GetGameUpdatesFromTitleID(UpdateTypeURL, TextBoxTitleID.Text); if (gameUpdates == null) { XtraMessageBox.Show("Unable to find details for this title ID.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { GridGameUpdates.DataSource = null; DataTable gameUpdateFiles = DataExtensions.CreateDataTable(new List <DataColumn> { new("File URL", typeof(string)), new("File SHA1", typeof(string)), new("File Name", typeof(string)), new("File Version", typeof(string)), new("File Size", typeof(string)), new("System Version", typeof(string)), });
public void TestExtractionWithGenericBindings([Values("http://cardlog.in/updater/find/customer", "http://localhost/updater/find/customer", "http://1.2.3.4/updater/find/customer", "http://cardlog.in/updater/find/customer?key=value&otherkey=othervalue")] string path) { string relativepath = HttpExtensions.GetRelativePath(path, new[] { "http://*/updater/" }); Assert.AreEqual("/find/customer", relativepath); }
public async Task <IEnumerable <Facility> > GetFacilities() { var results = await _client.GetAsync($"/projects/{_config.ProjectId}/facilities"); return(await HttpExtensions.SuccessOrThrow(results, data => { var facilities = JsonConvert.DeserializeObject <PacketFacilities>(data); return facilities.Facilities.Select(w => TinyMapper.Map <PacketFacility, Facility>(w)); })); }
private void AfterProcessing(NancyContext ctx) { if (ctx.Request.Method.Equals("OPTIONS", StringComparison.Ordinal)) { Dictionary <string, string> headers = HttpExtensions.GetOptions(); List <Tuple <string, string> > tps = headers.Select(a => new Tuple <string, string>(a.Key, a.Value)) .ToList(); ctx.Response.WithHeaders(tps.ToArray()); ctx.Response.ContentType = "text/plain"; } }
public IHttpActionResult GetDetails(string title, string details) { HttpStatusCode statusCode; string id = m_metacriticService.GetId(); string ip = HttpExtensions.GetClientIP(Request); IMetacriticData[] result = m_metacriticService.GetResult(id, string.Format("/person/{0}/{1}", title, details), ip, out statusCode); return(Content(statusCode, result)); }
public IHttpActionResult Get(string title, int?year, string details) { HttpStatusCode statusCode; string id = m_metacriticService.GetId(); string ip = HttpExtensions.GetClientIP(Request); IMetacriticData[] result = m_metacriticService.GetResult(id, string.Format("/{0}/{1}/{2}/{3}", m_keyword, title, year, details), ip, out statusCode); return(Content(statusCode, result)); }
public void TestRelativePathExtraction( [Values("http://updates.cardlog.in/find/customer", "http://localhost/updater/find/customer", "http://1.2.3.4/updates/find/customer", "http://updates.cardlog.in/find/customer?key=value&otherkey=othervalue")] string path) { string relativepath = HttpExtensions.GetRelativePath(path, Prefixes); Assert.AreEqual("/find/customer", relativepath); }
/// <summary> /// Initialize the database instance /// </summary> public DataCache() { if (!HttpExtensions.IsFileSizeEqual(DataHelper.DatabaseFilePath, AppExtensions.DatabaseUrl)) { HttpExtensions.DownloadFile(AppExtensions.DatabaseUrl, DataHelper.DatabaseFilePath); } if (File.Exists(DataHelper.SavedFilePath)) { using (var fs = File.Open(DataHelper.SavedFilePath, FileMode.Open, FileAccess.Read, FileShare.Read)) using (var bs = new BufferedStream(fs)) using (var sr = new StreamReader(bs)) { string s; while ((s = sr.ReadLine()) != null) { _savedFiles.Add(s); } } } var totalNoFiles = 0; long totalFileSize = 0; using (var fs = File.Open(DataHelper.DatabaseFilePath, FileMode.Open, FileAccess.Read, FileShare.Read)) using (var bs = new BufferedStream(fs)) using (var sr = new StreamReader(bs)) { var unused = sr.ReadLine(); string s; while ((s = sr.ReadLine()) != null) { // Messy way to split csv into a file object var lineParts = s.Split(','); var fileSize = long.Parse(lineParts[0]); var fileLastModified = DateTime.Parse(lineParts[1]); var fileUrl = lineParts[2]; var fileName = Path.GetFileName(Uri.UnescapeDataString(fileUrl)); _dbFiles.Add( new WebFile( fileName, fileSize, fileLastModified, fileUrl)); totalNoFiles++; totalFileSize += fileSize; } } _metadata = new Metadata( totalNoFiles, totalFileSize); }
public IHttpActionResult GetDetails(string title, string details, string offset = "", string limit = "") { HttpStatusCode statusCode; string id = m_metacriticService.GetId(); string ip = HttpExtensions.GetClientIP(Request); IMetacriticData[] result = m_metacriticService.GetResult(id, string.Format("/search/{0}/{1}?offset={2}&limit={3}", title, details, offset, limit), ip, out statusCode); return(Content(statusCode, result)); }
public static void search() { CertificateManagement cm = new CertificateManagement(); X509Certificate2 cert = cm.GetTrustedSystemPrivateCert(certPath, certPassword); //build the attributes AttributeHolder attr = new AttributeHolder(); attr.Id = "123"; attr.IssueInstant = DateTime.Now.ToUniversalTime(); attr.ElectronicEntityId = "https://mise.agencyone.gov/"; attr.FullName = "John Doe"; attr.CitizenCodes = new List <string>() { "USA" }; attr.LEI = true; attr.PPI = true; attr.COI = true; ServiceHandler sh = new ServiceHandler(); //send the saml login - the cookie represents the session CookieContainer session = sh.SendSamlRequest(cert, attr); ServiceEndPointManager sepm = new ServiceEndPointManager(); //set up a base search URL Uri url = new Uri(sepm.BuildServiceEndPoint("Search", "IAN", "")); //Assemble the query arguments - e.g. lat/lng, etc Dictionary <string, string> qd = new Dictionary <string, string>(); qd.Add("ulat", "10"); qd.Add("ulng", "-10"); qd.Add("llat", "-10"); qd.Add("llng", "10"); TimeSpan tStart = new TimeSpan(365, 0, 0, 0); //search the past years data TimeSpan tEnd = new TimeSpan(0, 0, 30); //cover search up to 30 seconds ago (data refresh rate determination) string start = DateTime.Now.Subtract(tStart).ToUniversalTime().ToString("o"); string end = DateTime.Now.Subtract(tEnd).ToUniversalTime().ToString("o"); qd.Add("start", start); qd.Add("end", end); url = HttpExtensions.AddQuery(url, qd); XDocument result = sh.SendQueryRequest(cert, session, url.ToString(), "application/xml"); Console.WriteLine(result.ToString()); }
public async Task <IEnumerable <OperatingSystem> > GetOperatingSystems(Plan plan) { var code = plan is PacketPlan cast ? cast.Name : plan.Name; var results = await _client.GetAsync("/operating-systems"); return(await HttpExtensions.SuccessOrThrow(results, data => { var systems = JsonConvert.DeserializeObject <PacketOperatingSystems>(data); return systems.OperatingSystems.Where(w => w.ProvisionableOn.Contains(code)).Select(w => { var mapped = TinyMapper.Map <PacketOperatingSystem, OperatingSystem>(w); return mapped; }); })); }
public async Task TestHttpExtensionsReadXml() { using (var res = new HttpResponseMessage(HttpStatusCode.OK)) { res.Content = new StringContent("<test>test</test>"); var ret = await res.ReadXml().ConfigureAwait(false); ret.Should().BeOfType <XmlDocument>(); } using (var res = new HttpResponseMessage(HttpStatusCode.OK)) { res.Content = new StringContent("<test>test</test"); await Assert.ThrowsAsync <ApplicationException>(async() => { await res.ReadXml().ConfigureAwait(false); }).ConfigureAwait(false); } await Assert.ThrowsAsync <ArgumentNullException>(async() => { await HttpExtensions.ReadXml(null).ConfigureAwait(false); }).ConfigureAwait(false); }
/// <summary> /// get path under which image for item is server (or null when no image exists) /// </summary> /// <param name="itemname">name of item</param> /// <returns>path to image on server</returns> public string GetImagePath(string itemname) { string path; if (!imagecache.TryGetValue(itemname.ToLower(), out path)) { string resourcepath = GetType().Namespace + ".Images." + itemname.ToLower() + ".png"; if (ResourceAccessor.ContainsResource(GetType().Assembly, resourcepath)) { path = $"http://localhost/streamrc/image/item?name={HttpExtensions.URLEncode(itemname.ToLower())}"; } imagecache[itemname.ToLower()] = path; } return(path); }
private Task <List <(DateTime, List <string>)> > FetchEntries(DateTime primaryKey, int takeAmount) { string url = PageStorage <BackendData> .Instance.StorageData.GetUrl("History"); if (url != "") { return(new HttpClient() .GetAsync(HttpExtensions.GetQueryString(url, "range", ("primaryKey", primaryKey), ("takeAmount", takeAmount))) .ContinueWith(task => JsonConvert .DeserializeObject <List <HistoryElement> >(task.EnsureResultSuccessStatusCode().Result.Content.ReadAsStringAsync().Result) .Select(historyElement => (TimeStamp: historyElement.TimeStamp, new List <string>() { historyElement.Status, historyElement.Source, historyElement.Message })).ToList())); } else { if (primaryKey == default(DateTime)) { return(Task.Run(() => PageStorage <HistoryData> .Instance.StorageData.HistoryElements.Take(takeAmount) .Select(historyElement => (historyElement.TimeStamp, new List <string>() { historyElement.Status, historyElement.Source, historyElement.Message })).ToList())); } else { return(Task.Run(() => PageStorage <HistoryData> .Instance.StorageData.HistoryElements .SkipWhile(element => element.TimeStamp != primaryKey).Take(takeAmount) .Select(historyElement => (historyElement.TimeStamp, new List <string>() { historyElement.Status, historyElement.Source, historyElement.Message })).ToList())); } } }
public async Task <Device> Deploy(AddDeviceRequest request) { var packetRequest = TinyMapper.Map(request, new PacketAddDeviceRequest()); var serialized = JsonConvert.SerializeObject(packetRequest, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); var result = await _client.PostAsync($"/projects/{_config.ProjectId}/devices", new StringContent(serialized, Encoding.Default, "application/json")); return(await HttpExtensions.SuccessOrThrow(result, data => { var device = JsonConvert.DeserializeObject <PacketDevice>(data); return TinyMapper.Map <PacketDevice, Device>(device); })); }
/// <summary> /// Initializes the portal's <see cref="VirtualPathProvider" />s. /// </summary> /// <remarks> /// The static constructor on the <see cref="PortalRequestModule" /> ensures that /// the <see cref="VirtualPathProvider" />s are initialized only once and on the /// first request to the portal application. /// </remarks> static PortalRequestModule() { // Virtual path providers are executed in the opposite order they are registered. // The order here reflects the most likely order that requests will be received, // so it should be the most performant order. For example, routes are requested // and parsed, then modules are loaded. Next CSS files are loaded because they are // typically at the top of the page. Images are then loaded in the body of the // page. Finally, in this framework the script resources are usually at the bottom // of the page and are loaded last. HttpExtensions.RegisterVirtualPathProvider(new ScriptProvider()); HttpExtensions.RegisterVirtualPathProvider(new ImageProvider()); HttpExtensions.RegisterVirtualPathProvider(new StyleProvider()); HttpExtensions.RegisterVirtualPathProvider(new ModuleProvider()); HttpExtensions.RegisterVirtualPathProvider(new RoutePathProvider()); LastModified = File.GetLastWriteTimeUtc(HttpContext.Current.Server.MapPath("~/bin/Loom.Web.Portal.dll")); }
private void MainWindow_Load(object sender, EventArgs e) { Text = $"AtomicX - {UpdateExtensions.CurrentVersionName}"; if (HttpExtensions.IsConnectedToInternet()) { LoadSettingsData(); UpdateExtensions.CheckApplicationVersion(); WorkerExtensions.RunWorkAsync(LoadData, InitializeFinished); EnableConsoleActions(); } else { SetStatus("Not connected to the interet. Enable this in your computer settings."); XtraMessageBox.Show(this, "You must be connected to the Internet to use this application.", "No Internet", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/// <summary> /// 复制请求头 /// </summary> /// <param name="context"></param> /// <param name="webRequest"></param> protected virtual void CopyRequestHeaders(HttpContext context, HttpWebRequest webRequest) { // 扩展点:允许替换默认实现方式 // 复制请求头 foreach (string name in context.Request.Headers.AllKeys) { // 过滤不允许直接指定的请求头 if (s_IgnoreRequestHeaders.FirstOrDefault(x => x.Equals(name, StringComparison.OrdinalIgnoreCase)) != null) { continue; } string value = context.Request.Headers[name]; SetRequestHeader(context, webRequest, name, value); } webRequest.Headers.Add(ProxyFlagHeader, "1"); webRequest.Headers.Add("x-UserHostAddress", context.Request.UserHostAddress); //webRequest.Headers.Remove("Cache-Control"); if (string.Equals(context.Request.Headers["Connection"], "keep-alive", StringComparison.OrdinalIgnoreCase)) { webRequest.KeepAlive = true; } string referer = context.Request.Headers["Referer"]; if (string.IsNullOrEmpty(referer) == false) { if (referer.IndexOf("://") > 0) { string refererRoot = HttpExtensions.GetWebSiteRoot(referer); string requestRoot = HttpExtensions.GetWebSiteRoot(webRequest.RequestUri.AbsoluteUri); string referer2 = requestRoot + referer.Substring(refererRoot.Length); SetRequestHeader(context, webRequest, "Referer", referer2); } } }
public static void CriarCsv(HttpResponse Response, System.Data.DataTable dataTable, string pstrNomeArquivo) { String path = Path.GetTempPath() + HttpContext.Current.Session.SessionID; TextWriter textWriter = new StreamWriter(path, false, Encoding.Unicode); String cabecalhos = String.Empty; for (int i = 0; i < dataTable.Columns.Count; i++) { if (i > 0) { cabecalhos += ";"; } string coluna = dataTable.Columns[i].ColumnName; cabecalhos += coluna; } textWriter.WriteLine(cabecalhos); String linha; foreach (DataRow row in dataTable.Rows) { linha = String.Empty; for (int i = 0; i < row.Table.Columns.Count; i++) { if (i > 0) { linha += ";"; } string linhaOk = row[i].ToString(); linha += String.Format("{0}", linhaOk.Replace("\"", "")); } textWriter.WriteLine(linha); } textWriter.Close(); HttpExtensions.ForceDownloadRealPath(HttpContext.Current.Response, path, pstrNomeArquivo); }
public async Task <IEnumerable <Plan> > GetPlans(Facility facility) { var code = facility != null && facility is PacketFacility cast ? cast.Code : facility?.Code; var results = await _client.GetAsync($"/projects/{_config.ProjectId}/plans?include=available_in"); return(await HttpExtensions.SuccessOrThrow <IEnumerable <Plan> >(results, data => { var plans = JsonConvert.DeserializeObject <PacketPlans>(data); // TODO make more performant. Packet plan api does not let you filter based on facility in the query, so we must do in memory. var formatted = plans.Plans.Select(w => { var mapped = TinyMapper.Map <PacketPlan, Plan>(w); mapped.Spec = w.Spec; return w; }); return code != null ? formatted.Where(w => w.AvailableIn.Select(a => a.Code).Any(a => a == code)) : formatted; })); }
/// <summary> /// Cache the latest database file /// </summary> /// <param name="databaseUrl">Url of the database</param> /// <param name="cacheLocation">Cache storage location</param> private void CacheDatabaseFile(string databaseUrl, string cacheLocation) { long dbFileSize = HttpExtensions.GetFileSize(new Uri(databaseUrl)); DatabaseSize = dbFileSize; if (File.Exists(cacheLocation)) { if (dbFileSize != new FileInfo(cacheLocation).Length) { HttpExtensions.DownloadFile(databaseUrl, cacheLocation); } } else { HttpExtensions.DownloadFile(databaseUrl, cacheLocation); } TotalFileCount = FileExtensions.CountLines(cacheLocation); }
public static void retrieve() { CertificateManagement cm = new CertificateManagement(); X509Certificate2 cert = cm.GetTrustedSystemPrivateCert(certPath, certPassword); //build the attributes AttributeHolder attr = new AttributeHolder(); attr.Id = "123"; attr.IssueInstant = DateTime.Now.ToUniversalTime(); attr.ElectronicEntityId = "https://mise.agencyone.gov/"; attr.FullName = "John Doe"; attr.CitizenCodes = new List <string>() { "USA" }; attr.LEI = true; attr.PPI = true; attr.COI = true; ServiceHandler sh = new ServiceHandler(); //send the saml login - the cookie represents the session CookieContainer session = sh.SendSamlRequest(cert, attr); ServiceEndPointManager sepm = new ServiceEndPointManager(); //set up a base retrieve URL Uri url = new Uri(sepm.BuildServiceEndPoint("Retrieve", "IAN", "")); Dictionary <string, string> qd = new Dictionary <string, string>(); qd.Add("entityid", "https://mise.agencyone.gov/"); qd.Add("recordid", "123456789"); url = HttpExtensions.AddQuery(url, qd); XDocument xd = sh.SendQueryRequest(cert, session, url.ToString(), "application/xml"); Console.WriteLine(xd.ToString()); }
private void ButtonSearch_Click(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(TextBoxTitleID.Text)) { XtraMessageBox.Show("You haven't specified a title ID.", "Empty Field"); return; } var gameTitle = HttpExtensions.GetGameTitleFromTitleID(TextBoxTitleID.Text); var gameUpdates = HttpExtensions.GetGameUpdatesFromTitleID(UpdateTypeURL, TextBoxTitleID.Text); if (gameUpdates == null) { DarkMessageBox.ShowError("Unable to find details for this title ID.", "Error"); return; } else { /* * DgvGameUpdates.Rows.Clear(); * * foreach (var update in gameUpdates.Tag.Package) * { * DgvGameUpdates.Rows.Add(update.Url, * update.Sha1sum, * gameTitle, * "v" + update.Version.RemoveFirstInstanceOfString("0"), * MainWindow.Settings.ShowFileSizeInBytes ? long.Parse(update.Size).ToString("#,0") + " bytes" : update.Size.FormatSize(), * "v" + update.Ps3_system_ver.RemoveFirstInstanceOfString("0").Replace("000", "00"), * ImageExtensions.ResizeBitmap(Properties.Resources.install, 20, 20), * ImageExtensions.ResizeBitmap(Properties.Resources.download_from_the_cloud, 20, 20)); * } */ } LabelNoGameUpdatesFound.Visible = DgvGameUpdates.MainView.RowCount < 1; }
/// <summary> /// handles a request to the service server /// </summary> /// <param name="context">http context</param> protected override void HandleRequest(HttpListenerContext context) { string path = HttpExtensions.GetRelativePath(context.Request.Url.AbsoluteUri, Prefixes); if (!ignorelogginpaths.Contains(path)) { OnRequestPath(path, context.Request?.RemoteEndPoint?.ToString()); } if (ProcessRequest(context, path)) { return; } if (context.Request.HttpMethod == "OPTIONS") { OnResponse(context, default(T)); } else { IServiceHandler <T> handler = GetService(path); if (handler == null) { throw new ServiceServerException($"Service handler for '{path}' not found"); } T response; try { response = handler.HandleRequest(context); } catch (Exception e) { throw new ServiceServerException("Error handling request", e); } OnResponse(context, response); } }
private async Task SetContactProperties(StoredContact contact, User user, User originalUser = null) { if (contact != null) { contact.RemoteId = ContactsManager.GetRemoteId(user); contact.GivenName = user.first_name; contact.FamilyName = user.last_name; if (!string.IsNullOrWhiteSpace(user.photo_max) && !user.photo_max.EndsWith(".gif")) { Stream responseStreamAsync = await HttpExtensions.TryGetResponseStreamAsync(user.photo_max); if (responseStreamAsync == null) { throw new Exception("failed to download contact pic " + user.photo_max); } await contact.SetDisplayPictureAsync(responseStreamAsync.AsInputStream()); } IDictionary <string, object> propertiesAsync = await contact.GetPropertiesAsync(); if (!string.IsNullOrWhiteSpace(user.site)) { propertiesAsync[KnownContactProperties.Url] = (object)user.site; } if (!string.IsNullOrWhiteSpace(user.mobile_phone) && this.IsPhoneNumber(user.mobile_phone)) { List <string> phoneNumbers = BaseFormatterHelper.ParsePhoneNumbers(user.mobile_phone); if (phoneNumbers.Count >= 1) { propertiesAsync[KnownContactProperties.MobileTelephone] = (object)phoneNumbers[0]; } if (phoneNumbers.Count >= 2) { propertiesAsync[KnownContactProperties.AlternateMobileTelephone] = (object)phoneNumbers[1]; } } if (!string.IsNullOrWhiteSpace(user.home_phone) && this.IsPhoneNumber(user.home_phone)) { List <string> phoneNumbers = BaseFormatterHelper.ParsePhoneNumbers(user.home_phone); if (phoneNumbers.Count >= 1) { propertiesAsync[KnownContactProperties.Telephone] = (object)phoneNumbers[0]; } if (phoneNumbers.Count >= 2) { propertiesAsync[KnownContactProperties.AlternateTelephone] = (object)phoneNumbers[1]; } } DateTime dateTime; if (!string.IsNullOrWhiteSpace(user.bdate) && ContactsManager.TryParseDateTimeFromString(user.bdate, out dateTime)) { TimeSpan timeSpan = DateTime.Now - DateTime.UtcNow; dateTime = dateTime.Add(timeSpan); DateTimeOffset dateTimeOffset = new DateTimeOffset(dateTime.Year, dateTime.Month, dateTime.Day, 0, 0, 0, 0, TimeSpan.Zero); propertiesAsync[KnownContactProperties.Birthdate] = (object)new DateTimeOffset(dateTime); } } if (originalUser == null) { return; } originalUser.first_name = user.first_name; originalUser.last_name = user.last_name; originalUser.site = user.site; originalUser.mobile_phone = user.mobile_phone; originalUser.home_phone = user.home_phone; originalUser.photo_max = user.photo_max; originalUser.bdate = user.bdate; }
public void ReadableAddressConversionTest([Values("www.gmx.de", "suche.gmx.de/web", "facebook.com/signin", "google.com/accounts/login")] string data) { string address = HttpExtensions.GetReadableAddress(data); }