Panel using stored procedure - Code not reacting as expected - asp.net

I have hit a small issue and hoping someone might be able to assist. I am using a panel - On the page load, it should list all the products as no category has been selected as per stored procedure (this works perfectly).
When a user clicks on a specific category, it should only show the products that have the specific CategoryID. When I run the code in SQL, it works a dream for this part too, so assume the stored procedure is ok.
At
CategoryID = CategoryID
in GetProducts, I get
Warning: Assignment made to same variable; did you mean to assign something else?
However I am following a tutorial video and this works fine. Is there another silly error that is preventing it from working?
I think I have included all the required code - sorry if its a bit overkill!!
Thanks as ever in advance - Jack
Code behind pnlCategories:
private void GetProducts(int CategoryID)
{
ShoppingCart k = new ShoppingCart();
{
CategoryID = CategoryID;
};

Error identified - additional ";" added at following line:
ShoppingCart k = new ShoppingCart();
Code now reads
ShoppingCart k = new ShoppingCart()
{
CategoryID = CategoryID
};
and functions as expected!

that looks like a c# error and not a SQL Server error.
The problem is here in your GetProducts method. CategoryID = CategoryID;
C# is case sensitive. If you check your tutorial carefully, one of these will probably be lower case. Make sure you type that carefully.
try code change below and see where the compiler complains.
CategoryID = categoryID;
private void GetProducts(int CategoryID)
{
ShoppingCart k = new ShoppingCart();
{
CategoryID = CategoryID;
};
dlProducts.DataSource = null;
dlProducts.DataSource = k.GetProdcuts();
dlProducts.DataBind();
}

Related

Dynamics AX - Adding tables to DatabaseLog programatically in AX 2009

I'm looking for a way to enable logging changes for certain tables.
I have tried and tested adding tables to database log programatically, but with various success so far - sometimes it works sometimes it doesn't (mostly it does not) - it seems simply inserting rows into DatabaseLog table doesn't quite do the trick.
What I have tried:
Adding row with proper tableId, fieldId, logType and . Domain had been assigned as 'Admin', main company, empty field and subcompanies with the same result.
I have created class that handles inserts, main two functions are:
public static void InsertBase(STR tableName, domainId _domain='Admin')
{
//base logging for insert, delete, uptade on fieldid=0
DatabaseLog DBDict;
TableId _tableId;
DatabaseLogType _logType;
fieldId _fieldId =0;
List logTypes;
int i;
ListEnumerator enumerator;
;
_tableId= tableName2id(tableName);
logTypes = new List(Types::Enum);
logTypes.addEnd(DatabaseLogType::Insert);
logTypes.addEnd(DatabaseLogType::Update);
logTypes.addEnd(DatabaseLogType::Delete);
logTypes.addEnd(DatabaseLogType::EventInsert);
logTypes.addEnd(DatabaseLogType::EventUpdate);
logTypes.addEnd(DatabaseLogType::EventDelete);
enumerator = logTypes.getEnumerator();
while(enumerator.moveNext())
{
_logType = enumerator.current();
select * from dbdict where
dbdict.logTable==_tableId && dbdict.logField==_fieldId
&& dbdict.logType==_logType;
if(!dbDict) //that means it doesnt exist
{
dbdict.logTable=_tableId;
dbdict.logField=_fieldId;
dbdict.logType=_logType;
dbdict.domainId=_domain;
dbdict.insert();
}
}
info("Success");
}
and the method that lists every single field and adds as logType::Update
public static void init(str TableName, DomainId domain='Admin')
{
DatabaseLogType logtype;
int i;
container kk, ll;
DatabaseLog dblog;
tableid _tableId;
fieldid _fieldid;
;
logtype = DatabaseLogType::Update;
//holds a container of not yet added table fields to databaselog
kk = BLX_AddTableToDatabaseLog::buildFieldList(logtype,TableName);
for(i=1; i <= conlen(kk);i++)
{
ll = conpeek(kk,i);
_tableid = tableName2id(tableName);
_fieldid = conpeek(ll,1);
info(strfmt("%1 %2", conpeek(ll,1),conpeek(ll,2)));
dblog.logType=logType;
dblog.logTable = _tableId;
dblog.domainId = domain;
dblog.logField =_fieldid;
dblog.insert();
}
}
result:
What am I missing ?
#EDIT with some additional info
Does not work for SalesTable and SalesLine, WMSBillOfLading.
I couldn't add log for SalesTable and SalesLine by using wizard in administration panel, but my colleague somehow did (she has done exactly the same things as me). We also tried to add log to various other tables and we often found out that she could while I could not and vice versa (and sometimes none managed to do it like in case of WMSBillOfLading table).
The inconsistency of this mechanism is what drove me to write this code, which I hoped would solve all the problems.
After doing your setup changes you probably have to call
SysFlushDatabaseLogSetup::main();
in order to flush any caches.
This method is also called in the standard AX code in the form method SysDatabaseLogTableSetup\Methods\close and in the class method SysDatabaseLogWizard\doRun.

Why showing it is null parameter?

I have wrote this code to see details in details view with petapoco. but it is not showing any data and it also showing null parameter. I have added and details view page.. here my database name FCBook and table is RMReceive and primary key is RrId.. please help to run this code successfully...
public ActionResult Details(int id)
{
var db = new PetaPoco.Database("FCBook");
var rmr = db.Single<RMReceive>("select * from RMReceive where RrId= #0",id);
return View(rmr);
}
You are using an expression here, your query probably won't work with raw SQL, try
var rmr = db.Single<RMReceive>(x => x.RrId == id);

Asp.net add multiply rows to CRM 2011 (2+ clients/User)

I've extended the customer portal from MS for 2011 with functionality to add an order.
Now i came across a problem when 2 or more user try to create an order at the same time.
first I created the SalesOrder with:
order = new SalesOrder();
order.SalesOrderId = OrderID;
order.Name = string.Format("Order {0}", DateTime.Now);
order.CustomerId = parentCustomer;
order.PriceLevelId = priceLevel.ToEntityReference();
OrderID = XrmContext.Create(order);
and after this i added products(SalesOrderDetail) with a foreach:
foreach (var product in OrdredProducts)
{
productToAdd = new SalesOrderDetail
{
SalesOrderId = new CrmEntityReference(SalesOrder.EntityLogicalName,
OrderID),
ProductId = new EntityReference(Product.EntityLogicalName,
product.ProductID),
Quantity = product.Quantity
};
XrmContext.Create(productToAdd);
}
this works fine when just one user orders something. But if 2+ users I get error for both user.
so I changed the code to this:
order = new SalesOrder();
OrderID = Guid.NewGuid();
order.SalesOrderId = OrderID;
order.Name = string.Format("Order {0}", DateTime.Now); //:d
order.CustomerId = parentCustomer;
order.PriceLevelId = priceLevel.ToEntityReference();
XrmContext.AddObject(order);
foreach (var product in OrdredProducts)
{
productToAdd = new SalesOrderDetail
{
SalesOrderId = new CrmEntityReference(SalesOrder.EntityLogicalName,
OrderID),
ProductId = new EntityReference(Product.EntityLogicalName,
product.ProductID),
Quantity = product.Quantity
};
XrmContext.AddObject(productToAdd);
}
XrmContext.SaveChanges();
Now if 2+ Users orders something, just one User fails not both like the first try.
the Errors I've got as far(every time an other one):
ValidateOpen - Encountered disposed CrmDbConnection when it should not be disposed
SQL timeout expired.
An unexpected error occurred.
Error retrieving next number (currentordernumber) for organization {guid): return value is empty
System.InvalidOperationException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #F60BF6A2
does anyone have some suggestion where the problem could be? is it the SQL Server/CRM Server/IIS/my code or something different?
Additional Information
SQL Server and CRM Server are not on same machine
I get the same error when i test in VS2012 server(back-end is the same SQL/CRM server)
i get the same error when one user runs over IIS and one over VS2012(debugg)
edit
XrmContext is a XrmServiceContext type and this is derived from CrmOrganizationServiceContext and this one is generated with the crmsvcutil
if someone gets the same problem i solved it following:
first i created the SalesOrder and added it to the CRM:
public void AddToCrm(Entity entity)
{
XrmContext.AddObject(entity);
}
then I created all Orders(SalesOrderDetail) and added them to the CRM(same function as above).
And finally i saved it:
public void SaveToCrm()
{
XrmContext.SaveChanges();
}
this behaviour is like a transaction in the database.
so all other Order have to wait till this one is done.

Retrieve data tables from database with stored procedure

Let me explain you in details the scenario that I am having and the solution I am looking for.
Firstfully, I created a stored procedure that outputs simple things such as 2 tables and a message 'don't stop here'"
T-SQL:
USE [mydb]
GO
/****** Object: StoredProcedure [dbo].[BackupDatabase] Script Date: 2/26/2013 11:29:10 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [dbo].[testing]
AS
BEGIN
select 'A' firstname, 'B' lastname;
print 'dont stop here'
select 1 final
END
Up until now I used to retriew the tables in a single manner by using datarowcollection class, and my static method looked like this:
C#:
public static class DataMan
{
public static DataRowCollection SelectData(string sql)
{
SqlDataSource DS = new SqlDataSource(CS, sql);
return ((DataView)DS.Select(DataSourceSelectArguments.Empty)).ToTable().Rows;
}
public static string CS = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
}
where I can easily get what i needed like here, and locate what evver row I wanted:
DataRowCollection people = Util.SelectData("Select * from students")
But now I am planning to create a stored procedure Like I mentioned above and do somthing like this, for instance:
**DataTableCollection** people = Util.SelectData("exec dbo.Testing")
UPDATE:
so I can locate the specific table from my storedprocedure.
I have tried to use DataTable, DataSet, DataTableCollections but no success.I can't use them in proper way.
Please help me
Thank You
Although it can be used in code-behind as you're illustrating here, the SqlDataSource is more typically used in a declarative manner on an ASP.NET markup page. However, given what you've started, when calling a stored procedure, you should set the SqlCommandType to StoredProcedure, supply the name of the procedure to SelectCommand, and return a DataReader. The DataReader, in turn, supports a NextResult() method that you can call to retrieve each discrete result set your procedure provides. Here is a framework of pseudo code that tries to illustrate how you might leverage this:
// pseudo code
void stub()
{
SqlDataSource d = new SqlDataSource(*connection string*);
d.DataSourceMode = SqlDataSourceMode.DataReader;
d.SelectCommandType = SqlDataSourceCommandType.StoredProcedure;
d.SelectCommand = "dbo.Testing";
// set some parameters
d.SelectParameters.Add("Parameter1Name","Parameter1Value"); // must be tailored to your proc!!
d.SelectParameters.Add("Parameter2Name","Parameter2Value"); // must be tailored to SqlDataReader r = (SqlDataReader) d.Select();
while (r.HasRows)
{
while (r.Read())
{
// do something with each row
}
// advance to next result set
r.NextResult();
}
r.Close();
}

Returning a column from a linked table in LINQ to SQL

My problem is that I am trying to return a simple query that contains an object Story. The Story object has a UserId in the table which links to aspnet_users' UserId column. I have created a partial class for Story that adds the UserName property since it does not exist in the table itself.
The following query gets all stories; however, a pagination helper takes the query and returns only what's necessary once this is passed back to the controller.
public IQueryable<Story> FindAllStories(){
var stories = (from s in db.Stories
orderby s.DateEntered descending
select new Story
{
Title = s.Title,
StoryContent = s.StoryContent,
DateEntered = s.DateEntered,
DateUpdated = s.DateUpdated,
UserName = s.aspnet_User.UserName
}
);
return stories;
}
When the helper does a .count() on the source it bombs with the following exception:
"Explicit construction of entity type 'MyWebsite.Models.Story' in query is not allowed."
Any ideas? It's not a problem with the helper because I had this working when I simply had the UserName inside the Story table. And on a side note - any book recommendations for getting up to speed on LINQ to SQL? It's really kicking my butt. Thanks.
The problem is precisely what it tells you: you're not allowed to use new Story as the result of your query. Use an anonymous type instead (by omitting Story after new). If you still want Story, you can remap it later in LINQ to Objects:
var stories = from s in db.Stories
orderby s.DateEntered descending
select new
{
Title = s.Title,
StoryContent = s.StoryContent,
DateEntered = s.DateEntered,
DateUpdated = s.DateUpdated,
UserName = s.aspnet_User.UserName
};
stories = from s in stories.AsEnumerable() // L2O
select new Story
{
Title = s.Title,
StoryContent = s.StoryContent,
...
};
If you really need to return an IQueryable from your method and still need the Username of the user you can use DataContext.LoadOptions to eagerload your aspnet_user objects.
See this example.

Resources