Login error when input wrong credentials " An unhandled exception occurred during the execution of the current web request - indexoutofrangeexception

These in ASP.NET application of which I am starting to learn. There is an error stating System.IndexOutOfRangeException: UserId.
Here is the code:
protected void ValidateUser(object sender, EventArgs e)
{
int userId = 0;
string roles = string.Empty;
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Validate_User"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Username", Login1.UserName);
cmd.Parameters.AddWithValue("#Password", Login1.Password);
cmd.Connection = con;
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
userId = Convert.ToInt32(reader["UserId"]);
roles = reader["Roles"].ToString();
con.Close();
}
switch (userId)
{
case -1:
Login1.FailureText = "Username and/or password is incorrect.";
break;
case -2:
Login1.FailureText = "Account has not been activated.";
break;
default:
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, Login1.UserName, DateTime.Now, DateTime.Now.AddMinutes(2880), Login1.RememberMeSet, roles, FormsAuthentication.FormsCookiePath);
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
if (ticket.IsPersistent)
{
cookie.Expires = ticket.Expiration;
}
Response.Cookies.Add(cookie);
Response.Redirect(FormsAuthentication.GetRedirectUrl(Login1.UserName, Login1.RememberMeSet));
break;
}
}
}
}
}
Here is the Image to the error
Error message

Related

Login failed. The login is from an untrusted domain and cannot be used with Integrated authentication. in Entity Framework

getting {"Login failed. The login is from an untrusted domain and cannot be used with Integrated authentication."} please give any suggetion why this error is throwing.
public int Find(string AccountNumber, DateTime DepositedDT)
{
IsPigmySync pigmySync = new IsPigmySync();
pigmySync.AccountNumber = AccountNumber;
pigmySync.DepositedDT = DepositedDT;
SqlParameter issynced = new SqlParameter("#p2", System.Data.SqlDbType.Int);
issynced.Direction = ParameterDirection.Output;
try
{
var sql = "exec Pigmy_GetPigmyItems #p0,#p1,#p2 OUT";
// var result = _context.Database.ExecuteSqlInterpolated(sqlQuery);
var result = _context.Database.ExecuteSqlCommand(sql, pigmySync.AccountNumber, pigmySync.DepositedDT, issynced);
int ab = result;
pigmySync.IsSynced = (int)issynced.Value;
return pigmySync.IsSynced;
}
catch (Exception ex)
{
return 0;
}
above is my code snippet. using entity framework,xamarin forms

IPP Add Account - The Account Isn't Valid

I am trying to add a bank account to QuickBooks Online using IPP. My code fails and says the account isn't valid. Here is my code:
Account account = new Account();
account.Desc = "Desc";
account.Name = "Checking2";
account.Type = AccountTypeEnum.Revenue;
account.TypeSpecified = true;
account.Subtype = AccountSubtypeEnum.Bank.ToString();
dataServices.Add(account);
Do I need to add fields? I also receive errors that an account with the same name exists, however, I do not see it.
I don't see any XML in my log:
OAuthRequestValidator oauthValidator = new OAuthRequestValidator(accessToken, accessTokenSecret, ConfigurationManager.AppSettings["consumerKey"].ToString(), ConfigurationManager.AppSettings["consumerSecret"].ToString());
ServiceContext context = new ServiceContext(oauthValidator, accessToken, companyID, IntuitServicesType.QBO);
context.EnableServiceRequestsLogging = true;
context.IdsLogger = new MyCustomLogger();
dataServices = new DataServices(context);
return "OK";
public class MyCustomLogger : ILogger
{
public MyCustomLogger()
{
}
public string ClearLog()
{
try
{
string path = HttpContext.Current.Server.MapPath("/qblog.txt");
if (File.Exists(path))
{
File.Delete(path);
}
return "OK";
}
catch (Exception ex)
{
return ex.ToString();
}
}
public void Log(TraceLevel idsTraceLevel, string messageToWrite)
{
string level = idsTraceLevel.ToString();
WriteToLog(new ErrorMessage(MessageSeverity.Error, "QBFS", messageToWrite));
}
public string WriteToLog(ErrorMessage message)
{
if (!String.IsNullOrEmpty(message.Message))
{
string path = HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath + "/qblog.txt");
FileStream fileStream = null;
//If the file exists, then append it
if (File.Exists(path))
{
fileStream = new FileStream(path, FileMode.Append);
}
else
{
fileStream = new FileStream(path, FileMode.OpenOrCreate);
}
StreamWriter sw = new StreamWriter(fileStream);
try
{
sw.WriteLine(String.Format("{0} : {1} {2} {3}", message.ApplicationName, message.Severity, DateTime.Now, message.Message));
return "OK";
}
//If there is an error, just do nothing. Don't stop.
catch (Exception ex)
{
return ex.ToString();
}
finally
{
sw.Close();
fileStream.Close();
}
}
return "Message is null or empty";
}
}
Here is my xml request:
<?xml version="1.0" encoding="utf-8"?><q1:Account xmlns="http://www.intuit.com/sb/cdm/qbo" xmlns:q1="http://www.intuit.com/sb/cdm/v2"><q1:Name>Checking</q1:Name><q1:Desc>Desc</q1:Desc><q1:Subtype>Bank</q1:Subtype></q1:Account>
Here is my response:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><FaultInfo xmlns="http://www.intuit.com/sb/cdm/baseexceptionmodel/xsd"><Message>Another account is already using this name. Please use a different name.</Message><ErrorCode>BAD_REQUEST</ErrorCode><Cause>-11202</Cause></FaultInfo>
I needed to specify the opening and current balance with the true variables:
ac = new Account();
ac.Desc = "Desc";
ac.Name = "Testy";
ac.Subtype = QboAccountDetailTypeEnum.Checking.ToString();
ac.OpeningBalanceDate = DateTime.Now;
ac.OpeningBalanceDateSpecified = true;
ac.CurrentBalance = 0;
ac.CurrentBalanceSpecified = true;
dataServices.Add(ac);
My Subtype was also incorrect. I needed to use the QboAccountDetailTypeEnum.

Prevent sending email and show message via plug-in

I am writing crm2011 plugin in "Email" entity with "Send" Message of Pre_operation. What i want to do is when i click "Send" button in email entity, I do the necessary checking before send. If the checking is not correct, I want to prevent and stop the sending email and show "the alert message" and stop the second plugin(this plugin send email and create the associated entity to convert "Case"). Please give me some suggestion for that plugin?
Should i use pre-Validation stage or Pre_operation state? And how can I return false to stop plugin.
public void Execute(IServiceProvider serviceProvider)
{
try
{
string message = null;
_serviceProvider = serviceProvider;
_context = (IPluginExecutionContext)
serviceProvider.GetService(typeof(IPluginExecutionContext));
_serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
_currentUser = _context.UserId;
message = _context.MessageName.ToLower();
if (message == "send")
{
if (_context.InputParameters != null && _context.InputParameters.Contains("EmailId"))
{
object objEmailId = _context.InputParameters["EmailId"];
if (objEmailId != null)
{
_emailId = new Guid(objEmailId.ToString());
FindEmailInfo();
if (_email != null)
{
if (_email.Attributes.Contains("description") && _email.Attributes["description"] != null)//Email descritpion is not null
{
string emaildescription = StripHTML();
//Find KB Article prefix no in system config entity
serviceguideprefix = "ServiceGuidesPrefix";
QueryByAttribute query = new QueryByAttribute("ppp_systemconfig");
query.ColumnSet = new ColumnSet(true);
query.AddAttributeValue(sysconfig_name, serviceguideprefix);
EntityCollection sysconfig = _service.RetrieveMultiple(query);
if (sysconfig.Entities.Count > 0)
{
Entity e = sysconfig.Entities[0];
if (e.Attributes.Contains("ppp_value"))
{
ppp_value = e.Attributes["ppp_value"].ToString();
}
}
if (ppp_value != null && ppp_value != string.Empty)
{
//var matches = Regex.Matches(emaildescription, #"KBA-\d*-\w*").Cast<Match>().ToArray();
var matches = Regex.Matches(emaildescription, ppp_value + #"-\d*-\w*").Cast<Match>().ToArray();
//ReadKBNo(emaildescription);
foreach (Match kbnumber in matches)
{
EntityCollection kbarticlecol = FindKBArticleIds(kbnumber.ToString());
if (kbarticlecol.Entities.Count > 0)
{
Entity kbariticle = kbarticlecol.Entities[0];
if (kbariticle.Attributes.Contains("mom_internalkm"))
{
bool internalserviceguide = (bool)kbariticle.Attributes["mom_internalkm"];
if (internalserviceguide) found = true;
else found = false;
}
else found = false;
}
}
}
if (found)
{
//-----
}
}
}
}
}
}
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException(ex.Message, ex);
}
}
Well stopping the plugin is dead easy you just throw InvalidPluginException, the message you give it will be shown to the user in a alert window. You will have to do this on the pre of the send. In this case I don't think it will matter if its pre-validation or pre-operation.
Edit:
Yes, you should throw an InvalidPluginException even if no exception has happened in code. I accept this isnt what we would normally do, but its the way its meant to work. Msdn has more details: http://msdn.microsoft.com/en-us/library/gg334685.aspx
So for example the code would look like:
public void Execute(IServiceProvider serviceProvider)
{
try
{
//This is where we validate the email send
if(emailIsOkay)
{
//Do something
}
else if(emailIsNotOkay)
{
//Throw and exception that will stop the plugin and the message will be shown to the user (if its synchronous)
throw new InvalidPluginExecutionException("Hello user, your email is not correct!!");
}
}
catch (InvalidPluginExecutionException invalid)
{
//We dont to catch exception for InvalidPluginExecution, so just throw them on
throw;
}
catch (Exception ex)
{
//This exception catches if something goes wrong in the code, or some other process.
throw new InvalidPluginExecutionException(ex.Message, ex);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Crm;
using Microsoft.Xrm.Sdk;
using System.ServiceModel;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Crm.Sdk.Messages;
using System.Text.RegularExpressions;
using System.Xml.Linq;
namespace SendEmail
{
public class Email : IPlugin
{
public void Execute(IServiceProvider serviceprovider)
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceprovider.GetService(typeof(IPluginExecutionContext));
if (!(context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity))
return;
//entity
Entity ent = (Entity)context.InputParameters["Target"];
if (ent.LogicalName != "entityName")//EntityName
throw new InvalidPluginExecutionException("Not a Service Request record! ");
//service
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceprovider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService _service = serviceFactory.CreateOrganizationService(context.UserId);
string Email="";
if (ent.Contains("emailidfiled"))
Email = (string)ent["emailidfiled"];
#region email template
QueryExpression query = new QueryExpression()
{
EntityName = "template",
Criteria = new FilterExpression(LogicalOperator.And),
ColumnSet = new ColumnSet(true)
};
query.Criteria.AddCondition("title", ConditionOperator.Equal, "templateName");
EntityCollection _coll = _service.RetrieveMultiple(query);
if (_coll.Entities.Count == 0)
throw new InvalidPluginExecutionException("Unable to find the template!");
if (_coll.Entities.Count > 1)
throw new InvalidPluginExecutionException("More than one template found!");
var subjectTemplate = "";
if (_coll[0].Contains("subject"))
{
subjectTemplate = GetDataFromXml(_coll[0]["subject"].ToString(), "match");
}
var bodyTemplate = "";
if (_coll[0].Contains("body"))
{
bodyTemplate = GetDataFromXml(_coll[0]["body"].ToString(), "match");
}
#endregion
#region email prep
Entity email = new Entity("email");
Entity entTo = new Entity("activityparty");
entTo["addressused"] =Email;
Entity entFrom = new Entity("activityparty");
entFrom["partyid"] = "admin#admin.com";
email["to"] = new Entity[] { entTo };
email["from"] = new Entity[] { entFrom };
email["regardingobjectid"] = new EntityReference(ent.LogicalName, ent.Id);
email["subject"] = subjectTemplate;
email["description"] = bodyTemplate;
#endregion
#region email creation & sending
try
{
var emailid = _service.Create(email);
SendEmailRequest req = new SendEmailRequest();
req.EmailId = emailid;
req.IssueSend = true;
GetTrackingTokenEmailRequest wod_GetTrackingTokenEmailRequest = new GetTrackingTokenEmailRequest();
GetTrackingTokenEmailResponse wod_GetTrackingTokenEmailResponse = (GetTrackingTokenEmailResponse)
_service.Execute(wod_GetTrackingTokenEmailRequest);
req.TrackingToken = wod_GetTrackingTokenEmailResponse.TrackingToken;
_service.Execute(req);
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException("Email can't be saved / sent." + Environment.NewLine + "Details: " + ex.Message);
}
#endregion
}
private static string GetDataFromXml(string value, string attributeName)
{
if (string.IsNullOrEmpty(value))
{
return string.Empty;
}
XDocument document = XDocument.Parse(value);
// get the Element with the attribute name specified
XElement element = document.Descendants().Where(ele => ele.Attributes().Any(attr => attr.Name == attributeName)).FirstOrDefault();
return element == null ? string.Empty : element.Value;
}
}
}

Submitting a WebRequest from within a CLR Trigger

I just implemented a prototype solution for updating my caching server in real-time by assigning a CLR Trigger to a table so that whenever a certain column is updated the URL called from the trigger will update the caching server with the correct data.
It's working fine and the code is as follows:
[Microsoft.SqlServer.Server.SqlTrigger(Name = "AdStatusChanged", Target = "Ads", Event = "FOR UPDATE")]
public static void AdStatusChanged()
{
SqlTriggerContext triggContext = SqlContext.TriggerContext;
int adID = 0, adStatusID_Old = 0, adStatusID_New = 0;
if (triggContext.TriggerAction == TriggerAction.Update)
{
using (SqlConnection conn = new SqlConnection("context connection=true"))
{
conn.Open();
SqlCommand sqlComm = new SqlCommand();
SqlPipe sqlP = SqlContext.Pipe;
sqlComm.Connection = conn;
sqlComm.CommandText = "SELECT AdID, AdStatusID from INSERTED";
SqlDataReader reader = sqlComm.ExecuteReader();
if (reader.Read())
{
adID = reader.GetInt32(0);
adStatusID_New = reader.GetInt32(1);
}
reader.Close();
sqlComm.CommandText = "SELECT AdID, AdStatusID from DELETED WHERE AdID = " + adID;
reader = sqlComm.ExecuteReader();
if (reader.Read())
{
adID = reader.GetInt32(0);
adStatusID_Old = reader.GetInt32(1);
}
}
if (adID == 0 || adStatusID_New == adStatusID_Old)
{
// Check could be more thorough !
return;
}
WebResponse httpResponse = null;
try
{
string apiURL = string.Format("{0}/{1}", "http://localhost:14003/Home", "UpdateAdStatus?adID=" + adID + "&adStatusID=" + adStatusID_New);
var httpWebRequest = (HttpWebRequest)WebRequest.Create(apiURL);
httpWebRequest.Method = "GET";
httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
// check for successful response
}
catch (Exception ex)
{
Log("WebRequest from within SQL Server failed ! " + ex.Message);
}
finally
{
if (httpResponse != null)
{
httpResponse.Close();
}
}
}
}
I would like to have some expert/experienced views on the "CONS" of this approach regarding performance, deadlocks, sql crashing, or other areas that could be of potential concern.
Has anyone tried this (I'm sure many must have) and what was the result ? a successful implementation or did you revert to some other method or updating the cache real-time?

Crystal report -- invalid log on parameter error

I have a crystal report which was working fine on my local machine but when I moved it to my server it's giving me a "Incorrect Log on parameters".
Code is below. It's called from a .net application
Dim CR As New ReportDocument
Dim str As String = Application.StartupPath
If PrintDialog1.ShowDialog() <> Windows.Forms.DialogResult.OK Then Exit Sub
CR.Load(Application.StartupPath & "\CR Reports\BookPickByConsignee.rpt")
CR.SetParameterValue("param_picknumber", Me.txtpickNumber.Text.Trim())
CR.DataSourceConnections.Item(0).SetConnection(Configuration.ConfigurationSettings.AppSettings("DatabaseServer").ToString(), Configuration.ConfigurationSettings.AppSettings("DatabaseName").ToString(), Configuration.ConfigurationSettings.AppSettings("UserName").ToString(), Configuration.ConfigurationSettings.AppSettings("Password").ToString())
'CR.DataSourceConnections.Item(0).SetLogon("sa", "pwd")
' CR.SetDatabaseLogon("sa", "pwd")
CR.PrintOptions.PrinterName = PrintDialog1.PrinterSettings.PrinterName
CR.PrintToPrinter(Me.txtCopies.Text, True, 1, 100)
CR.Close()
You can use the following code to apply certain connection details for a report at run time.
Sorry, code in c#.
Please use that method just after loading report rpt file, instead of CR.DataSourceConnections.Item(0).SetConnection and pass required connection details to method, it will work.
public static void CrystalReportLogOn(ReportDocument reportParameters,
string serverName,
string databaseName,
string userName,
string password)
{
TableLogOnInfo logOnInfo;
ReportDocument subRd;
Sections sects;
ReportObjects ros;
SubreportObject sro;
if (reportParameters == null)
{
throw new ArgumentNullException("reportParameters");
}
try
{
foreach (CrystalDecisions.CrystalReports.Engine.Table t in reportParameters.Database.Tables)
{
logOnInfo = t.LogOnInfo;
logOnInfo.ReportName = reportParameters.Name;
logOnInfo.ConnectionInfo.ServerName = serverName;
logOnInfo.ConnectionInfo.DatabaseName = databaseName;
logOnInfo.ConnectionInfo.UserID = userName;
logOnInfo.ConnectionInfo.Password = password;
logOnInfo.TableName = t.Name;
t.ApplyLogOnInfo(logOnInfo);
t.Location = t.Name;
}
}
catch
{
throw;
}
sects = reportParameters.ReportDefinition.Sections;
foreach (Section sect in sects)
{
ros = sect.ReportObjects;
foreach (ReportObject ro in ros)
{
if (ro.Kind == ReportObjectKind.SubreportObject)
{
sro = (SubreportObject)ro;
subRd = sro.OpenSubreport(sro.SubreportName);
try
{
foreach (CrystalDecisions.CrystalReports.Engine.Table t in subRd.Database.Tables)
{
logOnInfo = t.LogOnInfo;
logOnInfo.ReportName = reportParameters.Name;
logOnInfo.ConnectionInfo.ServerName = serverName;
logOnInfo.ConnectionInfo.DatabaseName = databaseName;
logOnInfo.ConnectionInfo.UserID = userName;
logOnInfo.ConnectionInfo.Password = password;
logOnInfo.TableName = t.Name;
t.ApplyLogOnInfo(logOnInfo);
}
}
catch
{
throw;
}
}
}
}
}