Sharepoint 2013 app user Guid - userid

i am having little problem in getting Sharepoint Userid (GUID) in SP App 2013.
so far i am getting Sharepoint user's Email address and his Full name using userProfile class of Sharepoint (SP.UserProfile.js).
i needed to get Unique id of the user which we say GUID.. i used below code for that , but everytime i get random so called Guid of the same User.(ehich is definitely not unique id of user).
How can i get sharepoint's user id that is unique on every login.
Please Help!
Thanks
Here is my code snippet
var targetUser;
var userProps;
var contxt_web = null;
var clientContext = new SP.ClientContext.get_current();
/** Get id of Current SP User*/
contxt_web = clientContext.get_web();
clientContext.load(contxt_web);
/***/
peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
userProps = peopleManager.getMyProperties(targetUser);
clientContext.load(userProps);
clientContext.executeQueryAsync(onRequestSuccess, onRequestFail);
}
function onRequestSuccess() {
var messageText = "Name : " + userProps.get_displayName()
+ " Sharepoint-ID : " + contxt_web.get_id()
+ " Email : " + userProps.get_email();
}

Try using userprops.get_userId ,it may works..

Related

How can I fix 'Unchecked runtime.lastError: The message port closed before a response was received.' when linking to G-Cal events?

I am attempting to generate a link that takes the user directly to the Google Calendar event selected.
The link I generate is identical to the link that you arrive at when going through the Calendar interface, however, when the user selects the link it loads a blank white page with the Google Calendar header and Keep/Tasks sidebar. None of the actual content loads and I'm given the Unchecked runtime.lastError: The message port closed before a response was received. error in console. Here's the below code, but as I said - the links are identical.
var events = [];
var today = new Date;
var myEvents = CalendarApp.getDefaultCalendar().getEventsForDay(today);
var calendarId = CalendarApp.getDefaultCalendar().getId();
myEvents.forEach(function(event){
var eventIdSplit = event.getId().split('#');
var newRecord = app.models.Calendar.newRecord();
newRecord.Date = event.getStartTime();
newRecord.Title = event.getTitle();
newRecord.Description = event.getDescription();
newRecord.calendarLink = 'https://calendar.google.com/calendar/r/eventedit/' + (Utilities.base64EncodeWebSafe(eventIdSplit[0] + " " + calendarId));
events.push(newRecord);
});
I've searched the error and found that other users suggested to disable all extensions, however, I am not running any.
I discovered that
newRecord.calendarLink = 'https://calendar.google.com/calendar/r/eventedit/' + (Utilities.base64EncodeWebSafe(eventIdSplit[0] + " " + calendarId));
generates several '==' at the end of the calendar link. These equal signs were the cause of the break.
Therefore, editing the above code to the below solves this:
newRecord.calendarLink = 'https://calendar.google.com/calendar/r/eventedit/' + (Utilities.base64EncodeWebSafe(eventIdSplit[0] + " " + calendarId)).replace(/=/g, "");

Get all appointments of all users or get all appointments of one room

I would like to get all appointments giving a specific date peroid. I check the API, it seems only can get appointnments for a specific user?
DateTime startDate = DateTime.Now;
DateTime endDate = startDate.AddDays(365);
const int NUM_APPTS = 5;
// Initialize the calendar folder object with only the folder ID.
CalendarFolder calendar = CalendarFolder.Bind(service, WellKnownFolderName.Calendar, new PropertySet());
// Set the start and end time and number of appointments to retrieve.
CalendarView cView = new CalendarView(startDate, endDate, NUM_APPTS);
// Limit the properties returned to the appointment's subject, start time, and end time.
cView.PropertySet = new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End);
// Retrieve a collection of appointments by using the calendar view.
FindItemsResults<Appointment> appointments = calendar.FindAppointments(cView);
Console.WriteLine("\nThe first " + NUM_APPTS + " appointments on your calendar from " + startDate.Date.ToShortDateString() +
" to " + endDate.Date.ToShortDateString() + " are: \n");
foreach (Appointment a in appointments)
{
Console.Write("Subject: " + a.Subject.ToString() + " ");
Console.Write("Start: " + a.Start.ToString() + " ");
Console.Write("End: " + a.End.ToString());
Console.WriteLine();
}
I hope can get all appointments or get all appointments for a specific room, then I can extract info by code. Thanks!
With EWS the findItems operation is done per Mailbox Folder so if you want query other calendars you need to do multiple operations. In your code if you wanted to query the Room Mailbox that had a Primary SMTP Address of room#domain.com you need to use the FolderId overload eg
FolderId cfFolderId = new FolderId(WellKnownFolderName.Calendar, "Room#doman.com");
CalendarFolder calendar = CalendarFolder.Bind(service, cfFolderId, new PropertySet());
Cheers
Glen

Why do e.values[] on formSubmitReply in Google Apps script has NaN?

I am trying to make a simple tool which stores ticket number and some details that are handovered to other team members. In that process i used a Form to submit a handover and store in Google Spreasheet. But i also want to notify the team members, so i wrote a script as below.
function formSubmitReply(e)
{
var timeStamp = e.values[0];
var sendTo = e.values[1];
var ticket = e.values[2];
var description = e.values[3];
MailApp.sendEmail(sendTo,
"New Handover",
+ ticket +" handovered to you at "+ timeStamp +"\n\nDescription:"+ description +
"\n\nKindly check it using the below link\n\nhttp://goo.gl/p16qdN",
{name:"Handover Mail"});
}
In the above code e.values[2] has the ticket number through form and in forms i have used a textbox with a regex validation [c.i][r,n][q,c] which means the first three words should be C/I,R/N/Q/C. for eg CRQ, IRC, INC..etc. Everything was working alright but suddenly one day NaN starting coming in the notification mail(below output). Details in Spreadsheet is fine.
NaN handovered to you at 12/4/2014 12:48:23
Description:Device Check after 4 hours
Kindly check it using the below link
http://goo.gl/p16qdN
The above is my primary issue that i want to solve. But also as a add on i need some advice or guide on how to set some value on a cell in spreadsheet which has a fixed column and variable row when a handover is submitted. I am referring http://goo.gl/wkD0Y7 for my work. But in that sheet.getRange(lastRow, getColIndexByName("Status")).setValue("New"); does not seem to work throwing some reference error.
Your error may have to do with the preceding "+" sign in the email body string and the GAS compiler interpreting the string as a number. Try this code instead:
function formSubmitReply(e){
var timeStamp = e.values[0];
var sendTo = e.values[1];
var ticket = e.values[2];
var description = e.values[3];
MailApp.sendEmail(
sendTo,
"New Handover",
ticket + " handovered to you at " +
timeStamp + "\n\nDescription:" +
description + "\n\nKindly check it using the below link\n\nhttp://goo.gl/p16qdN",
{name:"Handover Mail"}
);
}
As for your other question, there's no built-in getColIndexByName() method, so you'll either need to copy over the function from the tutorial you referenced or just set it manually like this:
var statusCol = 1;
sheet.getRange(sheet.getLastRow() + 1, statusCol).setValue("New");

Update Row in Table on Database for Each New User WebMatrix

I have a table (About_User) in my database (StarterSite) that is supposed to work so that each seperate row is for each seperate user. However, no matter which user is signed in, they all have access to the same row (in other words new rows aren't being created for each new user). I have triple checked to make sure everything in my database was set up correctly. I am using the StarterSite template with this Registration page (edited for question):
// If all information is valid, create a new account
if (Validation.IsValid()) {
// Insert a new user into the database
var db = Database.Open("StarterSite");
// Check if user already exists
var user = db.QuerySingle("SELECT Email FROM UserProfile WHERE LOWER(Email) = LOWER(#0)", email);
if (user == null) {
// Insert email into the profile table
db.Execute("INSERT INTO UserProfile (Email) VALUES (#0)", email);
// Create and associate a new entry in the membership database.
// If successful, continue processing the request
try {
bool requireEmailConfirmation = !WebMail.SmtpServer.IsEmpty();
var token = WebSecurity.CreateAccount(email, password, requireEmailConfirmation);
if (requireEmailConfirmation) {
var hostUrl = Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped);
var confirmationUrl = hostUrl + VirtualPathUtility.ToAbsolute("~/Account/Confirm?confirmationCode=" + HttpUtility.UrlEncode(token));
WebMail.Send(
to: email,
subject: "Please confirm your account",
body: "Your confirmation code is: " + token + ". Visit " + confirmationUrl + " to activate your account."
);
}
if (requireEmailConfirmation) {
// Thank the user for registering and let them know an email is on its way
Response.Redirect("~/Account/Thanks");
} else {
// Navigate back to the homepage and exit
WebSecurity.Login(email, password);
Response.Redirect("~/");
}
} catch (System.Web.Security.MembershipCreateUserException e) {
ModelState.AddFormError(e.Message);
}
} else {
// User already exists
ModelState.AddFormError("Email address is already in use.");
}
}
The table does have an ID column that (should) autoincrement.
The other columns are from a form that collects different information from the user like an 'About Me' page and therefore should be different for each person.
How can I accomplish this?
There are some things in your question that I don't understand. First of all your code doesn't look edited (it is the same as the template from row 39 to row 82). Second, your question has the mysql tag: if you are using a MySql database instead of the Sql Ce database of the Starter Site template, maybe this could be the problem (look at WebSecurity.CreateAccount fails for MySQL).
With the default StarteSite Sql Ce database the answer to your question is quite simple. Add the following row
db.Execute("INSERT INTO About_User(UserId, UserPage) VALUES (#0, #1)",
db.GetLastInsertId(), userPage);
just after the db.Execute("INSERT INTO UserProfile (Email) VALUES (#0)", email); statement.
There is no need of an ID autoincrement column in your About_User table, but only of a UserId Primary Key column as foreing key.

Not able to post announcements with same title using createAnnouncements in Google Apps Script

My objective is to fetch emails from a particular account and post it on sites as announcements. I have accomplished this. However there is a unique scenario where an email with additional information will appear with the same subject (subject is the title of the post). I need to fetch this and post it as an announcement too. However createAnnouncements throws an error saying that post already exists. However I can manually post two posts with same title.
I have tried a numerous things like getAnnouncements and getAllDecedents but nothing served my purpose or is coming close to it.
Is there a way bu which I can delete the old post and create the new post Or is there a way I can post messages with same title using createAnnouncements? Any help in this regard will much appreciated.
I have included a potion of my code below.
var pageTitlePattern = /^\[.*\] \[/;
var pageTitleArray = pageTitlePattern.exec(messageSubject);
var pageTitle = pageTitleArray[0].substr(1,pageTitleArray[0].length - 4);
var messageIdPattern = /\] \[.*\]$/;
var messageIdArray = messageIdPattern.exec(messageSubject);
var messageId = messageIdArray[0].substr(3,messageIdArray[0].length - 4);
var postBody = formatMessage(message, false) + "<br>" + "<font color=\"#ffffff\">" + messageId + "</font>";
var newAccouncement = postPage.createAnnouncement(pageTitle, postBody);
var files = message.getAttachments();
for (var k = 0; k < files.length; k++) {
newAccouncement.addHostedAttachment(files[k]);
cabinetPage.addHostedAttachment(files[k]);
}
message.markRead();
When you manually create multiple announcement posts with the same name, the Sites UI automatically makes the path for the announcement unique by appending a hyphen and an integer.
For instance, if you create two posts with the title "TestPost", you will have these pages added to your site:
https://sites.google.com/site/--site-id--/announcements/testpost
https://sites.google.com/site/--site-id--/announcements/testpost-1
I suggest you have your script perform similarly.
...
var pageTitlePattern = /^\[.*\] \[/;
var pageTitleArray = pageTitlePattern.exec(messageSubject);
var pageTitle = pageTitleArray[0].substr(1,pageTitleArray[0].length - 4);
// Check if this pageTitle already used
var announcements = page.getAnnouncements({
includeDrafts: false,
includeDeleted: false,
search: pageTitle });
// If other announcements have already used this pageTitle,
// make ours unique by appending a hyphen and unique number
if (announcements.length > 0) {
pageTitle += '-' + announcements.length;
}
...
The page.getAnnouncements() search is case-insensitive, and finds all announcements with the string pageTitle anywhere in the title or text. This might be more inclusive than you want. In that case, an alternative is to take over creation of your announcement's page name by using this variant of createAnnouncement().