Create ProfileProperty Through Code in DNN - dotnetnuke

How to Create Profile Property Through Code in DNN (DotNetNuke)?
I tried this code:
DotNetNuke.Entities.Profile.ProfilePropertyDefinition def =
DotNetNuke.Entities.Profile.ProfileController.GetPropertyDefinitionByName(this.PortalId, "Level");
if (def != null)
{
def.DataType = 10;
def.Length = 40;
def.PropertyValue = "Level";
def.PropertyName = "Level";
oUser.Profile.ProfileProperties.Add(def);
}
oUser.Profile.SetProfileProperty("Level", ddlLevel.SelectedItem.Text.ToString().Trim());
DotNetNuke.Entities.Profile.ProfileController.UpdateUserProfile(oUser, oUser.Profile.ProfileProperties);
But it won't work, please help me with suitable solution.

try out this code for adding Profile Property:
if (DotNetNuke.Entities.Profile.ProfileController.GetPropertyDefinitionByName(this.PortalId, "Level") == null)
{
DotNetNuke.Entities.Profile.ProfileController.AddPropertyDefinition(
new DotNetNuke.Entities.Profile.ProfilePropertyDefinition(this.PortalId)
{
PropertyName = "Name",
DataType = 10,
...
});
}

Related

2 object of same type returns true when != checked

I am using model.GetType().GetProperties() with foreach to compare properties of 2 object of same class.
like this
foreach (var item in kayit.GetType().GetProperties())
{
var g = item.GetValue(plu);
var b = item.GetValue(kayit);
if (g is string && b is string&& g!=b)
{
a += item.Name + "*";
}
else if (g is DateTime&& b is DateTime&& g!=b)
{
a += item.Name + "*";
}
}
But the problem is even if they have the same value g!=b returns a true all the time. I have used a break point to prove this and they are literally same thing. Actually I am taking the value putting it in textbox then creating another class after button click and comaring to see the changed properties. So even if I don't change anything it doesn't read the mas equals. Can someone help me about this please?
more info:
I get the plu from database and populate my control with it:
txtorder.Text = plu.OrderNo;
dtporder.Value = nulldate(plu.OrderDate);
dtp1fit.Value = nulldate(plu.FirstFitDate);
dtp1yorum.Value = nulldate(plu.FirstCritDate);
dtp2fit.Value = nulldate(plu.SecondFitDate);
dtp2yorum.Value = nulldate(plu.SecondCritDate);
dtpsizeset.Value = nulldate(plu.SizeSetDate);
dtpsizesetok.Value = nulldate(plu.SizeSetOkDate);
dtpkumasplan.Value = nulldate(plu.FabricOrderByPlan);
txtTedarikci.Text = plu.Fabric_Supplier;
dtpkumasFP.Value = nulldate(plu.FabricOrderByFD);
dtpfabarrive.Value = nulldate(plu.FabricArrive);
dtpbulk.Value = nulldate(plu.BulkFabricDate);
dtpbulkok.Value = nulldate(plu.BulkConfirmDate);
dtpaccessory.Value = nulldate(plu.AccessoriesDate);
dtpaccessoryarrive.Value = nulldate(plu.AccessoriesArriveDate);
dtpcutok.Value = nulldate(plu.ProductionStartConfirmation);
dtpcutstart.Value = nulldate(plu.ProductionStart);
dtpshipmentdate.Value = nulldate(plu.ShipmentDate);
dtpshipmentsample.Value = nulldate(plu.ShipmentSampleDate);
dtpshippedon.Value = nulldate(plu.Shippedon);
nulldate is just a method where I change null values to my default value.
And this is what I do after button click:
var kayit = new uretim();
kayit.OrderNo = txtorder.Text.ToUpper();
kayit.OrderDate = vdat(dtporder.Value);
kayit.FirstFitDate = vdat(dtp1fit.Value);
kayit.FirstCritDate = vdat(dtp1yorum.Value);
kayit.SecondFitDate = vdat(dtp2fit.Value);
kayit.SecondCritDate = vdat(dtp2yorum.Value);
kayit.SizeSetDate = vdat(dtpsizeset.Value);
kayit.SizeSetOkDate = vdat(dtpsizesetok.Value);
kayit.FabricOrderByPlan = vdat(dtpkumasplan.Value);
kayit.Fabric_Supplier = txtTedarikci.Text;
kayit.FabricOrderByFD = vdat(dtpkumasFP.Value);
kayit.FabricArrive = vdat(dtpfabarrive.Value);
kayit.BulkFabricDate = vdat(dtpbulk.Value);
kayit.BulkConfirmDate = vdat(dtpbulkok.Value);
kayit.AccessoriesDate = vdat(dtpaccessory.Value);
kayit.AccessoriesArriveDate = vdat(dtpaccessoryarrive.Value);
kayit.ProductionStartConfirmation = vdat(dtpcutok.Value);
kayit.ProductionStart = vdat(dtpcutstart.Value);
kayit.ShipmentDate = vdat(dtpshipmentdate.Value);
kayit.ShipmentSampleDate = vdat(dtpshipmentsample.Value);
kayit.Shippedon = vdat(dtpshippedon.Value);
kayit.Status = true;
kayit.WrittenDate = DateTime.Now;
kayit.GuidKey = plu.GuidKey != null ? plu.GuidKey : Guid.NewGuid().ToString("N");
I have proven by breakpoint that values are actually same. But the != check retruns a true.
When you are doing
g != b
compiler doesn't know that these objects are strings to compare so it compares their references. You can do:
g.Equals(b) //be carefull if one of them is null
or
g.ToString() != b.ToString()
EDIT
You can compare them after you check the type:
if (g is string && b is string)
{
if( g.ToString() != b.ToString() ){
}
}

Copy DNN HTML Pro module in content to another module

Below code is working fine for HTML module but not working for HTML PRO module.
HtmlTextController htmlTextController = new HtmlTextController();
WorkflowStateController workflowStateController = new WorkflowStateController();
int workflowId = htmlTextController.GetWorkflow(ModuleId, TabId, PortalId).Value;
List<HtmlTextInfo> htmlContents = htmlTextController.GetAllHtmlText(ModuleModId);
htmlContents = htmlContents.OrderBy(c => c.Version).ToList();
foreach (var content in htmlContents)
{
HtmlTextInfo htmlContent = new HtmlTextInfo();
htmlContent.ItemID = -1;
htmlContent.StateID = workflowStateController.GetFirstWorkflowStateID(workflowId);
htmlContent.WorkflowID = workflowId;
htmlContent.ModuleID = ModuleId;
htmlContent.IsPublished = content.IsPublished;
htmlContent.Approved = content.Approved;
htmlContent.IsActive = content.IsActive;
htmlContent.Content = content.Content;
htmlContent.Summary = content.Summary;
htmlContent.Version = content.Version;
}
htmlTextController.UpdateHtmlText(htmlContent, htmlTextController.GetMaximumVersionHistory(PortalId));
This is occurred due to HTML Pro module has different methods. That is partially different from DNN HTML Module. below is the code.
HtmlTextController htmlTextController = new HtmlTextController();
WorkflowStateController workflowStateController = new WorkflowStateController();
WorkflowStateInfo wsinfo = new WorkflowStateInfo();
int workflowId = wsinfo.WorkflowID;
HtmlTextInfo htmlContents = htmlTextController.GetLatestHTMLContent(ModuleModId);
HtmlTextInfo htmlContent = new HtmlTextInfo();
htmlContent.ItemID = -1;
htmlContent.StateID = workflowStateController.GetFirstWorkflowStateID(workflowId);
htmlContent.WorkflowID = workflowId;
htmlContent.ModuleID = ModuleId;
htmlContent.IsPublished = htmlContents.IsPublished;
htmlContent.Approved = htmlContents.Approved;
htmlContent.IsActive = htmlContents.IsActive;
htmlContent.Content = htmlContents.Content;
htmlContent.Summary = htmlContents.Summary;
htmlContent.Version = htmlContents.Version;
if (Tags != null && Tags.Count > 0)
{
foreach (KeyValuePair<string, string> tag in Tags)
{
if (htmlContent.Content.Contains(tag.Key))
{
htmlContent.Content = htmlContent.Content.Replace(tag.Key, tag.Value);
}
}
}
htmlTextController.SaveHtmlContent(htmlContent, newModule);
And please add below reference to the code to refer the methods.
using DotNetNuke.Modules.HtmlPro;
using DotNetNuke.Professional.HtmlPro;
using DotNetNuke.Professional.HtmlPro.Components;
using DotNetNuke.Professional.HtmlPro.Services;
If you are looking to simply "copy" the content from one to the other, you might investigate the usage of the "Import" and "Export" functions that are part of these modules.
I recommend using this route to help you ensure better compatibility as time progresses. Should they update fields or other data elements you will not have to investigate and then update your code as part of this.
You can simply look at the .dnn manifest for each of these modules and find the BusinessControllerClass which will have two methods "ImportModule" and "ExportModule" that you could use.

Get appointments from all Outlook calendars

I'm trying to read appointments from Outlook calendar using ExchangeServiceBinding but my solution takes appointments only from "default" outlook calendar and don't read from "sub calendars/custom calendars". Do you know how to define rest of the calendars or do you know better solution which contains all calendars?
Critical part is that solution shouldn't contain MAPI because of next use in web service.
My current code:
private static List<List<string>> ReadCalendarEvents(string email)
{
List<List<string>> calendarEvents = new List<List<string>>();
// Specify the request version.
esb.RequestServerVersionValue = new RequestServerVersion();
esb.RequestServerVersionValue.Version = ExchangeVersionType.Exchange2007;
// Form the FindItem request.
FindItemType findItemRequest = new FindItemType();
CalendarViewType calendarView = new CalendarViewType();
calendarView.StartDate = DateTime.Now.AddDays(-7);
calendarView.EndDate = DateTime.Now.AddDays(200);
calendarView.MaxEntriesReturned = 1000;
calendarView.MaxEntriesReturnedSpecified = true;
findItemRequest.Item = calendarView;
// Define which item properties are returned in the response.
ItemResponseShapeType itemProperties = new ItemResponseShapeType();
// Use the Default shape for the response.
//itemProperties.BaseShape = DefaultShapeNamesType.IdOnly;
itemProperties.BaseShape = DefaultShapeNamesType.AllProperties;
findItemRequest.ItemShape = itemProperties;
DistinguishedFolderIdType[] folderIDArray = new DistinguishedFolderIdType[1];
folderIDArray[0] = new DistinguishedFolderIdType();
folderIDArray[0].Id = DistinguishedFolderIdNameType.calendar;
//
folderIDArray[0].Mailbox = new EmailAddressType();
folderIDArray[0].Mailbox.EmailAddress = email;
findItemRequest.ParentFolderIds = folderIDArray;
// Define the traversal type.
findItemRequest.Traversal = ItemQueryTraversalType.Shallow;
try
{
// Send the FindItem request and get the response.
FindItemResponseType findItemResponse = esb.FindItem(findItemRequest);
// Access the response message.
ArrayOfResponseMessagesType responseMessages = findItemResponse.ResponseMessages;
ResponseMessageType[] rmta = responseMessages.Items;
int folderNumber = 0;
foreach (ResponseMessageType rmt in rmta)
{
// One FindItemResponseMessageType per folder searched.
FindItemResponseMessageType firmt = rmt as FindItemResponseMessageType;
if (firmt.RootFolder == null)
continue;
FindItemParentType fipt = firmt.RootFolder;
object obj = fipt.Item;
// FindItem contains an array of items.
if (obj is ArrayOfRealItemsType)
{
ArrayOfRealItemsType items =
(obj as ArrayOfRealItemsType);
if (items.Items == null)
{
folderNumber++;
}
else
{
foreach (ItemType it in items.Items)
{
if (it is CalendarItemType)
{
CalendarItemType cal = (CalendarItemType)it;
List<string> ce = new List<string>();
ce.Add(cal.Location);
ce.Add(cal.Start.ToShortDateString() + " " + cal.Start.ToShortTimeString());
ce.Add(cal.End.ToShortDateString() + " " + cal.End.ToShortTimeString());
ce.Add(cal.Subject);
if (cal.Organizer != null)
{
ce.Add(cal.Organizer.Item.Name);
}
calendarEvents.Add(ce);
Console.WriteLine(cal.Subject + " " + cal.Start.ToShortDateString() + " " + cal.Start.ToShortTimeString() + " " + cal.Location);
}
}
folderNumber++;
}
}
}
}
catch (Exception e)
{
throw;
}
finally
{
}
return calendarEvents;
}
In EWS you need to query one folder at a time, for non default folders you will first need to find the FolderId before you can then query the appointments (or items) within a Folder. To find all the Calendar folders in a Mailbox you need to use the FindFolder operation and create a restriction to limit the result to folder with a FolderClass of IPF.Appointment eg
// Create the request and specify the travesal type.
FindFolderType findFolderRequest = new FindFolderType();
findFolderRequest.Traversal = FolderQueryTraversalType.Deep;
// Define the properties that are returned in the response.
FolderResponseShapeType responseShape = new FolderResponseShapeType();
responseShape.BaseShape = DefaultShapeNamesType.Default;
findFolderRequest.FolderShape = responseShape;
// Identify which folders to search.
DistinguishedFolderIdType[] folderIDArray = new DistinguishedFolderIdType[1];
folderIDArray[0] = new DistinguishedFolderIdType();
folderIDArray[0].Id = DistinguishedFolderIdNameType.msgfolderroot;
IsEqualToType iet = new IsEqualToType();
PathToUnindexedFieldType FolderClass = new PathToUnindexedFieldType();
FolderClass.FieldURI = UnindexedFieldURIType.folderFolderClass;
iet.Item = FolderClass;
FieldURIOrConstantType constantType = new FieldURIOrConstantType();
ConstantValueType constantValueType = new ConstantValueType();
constantValueType.Value = "IPF.Appointment";
constantType.Item = constantValueType;
iet.FieldURIOrConstant = constantType;
// Add the folders to search to the request.
RestrictionType restriction = new RestrictionType();
restriction.Item = iet;
findFolderRequest.Restriction = restriction;
findFolderRequest.ParentFolderIds = folderIDArray;
try
{
// Send the request and get the response.
FindFolderResponseType findFolderResponse = esb.FindFolder(findFolderRequest);
// Get the response messages.
ResponseMessageType[] rmta = findFolderResponse.ResponseMessages.Items;
foreach (ResponseMessageType rmt in rmta)
{
// Cast to the correct response message type.
if (((FindFolderResponseMessageType)rmt).ResponseClass == ResponseClassType.Success) {
foreach (FolderType folder in ((FindFolderResponseMessageType)rmt).RootFolder.Folders) {
Console.WriteLine(folder.DisplayName);
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
You also might want to look at using the EWS Managed API which will save you greatly time and the amount of code you need to write
Cheers
Glen

context.SaveChanges() not persisting data in database

Im working on a MVC app.
When I call context.SaveChanges to update a specific records. The update is not registered in the database. I do not get any runtime error either. All in notice is that my Records is not updated. I still see the same values. Insert Functionality work Perfectly.
enter code here
public Admission Update(int stuid){
VDData.VidyaDaanEntities context = new VDData.VidyaDaanEntities();
VDData.Student_Master studentmaster = new VDData.Student_Master();
studentmaster.Student_ID = stuid;
studentmaster.Student_First_Name = this.FirstName;
studentmaster.Student_Middle_Name = this.MiddleName;
studentmaster.Student_Last_Name = this.LastName;
studentmaster.Student_Address_1 = this.Address;
studentmaster.Student_Address_2 = this.Address2;
studentmaster.Student_City = this.City;
studentmaster.Student_State = this.State;
studentmaster.Student_Pin_Code = this.Pincode;
context.SaveChanges(); // here it wont give any kind of error. it runs sucessfully. }
First get the entity you are going to update:
var entity = obj.GetEntity(id);
entity.col1 = "value";
context.SaveChanges(entity);
hope this will help.
It seems like you want to update, so your code should be
VDData.Student_Master studentmaster = context.Student_Masters.Single(p=>p.Student_ID == stuid);
And you should not change the Student_ID if it is the primary key.
public Admission Update(int stuid){
VDData.VidyaDaanEntities context = new VDData.VidyaDaanEntities();
//VDData.Student_Master studentmaster = new VDData.Student_Master();
//REPLACE WITH
VDData.Student_Master studentmaster = context.Student_Masters.Where(p=>p.Student_ID == stuid);
studentmaster.Student_ID = stuid;
studentmaster.Student_First_Name = this.FirstName;
studentmaster.Student_Middle_Name = this.MiddleName;
studentmaster.Student_Last_Name = this.LastName;
studentmaster.Student_Address_1 = this.Address;
studentmaster.Student_Address_2 = this.Address2;
studentmaster.Student_City = this.City;
studentmaster.Student_State = this.State;
studentmaster.Student_Pin_Code = this.Pincode;
context.SaveChanges();
Before
context.SaveChanges();
You need to call this
context.Student_Masters.Add(studentmaster );
Edit: introduce Abstraction to your Context class and Create a method in your context class like below, then you can call it whenever you want to create or update your objects.
public void SaveStudent_Master(Student_Master studentmaster)
{
using (var context = new VDData.VidyaDaanEntities())
{
if (studentmaster.Student_ID == 0)
{
context.Student_Masters.Add(studentmaster);
}
else if (studentmaster.Student_ID > 0)
{
//This Updates N-Level deep Object grapgh
//This is important for Updates
var currentStudent_Master = context.Student_Masters
.Single(s => s.Student_ID == studentmaster.Student_ID );
context.Entry(currentStudent_Master ).CurrentValues.SetValues(studentmaster);
}
context.SaveChanges();
}
Then in your Controller replace context.SaveChanges(); with _context.SaveStudent_Master(studentmaster);

Strange error message when using SaveChanges in EF with MVC

I have a dropdownlistfor with values that is not from my database, and when a user select values that does not exist in my database, I want to save it to the database(and if it already exist, I just use the existing data).
This work fine with some of my data(see code for where it does not work)
This is my repository:
public void newPerson(Person addperson)
{
db.Person.AddObject(addperson);
db.SaveChanges(); //This wont work
}
here is my controller:
[HttpPost]
public ActionResult Create(CreateNKIphase1ViewModel model)
{
if (ModelState.IsValid)
{
var goalcard = new GoalCard();
var companyChecker = "";
var dbCompanies = createNKIRep.GetCustomerByName();
var addcustomer = new Customer();
foreach (var existingcustomer in dbCompanies)
{
companyChecker = existingcustomer.CompanyName;
if (existingcustomer.CompanyName == model.CompanyName)
{
var customerId = existingcustomer.Id;
var selectedCustomerID = createNKIRep.GetByCustomerID(customerId);
goalcard.Customer = selectedCustomerID;
break;
}
}
if (companyChecker != model.CompanyName)
{
addcustomer.CompanyName = model.CompanyName;
createNKIRep.newCustomer(addcustomer); //This works!
goalcard.Customer = addcustomer;
}
if (model.PersonName != null)
{
var Personchecker = "";
var dbPersons = createNKIRep.GetPersonsByName();
foreach (var existingPerson in dbPersons)
{
Personchecker = existingPerson.Name;
if (existingPerson.Name == model.PersonName)
{
var personId = existingPerson.Id;
var selectedPersonID = createNKIRep.GetByPersonID(personId);
goalcard.Person = selectedPersonID;
break;
}
}
if (Personchecker != model.PersonName)
{
Person newPerson = new Person();
newPerson.Name = model.PersonName;
createNKIRep.newPerson(newPerson);//Where repository is called
goalcard.Person = newPerson;
}
}
But when I try to save a new Person I get the following error message:
The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.
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.
Even though Person only have Id and name as attributes in my database.
Is there anything wrong in my code, or is it any setting in my database that has to be changed?
Thanks in advance.
It's because I use db.SaveChanges(); multiple times in one post. Reducing numbers of time I use db.SaveChanges helped me get rid of the error.

Resources