Delete User In MemberShip System - asp.net-membership

I use three table for a section of my program :
1- aspnet_membership (Fields of table are in asp.net membership )
2-aspnet_user (Fields of table are in asp.net membership )
3-TBL_INFO (Filds : INFO_ID,INFO_USERNAME,INFO_ADDRESS,INFO_TELL)
So,When I want show the required field in Gridview , everything is ok and I don't have any problem .
Store Procedure for SELECT :
CREATE PROCEDURE STR_SELECT_USERS_ADMIN
AS
SELECT aspnet_Users.UserId, aspnet_Users.UserName, aspnet_Membership.CreateDate, TB_INFO.INFO_ADDRESS, TB_INFO.INFO_TELL, aspnet_Membership.Email,
aspnet_Membership.LastLoginDate
FROM aspnet_Membership INNER JOIN
aspnet_Users ON aspnet_Membership.UserId = aspnet_Users.UserId INNER JOIN
TB_INFO ON aspnet_Users.UserName = TB_INFO.INFO_USERNAME
But when i decide to delete a user , I can't :
Stored Procedure for Delete :
ALTER PROCEDURE STR_DELETE_USER
(
#UserId UNIQUEIDENTIFIER
)
AS
DELETE FROM aspnet_Users
WHERE (UserId = #UserId)
and my code in Program for delete in GridView is as Below :
protected void GridView1_SelectedIndexChanged1(object sender, EventArgs e)
{
string strUserName = GridView1.Rows[GridView1.SelectedIndex].Cells[0].Text;
if (Membership.DeleteUser(strUserName, true) == true)
{
//GridView1.DataBind();
lblResult.Text = "Delete Successfully";
}
else
{
lblResult.Text = "Delete Faild";
}
GridView1.DataBind();
}
and The error when i'm going delete a record create as below :
Server Error in '/' Application.
--------------------------------------------------------------------------------
The parameter 'username' must not be empty.
Parameter name: username
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: The parameter 'username' must not be empty.
Parameter name: username
Source Error:
Line 26: string strUserName = GridView1.Rows[GridView1.SelectedIndex].Cells[0].Text;
Line 27:
Line 28: if (Membership.DeleteUser(strUserName, true) == true)
Line 29: {
Line 30: //GridView1.DataBind();
Thank You For Your Time. Thank You So Much

Related

Problem in updating a data column in spring

I have a Database table called ProgramData. their i have a data column called Id and executed. id set to be as auto increment.
Table structure is like this.
What i want is according to id executed column need to be updated. following is my code segment.
public void saveDtvProgDataExecuted()
{
ProgramData programeData = new ProgramData();
String SQL = "UPDATE program_data SET executed=1 WHERE programeData.id = ?";
this.jdbcTemplate.update(SQL);
}
If i run this code this gives me error like bad SQL grammar [UPDATE program_data SET executed=1 WHERE programeData.id = ?]; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '?' at line 1
Problem is you’re not passing the ID value to the jdbctemplate.
You should use
this.jdbctemplate.update(SQL, id);
Where id is the id of the record you’re updating.
Please refer to the documentation for more information:
http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#jdbc-updates
TRY THIS statement while you are passing ? in your sql query it need to be set while execution.
String SQL = "UPDATE program_data SET executed=1 WHERE programeData.id = ?";
this.jdbcTemplate.update(SQL,new PreparedStatementCallback<Boolean>(){
#Override
public Boolean doInPreparedStatement(PreparedStatement ps)
throws SQLException, DataAccessException {
ps.setInt(1,"here you need to pass value of programeData.id);
return ps.execute();
}
});

Associate user when created with an existing Account

I have a code that checks an inquery database a for user,
If the user does not exist, then the code will create a new user in Contact,
Here is only part of the code:
newcontact = [SELECT Id, FirstName FROM Contact WHERE Contact.Email =inquery.email__c];
if(newcontact.size() == 0) {
Account[] aa = [SELECT Id FROM Account WHERE Name = :inquery.Institution__c];
contact = new Contact();
contact.FirstName = inquery.First_Name__c;
contact.LastName = inquery.Last_Name__c;
contact.Email = inquery.email__c;
contact.AccountId = aa.Id;
try {
insert contact; // inserts the new record into the database
} catch (DMLException e) {
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error creating new contact'));
return null;
}
I am trying to associate that user with an existing Account?
But the following line gives me an error:
contact.AccountId = aa.Id;
Which is
Initial term of field expression must be a concrete SObject: LIST<Account> at line
And aa.size() returns 1, as it should,
Because the account exists,
Can someone please tell me what wrong?
Thanks
This line contact.AccountId = aa.get(0).Id; will fail if your query returns 0 rows. Make sure to wrap your code within a if (aa.size() > 0) clause to ensure proper execution in all cases.
Ok I fixed it, as follows:
contact.AccountId = aa.get(0).Id;
Best

An object with the same key already exists in the ObjectStateManage

I have a repository model method:-
public void InsertOrUpdateServer(TMSServer server, string username,long assetid)
{
var resource = GetResourceDetials(assetid);
if (server.ServerID == default(int))
{
//code goes here>>>>>>>>.......>>>
}
else
{
// Existing entity
var auditinfo = IntiateAudit(
tms.AuditActions.SingleOrDefault(
a => a.Name.ToUpper() == "EDIT").ActionID,
tms.TechnologyTypes.SingleOrDefault(
a => a.Name.ToUpper() == "Server").AssetTypeID,
username, server.ServerID
);
server.IT360SiteID = resource.SITEID.Value;
tms.Entry(server).State = EntityState.Modified; // this will raise the esception
InsertOrUpdateAudit(auditinfo);
}
}
but when this method is call i will get the folloiwng exception on :-
tms.Entry(server).State = EntityState.Modified;
An object with the same key already exists in the ObjectStateManager.
The ObjectStateManager cannot track multiple objects with the same
key. Description: An unhandled exception occurred during the
execution of the current web request. Please review the stack trace
for more information about the error and where it originated in the
code.
Exception Details: System.InvalidOperationException: An object with
the same key already exists in the ObjectStateManager. The
ObjectStateManager cannot track multiple objects with the same key.
Source Error: Line 1046: username, server.ServerID);
Line 1047: server.IT360SiteID =
resource.SITEID.Value;///// Line 1048:
tms.Entry(server).State = EntityState.Modified; Line 1049:
// tms.Entry(technologyIP).State = EntityState.Modified; Line 1050:
InsertOrUpdateAudit(auditinfo);
So i can not figure out what is causing this isssue , since i am only tracking one object named servev ?? can anyone advice on what is going on ?

Entity Framework and Oracle Client - Issue with stored procedure

I am using Entity Framework with Oracle in a project and trying to call a stored procedure from EF. The procedure goes as
Create or Replace Procedure usp_RotaPlateProductie_Select(
p_afdelingId in varchar2,
p_productTypeId in varchar2,
p_productieData out sys_refcursor)
IS
Begin
Open p_productieData for
Select rp.Batchnummer, cppo.Productnummer, p.Omschrijving, pra.Bruto_In_Meters
From Rotaplateproductie rp inner join Productieresultaatrtplrol pra
on rp.Batchnummer = pra.Batchnummer inner join Cpiplusproductieorder cppo
on pra.ProductieNummer = cppo.ProductNummer inner join Product p
on cppo.Productnummer = p.Productnummer Where rp.Afdelingid = p_afdelingId
and rp.producttype = p_productTypeId;
END;
But when EF executes the function I am getting the error below
ORA-06550: line 1, column 8:
PLS-00306: wrong number or types of arguments in call to 'USP_ROTAPLATEPRODUCTIE_SELECT.
ORA-06550: line 1, column 8:
PL / SQL: Statement IGNORED.
I am calling this procedure using the below code
public ObjectResult<RotaPlateProductie> Search_RotaPlateProductie(global::System.String p_AFDELINGID, global::System.String p_PRODUCTTYPEID)
{
ObjectParameter p_AFDELINGIDParameter;
if (p_AFDELINGID != null)
{
p_AFDELINGIDParameter = new ObjectParameter("P_AFDELINGID", p_AFDELINGID);
}
else
{
p_AFDELINGIDParameter = new ObjectParameter("P_AFDELINGID", typeof(global::System.String));
}
ObjectParameter p_PRODUCTTYPEIDParameter;
if (p_PRODUCTTYPEID != null)
{
p_PRODUCTTYPEIDParameter = new ObjectParameter("P_PRODUCTTYPEID", p_PRODUCTTYPEID);
}
else
{
p_PRODUCTTYPEIDParameter = new ObjectParameter("P_PRODUCTTYPEID", typeof(global::System.String));
}
return base.ExecuteFunction<RotaPlateProductie>("Search_RotaPlateProductie", p_AFDELINGIDParameter, p_PRODUCTTYPEIDParameter);
}
Here RotaPlateProductie is the entity from which I am binding the result set
Please help.
You must add configuration;iIn your case should be as follows:
<oracle.dataaccess.client
<settings>
<add name="rp.usp_RotaPlateProductie_Select.RefCursor.p_productieData" value="implicitRefCursor bindinfo='mode=Output'" />...
<settings>
</oracle.dataaccess.client

Explicit construction of entity type in query is not allowed [duplicate]

Using Linq commands and Linq To SQL datacontext, Im trying to instance an Entity called "Produccion" from my datacontext in this way:
Demo.View.Data.PRODUCCION pocoProduccion =
(
from m in db.MEDICOXPROMOTORs
join a in db.ATENCIONs on m.cmp equals a.cmp
join e in db.EXAMENXATENCIONs on a.numeroatencion equals e.numeroatencion
join c in db.CITAs on e.numerocita equals c.numerocita
where e.codigo == codigoExamenxAtencion
select new Demo.View.Data.PRODUCCION
{
cmp = a.cmp,
bonificacion = comi,
valorventa = precioEstudio,
codigoestudio = lblCodigoEstudio.Content.ToString(),
codigopaciente = Convert.ToInt32(lblCodigoPaciente.Content.ToString()),
codigoproduccion = Convert.ToInt32(lblNroInforme.Content.ToString()),
codigopromotor = m.codigopromotor,
fecha = Convert.ToDateTime(DateTime.Today.ToShortDateString()),
numeroinforme = Convert.ToInt32(lblNroInforme.Content.ToString()),
revisado = false,
codigozona = (c.codigozona.Value == null ? Convert.ToInt32(c.codigozona) : 0),
codigoclinica = Convert.ToInt32(c.codigoclinica),
codigoclase = e.codigoclase,
}
).FirstOrDefault();
While executing the above code, I'm getting the following error that the stack trace is included:
System.NotSupportedException was caught
Message="The explicit construction of the entity type 'Demo.View.Data.PRODUCCION' in a query is not allowed."
Source="System.Data.Linq"
StackTrace:
en System.Data.Linq.SqlClient.QueryConverter.VisitMemberInit(MemberInitExpression init)
en System.Data.Linq.SqlClient.QueryConverter.VisitInner(Expression node)
en System.Data.Linq.SqlClient.QueryConverter.Visit(Expression node)
en System.Data.Linq.SqlClient.QueryConverter.VisitSelect(Expression sequence, LambdaExpression selector)
en System.Data.Linq.SqlClient.QueryConverter.VisitSequenceOperatorCall(MethodCallExpression mc)
en System.Data.Linq.SqlClient.QueryConverter.VisitMethodCall(MethodCallExpression mc)
en System.Data.Linq.SqlClient.QueryConverter.VisitInner(Expression node)
en System.Data.Linq.SqlClient.QueryConverter.Visit(Expression node)
en System.Data.Linq.SqlClient.QueryConverter.VisitFirst(Expression sequence, LambdaExpression lambda, Boolean isFirst)
en System.Data.Linq.SqlClient.QueryConverter.VisitSequenceOperatorCall(MethodCallExpression mc)
en System.Data.Linq.SqlClient.QueryConverter.VisitMethodCall(MethodCallExpression mc)
en System.Data.Linq.SqlClient.QueryConverter.VisitInner(Expression node)
en System.Data.Linq.SqlClient.QueryConverter.ConvertOuter(Expression node)
en System.Data.Linq.SqlClient.SqlProvider.BuildQuery(Expression query, SqlNodeAnnotations annotations)
en System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query)
en System.Data.Linq.DataQuery`1.System.Linq.IQueryProvider.Execute[S](Expression expression)
en System.Linq.Queryable.FirstOrDefault[TSource](IQueryable`1 source)
en Demo.View.InformeMedico.realizarProduccionInforme(Int32 codigoExamenxAtencion, Double precioEstudio, Int32 comi) en D:\cs_InformeMedico\app\InformeMedico.xaml.cs:línea 602
en Demo.View.InformeMedico.UpdateEstadoEstudio(Int32 codigo, Char state) en D:\cs_InformeMedico\app\InformeMedico.xaml.cs:línea 591
en Demo.View.InformeMedico.btnGuardar_Click(Object sender, RoutedEventArgs e) en D:\cs_InformeMedico\app\InformeMedico.xaml.cs:línea 683
InnerException:
Is that now allowed in LINQ2SQL?
Entities can be created outside of queries and inserted into the data store using a DataContext. You can then retrieve them using queries. However, you can't create entities as part of a query.
I am finding this limitation to be very annoying, and going against the common trend of not using SELECT * in queries.
Still with c# anonymous types there is a workaround, by fetching the objects into an anonymous type, and then copy it over into the correct type.
For example:
var q = from emp in employees where emp.ID !=0
select new {Name = emp.First + " " + emp.Last, EmployeeId = emp.ID }
var r = q.ToList();
List<User> users = new List<User>(r.Select(new User
{
Name = r.Name,
EmployeeId = r.EmployeeId
}));
And in the case when we deal with a single value (as in the situation described in the question) it is even easier, and we just need to copy directly the values:
var q = from emp in employees where emp.ID !=0
select new { Name = emp.First + " " + emp.Last, EmployeeId = emp.ID }
var r = q.FirstOrDefault();
User user = new User { Name = r.Name, EmployeeId = r.ID };
If the name of the properties match the database columns we can do it even simpler in the query, by doing select
var q = from emp in employees where emp.ID !=0
select new { emp.First, emp.Last, emp.ID }
One might go ahead and write a lambda expression that can copy automatically based on the property name, without needing to specify the values explictly.
Here's another workaround:
Make a class that derives from your LINQ to SQL class. I'm assuming that the L2S class that you want to return is Order:
internal class OrderView : Order { }
Now write the query this way:
var query = from o in db.Order
select new OrderView // instead of Order
{
OrderID = o.OrderID,
OrderDate = o.OrderDate,
// etc.
};
Cast the result back into Order, like this:
return query.Cast<Order>().ToList(); // or .FirstOrDefault()
(or use something more sensible, like BLToolkit / LINQ to DB)
Note: I haven't tested to see if tracking works or not; it works to retrieve data, which is what I needed.
I have found that if you do a .ToList() on the query before trying to contruct new objects it works
I just ran into the same issue.
I found a very easy solution.
var a = att as Attachment;
Func<Culture, AttachmentCulture> make =
c => new AttachmentCulture { Culture = c };
var culs = from c in dc.Cultures
let ac = c.AttachmentCultures.SingleOrDefault(
x => x.Attachment == a)
select ac == null ? make(c) : ac;
return culs;
I construct an anonymous type, use IEnumerable (which preserves deferred execution), and then re-consruct the datacontext object. Both Employee and Manager are datacontext objects:
var q = dc.Employees.Where(p => p.IsManager == 1)
.Select(p => new { Id = p.Id, Name = p.Name })
.AsEnumerable()
.Select(item => new Manager() { Id = item.Id, Name = item.Name });
Within the book "70-515 Web Applications Development with Microsoft .NET Framework 4 - Self paced training kit", page 638 has the following example to output results to a strongly typed object:
IEnumerable<User> users = from emp in employees where emp.ID !=0
select new User
{
Name = emp.First + " " + emp.Last,
EmployeeId = emp.ID
}
Mark Pecks advice appears to contradict this book - however, for me this example still displays the above error as well, leaving me somewhat confused. Is this linked to version differences? Any suggestions welcome.
I found another workaround for the problem that even lets you retain your result as IQueryale, so it doesn't actually execute the query until you want it to be executed (like it would with the ToList() method).
So linq doesn't allow you to create an entity as a part of query? You can shift that task to the database itself and create a function that will grab the data you want. After you import the function to your data context, you just need to set the result type to the one you want.
I found out about this when I had to write a piece of code that would produce a IQueryable<T> in which the items don't actually exist in the table containing T.
pbz posted a work around by creating a View class inherited from an entity class that you could be working with. I'm working with a dbml model of a table that has > 200 columns. When I try and return the whole table I get "Root Element missing" errors. I couldn't find anyone who wanted to deal with my particular issue so I was looking at rewriting my entire approach. Just creating a view class for the entitiy class worked in my case.
As pbz suggests : Create a view class that inherits from your entity class. For me this is tbCamp so :
internal class tbCampView : tbCamp
{
}
Then use the view class in your query :
using (var dc = ConnectionClass.Connect(Dev))
{
var camps = dc.tbCamps.Select(s => new tbCampView
{
active = s.active,
idCamp = s.idCamp,
campName = s.campName
});
SmartTableViewer(camps, dg1);
}
private void SmartTableViewer<T>(IEnumerable<T> allRecords)
{
// Build sorted rows back into new table
var table = new DataTable();
// Create columns based on type
if (allRecords is IEnumerable<tbCamp> tbCampRecords)
{
// Get the columns you want
table.Columns.Add("idCamp");
table.Columns.Add("campName");
foreach (var record in tbCampRecords)
{
// Make a new row
var r = table.NewRow();
// Add the contents to each column of the row
r["idCamp"] = record.idCamp;
r["campName"] = record.campName;
// Add the row to the table.
table.Rows.Add(r);
}
}
else
{
MessageBox.Show("Unhandled type. Add support for new data type in SmartTableViewer()");
return;
}
// Update table in grid
dg1.DataSource = table.DefaultView;
}
Here is what happens when you try and create an entity class object in the query.
I didn't want to have to use an anonymous type if I could help it because I wanted the type to be tbCamp. Since tbCampView is of type tbCamp the is operator works well. see Brian Hasden's answer Passing a generic List<> in C#
I'm surprised this is even an issue but with larger tables I run into this error so I thought I would just show it here :
When trying to read this table into memory I get the following error. There are < 2000 rows but the columns are > 200 for each. I don't know if that is an issue or not.
If I just want a few columns I need to create a custom class and handle that which isn't that big of a pain. With the approach pbz provided I don't have to worry about it.
Here is the entire project in case it helps someone.
public partial class Form1 : Form
{
private const bool Dev = true;
public Form1()
{
InitializeComponent();
}
private void btnGetAllCamps_Click(object sender, EventArgs e)
{
using (var dc = ConnectionClass.Connect(Dev))
{
IQueryable<tbCampView> camps = dc.tbCamps.Select(s => new tbCampView
{
// Project columns as needed.
active = s.active,
idCamp = s.idCamp,
campName = s.campName
});
// pass in as a
SmartTableViewer(camps);
}
}
private void SmartTableViewer<T>(IEnumerable<T> allRecords)
{
// Build sorted rows back into new table
var table = new DataTable();
// Create columns based on type
if (allRecords is IEnumerable<tbCamp> tbCampRecords)
{
// Get the columns you want
table.Columns.Add("idCamp");
table.Columns.Add("campName");
foreach (var record in tbCampRecords)
{
//var newRecord = record;
// Make a new row
var r = table.NewRow();
// Add the contents to each column of the row
r["idCamp"] = record.idCamp;
r["campName"] = record.campName;
// Add the row to the table.
table.Rows.Add(r);
}
}
else
{
MessageBox.Show("Unhandled type. Add support for new data type in SmartTableViewer()");
return;
}
// Update table in grid
dg1.DataSource = table.DefaultView;
}
internal class tbCampView : tbCamp
{
}
}

Resources