public override void DidSelectPost() { string shortenedUrl = ""; try { foreach (NSItemProvider itemProvider in this.ExtensionContext.InputItems[0].Attachments) { if (itemProvider.HasItemConformingTo(MobileCoreServices.UTType.URL)) { itemProvider.LoadItem(MobileCoreServices.UTType.URL, null, async(item, error) => { if (item is NSUrl) { var urlToShorten = ((NSUrl)item).AbsoluteUrl.ToString(); var request = new ShortRequest { TagWt = false, TagUtm = false, Campaign = ContentText, Mediums = new List <string>() { "twitter" }, Input = urlToShorten }; var defaults = new NSUserDefaults(Constants.GroupName, NSUserDefaultsType.SuiteName); var url = defaults.StringForKey(Constants.IOS_SettingsKey); shortenedUrl = await ShorteningService.ShortenUrl(request, url); InvokeOnMainThread(() => { UIPasteboard clipboard = UIPasteboard.General; clipboard.String = shortenedUrl; UIAlertController alert = UIAlertController.Create("Share extension", $"https://{shortenedUrl} has been copied!", UIAlertControllerStyle.Alert); PresentViewController(alert, true, () => { var dt = new DispatchTime(DispatchTime.Now, TimeSpan.FromSeconds(1)); DispatchQueue.MainQueue.DispatchAfter(dt, () => { ExtensionContext.CompleteRequest(null, null); }); }); }); } }); } } } catch (Exception ex) { Console.WriteLine(ex); } }
public static async Task <HttpResponseMessage> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, ILogger log, ExecutionContext context) { log.LogInformation($"C# HTTP trigger function processed this request: {req}"); // Validation of the inputs if (req == null) { return(req.CreateResponse(HttpStatusCode.NotFound)); } ShortRequest input = await req.Content.ReadAsAsync <ShortRequest>(); if (input == null) { return(req.CreateResponse(HttpStatusCode.NotFound)); } // If the Url parameter only contains whitespaces or is empty return with BadRequest. if (string.IsNullOrWhiteSpace(input.Url)) { return(req.CreateErrorResponse(HttpStatusCode.BadRequest, "The url parameter can not be empty.")); } // Validates if input.url is a valid aboslute url, aka is a complete refrence to the resource, ex: http(s)://google.com if (!Uri.IsWellFormedUriString(input.Url, UriKind.Absolute)) { return(req.CreateErrorResponse(HttpStatusCode.BadRequest, $"{input.Url} is not a valid absolute Url. The Url parameter must start with 'http://' or 'http://'.")); } var result = new ShortResponse(); var config = new ConfigurationBuilder() .SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); StorageTableHelper stgHelper = new StorageTableHelper(config["UlsDataStorage"]); try { string longUrl = input.Url.Trim(); string vanity = string.IsNullOrWhiteSpace(input.Vanity) ? "" : input.Vanity.Trim(); string title = string.IsNullOrWhiteSpace(input.Title) ? "" : input.Title.Trim(); ShortUrlEntity newRow; if (!string.IsNullOrEmpty(vanity)) { newRow = new ShortUrlEntity(longUrl, vanity, title); if (await stgHelper.IfShortUrlEntityExist(newRow)) { return(req.CreateResponse(HttpStatusCode.Conflict, "This Short URL already exist.")); } } else { newRow = new ShortUrlEntity(longUrl, Utility.GetValidEndUrl(vanity), title); } await stgHelper.SaveShortUrlEntity(newRow); var host = req.RequestUri.GetLeftPart(UriPartial.Authority); log.LogInformation($"-> host = {host}"); result = new ShortResponse(host, newRow.Url, newRow.RowKey, newRow.Title); log.LogInformation("Short Url created."); } catch (Exception ex) { log.LogError(ex, "An unexpected error was encountered."); return(req.CreateResponse(HttpStatusCode.BadRequest, ex)); } return(req.CreateResponse(HttpStatusCode.OK, result)); }
public static async Task <HttpResponseMessage> ShortenUrl( [HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequestMessage req, [Table(Utility.TABLE, "1", Utility.KEY, Take = 1)] NextId keyTable, [Table(Utility.TABLE)] CloudTable tableOut, ILogger log) { log.LogInformation($"C# triggered function called with req: {req}"); if (req == null) { return(req.CreateResponse(HttpStatusCode.NotFound)); } var check = SecurityCheck(req); if (check != null) { return(check); } ShortRequest input = await req.Content.ReadAsAsync <ShortRequest>(); if (input == null) { return(req.CreateResponse(HttpStatusCode.NotFound)); } try { var result = new List <ShortResponse>(); var analytics = new Analytics(); // determine whether or not to process analytics tags bool tagMediums = analytics.Validate(input); var campaign = string.IsNullOrWhiteSpace(input.Campaign) ? DefaultCampaign : input.Campaign; var url = input.Input.Trim(); var utm = analytics.TagUtm(input); var wt = analytics.TagWt(input); log.LogInformation($"URL: {url} Tag UTM? {utm} Tag WebTrends? {wt}"); log.LogInformation($"Current key: {keyTable.Id}"); // get host for building short URL var host = req.RequestUri.GetLeftPart(UriPartial.Authority); // strategy for getting a new code string getCode() => Utility.Encode(keyTable.Id++); // strategy for logging void logFn(string msg) => log.LogInformation(msg); // strategy to save the key async Task saveKeyAsync() { var operation = TableOperation.Replace(keyTable); await tableOut.ExecuteAsync(operation); } // strategy to insert the new short url entry async Task saveEntryAsync(TableEntity entry) { var operation = TableOperation.Insert(entry); var operationResult = await tableOut.ExecuteAsync(operation); } // strategy to create a new URL and track the dependencies async Task saveWithTelemetryAsync(TableEntity entry) { await TrackDependencyAsync( "AzureTableStorageInsert", "Insert", async() => await saveEntryAsync(entry), () => true); await TrackDependencyAsync( "AzureTableStorageUpdate", "Update", async() => await saveKeyAsync(), () => true); } if (tagMediums) { // this will result in multiple entries depending on the number of // mediums passed in result.AddRange(await analytics.BuildAsync( input, Source, host, getCode, saveWithTelemetryAsync, logFn, HttpUtility.ParseQueryString)); } else { // no tagging, just pass-through the URL result.Add(await Utility.SaveUrlAsync( url, null, host, getCode, logFn, saveWithTelemetryAsync)); } log.LogInformation($"Done."); return(req.CreateResponse(HttpStatusCode.OK, result)); } catch (Exception ex) { log.LogError(ex, "An unexpected error was encountered."); return(req.CreateErrorResponse(HttpStatusCode.BadRequest, ex)); } }
public void Setup() { _analytics = new Analytics(); _request = new ShortRequest(); }
public static async Task <HttpResponseMessage> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, ILogger log, ExecutionContext context) { log.LogInformation($"C# HTTP trigger function processed this request: {req}"); // Validation of the inputs if (req == null) { return(req.CreateResponse(HttpStatusCode.NotFound)); } ShortRequest input = await req.Content.ReadAsAsync <ShortRequest>(); if (input == null) { return(req.CreateResponse(HttpStatusCode.NotFound)); } var result = new ShortResponse(); var config = new ConfigurationBuilder() .SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); StorageTableHelper stgHelper = new StorageTableHelper(config["UlsDataStorage"]); try { string longUrl = input.Url.Trim(); string vanity = input.Vanity.Trim(); ShortUrlEntity newRow; if (!string.IsNullOrEmpty(vanity)) { newRow = new ShortUrlEntity(longUrl, vanity); if (await stgHelper.IfShortUrlEntityExist(newRow)) { return(req.CreateResponse(HttpStatusCode.Conflict, "This Short URL already exist.")); } } else { newRow = new ShortUrlEntity(longUrl, await Utility.GetValidEndUrl(vanity, stgHelper)); } await stgHelper.SaveShortUrlEntity(newRow); var host = req.RequestUri.GetLeftPart(UriPartial.Authority); log.LogInformation($"-> host = {host}"); result = new ShortResponse(host, newRow.Url, newRow.RowKey); log.LogInformation("Short Url created."); } catch (Exception ex) { log.LogError(ex, "An unexpected error was encountered."); return(req.CreateResponse(HttpStatusCode.BadRequest, ex)); } return(req.CreateResponse(HttpStatusCode.OK, result)); }
protected void SubmitBtn_Click(object sender, EventArgs e) { ShortRequest shreq = new ShortRequest() { StudentName = user.Name, DeviceType = DeviceType, MACAddress = MACAddrInput.Text }; if (!ValidateMAC()) { ErrorMessage.Text = "The MAC Address you entered is not valid--please check to make sure it is correct."; LogError("Invalid MAC Address for {0}", shreq.ToString()); ErrorPanel.Visible = true; return; } using (WebhostEntities db = new WebhostEntities()) { //Check for Existing Mac Address Request. if (db.RegistrationRequests.Where(req => req.MacAddress.Equals(MACAddress)).Count() > 0) { WebhostMySQLConnection.RegistrationRequest request = db.RegistrationRequests.Where(req => req.MacAddress.Equals(MACAddress)).Single(); if (request.RequestCompleted) { ErrorMessage.Text = "This Device has already been registered. If you are experiencing difficulties, email Mr. Cox or Mr. Harrison."; LogError("The device has already been registered: {0}", shreq.ToString()); MailControler.MailToUser("Your Registration Request has already been registered.", shreq.ToString(), user); } else if (request.RequestDenied) { ErrorMessage.Text = "This device has been rejected. Please see Mr. Cox or Mr. Harrison for details."; LogError("Registration Request has been rejected: {0}", shreq.ToString()); MailControler.MailToUser("Your Registration Request has been rejected.", shreq.ToString(), user); } else { ErrorMessage.Text = "This Device is pending registration. Don't worry--we'll get to it soon =)"; LogError("Impatient User: {0}", shreq); MailControler.MailToUser("Your Registration Request is pending review.", shreq.ToString(), user); } ErrorPanel.Visible = true; return; } int reqid = db.RegistrationRequests.Count() > 0 ? db.RegistrationRequests.OrderBy(req => req.id).ToList().Last().id + 1 : 0; WebhostMySQLConnection.RegistrationRequest nrequest = new WebhostMySQLConnection.RegistrationRequest() { id = reqid, StudentId = ((BasePage)Page).user.IsStudent?((BasePage)Page).user.ID:10, MacAddress = MACAddress, DeviceType = DeviceType, RequestCompleted = false, RequestDenied = false }; db.RegistrationRequests.Add(nrequest); db.SaveChanges(); LogInformation("New Request submitted: {0}", shreq.ToString()); if (EmailEnabled) { MailControler.MailToWebmaster("New Device Registration Request.", shreq.ToString(), user); MailControler.MailToUser("New Device Registration Request.", shreq.ToString(), "*****@*****.**", "Jeff Harrison", user); MailControler.MailToUser("Your Registration Request has been successfully submitted.", shreq.ToString(), user); } SuccessPanel.Visible = true; } }