I am using the createUserWizard control to register the users for my website, but I also use my own table to store information (address, image, description, ...) about these users.
When creating a user, I also want to create a new instance in my own table. I want to link my own table to ASP.NET's user table via the userID. I tried grabbing this from the createUserWizard with Membership, but ASP doesn't recognize membership. Am I forgetting to add something?
Here's my code (code behind)
protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
{
try
{
BLLorganisation BLLo = new BLLorganisation();
Organisation o = new Organisation();
TextBox t = new TextBox();
t = (TextBox)(this.CreateUserWizard1.FindControl("UserName"));
o.organisation_name = t.Text;
o.fk_user_id = Membership.GetUser(CreateUserWizard1.UserName).ProviderUserKey.ToString();
BLLo.insertOneOrganisation(o);
}
catch (Exception ex)
{
feedback.InnerHtml = ex.Message;
feedback.Style.Add("display", "block");
}
}
Include using System.Web.Security;
Related
I have an asp.net webforms SaaS application where multiple ecommerce websites are running. Each website has its own domain (abc.com, xyz.com etc.) and each website's content is fetched from the database based on the domain.
Now, in order to improve home page performance I am implementing Output Cache. Please note that the home page already contains multiple user controls (header, footer, top menu, user menu, mini cart, banners, home products etc.). All the user controls are eligible for Output Cache accept user menu (where logged in usernames are displayed, otherwise signup/login links) and mini cart (where no. of cart items are displayed and on click it shows the list of items in cart).
I added Output cache directive on each user control (that I want to be cached) with VaryByCustom to create separate cache for each domain.
<%# OutputCache Duration="300" VaryByParam="*" VaryByCustom="Host" %>
As VaryByHeader is not an available option for UserControls, I added an override function in Global.asax to return current host.
public override string GetVaryByCustomString(HttpContext context, string arg)
{
if (arg == "Host")
{
return context.Request.Url.Host;
}
return String.Empty;
}
Till now, everything is working perfect. User controls are being cached for different domains (hosts) and are being expired on the specified time.
THE PROBLEM: I want to give an option in the admin panel to the website admin users to manually refresh cache of their websites. For that I created a page (refreshcache.aspx) in the frontend application, and simply open that url (for example: abc.com/refreshcache.aspx) when the admin users click the refresh cache button from the admin panel.
I researched a lot and tried multiple approaches to clear user controls cache but failed. The last thing that I implemented is the following code which I added in the home page aspx which creates an object of StaticPartialCachingControl and adds key dependency on user controls cache.
In Home.aspx, I added the following code which is called in Page_Load
protected void LoadControlsCache()
{
CacheKey = "Host-" + Request.Url.Host;
CacheKeyArray[0] = CacheKey;
if (Cache[CacheKey] == null)
{
AddControlCache(header1);
AddControlCache(footer1);
AddControlCache(banner1);
AddControlCache(products1);
}
}
protected void AddControlCache(UserControl uc)
{
StaticPartialCachingControl pcc = (StaticPartialCachingControl)uc.Parent;
pcc.Dependency = new CacheDependency(null, CacheKeyArray);
Cache.Insert(CacheKey, "value", null, DateTime.Now.AddSeconds(300), Cache.NoSlidingExpiration);
}
And to remove the cache for a particular host, I used Cache.Remove method with the host specific key.
In refreshcache.aspx I added the following code
protected void Page_Load(object sender, EventArgs e)
{
Cache.Remove("Host-" + Request.Url.Host);
Response.Redirect("/");
}
I am not sure what I am missing or doing wrong. Just want a way to clear usercontrols cache for a particular host (domain).
Finally got the issue resolved by creating separate keys for all user controls, and adding dependency on user control object.
protected void LoadControlsCache()
{
string CacheKey = Request.Url.Host;
AddControlCache(header1, "header-" + CacheKey);
AddControlCache(footer1, "footer-" + CacheKey);
AddControlCache(banner1, "banner-" + CacheKey);
AddControlCache(products1, "products-" + CacheKey);
}
protected void AddControlCache(UserControl uc, string CacheKey)
{
if (Cache[CacheKey] == null && uc != null)
{
uc.Cache.Insert(CacheKey, 1);
uc.CachePolicy.Dependency = new System.Web.Caching.CacheDependency(null, new string[] { CacheKey });
}
}
Then to clear the cache, used Cache.Remove() with all the usercontrol keys.
protected void Page_Load(object sender, EventArgs e)
{
string CacheKey = Request.Url.Host;
Cache.Remove("header-" + CacheKey);
Cache.Remove("footer-" + CacheKey);
Cache.Remove("banner-" + CacheKey);
Cache.Remove("products-" + CacheKey);
Response.Redirect("/");
}
Hope it might help someone with a similar question!
I am really confused right now. Ive read some solutions to this problem, but every single one is different.... some people say that web applications projects and web site projects need different solutions.
What I have in thoughts:
I have a web application project
I created a table UserProfile in that table where I store additional columns like a link to an image.
My problem right now is that when I call RegisterUser_CreatedUser on submit, I can't find any way to get Guid of the newly created user :
protected void RegisterUser_CreatedUser(object sender, EventArgs e)
{
FormsAuthentication.SetAuthCookie(RegisterUser.UserName, createPersistentCookie: false);
TextBox ImageUrl = RegisterUserWizardStep.ContentTemplateContainer.FindControl("ImageUrl") as TextBox;
UserProfile.SaveNewProfileInformation("place for new created user guid", ImageUrl.Text);
string continueUrl = RegisterUser.ContinueDestinationPageUrl;
if (!OpenAuth.IsLocalUrl(continueUrl))
{
continueUrl = "~/";
}
Response.Redirect(continueUrl);
}
How do I get the guid of new created user? and am i on the right track at all to solve this problem?
You need to get the created user with the UserName
{
FormsAuthentication.SetAuthCookie(RegisterUser.UserName, createPersistentCookie: false);
//If user is created, get it by UserName
MembershipUser createdUser = Membership.GetUser(RegisterUser.UserName);
Guid userID = new Guid(createdUser.ProviderUserKey.ToString());
TextBox ImageUrl = RegisterUserWizardStep.ContentTemplateContainer.FindControl("ImageUrl") as TextBox;
//Use the userID from the above code
UserProfile.SaveNewProfileInformation(userID, ImageUrl.Text);
}
I have a website for dance academy where Users can register and add/drop dance classes.
In the web page to drop a particular dance, for a particular user, the dropdown displays her registered dances.
Now I want to delete one of the dances from the list.
So i'll remove the row from the table and also from the dropdownlist. The problem is that every time the item with the lowest ID (index) is getting deleted, no matter which one the user selects.
I think I am storing the DataTextField and DataValueField for the dropdown incorrectly. Can someone please help me out?
The code is:
private void PopulateDanceDropDown()
{
var registereddanceList = from dd in context.DANCER_AND_DANCE
where dd.UserId == dancerId
select new
{
Text = dd.DanceName,
Value = dd.DanceId
};
dances.DataSource = registereddanceList;
dances.DataTextField = "Text";
dances.DataValueField = "Value";
dances.DataBind();
}
protected void dropthedance(object o, EventArgs e)
{
String strDataValueField = dances.SelectedItem.Value;
int danceIDFromDropDown = Convert.ToInt32(strDataValueField);
var dancer_dance = from dd in context.DANCER_AND_DANCE
where dd.DanceId == danceIDFromDropDown
select dd;
foreach (var dndd in dancer_dance)
{
context.DANCER_AND_DANCE.DeleteOnSubmit(dndd);
}
try
{
context.SubmitChanges();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
PopulateDanceDropDown();
}
<asp:DropDownList ID = "dances" runat="server">
</asp:DropDownList>
<asp:Button ID="dropDance" runat="server" OnClick="dropthedance" Text="Drop Class" BackColor="Maroon" ForeColor="#FFCC99"/>
As your question says you want to access records without storing it in Linq.
So below one could be an alternative for you.
First store all the data from Database to, lets say List<NameIDPair>
Heres what NameIDPair could be:
class NameIDPair
{
public NameIDPair(){}
public string NameValue{get;set;}
public string IDValue{get;set;}
}
Then populate drop down list as follows:
List<NameIDPair> storeInMe = From Database
foreach(NameIDPair pair in storeInMe )
{
ListItem item = new ListItem();
item.Value = pair.IDValue;
item.Text = pair.NameValue;
ddldancesList.Items.Add(item);
}
Then for droppingTheDance, you can call the delete stored procedure to delete the same...
Hope this helps...
i am newbie of c# and win phone 7
i create a simple database i read this example
http://f5debug.net/2012/02/26/learn-windows-phone-7-development-in-31-days-day-26-working-with-creating-a-local-database-in-wp7/
i open Db in Mainpage
public partial class MainPage : PhoneApplicationPage
{
// short connection string format
private const string strConnectionString = #"isostore:/ManutenzioneDB.sdf";
// Costruttore
public MainPage()
{
InitializeComponent();
using (SampleData.EventoDataContext Empdb = new SampleData.EventoDataContext(strConnectionString))
{
// se il db non esiste creo il db
if (Empdb.DatabaseExists() == false)
{
Empdb.CreateDatabase();
// MessageBox.Show("Employee Database Created Successfully!!!");
}
}
now in Main page i create a button than open an other page
private void button1_Click(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/InsertData.xaml", UriKind.Relative));
}
now i don't know can access to Db from InsertData page (InsertData.xaml.cs),
best regads
Antonio
Simpler than you think. :)
var db = new SampleData.EventoDataContext();
db.MyTable.InsertOnSubmit(new MyTable() { ... });
db.Submit();
"MyTable" is the name of the table you defined inside the database.
Make sure you define a primary key, or inserting into the table will fail.
You will need to initialize your table inside the {...} part.
To get items from the table:
foreach (var item in db.MyTable.Where(x => x.SomeProp == 1))
{
//…
}
This will return all the rows where SomeProp is 1. You can now inspect item to see what the row contains.
Try to study the vici cool stored procedure. It is very very simple to create, add, and retrieve data from any db in WP7 applications
http://viciproject.com/wiki/projects/coolstorage/home
Here is the scenario (ADO.NET Entity Framework and C#).
Contact*:
String name;
Address addr;
Address*:
String street;
String city;
**this is not the real code, but you get the picture*
I am trying to create a Windows Form that appears flat to the user. In other words, the Form will have four fields (name,addr,street,city), and when the users clicks on the Add button in a bindingSourceNavigator, I want to create a new instance of Contact such that Contact.addr is a reference to a newly created Address.
If I were only working with objects this would be simple, but I'm trying to create a new row in the table that backs Address.
Here is what I've tried so far:
private void contactBindingSource_AddingNew(object sender, AddingNewEventArgs e)
{
Contact newContact = new Contact();
Address newContactAddr = new Address();
newContact.Address = newContactAddr;
newContactAddr.Contacts.Add(newContact);
//I realize I don't need the Contact list reference in Address,
//but VS2010 created it, so I'm just adding the new Contact to
//the list for now.
e.NewObject = newContact;
}
private void contactBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
contactBindingSource.EndEdit();
context.SaveChanges(); //throws UpdateException
}
Some background: The Form has a binding source for Contact, and this method is the event handler for when new Contacts are created. I read on MSDN that this is how one modifies the object before it is actually added to the BindingSource. context refers to my entity model.
What happens: When I click the add button, I am able to enter in the contact information. But when I click the save button, I get an UpdateException. I suspect this is because I did not create the Address properly, but being new to the ADO.NET framework (and .NET programming in general), I don't really know the correct way to do this.
An example:
I have 3 tables, Users, UserRoles and Roles.
when i create a user i want this user to receive a role and i would then do
using(DatabaseEntities db = new DatabaseEntities())
{
//creates the user and add the properties except roles
Users user = new Users();
user.username = "Test";
//get an existing role
var role = db.Roles.SingleOrDefault(r => r.roleName == "User");
//adds the userid and roleid in to userRoles
user.Roles.Add(role);
db.Users.AddObject(user);
//saves it to the db
db.SaveChanges();
}
so, in order for it to work in your example, you would first need to insert One of them to the db before using it in order to save the other object along with the row to the table that links them together.
I hope this simple example helps you.