IsPostBack Issue - c#

I am trying to do a 3 tier volunteers sign up for packaging session system. First, on the page load, I get the details of certain packaging session:
if (!IsPostBack)
{
string packingID = Request.QueryString["id"];
packingIndv = packing.getPacking(packingID);
if (packingIndv == null)
{
lbl_msg.Text = "Error in getting packing session details!";
}
else
{
lbl_ID.Text = packingIndv.packingID;
lbl_date.Text = packingIndv.date.ToString("dd/M/yyyy", CultureInfo.InvariantCulture); ;
lbl_location.Text = packingIndv.location;
lbl_volunteerAvailable.Text = packingIndv.volunteerAvailable.ToString();
lbl_status.Text = packingIndv.status;
}
}
After that, volunteers can click on the join button, and the program will execute:
In presentation layer after join button is on click:
string userLogged = Session["userLogged"].ToString();
UserBLL user = new UserBLL();
string userID = user.getUserIDByName(userLogged);
PackingBLL packing = new PackingBLL();
string msg = "";
msg = packing.joinPacking(userID, lbl_ID.Text);
lbl_msg.Text = msg;
In business logic layer:
public string joinPacking(string userID, string packingID)
{
string returnMessage = "";
if(returnMessage.Length == 0)
{
Packing packing = new Packing(userID, packingID);
Boolean success = packing.checkJoinedSession();
if (success)
{
returnMessage += "Same volunteer cannot join same packing session for more than once! <br/>";
}
else
{
int nofRows = 0;
nofRows = packing.joinPacking();
if (nofRows > 0)
{
returnMessage = "Request to volunteer for packing session saved successfully.";
int successUpdate = packing.updateRemaining();
if (successUpdate > 0)
{
getPacking(packingID);
}
}
else
{
returnMessage = "Error! Please try again.";
}
}
}
return returnMessage;
}
In data access layer:
public int updateRemaining()
{
int result = 0;
using (var connection = new SqlConnection(FFTHDb.connectionString)) // get your connection string from the other class here
{
SqlCommand command = new SqlCommand("UPDATE PackingSession SET volunteerAvailable = volunteerAvailable + 1 WHERE packingID = '" + packingID + "'", connection);
connection.Open();
result = command.ExecuteNonQuery();
connection.Close();
}
return result;
}
For every join from each volunteer, the volunteer available will be increased by one. What I am trying to do is from the page load, I display the details of packaging session. Then when volunteer joins it, the volunteerAvailable will straight away increased by one. All my database works perfectly, it just wont increase the volunteer available automatically after each successful update sql statement, as in I have to refresh the browser in order to see the changes.

Related

paypal Amount Total mismatch

When I check in my website using Paypal it gives me this message: "Checkout Error - Amount total mismatch" I used Microsoft tutorial to implement PayPal:
https://learn.microsoft.com/en-us/aspnet/web-forms/overview/getting-started/getting-started-with-aspnet-45-web-forms/checkout-and-payment-with-paypal
I did exactly what it said I even did twice but somehow keep getting this error Appreciate your help Thanks
public partial class CheckoutReview : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
NVPAPICaller payPalCaller = new NVPAPICaller();
string retMsg = "";
string token = "";
string PayerID = "";
NVPCodec decoder = new NVPCodec();
token = Session["token"].ToString();
bool ret = payPalCaller.GetCheckoutDetails(token, ref PayerID, ref decoder, ref retMsg);
if (ret)
{
Session["payerId"] = PayerID;
var myOrder = new Order();
myOrder.OrderDate = Convert.ToDateTime(decoder["TIMESTAMP"].ToString());
myOrder.Username = User.Identity.Name;
myOrder.FirstName = decoder["FIRSTNAME"].ToString();
myOrder.LastName = decoder["LASTNAME"].ToString();
myOrder.Address = decoder["SHIPTOSTREET"].ToString();
myOrder.City = decoder["SHIPTOCITY"].ToString();
myOrder.State = decoder["SHIPTOSTATE"].ToString();
myOrder.PostalCode = decoder["SHIPTOZIP"].ToString();
myOrder.Country = decoder["SHIPTOCOUNTRYCODE"].ToString();
myOrder.Email = decoder["EMAIL"].ToString();
myOrder.Total = Convert.ToDecimal(decoder["AMT"].ToString());
// Verify total payment amount as set on CheckoutStart.aspx.
try
{
decimal paymentAmountOnCheckout = Convert.ToDecimal(Session["payment_amt"].ToString());
decimal paymentAmoutFromPayPal = Convert.ToDecimal(decoder["AMT"].ToString());
if (paymentAmountOnCheckout != paymentAmoutFromPayPal)
{
Response.Redirect("CheckoutError.aspx?" + "Desc=Amount%20total%20mismatch.");
}
}
catch (Exception)
{
Response.Redirect("CheckoutError.aspx?" + "Desc=Amount%20total%20mismatch.");
}
// Get DB context.
ProductContext _db = new ProductContext();
// Add order to DB.
_db.Orders.Add(myOrder);
_db.SaveChanges();
// Get the shopping cart items and process them.
using (WingtipToys.Logic.ShoppingCartActions usersShoppingCart = new WingtipToys.Logic.ShoppingCartActions())
{
List<CartItem> myOrderList = usersShoppingCart.GetCartItems();
// Add OrderDetail information to the DB for each product purchased.
for (int i = 0; i < myOrderList.Count; i++)
{
// Create a new OrderDetail object.
var myOrderDetail = new OrderDetail();
myOrderDetail.OrderId = myOrder.OrderId;
myOrderDetail.Username = User.Identity.Name;
myOrderDetail.ProductId = myOrderList[i].ProductId;
myOrderDetail.Quantity = myOrderList[i].Quantity;
myOrderDetail.UnitPrice = myOrderList[i].Product.UnitPrice;
// Add OrderDetail to DB.
_db.OrderDetails.Add(myOrderDetail);
_db.SaveChanges();
}
// Set OrderId.
Session["currentOrderId"] = myOrder.OrderId;
// Display Order information.
List<Order> orderList = new List<Order>();
orderList.Add(myOrder);
ShipInfo.DataSource = orderList;
ShipInfo.DataBind();
// Display OrderDetails.
OrderItemList.DataSource = myOrderList;
OrderItemList.DataBind();
}
}
else
{
Response.Redirect("CheckoutError.aspx?" + retMsg);
}
}
}
protected void CheckoutConfirm_Click(object sender, EventArgs e)
{
Session["userCheckoutCompleted"] = "true";
Response.Redirect("~/Checkout/CheckoutComplete.aspx");
}
}
I encountered the same problem while doing the tutorial, so here is my solution in case someone encounters it as well.
The main problem here is that Asp.NET displays the string versions of the amounts as XX,XX instead of XX.XX. This is because the .ToString()-function displays decimals as they are written in the current region.
To solve this problem, every .ToString() and Convert.ToDecimal() should be called with an extra parameter called CultureInfo.InvariantCulture, which ensures that the string amounts are stored in memory in the XX.XX-format.
I hope this helps someone in the future.

My boolean value is false even though all the code is correct

About my Program:
My algorithm(this class) is meant to check whether a delivery has been finished and afterwards makes the truck/trailer/driver available for another delivery, at the same time this algorithm sends another truck/trailer/driver on a delivery. To sum it up this class does the following:
Check whether a booking is in Allocation mode (Allocation mode basically means that the "booking" is in progress of being delivered
Check whether there is tonnage left of the booking (Ex. I want to sent 500 ton to a place, but a delivery can only be 30 ton at a time so it checks if there is still ton that needs to be delivered)
To make the Driver(s)/Truck(s)/Trailer(s) available that finished their delivery.
To automatically allocate tonnage to a Driver/Trailer/Truck.
Deleting entries that are finished (any bookings that are finished - Logs still stay in the database).
My Problem:
I have no idea what is wrong with my class, I have been hours at it and can't seem to figure out what is causing my boolean variable (forLoopBreak) to trigger a "false" value when it is calling the method checkAvailTrailers(). The problem seems to be in there but I can't figure out what causes the problem.
Class:
[https://pastebin.com/4up8eppd][1]
( I couldn't paste it here as I met the limit of characters)
Notes:
I know my programming looks but, but I am still new to this.
I decided to attach the whole class as the problem may be at a different place.
Edit:
My code is too large to investigate so here is the relevant parts:
private void startAlgo()
{
checkAvailTrailers();
if (forloopBreak == false)
{
setErrorMessage("Avail Trailers not enough!");
}
}
private void checkAvailTrailers()
{
string trailerRouteAllocation = null;
string trailerVragAllocation = null;
string tempHolderTrailer = null;
string myNewTempT = null;
string trailermyTemp = null;
int trailerCount = 0;
int tempTra = -1;
//Gets trailer route classification
using (SqlCommand selectTrailer = new SqlCommand("SELECT [TR_Routes] FROM dbo.TrailerDetail WHERE [TR_Allocation] = " + 0, con))
{
using (SqlDataReader reader = selectTrailer.ExecuteReader())
{
while (reader.Read())
{
trailerRouteAllocation = reader.GetString(0);
tempHolderTrailer = trailerRouteAllocation;
myNewTempT = trailerRouteAllocation;
for (int l = 0; l < tempHolderTrailer.Length; l++)
{
tempTra = myNewTempT.IndexOf(",");
if (tempTra >= 0)
{
trailermyTemp = myNewTempT.Substring(0,tempTra);
}
else
{
trailermyTemp = myNewTempT;
if (trailermyTemp == myCurrentBookingRoute.ToString())
{
mycurrentTrailerAvailableRoute[trailerCount] = tempHolderTrailer;
}
break;
}
myNewTempT = myNewTempT.Substring(tempTra + 1);
if (trailermyTemp == myCurrentBookingRoute.ToString())
{
mycurrentTrailerAvailableRoute[trailerCount] = trailerRouteAllocation;
}
}
trailerCount++;
}
reader.Close();
}
}
//gets trailer vrag classification.
int countTrailerVrag = 0;
for (int l = 0; l < mycurrentTrailerAvailableRoute.Length; l++)
{
if (mycurrentTrailerAvailableRoute[l] != null)
{
using (SqlCommand select = new SqlCommand("Select [TR_Classification] FROM dbo.TrailerDetail WHERE [TR_Routes] = '" + mycurrentTrailerAvailableRoute[l] + "' AND [TR_Allocation] = " + 0, con))
{
using (SqlDataReader readerS = select.ExecuteReader())
{
while (readerS.Read())
{
trailerVragAllocation = readerS.GetString(0);
myAvailableTrailerVragClassification[countTrailerVrag] = trailerVragAllocation;
countTrailerVrag++;
}
readerS.Close();
}
}
}
}
int countTrailers = 0;
string trailerRegNum = null;
for (int l = 0; l < mycurrentTrailerAvailableRoute.Length; l++)
{
if (mycurrentTrailerAvailableRoute[l] != null)
{
using (SqlCommand selectT = new SqlCommand("Select [TR_RegNumber] FROM dbo.TrailerDetail WHERE [TR_Routes] = '" + mycurrentTrailerAvailableRoute[l] + "'" + " AND [TR_Classification] = '" + myAvailableTrailerVragClassification[l] + "' AND [TR_Allocation] = " + 0, con))
{
SqlDataReader readerT = selectT.ExecuteReader();
if (readerT.HasRows)
{
while (readerT.Read())
{
trailerRegNum = readerT.GetString(0);
myAvailableCurrentTraillerRegNumber[countTrailers] = trailerRegNum;
countTrailers++;
}
}
else
{
forloopBreak = false;
}
readerT.Close();
}
}
}//END OF TRAILER CHECKING
//gets trailer's max tonnage
int myTrailerTonMax = 0;
int myTrailerTon = 0;
for (int l = 0; l < mycurrentTrailerAvailableRoute.Length; l++)
{
if (mycurrentTrailerAvailableRoute[l] != null)
{
using (SqlCommand selectT = new SqlCommand("Select [TR_MaxTonnage] FROM dbo.TrailerDetail WHERE [TR_Routes] = '" + mycurrentTrailerAvailableRoute[l] + "'" + " AND [TR_Classification] = '" + myAvailableTrailerVragClassification[l] + "'", con))
{
using (SqlDataReader readerS = selectT.ExecuteReader())
{
while (readerS.Read())
{
myTrailerTon = readerS.GetInt32(0);
myTrailerAvailableTonMax[myTrailerTonMax] = myTrailerTon;
myTrailerTonMax++;
}
readerS.Close();
}
}
}
}
}
Extra:
- The data in my database matches the criteria, the while loop even executes but in the end my boolean value returns a false.
The readerT.HasRows clause will always be true if there is any data initially in the reader. Here is the property's description from the MSDN page
Gets a value that indicates whether the SqlDataReader contains one or more rows.
What you want to do instead (I assume) is set forloopBreak = false; when the while loop is finished. So inside the using block you put this:
SqlDataReader readerT = selectT.ExecuteReader();
while (readerT.Read())
{
trailerRegNum = readerT.GetString(0);
myAvailableCurrentTraillerRegNumber[countTrailers] = trailerRegNum;
countTrailers++;
}
forloopBreak = false;
readerT.Close();
Let me know if this works!

Passing values between Windows form and a database

I faced a problem while trying to build a Windows form solution for a college assignment, and hope somebody can point out my mistake.
The solution is about a mobile shop. I have two classes, Apple and Android forms. I need to read the data in the database table, categorize the entries to either Android or Apple phones, and then display all phones in a list when the form loads.
I can successfully categorize phones, but when trying to read the entries, I always end up with the same entry twice in my list on the form, while the second entry doesn't appear at all.
I know I made a big stupid mistake while doing the connection but I can't find it!.
Here is my code:
public abstract class MobilePhone {
private Int32 phoneID;
private string operatingSystem;
private string make;
private string model;
public enum Condition { Poor, Fair, Good, Mint };
private Condition condition;
private decimal originalPrice;
private DateTime datePurchase;
private string description;
private clsDataConnection dbConnection;
//constructor
public MobilePhone(string make, string model, decimal originalPrice, DateTime datePurchase, Condition condition, string description) {
this.make = make;
this.model = model;
this.originalPrice = originalPrice;
this.datePurchase = datePurchase;
this.condition = condition;
this.description = description;
}
Not complete, but that's what is relevant:
public class ApplePhone : MobilePhone {
decimal ApproxValue;
public ApplePhone(string make, string model, decimal originalPrice, DateTime datePurchase, Condition condition, string description)
: base(make, model, originalPrice, datePurchase, condition, description) {
}
The Android class is the same but with different other functions.
class Shop {
clsDataConnection dbConnection;
const int NotAdded = -1; // invalid primary key
private string name;
private decimal ApproxValue;
private Int32 phoneID;
private string operatingSystem;
private string make;
private string model;
private MobilePhone.Condition condition;
private decimal originalPrice;
private DateTime datePurchase;
private string description;
Int32 Index;
private List<MobilePhone> phonesForSale;
//constructor
public Shop(string name) {
this.name = name;
}
MobilePhone phone;
public void SelectAll() {
dbConnection = new clsDataConnection();
dbConnection.Execute("SellectAllPhones");
}
public void FilterByOperatingSystem(string operatingSystem) {
dbConnection = new clsDataConnection();
dbConnection.AddParameter("#OperatingSystem", operatingSystem);
dbConnection.Execute("FilterByOperatingSystem");
}
public Int32 Count {
get {
//return the count of records
return dbConnection.Count;
}
}
public string DescribeCurrentPhone(int Index) {
Int32 phoneID;
string make;
string model;
MobilePhone.Condition condition;
decimal originalPrice;
DateTime datePurchase;
string description;
phoneID = Convert.ToInt32(phonesForSale[Index].PhoneID);
make = Convert.ToString(phonesForSale[Index].Make);
model = Convert.ToString(phonesForSale[Index].Model);
condition = phonesForSale[Index].GetCondition;
originalPrice = Convert.ToDecimal(phonesForSale[Index].OriginalPrice);
datePurchase = Convert.ToDateTime(phonesForSale[Index].DatePurchased);
description = Convert.ToString(phonesForSale[Index].Description);
//set up a new object of class list item
string listItemText = make + " " + "|" + " " + model + " " + "|" + " " + condition + " " + "|" + " " + "£" + Math.Round(originalPrice, 2) + " " + "|" + " " + datePurchase.ToShortDateString() + " " + "|" + " " + description;
return listItemText;
}
public List<MobilePhone> Allphones {
get {
phonesForSale = new List<MobilePhone>();
int count = Count;
Index = 0;
while (Index < count) {
phoneID = Convert.ToInt32(dbConnection.DataTable.Rows[Index]["PhoneId"]);
operatingSystem = Convert.ToString(dbConnection.DataTable.Rows[Index]["OperatingSystem"]);
make = Convert.ToString(dbConnection.DataTable.Rows[Index]["Make"]);
model = Convert.ToString(dbConnection.DataTable.Rows[Index]["Model"]);
string conditionString = Convert.ToString(dbConnection.DataTable.Rows[Index]["Condition"]);
originalPrice = Convert.ToInt32(dbConnection.DataTable.Rows[Index]["OriginalPrice"]);
datePurchase = Convert.ToDateTime(dbConnection.DataTable.Rows[Index]["DatePurchased"]);
description = Convert.ToString(dbConnection.DataTable.Rows[Index]["Description"]);
// Set Condition
if (conditionString == "Poor") {
condition = MobilePhone.Condition.Poor;
} else if (conditionString == "Fair") {
condition = MobilePhone.Condition.Fair;
} else if (conditionString == "Good") {
condition = MobilePhone.Condition.Good;
} else if (conditionString == "Mint") {
condition = MobilePhone.Condition.Mint;
}
//check Operating System
if (operatingSystem == "IOS") {
phone = new ApplePhone(make, model, originalPrice, datePurchase, condition, description);
//ApproxValue = ApplePhone.CalculateApproximateValue();
} else if (operatingSystem == "Android") {
phone = new AndroidPhone(make, model, originalPrice, datePurchase, condition, description);
//ApproxValue = AndroidPhone.CalculateApproximateValue();
}
Index++;
phonesForSale.Add(phone);
}
return phonesForSale;
}
}
And the form code is:
public partial class FormMain : Form {
public FormMain() {
InitializeComponent();
Shop shop = new Shop("");
}
private void FormMain_Load(object sender, EventArgs e) {
DisplayItems("");
}
protected int DisplayItems(string operatingSystem) {
Shop MyShop = new Shop("");
Int32 RecordCount;
Int32 Index = 0;
Int32 PID;
if (operatingSystem != "") {
MyShop.FilterByOperatingSystem(operatingSystem);
} else {
MyShop.SelectAll();
}
RecordCount = MyShop.Count;
ArrayList MyPhones = new ArrayList();
while (Index < RecordCount) {
// I Suspect this line is the problem but don't know how to fix it
PID = MyShop.Allphones[Index].PhoneID
string listItemText = MyShop.DescribeCurrentPhone(PID);
//add the new item to the list
MyPhones.Add(listItemText);
//increment the index
Index++;
}
listBox1.DataSource = MyPhones;
return RecordCount;
}
I am not used to connecting to databases, so any advice will be of help!
An example of an alternative to the DB connection you have made is below
List<MyPhone> myIPhoneList = new List<Myphone>();
List<MyPhone> myAndroidList = new List<Myphone>();
SqlConnection myDBConnection = new SqlConnection("MyConnectionString"); //DB Connection
SqlCommand dbCommand = new SqlCommand("SelectAllPhones"); //Stored Procedure
SqlDataReader recordReader = dbCommand.ExecuteReader(); //Execute
//Read records return in to phone objects
while (recordReader.Read()) {
var phoneField1 = recordReader["PhoneField1FromDatabase"];
var phoneField2 = recordReader["PhoneField2FromDatabase"];
//etc...
var myPhone = new MyPhone();
myPhone.Name = phoneField1;
//etc...
if (myPhone.OS == "iPhone")
myIPhoneList.Add(myPhone);
if (myPhone.OS = "Android")
myAndroidList.Add(myPhone);
}
Just a twist to Wheels answer really,
I'd personally put a filter on the stored-proc.
SqlCommand dbCommand = new SqlCommand("SelectAllPhones"); //Stored Procedure
becomes something like:
using (SqlConnection conn = new SqlConnection())
{
using (SqlCommand cmd = new SqlCommand("SelectAllPhones", conn))
{
cmd.Parameters.Add(new SqlParameter() { ParameterName = "#OS", SqlDbType = SqlDbType.VarChar, Direction = ParameterDirection.Input, Value = phoneOS });
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
// load your data...
}
}
}
Only because there is very little point dragging both sets of phone data (android/iphone) for each class. You may as well only pull back the data you require.
Of course the Stored-Proc will need an update to cater for the parameter.
something like:
AND PhoneOS = #OS
needs appending to your SQL condition.
clsDataConnection dbConnection; is unknown to me - is this a third party library or a class you've wrote and not included?
public Int32 Count
{
get
{
//return the count of records
return dbConnection.Count;
}
}
dbConnection.Count seems very non-standard. Doesn't read as if you're trying to get the number of rows, more the number of connections - which is invalid here.
dbConnection.DataTables[0].Rows.Count; would be a better way of determining the rows using your existing code, as currently it reads as if your counting the number of database connections which isn't what your after - and would be redundant if using either mine or Wheels as you wont need to know beforehand how many rows your about to process.

C# Webservice stucks. Need to override published file to restart

Please help me, I'm facing a fatal problem here. If someone could fix this, I swear I will treat u to a huge drink whenever u step into my country (Vietnam). Ok here's the problem: I'm coding a webservice for multi connection simultaneously from tablet (around 100 clients). It ran well but recently whenever high traffic occurs, my webservice seems to stuck somehow and I need to copy - override the published file of webservice in order for it to run again (restart website in IIS is no use) ...
This is my w/s code for handling the data:
public string Info_Handling(string id, string name, string strDetails)
{
string checkExist = "";
string str = "";
string str2 = "";
MLL_Customer _customerClient = new MLL_Customer();
MLL_CustomerCategory _categoryClient = new MLL_CustomerCategory();
MLL_Product _productClient = new MLL_Product();
MLL_SampleProduct _sampleClient = new MLL_SampleProduct();
if (_customerClient.CheckExistCustomer(id, name.ToUpper(), 2) == 1) // SID & NAME
{
checkExist = "EXIST";
}
using (SqlConnection connection = new SqlConnection(ConfigurationSettings.AppSettings["Main.ConnectionString"]))
{
connection.Open();
SqlTransaction trans = connection.BeginTransaction("XXX");
try
{
// ID Example: 11 means VIP - 12 means Normal - 13 means ples... jkg
// First - Insert Customer
string strCustomerCategory = _categoryClient.SelectCategoryByID(id).ToString();
if (!checkExist.Equals("EXIST"))
{
Customer businessObject = new Customer();
businessObject.ID = sid;
businessObject.Name = name.ToUpper();
businessObject.CategoryID = strCustomerCategory;
str = "" + _customerClient.Insert(businessObject, connection, trans);
}
// Second Insert Product spliting from a string Ex: "TV&Laptop&CD"
string[] productDetails = strDetails.Split(new char[] { '&' });
object obj3;
SampleProduct objSample;
Product objProduct;
for (int j = 0; j < productDetails.Length; j++)
{
if (_productClient.CheckExist(id, productDetails[j])) == null) // Check if customer already owns this product
{
// Get the properties of sample product.
objSample = _sampleClient.SelectSampleProduct(productDetails[j]);
objProduct = new Product();
objProduct.SID = sid;
objProduct.Testcode = objSample.TestCode;
objProduct.Category = objSample.Category;
objProduct.Unit = objSample.Unit;
objProduct.Price = objSample.Price;
if (_productClient.Insert(objProduct, connection, trans) != 0)
{
str2 = str2 + "&" + objProduct.Testcode;
// return the code of product in order to see which product has been inserted successfully
}
}
}
trans.Commit();
SqlConnection.ClearAllPools();
}
catch (Exception exception)
{
str = "0";
str2 = exception.Message + exception.Source;
try
{
trans.Rollback();
}
catch (Exception)
{
}
}
}
if (!str2.Equals(""))
{
return (str + "&" + id + str2);
}
return ("0&" + sid + str);
}
I modified the code but this is basically how i roll. Could anyone plz tell me some solution. Deeply thank u.
1 more thing about ClearAllPools() method: I know how it works but I dont even know why I need it. Without this, my data will be messed up terrible. CategoryID of one customer will be assigned for another customer sometimes. ???? How could it happened ?? HELP

Binding Links in a Custom Object using Upsert function in C# SalesForce?

I have the following code which creates a Task in Salesforce and then tracks a user's browsing history and stores it in SalesForce. Currently, it displays each and every page the user has browsed as an individual entry. I want to group all those entries together in the Browsing_History__c object instead of task being created every time a user visits a page.
Any help would be appreciated..I am not familiar with SF very much. :)
private void CreateTaskInSF(string id, string type, string details, string description)
{
// if there's a similar Event in the past 2 hours, don't add it
QueryResult qr = null;
try // get events from past 2 hours
{
qr = Binding.query("Select Details__c from Task WHERE WhoId='" + id + "' and Type__c='" + type + "' and CreatedDate > " + DateTime.UtcNow.AddHours(-2).ToString("s") + "Z");
}
catch (Exception e)
{
return;
}
bool logged = false;
if (qr != null) // if there are Tasks in past 2 hours
{
sforce.sObject[] browsing = qr.records;
if (browsing != null)
{
// iterate through events to make sure the new Task isn't logged
for (int i = 0; i < browsing.Length; i++)
{
Task currTask = (Task)browsing[i];
if (currTask.Details__c == details)
{
if (description != "") // is there a description to check for?
{
string oldTaskDescription = "";
if (currTask.Description != null)
oldTaskDescription = currTask.Description;
if (oldTaskDescription == description) // if there is a description match
logged = true;
}
else
logged = true; // there's no description, so check only on details field
}
}
}
}
if (logged == true)
{
return; // if Activity is already logged, don't log it again
}
else if (type == "Browsing")
{
QueryResult browsingQuery = null;
try // get events from past 2 hours
{
browsingQuery = Binding.query("Select Web_Browsing__c from Task WHERE WhoId='" + id + "' and Subject='" + type + "' and Details__c='" + details + "' and CreatedDate > " + DateTime.UtcNow.AddHours(-2).ToString("s") + "Z");
}
catch
{
}
Boolean createNewBrowsing = false;
if (browsingQuery != null) // if there are Tasks in past 2 hours
{
sforce.sObject[] webBrowsing = browsingQuery.records;
if (webBrowsing != null)
{
//find correct object and update Browsing_History__c
//Binding.update
}
else
{
createNewBrowsing = true;
}
}
else
{
createNewBrowsing = true;
}
if (createNewBrowsing)
{
Web_Browsing__c newTask = new Web_Browsing__c();
newTask.Lead__c = id;
newTask.Browsing_History_255__c = details;
newTask.Type__c = type;
newTask.Browsing_History__c = details;
newTask.CreatedDate = DateTime.Now;
//if(type == "Browsing") newTask. = details;
//SaveResult[] createResult = Binding.create(new sObject[] { newTask });
try
{
SaveResult[] createResult = Binding.create(new sObject[] { newTask });
}
catch (Exception e)
{
return;
}
}
}
else
{
// if this new Activity isn't logged, then create a new Activity Task
sforce.Task newTask = new sforce.Task();
newTask.WhoId = id;
newTask.Subject = type;
newTask.Details__c = details;
if (description != "") newTask.Description = description;
newTask.Status = "Completed";
newTask.Priority = "Normal";
newTask.ActivityDate = DateTime.Now;
newTask.ActivityDateSpecified = true;
// insert it
try
{
SaveResult[] createResult = Binding.create(new sforce.sObject[] { newTask });
}
catch (Exception e)
{
return;
}
}
}
You'll need to update your query to ask for the browsing history object and update the code to create a browsing history object instead of a task.
If you haven't already, review the Web Services API docs, it has examples for querying and creating in java/c#.

Categories

Resources