Continue foreach loop even after an exception is encounterd in asp.net core razor pages - asp.net-core

I have to log the exception into a database table and continue the foreach loop without any interruptions .
When i am trying to insert the exception into database table in catch block,its throwing null referenece exception. Here is my code.
foreach (var row in toEmailList)
{
foreach (var matrix in emailMatrixList.Where(u => names.Contains(u.BusinessUnit)))
{
// Send to Staff + Supervisor/Manager
if (row.DaysDueDate <= 42 && row.DaysDueDate >= 28)
{
if (matrix.StaffID.Equals(row.StaffID))
{
if (!row.EmailLevelSent.Equals("First Level"))
{
try {
var message = new MailMessage();
var bodyText = "<div style='font-family: Calibri, Arial, Helvetica, sans-serif;'>" +
"<p>Dear #FirstName #LastName,</p>" +
"<p>This is a notification to remind you that you have <b>#DaysDueDate</b> days to complete the following online <b>#TrainingTitle</b> training.</p>" +
"<p>Please remember to complete the training course within the next few days.</p>" +
"<p>If you do not complete this training within the required time frame, this information will be forwarded to your next level manager.</p>" +
"<p>Thank you very much,<br/>Kind regards,</p>" +
"<p>Manager</p>" +
"</div>";
var body = bodyText.Replace("#FirstName", row.FirstName).Replace("#LastName", row.LastName).Replace("#DaysDueDate", row.DaysDueDate.ToString()).Replace("#TrainingTitle", row.TrainingTitle.ToString());
if (matrix.StaffEmail.Contains("#domain.com"))
{
message.To.Add(new MailAddress(row.StaffEmail));
}
else if (matrix.ManagerEmail.Contains("#domain.com"))
{
message.To.Add(new MailAddress(matrix.ManagerEmail));
}
message.From = new MailAddress(_from);
message.Subject = "Training Notification for " + row.TrainingTitle;
if (matrix.ManagerEmail.Contains("#domain.com"))
{
message.CC.Add(new MailAddress(matrix.ManagerEmail));
}
else if ((matrix.ManagerEmail.Contains("N/A")) || (matrix.ManagerEmail.Contains("NA")) || (matrix.ManagerEmail.Contains("#N/A")) || (matrix.ManagerEmail.Contains("na")))
{
message.To.Add(new MailAddress(row.StaffEmail));
}
if (!string.IsNullOrEmpty(matrix.InTheLoop))
{
message.CC.Add(new MailAddress(matrix.InTheLoop));
}
message.Body = string.Format(body);
message.IsBodyHtml = true;
await smtp.SendMailAsync(message);
TempData["MailSent"] = "MailSent";
Debug.WriteLine("Sending first level email to " + row.FirstName + " " + row.LastName);
Debug.WriteLine("CC: " + message.CC.ToString());
row.EmailLevelSent = "First Level";
Debug.WriteLine("First Level email sent to " + row.FirstName);
}
catch (Exception e)
{
FailedEmails.StaffID = row.StaffID;
FailedEmails.FirstName = row.FirstName;
FailedEmails.LastName = row.LastName;
FailedEmails.StaffEmail = row.StaffEmail;
FailedEmails.ExceptionLog = e.Message;
FailedEmails.SentDate = DateTime.Now;
_context.Entry(FailedEmails).State = EntityState.Added;
}
}
}
}
}
}
Any help would be appreciated, is there anything i am missing. Thanks!

Related

SQL injection error in Dynamic SQL with prepared statement

I my application we are collection some user inputs from UI and based on those values we are generating dynamic SQLs with different 'Where' conditions to query data.
It is found that that piece of code has some SQL injection flaw.
public void filter(String strSerialNumberLogic, String strSerialNumber1,
String strSerialNumber2, String strCreationDateLogic,
long lngCreationDate1, long lngCreationDate2,
String strTypeNumbers, String strTitles, long lngLoc)
throws SQLException, ClassNotFoundException {
StringBuffer strWhere = new StringBuffer();
List paramList = new ArrayList();
String arrTypeNumbers[];
String arrTitles[];
int i;
boolean bolHit;
if (!strTypeNumbers.equals("") || !strTitles.equals("")) {
arrTypeNumbers = strTypeNumbers.split(",");
arrTitles = strTitles.split(",");
bolHit = false;
strWhere.append("(");
for (i = 0; i < arrTypeNumbers.length; i++) {
if (arrTypeNumbers[i].length() > 0) {
if (bolHit) {
strWhere.append(" OR ");
} else {
bolHit = true;
}
strWhere.append(" REPORT_NUMBER = ?");
paramList.add(arrTypeNumbers[i]);
}
}
for (i = 0; i < arrTitles.length; i++) {
if (arrTitles[i].length() > 0) {
if (bolHit) {
strWhere.append(" OR ");
} else {
bolHit = true;
}
strWhere.append(" REPORT_NAME = ?");
paramList.add(arrTitles[i]);
}
}
strWhere.append(") ");
}
if (!strSerialNumber1.equals("")) {
if (!strWhere.equals("")) {
strWhere.append(" AND ");
}
strWhere.append(" REPORT_FILE_NO " + strSerialNumberLogic + " ? ");
paramList.add(strSerialNumber1);
if (strSerialNumberLogic.equals("between")) {
strWhere.append(" AND ? ");
paramList.add(strSerialNumber2);
}
}
if (lngCreationDate1 != 0) {
if (!strWhere.equals("")) {
strWhere.append(" AND ");
}
strWhere.append(" REPORT_CREATION_DATE " + strCreationDateLogic + " ? ");
paramList.add(Long.toString(lngCreationDate1));
if (strCreationDateLogic.equals("between")) {
strWhere.append(" AND ? ");
paramList.add(Long.toString(lngCreationDate2));
}
}
if (lngLoc != 0) {
if (!strWhere.equals("")) {
strWhere.append(" AND ");
}
strWhere.append(" REPORT_FILE_LOCATION = ? ");
paramList.add(Long.toString(lngLoc));
}
String finalQuery = "";
if (!strWhere.equals("")) {
finalQuery = "WHERE " + strWhere.toString();
}
String strSQL = "SELECT * " + "FROM D990800 "
+ "LEFT JOIN D990400 ON REPORT_SYSTEM_ID ||" + " REPORT_NO = REPORT_NUMBER " + finalQuery
+ "ORDER BY REPORT_FILE_NO ASC";
System.out.println("strSQL:" + strSQL );
System.out.println("paramList:" + paramList );
Connection conn = ConnectionFactory.instance().getConnection();
PreparedStatement preparedStatement = null;
preparedStatement = conn.prepareStatement(strSQL);
for (int index = 0; index < paramList.size(); index++) {
String param = (String) paramList.get(index);
if (isParsableInt(param)) {
preparedStatement.setInt(index+1, Integer.parseInt(param));
} else {
preparedStatement.setString(index+1, param);
}
}
ResultSet rsReports = preparedStatement.executeQuery();
buildCollection(rsReports);
rsReports.close();
preparedStatement.close();
conn.close();
}
How did you come to the conclusion that you have SQL injection in this code? That would help clearing that up.
Anyway, looking at your code it seems that both strSerialNumberLogic and strCreationDateLogic are variables that comes from an external source, and are concatinated in a way that allows SQL to be injected. If this external source is the user, SQL injection can be executed. If not, than this is probably a false positive. I would improve the code anyway by chaning the logic variables turning them into Enums.

How to avoid to fetch a list of followers of the same Twitter user that was displayed before

I'm very new at coding and I'm having some issues. I'd like to display the followers of followers of ..... of followers of some specific users in Twitter. I have coded this and I can set a limit for the depth. But, while running the code with a small sample, I saw that I run into the same users again and my code re-display the followers of these users. How can I avoid this and skip to the next user? You can find my code below:
By the way, while running my code, I encounter with a 401 error. In the list I'm working on, there's a private user, and when my code catches that user, it stops. Additionally, how can I deal with this issue? I'd like to skip such users and prevent my code to stop.
Thank you for your help in advance!
PS: I know that I'll encounter with a 429 error working with a large sample. After fixing these issues, I'm planning to review relevant discussions to deal with.
public class mainJava {
public static Twitter twitter = buildConfiguration.getTwitter();
public static void main(String[] args) throws Exception {
ArrayList<String> rootUserIDs = new ArrayList<String>();
Scanner s = new Scanner(new File("C:\\Users\\ecemb\\Desktop\\rootusers1.txt"));
while (s.hasNextLine()) {
rootUserIDs.add(s.nextLine());
}
s.close();
for (String rootUserID : rootUserIDs) {
User rootUser = twitter.showUser(rootUserID);
List<User> userList = getFollowers(rootUser, 0);
}
}
public static List<User> getFollowers(User parent, int depth) throws Exception {
List<User> userList = new ArrayList<User>();
if (depth == 2) {
return userList;
}
IDs followerIDs = twitter.getFollowersIDs(parent.getScreenName(), -1);
long[] ids = followerIDs.getIDs();
for (long id : ids) {
twitter4j.User child = twitter.showUser(id);
userList.add(child);
getFollowers(child, depth + 1);
System.out.println(depth + "th user: " + parent.getScreenName() + " Follower: " + child.getScreenName());
}
return userList;
}
}
I guess graph search algorithms can be implemented for this particular issue. I chose Breadth First Search algorithm because visiting root user's followers at first would be better. You can check this link to additional information about algorithm.
Here is my implementation for your problem:
public List<User> getFollowers(User parent, int startDepth, int finalDepth) {
List<User> userList = new ArrayList<User>();
Queue<Long> queue = new LinkedList<Long>();
HashMap<Long, Integer> discoveredUserId = new HashMap<Long, Integer>();
try {
queue.add(parent.getId());
discoveredUserId.put(parent.getId(), 0);
while (!queue.isEmpty()) {
long userId = queue.remove();
int discoveredDepth = discoveredUserId.get(userId);
if (discoveredDepth == finalDepth) {
continue;
}
User user = twitter.showUser(userId);
handleRateLimit(user.getRateLimitStatus());
if (user.isProtected()) {
System.out.println(user.getScreenName() + "'s account is protected. Can't access followers.");
continue;
}
IDs followerIDs = null;
followerIDs = twitter.getFollowersIDs(user.getScreenName(), -1);
handleRateLimit(followerIDs.getRateLimitStatus());
long[] ids = followerIDs.getIDs();
for (int i = 0; i < ids.length; i++) {
if (!discoveredUserId.containsKey(ids[i])) {
discoveredUserId.put(ids[i], discoveredDepth + 1);
User child = twitter.showUser(ids[i]);
handleRateLimit(child.getRateLimitStatus());
userList.add(child);
if (discoveredDepth >= startDepth && discoveredDepth < finalDepth) {
System.out.println(discoveredDepth + ". user: " + user.getScreenName() + " has " + user.getFollowersCount() + " follower(s) " + (i + 1) + ". Follower: " + child.getScreenName());
}
queue.add(ids[i]);
} else {//prints to console but does not check followers. Just for data consistency
User child = twitter.showUser(ids[i]);
handleRateLimit(child.getRateLimitStatus());
if (discoveredDepth >= startDepth && discoveredDepth < finalDepth) {
System.out.println(discoveredDepth + ". user: " + user.getScreenName() + " has " + user.getFollowersCount() + " follower(s) " + (i + 1) + ". Follower: " + child.getScreenName());
}
}
}
}
} catch (TwitterException e) {
e.printStackTrace();
}
return userList;
}
//There definitely are more methods for handling rate limits but this worked for me well
private void handleRateLimit(RateLimitStatus rateLimitStatus) {
//throws NPE here sometimes so I guess it is because rateLimitStatus can be null and add this conditional expression
if (rateLimitStatus != null) {
int remaining = rateLimitStatus.getRemaining();
int resetTime = rateLimitStatus.getSecondsUntilReset();
int sleep = 0;
if (remaining == 0) {
sleep = resetTime + 1; //adding 1 more second
} else {
sleep = (resetTime / remaining) + 1; //adding 1 more second
}
try {
Thread.sleep(sleep * 1000 > 0 ? sleep * 1000 : 0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
in this code HashMap<Long, Integer> discoveredUserId is used to prevent program checking same users repeatedly and storing in which depth we faced with this user.
and for private users, there is isProtected() method in twitter4j library.
Hope this implementation helps.

using AE.Net.Mail how to send mail with image inline

I using AE.Net.Mail in .net project.
I sent html mail and file attachment by gmail api and it work perfect.
But i dont know way to embed an image in body mail with it?
Somebody help me ?
string To = txtTo.Text;
string Subject = txtEmailSubject.Text;
string Body = hdfEmailContentSend.Value;
string InputAttachmentArr = hdfInputAttachmentArr.Value;
var msg = new AE.Net.Mail.MailMessage();
msg.From = new MailAddress("haunguyen1791990#gmail.com", "=?UTF-8?B?" + EncodeTo64UTF8(User.FullName) + "?=");
msg.ReplyTo.Add(msg.From);
msg.To.Add(new MailAddress(To));
msg.Subject = "=?UTF-8?B?" + EncodeTo64UTF8(Subject) + "?=";
msg.Body = Body;
var result = SendMessage(InputAttachmentArr, msg, "");
private Google.Apis.Gmail.v1.Data.Message SendMessage(string InputAttachmentArr, AE.Net.Mail.MailMessage msg, string ThreadId) {
try {
bool isAttackFile = false;
string boundary = "boundary_" + DateTime.Now.ToString("yyyyMMddHHmmss");
var service = CRMGmailUtils.DefineServiceGet(Server.MapPath(".") + "\\client_secret.json");
//get info file attachment
List<string> lstAttachFile = InputAttachmentArr.Split(',').ToList();
lstAttachFile.RemoveAll(item => item.Length == 0);
foreach (var item in lstAttachFile) {
string filePath = Server.MapPath("~/" + "Upload/gmail/" + item);
var bytes = File.ReadAllBytes(filePath);
AE.Net.Mail.Attachment file = new AE.Net.Mail.Attachment(bytes, GetMimeType(item), item, true);
msg.Attachments.Add(file);
isAttackFile = true;
}
var msgStr = new StringWriter();
//if file attachment not exists, set type mail is html
if (!isAttackFile) {
msg.ContentType = "text/html";
}
msg.Save(msgStr);
string data = msgStr.ToString();
//else i customize body mail with new boundary
if (isAttackFile) {
string beginBody = "Content-Type: multipart/alternative; boundary=" + boundary;
//beginBody += "\n\n--" + boundary;
//beginBody += "\nContent-Type: text/plain; charset=UTF-8";
//beginBody += "\n\n*2*";
beginBody += "\n\n--" + boundary;
beginBody += "\nContent-Type: text/html; charset=UTF-8";
string endBody = "\n\n--" + boundary + "--";
msg.Body += endBody;
string parentBoundary = Regex.Match(data, #"----(.*?)--").Groups[1].Value;
Regex rgx = new Regex("----" + parentBoundary);
data = rgx.Replace(data, "----" + parentBoundary + "\n" + beginBody, 1);
}
string raw = Base64UrlEncode(data.ToString());
var result = new Google.Apis.Gmail.v1.Data.Message();
//case send with reply
if (!string.IsNullOrEmpty(ThreadId)) {
result = service.Users.Messages.Send(new Google.Apis.Gmail.v1.Data.Message { Raw = raw, ThreadId = ThreadId }, "me").Execute();
} else {
//case send new mail
result = service.Users.Messages.Send(new Google.Apis.Gmail.v1.Data.Message { Raw = raw }, "me").Execute();
}
DeleteAttackFile(lstAttachFile);
return result;
} catch (Exception objEx) {
throw objEx;
}
}

Waiting for process to terminate fails

I'm working on this function to wait for a WPF app to finish.
while (stillRunning)
{
if (timeOut > maxTime)
{
Log["Error"]("The App failed to shutdown correctly.");
break;
}
else
{
if (Aliases[process]["Exists"])
{
timeOut+=1000;
if ((timeOut % 1000) == 0)
{
Log["Message"]("The Application process is still running. " + (timeOut / 1000) + " seconds and waiting");
}
}
else
{
stillRunning = false;
}
}
}
Log["Message"]("The Application process has been shutdown correctly.");
}
Now, the thing is TestComplete 9 won't recognize when the application's been closed. I mean... I can clearly see how the process is not there anymore in Task Manager whereas TC keeps counting until it reaches the limit time (more than enough in this case).
Any clues?
Use this code:
function test()
{
var timeout = 5000;
var startTime = GetTickCount();
var pClosed = waitProcessClose("notepad", timeout);
var endTime = GetTickCount();
var closeTimeS = Math.round((endTime - startTime) / 100) / 10;
if (pClosed) {
Log.Message("The process was closed in " + closeTimeS + " seconds.");
}
else {
Log.Warning("The process was not closed in " + (timeout / 1000) + " seconds.");
}
}
function waitProcessClose(processName, timeout)
{
var endTime = GetTickCount() + timeout;
var proc = Sys.WaitProcess(processName);
while (proc.Exists) {
var secondsLeft = Math.floor((endTime - GetTickCount()) / 1000);
Delay(200, "Waiting for the '" + processName + "' process to be closed: " + secondsLeft);
if (GetTickCount() > endTime) {
Log.Warning("The process is not closed within '" + timeout + "' ms.");
return false;
}
}
return true;
}

How to disable/deactivate a SalesForce User through SOAP API?

I want to disable a User programmetically by using SOAP API. How can I do that? I am using Partner API and I have Developer edition. I have manage users persmissions set. I have gone through this link. I am looking for code which can help me disable/deactivate a User.
This is my code:
import com.sforce.soap.partner.Connector;
import com.sforce.soap.partner.PartnerConnection;
import com.sforce.soap.partner.QueryResult;
import com.sforce.soap.partner.sobject.SObject;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;
public class DeactivateUser {
public static void main(String[] args) {
ConnectorConfig config = new ConnectorConfig();
config.setUsername("waprau#waprau.com");
config.setPassword("sjjhggrhgfhgffjdgj");
PartnerConnection connection = null;
try {
connection = Connector.newConnection(config);
QueryResult queryResults = connection.query("SELECT Username, IsActive from User");
if (queryResults.getSize() > 0) {
for (SObject s : queryResults.getRecords()) {
if(s.getField("Username").equals("abcd#pqrs.com")){
System.out.println("Username: " + s.getField("Username"));
s.setField("IsActive", false);
}
System.out.println("Username: " + s.getField("Username") + " IsActive: " + s.getField("IsActive"));
}
}
} catch (ConnectionException ce) {
ce.printStackTrace();
}
}
}
This is output:
Username: waprau#waprau.com IsActive: true
Username: jsmith#ymail.net IsActive: false
Username: abcd#pqrs.com
Username: abcd#pqrs.com IsActive: false
However in UI when I go to My Name > Setup > Manage Users > Users, it always show 'Active' check box for user abcd#pqrs.com selected :-(
It doesn't look like you're actually sending the update back to Salesforce - you're just setting IsActive to false locally. You will need to use a call to PartnerConnection.update(SObject[] sObjects) in order for Salesforce to reflect your changes, like so:
try {
connection = Connector.newConnection(config);
QueryResult queryResults = connection.query("SELECT Id, Username, IsActive from User");
if ( queryResults.getSize() > 0 ) {
// keep track of which records you want to update with an ArrayList
ArrayList<SObject> updateObjects = new ArrayList<SObject>();
for (SObject s : queryResults.getRecords()) {
if ( s.getField("Username").equals("abcd#pqrs.com") ){
System.out.println("Username: " + s.getField("Username"));
s.setField("Id", null);
s.setField("IsActive", false);
}
updateObjects.add(s); // if you want to update all records...if not, put this in a conditional statement
System.out.println("Username: " + s.getField("Username") + " IsActive: " + s.getField("IsActive"));
}
// make the update call to Salesforce and then process the SaveResults returned
SaveResult[] saveResults = connection.update(updateObjects.toArray(new SObject[updateObjects.size()]));
for ( int i = 0; i < saveResults.length; i++ ) {
if ( saveResults[i].isSuccess() )
System.out.println("record " + saveResults[i].getId() + " was updated successfully");
else {
// There were errors during the update call, so loop through and print them out
System.out.println("record " + saveResults[i].getId() + " failed to save");
for ( int j = 0; j < saveResults[i].getErrors().length; j++ ) {
Error err = saveResults[i].getErrors()[j];
System.out.println("error code: " + err.getStatusCode().toString());
System.out.println("error message: " + err.getMessage());
}
}
}
}
} catch (ConnectionException ce) {
ce.printStackTrace();
}
It is possible to directly work with the user record without the SOQL query if you already know the Id.
SalesforceSession session = ...;
sObject userSObject = new sObject();
userSObject.Id = "00570000001V9NA";
userSObject.type = "User";
userSObject.Any = new System.Xml.XmlElement[1];
XmlDocument xmlDocument = new XmlDocument();
XmlElement fieldXmlElement = xmlDocument.CreateElement("IsActive");
fieldXmlElement.InnerText = bool.FalseString;
userSObject.Any[0] = fieldXmlElement;
SaveResult[] result = session.Binding.update(new sObject[] { userSObject });
foreach(SaveResult sr in result)
{
System.Diagnostics.Debug.WriteLine(sr.success + " " + sr.id);
if(!sr.success)
{
foreach(Error error in sr.errors)
{
System.Diagnostics.Debug.WriteLine(error.statusCode + " " + error.message);
}
}
}