How to add a module on my page in DNN programatically - c#

So far, I have tried below code to add a module through code on my page in DNN.
protected void Page_Load(object sender, EventArgs e)
{
ModuleController MC = new ModuleController();
ModuleInfo MInfo = new ModuleInfo();
MInfo = MC.GetModule(507, 116,false);//Just Hard coded for testing
MInfo.TabID = PortalSettings.ActiveTab.TabID;
MInfo.PaneName = "ContentPane";
MInfo.Alignment = "left";
MC.AddModule(MInfo);//Line throwing error :-
}
I am trying to add a module which is present on tabid=116 and having moduleId=507 on my current tab or page in pageLoad Event.But the last line throwing a error saying
"Violation of UNIQUE KEY constraint 'IX_TabModules_UniqueId'. Cannot insert duplicate key in object 'dbo.TabModules'. The duplicate key value is (555ba77a-be19-40a0-bb72-559672230345)."
Please tell me where i am doing wrong ? and is this the correct way to add a module ?

The first thing that I notice is that you're effectively trying to add the same instance of the module to the database. You've changed the TabID, but otherwise all of the other IDs within the ModuleInfo instance are still there.
Looking at how DNN adds an existing module (look in the DoAddExistingModule method), they start by calling Clone() on the ModuleInfo instance, and then reset the UniqueId (which is the constraint you're hitting):
newModule.UniqueId = Guid.NewGuid();

Related

The settings key with code name 'XX' already exists

I am trying to save a setting in Kentico and I get this error:
The settings key with code name 'AvalaraOrderStatus' already exists.
I already created the setting and I have saved a value to it. The code worked fine in Kentico 8, but I was asked for no SiteInfiIdentifer.
Here is the code I created to make the setting:
//if the setting does not exist, then create it
if (SettingsKeyInfoProvider.GetSettingsKeyInfo(siteName + ".AvalaraOrderStatus", siteID) == null)
{
// Create and set up new SettingsKey
SettingsKeyInfo si = new SettingsKeyInfo();
si.KeyName = "AvalaraOrderStatus";
si.KeyDisplayName = "Avalara Order Status";
si.KeyDescription = "Avalara order status for this site";
si.KeyType = "string";
si.KeyValue = string.Empty;
si.KeyCategoryID = category.CategoryID;
SettingsKeyInfoProvider.SetSettingsKeyInfo(si);
}
The code throws the error on the last line. Here is my code:
int currentSiteID = CMS.SiteProvider.SiteContext.CurrentSiteID;
SiteInfoIdentifier siteId = new SiteInfoIdentifier(currentSiteID);
//update settings in system
SettingsKeyInfoProvider.SetValue(siteName + ".AvalaraOrderStatus", siteId, orderStatus.Trim());
A few things to note:
The first parameter of the SettingsKeyInfoProvider.GetSettingsKeyInfo method does not need to be prefixed with the site name. This is why a site identifier is provided (in your case, the SiteID). Otherwise, you might be getting a null value every time the if statement evaluates, which is why the setting key is being recreated even if it exists. So that should be:
SettingsKeyInfoProvider.GetSettingsKeyInfo("AvalaraOrderStatus", siteID)
The same applies for the SettingsKeyInfoProvider.SetValue method - no need to prefix the site name:
SettingsKeyInfoProvider.SetValue("AvalaraOrderStatus", siteId, orderStatus.Trim())
The CurrentSiteID integer is a valid SiteIdentifier, so there is no need to explicitly instantiate a SiteInfoIdentifier object:
SettingsKeyInfoProvider.SetValue("AlavaraOrderStatus", CMS.SiteProvider.SiteContext.CurrentSiteID, orderStatus.Trim())

C# Session doesn't exist in current content

I want to save the userid in the session to use in the application. I gave the following code.
But getting compilation error saying The name Session doesn't exist in the current context. is there any library that I need to use?. Please advise.
private void button1_Click(object sender, EventArgs e)
{
Session["Username"] = user.Text;
}
if it is a web application it should have worked.
anyways try adding
HttpContext.Current.Session["Username"] = user.Text;
I went ahead and solved this for myself, was having the same problem until I read the MS documentation: https://msdn.microsoft.com/en-us/library/system.web.httpcontext.session%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396. Basically, outside of the WebForms class, you need to grab a reference to the context. Example follows for getting and setting the sessionStorage.
using System.Web;
HttpContext context = HttpContext.Current;
Setting:
context.Session["FirstName"] = firstName;
Getting:
firstName = (string)(context.Session["FirstName"]);

Updating a lookup field from a Silverlight app - CRM 2011

I'm using the following code to try and update a lookup field value in my CRM 2011 system from a silverlight app:
try
{
ma.my_ActionDetails = details;
Guid userId = new Guid();
foreach (SystemUser s in SystemUsers)
{
if (s.FullName.Equals(comboBox1.SelectedItem))
{
userId = s.SystemUserId;
}
}
// Define eval statements for setting lookup to a value and null
string setLookupJscript = #"Xrm.Page.getAttribute(""{0}"").setValue([ {{ id: ""{1:B}"", typename: ""{2}"", name: ""{3}"" }}])";
string evalStatement = null;
// Set the statement to be evaluated based upon the value of the id argument
// Setting the lookup to a value
evalStatement = string.Format(setLookupJscript, "my_salesperson", userId, "my_memberaction", ma.my_SalesPerson.Name);
HtmlPage.Window.Eval(evalStatement);
_context.UpdateObject(ma);
_context.BeginSaveChanges(OnUpdateAccountComplete, ma);
}
catch (SystemException se)
{
_syncContext.Send(new SendOrPostCallback(showErrorDetails), se);
}
However when I run this code it generates the following errors:
In the browser:
'Xrm' is undefined
From the code:
System.InvalidOperationException: [Common_MethodFailed]
Can anyone explain whats going on here?
Thanks,
Jack
You need to be within the context of a CRM form for the Xrm namespace to be available. Are you running from within a form?
From the CRM SDK:
If your Silverlight web resource is designed to be viewed in an entity form, the form has an Xrm.Page.context object you can use to access contextual information.
If you need your Silverlight application to appear outside the context of the form you must configure an HTML web resource to provide this context information by adding a reference to the ClientGlobalContext.js.aspx page. After this reference is added, your Silverlight application can access contextual information in the same way it can in an entity form. The following sample shows how to call the getServerUrl function from the Xrm.Page.context object.
private string serverUrl = "";
ScriptObject xrm = (ScriptObject)HtmlPage.Window.GetProperty("Xrm");
ScriptObject page = (ScriptObject)xrm.GetProperty("Page");
ScriptObject pageContext = (ScriptObject)page.GetProperty("context");
serverUrl = (string)pageContext.Invoke("getServerUrl");

NullReferenceException when deleting a sitecore items children

i'm trying to import some legacy poll data into our sitecore solution. For part of the import, i'm trying to create new sitecore items to hold the data based off of a master page we already have set up for polls. this master has a couple of default items set up underneath of it, and I want to delete a couple of specific default items before I add the legacy poll data. however, when i attempt to delete one of the default items using item.DeleteChildren(), i get a NullReferenceException thrown by Sitecore.Tasks.ItemEventHandler.OnItemDeleted(Object sender, EventArgs args) in the sitecore kernel. if anyone has any idea what could be causing this, i'd appreciate it. we're on sitecore version 5.3.2.
here is the code i'm using to attempt to create/edit the item based off of a master. the creation all works perfectly, it's the DeleteChildren() call that doesn't work.
Guid LegacyPollFolderGuid = new Guid("8AE89A44-9DCD-4AC2-B0F3-DD438188A575");
Guid QuizOMaticMasterGuid = new Guid("74B95ABF-1898-4870-8B4F-50AF0078AE22");
var master = Sitecore.Configuration.Factory.GetDatabase("master");
var root = master.GetItem(new Sitecore.Data.ID(LegacyPollFolderGuid));
var quizMasterTemplate = master.Masters[new Sitecore.Data.ID(QuizOMaticMasterGuid)];
var quizPage = root.Add("Test Quiz", quizMasterTemplate);
if (quizPage != null)
{
var quiz = quizPage.Children["Column One"].Children["QuizOMatic"];
if (quiz != null)
{
var questionFolder = quiz.Children["Questions"];
var questionTemplate = questionFolder.Children[0].Template;
var resultsFolder = quiz.Children["Results"];
var linksFolder = quiz.Children["Links"];
using (new Sitecore.SecurityModel.SecurityDisabler())
{
questionFolder.DeleteChildren();
}
}
I've built a tool with the same functionality; removing all items under a specific folder. I got the same error, but I saw items being deleted. So I reran the tool multiple times and eventually all items were deleted.

could not find new column in aspnet_Membership table

I had added in a new column called "ForgotPasswordDate" into aspnet_Membership table. When a user hit the submit button in the Password Recovery Control, it would store the timing that user hit the button into the "ForgotPasswordDate" column by using the getDate() method.
After which, user would receive an email which contain an URL directing them into ChangePassword.apsx.
I wanted to make the ChangePassword.aspx page expired after 1 day the user had requested for new password. This would be done by using the time in "ForgotPasswordDate" column and using the AddDay() method.
However, the code gave me a problem. Which I think they could not recognize the "ForgotPasswordDate" column inside the Membership table.
This is the code which had an error:
if (DateTime.Now < user.ForgotPasswordDate.AddMinutes(3))
for testing purposes, currently I just set the logic as 3 minutes.
And the error message is:
System.Web.Security.MembershipUser' does not contain a definition for 'ForgotPasswordDate' and no extension method 'ForgotPasswordDate' accepting a first argument of type 'System.Web.Security.MembershipUser' could be found (are you missing a using directive or an assembly reference?
Here is the whole code:
protected void Page_Load(object sender, EventArgs e)
{
//if the id is in the query string
if (!string.IsNullOrEmpty(Request.QueryString["ID"]))
{
//store the user id
Guid userId = new Guid(Request.QueryString["ID"]);
//attempt to get the user's information
MembershipUser user = Membership.GetUser(userId);
if (DateTime.Now < user.ForgotPasswordDate.AddMinutes(3)) //here is the part
{
//Page not expire yet.
hidden.Text = user.ProviderUserKey.ToString();
Server.Transfer("~/ChangePassword.aspx");
}
else
{
//Expired; direct to Page Expired Page
Server.Transfer("~/PageExpired.aspx");
}
}
}
is there anyway that the system could recognize the new column in aspnet_membership table?
I would find out which stored procedure the membership uses, modify and include the new columns. Then you may have to override the current membership class to include the new properties.

Categories