How to get the row reference for the current cell in Google Scripts? - scripting

EDITED POST
I am a script newbie so bear with me... :)
I am getting the script to send an email using the info in the 28th thru 32nd column. I need to get the value of those cells in the current row.
With the script below, it works perfect if it is row 4 and I write 4.
function SendEmail() {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var sheet1=ss.getSheetByName('Form Responses 1');
var sheet2=ss.getSheetByName('TEMPLATE');
var subject = sheet2.getRange(2,1).getValue();
var addressee=sheet1.getRange(4,28).getValue();
var emailAddress = sheet1.getRange(4,29).getValue();
var room=sheet1.getRange(4,30).getValue();
var date=sheet1.getRange(4,31).getValue();
var time=sheet1.getRange(4,32).getValue();
var message = sheet2.getRange(2,2).getValue();
message=message.replace("<addressee>",addressee).replace("<room>",room).replace("<date>",date).replace("<time>",time);
MailApp.sendEmail(emailAddress, subject, message);
};
How do I get it to recognize what row is active and use that value? U sed the suggestion from "Huaye sun" as follows but I get the following error... "Exception: Failed to send email: no recipient"
The email address it should grab is in fact there. What am I missing?
function SendEmail() {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var sheet1=ss.getSheetByName('Form Responses 1');
var sheet2=ss.getSheetByName('TEMPLATE');
var subject = sheet2.getRange(2,1).getValue();
var activeCell = sheet1.getActiveCell();
var currentRow = activeCell.getRow();
var addressee=sheet1.getRange(currentRow,28).getValue();
var emailAddress = sheet1.getRange(currentRow,29).getValue();
var room=sheet1.getRange(currentRow,30).getValue();
var date=sheet1.getRange(currentRow,31).getValue();
var time=sheet1.getRange(currentRow,32).getValue();
var message = sheet2.getRange(2,2).getValue();
message=message.replace("<addressee>",addressee).replace("<room>",room).replace("<date>",date).replace("<time>",time);
MailApp.sendEmail(emailAddress, subject, message);
};

Related

Email confirmation - strange behavior

Does anyone have an idea why this is happening to me?
In this case, 'result' is 'Success':
public async Task<IActionResult> TestConfirmInSameRequest(string userId)
{
var user = await this._userManager.FindByIdAsync(userId);
var code = await this._userManager.GenerateEmailConfirmationTokenAsync(user);
var result = await this._userManager.ConfirmEmailAsync(user, code);
var newLocation = ...
return Redirect(newLocation);
}
And in this case, 'result' always is 'InvalidToken' (even when I manually copy the original code and test with it)
public async Task<IActionResult> ConfirmEmail(string userId, string code)
{
var user = await this._userManager.FindByIdAsync(userId);
var result = await this._userManager.ConfirmEmailAsync(user, code);
var newLocation = ...;
return Redirect(newLocation);
}
protected async Task SendConfirmationEmail(string userId, bool originMobile)
{
var user = await this._userManager.FindByIdAsync(userId);
var code = await this._userManager.GenerateEmailConfirmationTokenAsync(user);
var encodedCode = HttpUtility.UrlEncode(code);
var callbackUrl = $"https://.../api/account/confirmemail?userId={userId}&code={encodedCode}";
await this._userService.SendConfirmationEmailAsync(userId, callbackUrl);
}
When sending (SendConfirmationEmail) the e-mail you urlencode the token, but in ConfirmEmail you are not decoding the token.
Encoding it just makes sure it can be used in a URL and no breaking characters are in the URL. However, the token you should validate is not the encoded one, its still the token you got before encoding. In other words; you need to decode the token again so its back to the way it was when it got generated.

get url of image from Umbraco examine search UDI

I'm using Umbraco with Lucene and Examine
I'm trying to get the url of a image but at the moment I get the following
"umb://media/57ad107794724d0289b4f9fe44c298a8"
How can I get the URL for the media from the UDI, my code attempt so far is below.
foreach (var item in searchResults)
{
var content = Umbraco.Content(item.Fields["id"]);
if (item.Fields.Keys.Contains("image"))
{
var image = item.Fields["image"].Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries);
var pathToImage = string.Join(",", image);
var mediaItem = Umbraco.TypedContent(pathToImage);
var test3 = mediaItem.Url; <--------------------Throws NullReferenceException
}
}
Any help appreciated
Try the following
if (item.Fields.Keys.Contains("image"))
{
var imgUdi = item.Fields["image"];
var udi = Udi.Parse(imgUdi);
var mediaTest = Umbraco.TypedMedia(udi);
string pathToImage = mediaTest.Url;
}
Notice how I'm using Udi.Parse to get the ID, then you can use that to get the url

identity framekwork: how to get current login

[HttpPost]
public async Task<IActionResult> Upload(IFormFile files)
{
//var info = await _signInManager.GetExternalLoginInfoAsync();
//var user = await _userManager.FindByIdAsync(User.Identity.GetUserId());
//var user = await _userManager.FindByIdAsync(_userManager.GetUserId(Request.HttpContext.User));
//var user = User.Identity.GetUserId(HttpContext.User); _userManager.GetUserId(Request.HttpContext.User);
//var user1 = await GetCurrentUserAsync();
//var userId = user?.Id;
var filePath = Path.GetTempFileName();
var stream = files.OpenReadStream();
var name = files.FileName;
byte[] fileData = ReadFully(stream);
return Content("Error in uploads");
}
I have this action method. I have created login action whose result is success.
I am trying to get the ID of the current login user but im not able to get that. I have tried 50 ways to do that but failing again and again.
help needed
thanks in adv
I think you forgot to add HttpContext.user
var user = await _userManager.GetUserAsync(HttpContext.User);
if (user == null) return View("Error");

Importing Gmail text to a specific Google Sheets

I receive everyday the same email from an app I've made. Those emails have the same text except for some numbers (for example 2 instead of 9). I'm trying to build a script that automatically compiles my Google Sheets report.
function myFunction() {
var thread = GmailApp.getUserLabelByName("").getThreads(0,1)[0]; // get first thread in inbox
var message = thread.getMessages()[0]; // get first message
Logger.log(message.getBody()); // log contents of the body
}
but it doesn't work.
What am I doing wrong?
The following script works for me. Note that due to the time it takes to execute and to stop duplicate results, I change the label after it is moved to the spreadsheet.
function myFunction() {
var ss = SpreadsheetApp.openById("Insert Sheet ID");
var sheet = ss.getSheetByName("Email Import");
var label = GmailApp.getUserLabelByName("Label");
var labelNew = GmailApp.getUserLabelByName("Label Moved");
var threads = label.getThreads();
for (var i=0; i<threads.length; i++)
{
var messages = threads[i].getMessages();
for (var j=0; j<messages.length; j++)
{
var sub = messages[j].getBody();
sheet.appendRow([sub])
}
threads[i].addLabel(labelNew);
threads[i].removeLabel(label);
}
}

Multiple HTTP Requests in WinRT / Win8

Is it possible to send more than two HTTP requests concurrently in WinRT? I'm trying to load multiple JSON documents from a server and HttpWebRequest fails to respond after the second call. Here is a sample snippet that illustrates this:
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
const string url = "http://www.bom.gov.au/fwo/IDV60901/IDV60901.94868.json";
const int iterations = 3;
var tasks = new List<Task>();
var ticks = DateTime.Now.Ticks;
for (var i = 0; i < iterations; i++)
{
// Create unique URL by appending a generated number.
var uniqueUrl = string.Format("{0}?v={1}", url, (i + ticks));
// Create the request.
var request = WebRequest.CreateHttp(uniqueUrl);
// Create the async task and store it for later.
var task = request.GetResponseAsync();
tasks.Add(task);
}
// Await all tasks in collection.
await Task.WhenAll(tasks);
Debugger.Break(); // <----- This will never break when iterations > 2
}
Put this code in a blank MainPage.xaml.cs and play around with the iterations value. If you set it to 2, then it works. Anything above that, it will fail.
NOTE :: Do not use Fiddler when testing this. Fiddler does something funny and it allows all these connections to go through. I don't know how nor why. You can test this yourself. If you run the code above with fiddler open, then success.
NOTE :: This is not real code. I'm only using this example to illustrate the issue.
I haven't tried using the WebClient API in WinRT, I've only used the HttpClient API (which I'm using quite extensively in my application).
This code works:
const string url = "http://www.bom.gov.au/fwo/IDV60901/IDV60901.94868.json";
const int iterations = 10;
var tasks = new List<Task<HttpResponseMessage>>();
var ticks = DateTime.Now.Ticks;
for (var i = 0; i < iterations; i++)
{
// Create unique URL by appending a generated number.
var uniqueUrl = string.Format("{0}?v={1}", url, (i + ticks));
var handler = new HttpClientHandler();
var client = new HttpClient(handler)
{
BaseAddress = new Uri(uniqueUrl)
};
var task = client.GetAsync(client.BaseAddress);
tasks.Add(task);
}
// Await all tasks in collection.
await Task.WhenAll(tasks);
It is a bit more tedious to get out the response body though as you need to do an async read of all the responses like so:
var responseTasks = tasks.Select(task => task.Result.Content.ReadAsStringAsync());
await Task.WhenAll(responseTasks);
Then you can iterate through the responseTask objects and take their result.