Google Sheet Api - Error when sending the request in ASP .NET - asp.net

I am using Google Sheets Api to read information from a sheet. Locally on Visual Studio, the code works properly, I am able to get all the information.
However when I implement my website on IIS I get the following error:
Error al enviar la solicitud (error occuring while sending the request)
The exception message is not very specific about what is happening and where.
I don't know if the IIS executed by Visual Studio has a different configuration and this is why is working locally.
This is my code
try {
string path = Server.MapPath("Updating");
ServiceAccountCredential credential;
string[] Scopes = { SheetsService.Scope.Spreadsheets };
string serviceAccountEmail = "account.com";
string jsonfile = Path.Combine(path, "cred.json");
using (Stream stream = new FileStream(jsonfile, FileMode.Open, FileAccess.Read, FileShare.Read))
{
credential = (ServiceAccountCredential)
GoogleCredential.FromStream(stream).UnderlyingCredential;
var initializer = new ServiceAccountCredential.Initializer(credential.Id)
{
User = serviceAccountEmail,
Key = credential.Key,
Scopes = Scopes
};
credential = new ServiceAccountCredential(initializer);
}
var service = new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
String spreadsheetId = "1zkqBR9svQInKwM9hqPzrzhOFQB....";
string range = "Info!A:D";
string firmasRange = "Info!A:D";
SpreadsheetsResource.ValuesResource.GetRequest request = service.Spreadsheets.Values.Get(spreadsheetId, range);
var response = request.Execute(); //It seems that the error happens here
IList<IList<Object>> values = response.Values;
sincronizeSheet(values);
}
This is the stacktrace
CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) en Google.Apis.Auth.OAuth2.ServiceAccountCredential.d__33.MoveNext() --- Fin del seguimiento de la pila de la ubicación anterior donde se produjo la excepción --- en System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() en System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) en Google.Apis.Auth.OAuth2.TokenRefreshManager.d__12.MoveNext() --- Fin del seguimiento de la pila de la ubicación anterior donde se produjo la excepción --- en System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() en System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) en Google.Apis.Auth.OAuth2.TokenRefreshManager.<g__LogException|10_0>d.MoveNext() --- Fin del seguimiento de la pila de la ubicación anterior donde se produjo la excepción --- en System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() en Google.Apis.Requests.ClientServiceRequest`1.Execute() en Xerox_Mailroom.CoordinarCelular.ButtonSincronizar_Click(Object sender, EventArgs e)

For someone who is getting the same error the problem was pretty obvious, the connection with google api is made by the server, and it doesn't have internet access, so it never could validate the token.

Related

Asp.net mvc 5 identity smtp connection

I search all way for use forgot passwrod on (youtube,docMicrosoft..) with no result . Please someone explain me the error and expose part by part the process forgotpassword from webconfig to identityConfig service . Thanks
this is the error :
Le serveur SMTP requiert une connexion sécurisée ou le client n'était pas authentifié. La réponse du serveur était : 5.5.1 Authentication Required. Learn more at
this is methode of controller :
public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindByEmailAsync(model.Email);
if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
{
// Ne révélez pas que l'utilisateur n'existe pas ou qu'il n'est pas confirmé
return View("ForgotPasswordConfirmation");
}
// Pour plus d'informations sur l'activation de la confirmation de compte et de la réinitialisation de mot de passe, visitez https://go.microsoft.com/fwlink/?LinkID=320771
// Envoyer un message électronique avec ce lien
string Code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code= Code }, protocol: Request.Url.Scheme);
await UserManager.SendEmailAsync(user.Id, "Réinitialiser le mot de passe", "Réinitialisez votre mot de passe en cliquant ici");
return RedirectToAction("ForgotPasswordConfirmation", "Account");
}
And this is my methode IndentyConfig :
public class EmailService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
// Credentials:
var credentialUserName = "morad21838#gmail.com";
var sentFrom = "morad21838#gmail.com";
var pwd = "95147823";
// Configure the client:
System.Net.Mail.SmtpClient client =
new System.Net.Mail.SmtpClient("smtp.gmail.com");
client.Port = 587;
client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
// Creatte the credentials:
System.Net.NetworkCredential credentials =
new System.Net.NetworkCredential(credentialUserName, pwd);
client.EnableSsl = true;
client.Credentials = credentials;
// Create the message:
var mail = new System.Net.Mail.MailMessage(sentFrom, message.Destination);
mail.Subject = message.Subject;
mail.Body = message.Body;
// Send:
return client.SendMailAsync(mail);
}
}
And this is my web.config :
</appSetting>
<system.net>
<mailSettings>
<smtp from="haniyac1#gmail.com">
<network host="smtp-relay.gmail.com"
port="587"
userName="haniyac1#gmail.com"
password="95147823" />
</smtp>
</mailSettings>
</system.net>
Hello I find solution and is work perfectly wish that help someone have the same error .
this is updated file :
IdentityConfig
public class EmailService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
SmtpClient client = new SmtpClient();
return client.SendMailAsync(ConfigurationManager.AppSettings["toEmail"],
message.Destination,
message.Subject,
message.Body);
}
}
Web.Config
<!--Smptp Server (confirmations emails)-->
<add key="toEmail" value="haniyac1#gmail.com" />
<add key="UserId" value="haniyac1#gmail.com" />
<add key="Password" value="95147823" />
<add key="SMTPPort" value="587" />
<add key="Host" value="smtp.gmail.com" />
> </appSettings>
> <appSettings>
> <system.net>
> <mailSettings>
> <smtp from="morad28138#gmail.com">
> <network host="smtp.gmail.com" userName="morad28138" defaultCredentials="false" password="95147823" port="587"
> enableSsl="true" />
> </smtp>
> </mailSettings>
Controller forgotPassword Method :
public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindByEmailAsync(model.Email);
if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
{
// Ne révélez pas que l'utilisateur n'existe pas ou qu'il n'est pas confirmé
return View("ForgotPasswordConfirmation");
}
// Pour plus d'informations sur l'activation de la confirmation de compte et de la réinitialisation de mot de passe, visitez https://go.microsoft.com/fwlink/?LinkID=320771
// Envoyer un message électronique avec ce lien
string Code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code= Code }, protocol: Request.Url.Scheme);
await UserManager.SendEmailAsync(user.Id, "Réinitialiser le mot de passe", "Réinitialisez votre mot de passe en cliquant ici");
return RedirectToAction("ForgotPasswordConfirmation", "Account");
}
// Si nous sommes arrivés là, un échec s’est produit. Réafficher le formulaire
return View(model);
}
Register : post
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.UserName, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
// Pour plus d'informations sur l'activation de la confirmation de compte et de la réinitialisation de mot de passe, visitez https://go.microsoft.com/fwlink/?LinkID=320771
// Envoyer un message électronique avec ce lien
string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
var callbackUrll = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, Code = code }, protocol: Request.Url.Scheme);
await UserManager.SendEmailAsync(user.Id, "Confirmez votre compte", "Confirmez votre compte en cliquant ici");
string callbackUrl = await SendEmailConfirmationTokenAsync(user.Id, "Confirm your account");
//await this.UserManager.AddToRolesAsync(user.Id, model.Roles);
return RedirectToAction("Index", "Home");
}
ViewBag.Roles = new SelectList(db.Roles.Where(a => !a.Name.Contains("Admins")), "Name", "Name");
AddErrors(result);
}
// Si nous sommes arrivés là, un échec s’est produit. Réafficher le formulaire
return View(model);
}
Hope that help

Error while running Enable-Migrations in Visual studio 2017

I am trying to migrate my web app from membership to ASP.Net Identity by following this tutorial. But I get this error when I execute the Enable-migrations command:
Blockquote
PM> Enable-migrations
System.ArgumentException: Paramètre incorrect. (Exception de HRESULT : 0x80070057 (E_INVALIDARG))
Server stack trace:
à EnvDTE.Properties.Item(Object index)
à System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Object[]& outArgs)
à System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg)
Exception rethrown at [0]:
à System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
à System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
à EnvDTE.Properties.Item(Object index)
à System.Data.Entity.Migrations.Extensions.ProjectExtensions.GetPropertyValue[T](Project project, String propertyName)
à System.Data.Entity.Migrations.MigrationsDomainCommand.GetFacade(String configurationTypeName, Boolean useContextWorkingDirectory)
à System.Data.Entity.Migrations.EnableMigrationsCommand.FindContextToEnable(String contextTypeName)
à System.Data.Entity.Migrations.EnableMigrationsCommand.<>c__DisplayClass2.<.ctor>b__0()
à System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
Paramètre incorrect. (Exception de HRESULT : 0x80070057 (E_INVALIDARG))
I tried with the parameters -ProjectName and -StartUpProjectName but it does not work. I use EntityFramework 6.2.0. Need help please.
For those who are interested, I finally created a library a c# in my project (select your project then file-> new project-> visual c# -> class library). I made the migrations in this library and I added it as a reference to my project and it worked.

Populate a gridview with Object

I create a class with 3 parameters so as to populate and display a gridview.
this object is composed like this : string, string, list.
I managed to display the first and the second parameter, but not the third one, like this :
enter image description here
This is my main code :
protected void Page_Load(object sender, EventArgs e)
{
// Process principal
try
{
// Requête en chaînes de caractères qui sera utilisée pour récupérer les données dans la table Template
string request = "SELECT Id, Name, Content From Template";
// Connexion à la base de données et à la table et utilisation de la requêtes SQL
SqlCommand cmd = new SqlCommand(request, connect);
connect.Open();
// Exécution de la requête SQL
SqlDataReader sdr = cmd.ExecuteReader();
// Si la commande comporte des lignes
if (sdr.HasRows)
{
Liste_template = new List<TemplateObject>();
// Tant que le DataReader lit des informations.
while(sdr.Read())
{
string temp_name = sdr["Name"].ToString();
string temp_id = sdr["Id"].ToString();
TemplateObject newTemplate = new TemplateObject(temp_id, temp_name, liste_id_form("Content", sdr));
Liste_template.Add(newTemplate);
}
}
gv.DataSource = Liste_template;
gv.DataBind();
}
finally
{
connect.Close();
}
}
// Méthode pour délimiter chaque chaque chaine de caractères à partir des symboles dans le tableau delimiterChars.
public string[] RecupChaines(string chaine)
{
char[] delimiterChars = { ';', '&', '=', '"' };
string[] words = chaine.Split(delimiterChars);
return words;
}
// Méthode de récupération des Id des Form dans le champs Content de la table Template.
public List<String> liste_id_form(string field, SqlDataReader sdr)
{
List<string> listIdForm = new List<string>();
// enregistrement du contenu du champs Content dans une variable
string content = sdr[field].ToString();
// Tentative de séparation des deux parties de la chaine de caracteres
string chaineACouper = "<Property Name=\"Description\" Value=\"\" />";
string[] chaineArrive = content.Split(new string[] { chaineACouper }, StringSplitOptions.None);
chaineArrive[0] += chaineACouper;
// Séparation des deux parties.
string stringPartOne = chaineArrive[0];
string stringPartTwo = chaineArrive[1];
// Récuperation de la liste des valeurs des FormId de la chaine de caractères
string[] words = RecupChaines(stringPartTwo);
for (int i = 0; i < words.Length; i++)
{
if (words[i].Equals("FormId"))
{
listIdForm.Add(words[i + 5]);
}
}
return listIdForm;
}
}
I don't know how to loop on list_id_form, so as to display it on my gridview. For information, my class has an id, a name, and a list of datas.
I have to work with strings, because the datas from the database is not correctly stored. I don't have hand on this and i can't modify this.

Datas from database to custom List

I would like to store some datas from a database to a list of a class.
Unfortunatly, my webpage is totally blank and totally emply...
This my code :
CODE BEHIND :
protected void Page_Load(object sender, EventArgs e)
{
// Requête en chaînes de caractères qui sera utilisée pour récupérer les données dans la table Template
string request = "SELECT Id, Name, Content From Template";
// Process principal
try
{
// Connexion à la base de données et à la table et utilisation de la requêtes SQL
SqlCommand cmd = new SqlCommand(request, connect);
connect.Open();
// Exécution de la requête SQL
SqlDataReader sdr = cmd.ExecuteReader();
// Si la commande comporte des lignes
if (sdr.HasRows)
{
sdr.Read();
string temp_name = sdr["Name"].ToString();
string temp_id = sdr["Id"].ToString();
List<TemplateObject> Liste_template = new List<TemplateObject>()
{
new TemplateObject(temp_id,temp_name)
};
}
GridView1.DataSource = Liste_template;
GridView1.DataBind();
}
finally
{
connect.Close();
}
}
Code from the Class i created :
public class TemplateObject
{
string Id_template { get; set; }
string Name_template { get; set; }
public TemplateObject(string id, string name)
{
this.Id_template = id;
this.Name_template = name;
}
}
I would like to store and display an object which is composed of one TemplateObject and one FormObject, composed with two parameters (as TemplateObject) : id and name. I d'ont create the FormObject, because i'm starting with one at first.
I have to store my datas like this, beacause the datasource is a bit weird and i only work with strings.
You need a loop
create the list before that loop
fill the list in the loop
List<TemplateObject> Liste_template = new List<TemplateObject>()
while(sdr.Read())
{
string temp_name = sdr["Name"].ToString();
string temp_id = sdr["Id"].ToString();
TemplateObject newObject = new TemplateObject(temp_id,temp_name);
Liste_template.Add(TemplateObject)
}
Now you can assign it as DataSource of the GridView:
GridView1.DataSource = Liste_template;
GridView1.DataBind();

string.Contains with Linq To Sql return an Null exception

My Linq To Sql query
PROJETS = PROJETS.Where(p => (p.VilleArrive != "" && p.VilleArrive != null) && p.VilleArrive.Contains(alerte.VilleArrive));
is translated like this
SELECT * // (many columns)
FROM [dbo].[cov_Projet] AS [t0]
WHERE ([t0].[VilleArrive] <> #p0) // city != ""
AND ([t0].[VilleArrive] IS NOT NULL) // city != null
AND ([t0].[VilleArrive] LIKE #p1) // city.contains(alert.city)
ORDER BY [t0].[DateDebut]
It is well executed when i run it manually into sql server. But it returns a ArgumentNullException exception when executed by linq.
Actually the column tested "VilleArrive" ("city") is never null but always an empty string
I really don't understand why it appends.
My problem looks like this one LINQ to SQL and Null strings, how do I use Contains?
but answers do not work with me.
The "LIKE" keyword seems to invoke the Linq.SqlClient.SqlHelpers.GetStringContainsPattern(String text, Char escape)
Thank you for your help , sorry for my english.
Here the stack trace my project is an ASP MVC 1.0 project
System.ArgumentNullException was
unhandled by user code Message="La
valeur ne peut pas être null.\r\nNom
du paramètre : text"
Source="System.Data.Linq"
ParamName="text" StackTrace:
à System.Data.Linq.SqlClient.SqlHelpers.GetStringContainsPattern(String
text, Char escape)
à System.Data.Linq.SqlClient.PostBindDotNetConverter.Visitor.TranslateStringMethod(SqlMethodCall
mc)
à System.Data.Linq.SqlClient.PostBindDotNetConverter.Visitor.VisitMethodCall(SqlMethodCall
mc)
à System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode
node)
à System.Data.Linq.SqlClient.SqlVisitor.VisitExpression(SqlExpression
exp)
à System.Data.Linq.SqlClient.SqlVisitor.VisitBinaryOperator(SqlBinary
bo)
à System.Data.Linq.SqlClient.PostBindDotNetConverter.Visitor.VisitBinaryOperator(SqlBinary
bo)
à System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode
node)
à System.Data.Linq.SqlClient.SqlVisitor.VisitExpression(SqlExpression
exp)
à System.Data.Linq.SqlClient.SqlVisitor.VisitSelectCore(SqlSelect
select)
à System.Data.Linq.SqlClient.PostBindDotNetConverter.Visitor.VisitSelect(SqlSelect
select)
à System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode
node)
à System.Data.Linq.SqlClient.SqlVisitor.VisitAlias(SqlAlias
a)
à System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode
node)
à System.Data.Linq.SqlClient.SqlVisitor.VisitSource(SqlSource
source)
à System.Data.Linq.SqlClient.SqlVisitor.VisitSelectCore(SqlSelect
select)
à System.Data.Linq.SqlClient.PostBindDotNetConverter.Visitor.VisitSelect(SqlSelect
select)
à System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode
node)
à System.Data.Linq.SqlClient.SqlVisitor.VisitUnion(SqlUnion
su)
à System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode
node)
à System.Data.Linq.SqlClient.SqlVisitor.VisitAlias(SqlAlias
a)
à System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode
node)
à System.Data.Linq.SqlClient.SqlVisitor.VisitSource(SqlSource
source)
à System.Data.Linq.SqlClient.SqlVisitor.VisitSelectCore(SqlSelect
select)
à System.Data.Linq.SqlClient.PostBindDotNetConverter.Visitor.VisitSelect(SqlSelect
select)
à System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode
node)
à System.Data.Linq.SqlClient.SqlProvider.BuildQuery(ResultShape
resultShape, Type resultType, SqlNode
node, ReadOnlyCollection1
parentParameters, SqlNodeAnnotations
annotations)
à System.Data.Linq.SqlClient.SqlProvider.BuildQuery(Expression
query, SqlNodeAnnotations annotations)
à System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.GetQueryText(Expression
query)
à System.Data.Linq.DataQuery1.ToString()
à covCake.Services.ProjetAlerts.RetrieveProjectsByUsers(Boolean
UpdateAlerts) dans
D:\AspProject\covCake\covCake\Services\ProjetAlerts.cs:ligne
111
à covCake.Controllers.AlertesController.SendAlertEmail(String
p) dans
D:\AspProject\covCake\covCake\Controllers\AlertesController.cs:ligne
152
à lambda_method(ExecutionScope , ControllerBase , Object[] )
à System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase
controller, Object[] parameters)
à System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext
controllerContext, IDictionary2
parameters)
à System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext
controllerContext, ActionDescriptor
actionDescriptor, IDictionary2
parameters)
à System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClassa.b__7()
à System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter
filter, ActionExecutingContext
preContext, Func`1 continuation)
InnerException:
Try removing the != "" comparison, and make sure the parameter you are passing isn't null:
PROJETS = PROJETS.Where(p => (p.VilleArrive != null) &&
(alerte.VilleArrive != null) &&
p.VilleArrive.Contains(alerte.VilleArrive));

Resources