how to save custom entity with service builder liferay - liferay

how to save custom entity with service builder liferay?
i create new entity (name=BasicProfile)
and build by service builder liferay but
an exception occurred while saving.
my code :
BasicProfile basicProfile = new BasicProfileImpl();
basicProfile.setUserId(11701L);
basicProfile.setBirthCertificateSerial(birthCertificate);
basicProfile.setCreateDate(new Date());
basicProfile.setFatherName(fatherName);
basicProfile.setExtCustId(acceptorNumber);
basicProfile.setMobileNumber(telNumber);
basicProfile.setNationalCode(nationalCode);
basicProfile = BasicProfileLocalServiceUtil.addBasicProfile(basicProfile);

In your BasicProfileLocalServiceImpl.java create the following method:
public BasicProfile create(long userId, String birthCertificate, String fatherName, String acceptorNumber, String telNumber, String nationalCode) throws Exception {
long id = counterLocalService.increment();
BasicProfile obj = createBasicProfile(id);
obj.setUserId(userId);
obj.setBirthCertificateSerial(birthCertificate);
obj.setCreateDate(new Date());
obj.setFatherName(fatherName);
obj.setExtCustId(acceptorNumber);
obj.setMobileNumber(telNumber);
obj.setNationalCode(nationalCode);
obj = updateProduct(obj);
return obj;
}
Then in your code call that method to create a new object:
BasicProfile basicProfile = BasicProfileLocalServiceUtil.create(userId, birthCertificate, fatherName, acceptorNumber, telNumber, nationalCode);

Related

How to update azure ad b2c custom user attribute using graph api

I'm new to the Azure B2C .I created custom attribute extension_role against a user object.i want to update this attribute using graph api.I tried below code
public async Task UpdateUsersRole(string id)
{
IDictionary<string, object> extensionInstance = new Dictionary<string, object>();
extensionInstance.Add("extension_role", "admin");
var user = new User
{
AdditionalData = extensionInstance
};
await GraphClient.Users[id]
.Request()
.UpdateAsync(user);
}
is that correct way to update the custom attribute?.While executing i got an error also
Code: Request_BadRequestMessage: One or more property values specified
are invalid.Inner error
Please check the below code changes and also verify whether the user you are trying update has the custom attribute or not.
public static async Task UpdateCustomAtrributeUserId(GraphServiceClient graphClient)
{
Console.Write("Enter user object ID: ");
string userId = Console.ReadLine();
string CustomAtrribute = "B2C_Custom_AtrributeName";
Console.WriteLine($"Looking for user with object ID '{userId}'...");
try
{
//Get User details to Verify the existing values
var result = await graphClient.Users[userId]
.Request()
.Select($"id,givenName,surName,displayName,identities,{CustomAtrribute}")
.GetAsync();
Console.WriteLine(result);
if (result != null)
{
//Enter the New custom attribute value
Console.WriteLine("Enter custom attribute value");
string updatecustomeattribvalue = Console.ReadLine();
//Fill custom attribute value
IDictionary<string, object> extensionInstance = new Dictionary<string, object>();
extensionInstance.Add(CustomAtrribute, updatecustomeattribvalue);
//Updating the custom attribute
var updatedresult = await graphClient.Users[userId]
.Request()
.UpdateAsync(new User {
AdditionalData = extensionInstance
});
Console.WriteLine(JsonConvert.SerializeObject(updatedresult));
}
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(ex.Message);
Console.ResetColor();
}
}

Get User Profile using Profile Manager in Visual Web Part SharePoint 2010

I am receiving the error "Access Denied: Only an administrator may retrieve a count of all users." though I am using SPSecurity.RunwithElevatedPrivileges
What am I missing ? Please help.
private UserProfile GetUserInfo(string AccountName)
{
UserProfile profile = null;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPServiceContext serviceContext = SPServiceContext.Current;
UserProfileManager profileManager = new UserProfileManager(serviceContext);
if (AccountName != string.Empty)
{
if (profileManager.UserExists(AccountName))
{
profile = profileManager.GetUserProfile(AccountName);
}
}
//else
//{
// profile = profileManager.GetUserProfile(SPContext.Current.Web.CurrentUser.RawSid);
//}
});
return profile;
}
I was able to retrieve the user profile with the help of below code
SPSecurity.RunWithElevatedPrivileges(
delegate()
{
using (SPSite thisSite = new SPSite(SPContext.Current.Site.Url))
{
HttpContext tmp = HttpContext.Current;
HttpContext.Current = null;
SPServiceContext serviceContext = SPServiceContext.GetContext(thisSite);
UserProfileManager mgr = new UserProfileManager(serviceContext, true);
users.Text += "The total number of user profiles available: " + mgr.Count;
HttpContext.Current = tmp;
}
}
);
Source : http://weblogs.asp.net/sreejukg/access-denied-error-when-retrieving-user-profiles-count-from-sharepoint
yes, you need to generate a new context.
In you old code :
SPServiceContext serviceContext = SPServiceContext.Current;
UserProfileManager profileManager = new UserProfileManager(serviceContext);
You generate a new UPM with you current context, so you RunWithElevatedPrivileges is useless.
In you new Code :
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite thisSite = new SPSite(SPContext.Current.Site.Url))
{
[...]
SPServiceContext serviceContext = SPServiceContext.GetContext(thisSite);
UserProfileManager mgr = new UserProfileManager(serviceContext, true);
You get a new Context with Eleveted (because you instantiate a new SPSite in the ElevatedPrivileges) and thats why you can now use the UPM

Multithreaded Hibernate Session

I've got an issue involving scheduled tasks and Hibernate. I'm trying to use the java Timer object to schedule a task to run once a second. That tasks involves querying a database via hibernate. Now, as far as I understand it, Hibernate getCurrentSession() method will return a session bound to the current context.
Firstly, I am using this code to schedule the task:
timer = new Timer();
task = new UpdateTask();
// Schedule the task for future runs.
timer.scheduleAtFixedRate(task, 1000, 1000);
The code for the task is as follows:
public void run() {
FilterMeetingDao fmService = new FilterMeetingDao();
Set<String> codes = new HashSet<String>();
String date = new SimpleDateFormat(Constants.DATE_FORMAT).format(new Date());
try {
List<Meeting> meetings = new MeetingDao().getMeetings(date);
for(Meeting m : meetings)
{
if(RawMeetingFilter.isDefaultMeeting(m)) {
// Is a default meeting. Insert into the database.
codes.add(m.getCode());
}
}
fmService.add(codes, date);
} catch (ParseException e) {
e.printStackTrace();
}
}
Finally, here is the code is the DAO object that is retrieving the information:
public List<Meeting> getMeetings(String date) throws ParseException{
SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATE_FORMAT);
Date startDate = sdf.parse(date);
Query query = getSession().createQuery("from Meeting m where m.startDate = :startDate and source not like 'TTV' order by countrycode, categorycode, description");
query.setParameter("startDate", startDate);
return query.list();
}
And the getSession method is the origin of the NPE, which is as follows:
public Session getSession(){
return sessionFactory.getCurrentSession();
}
The line return sessionFactory.getCurrentSession(); is the origin of the error. Now, this obviously means the sessionFactory is null. However, in my code, the exact same database request is made in the previous line. This tells me that the sessionFactory isn't null because the previous request is successful.
Here is a stack trace of the NullPointerException:
Exception in thread "Timer-0" java.lang.NullPointerException
at com.sis.rawfilter.dao.impl.BaseDao.getSession(BaseDao.java:13)
at com.sis.rawfilter.dao.impl.MeetingDao.getMeetings(MeetingDao.java:21)
at com.sis.rawfilter.domain.UpdateTask.run(UpdateTask.java:32)
at java.util.TimerThread.mainLoop(Timer.java:555)
at java.util.TimerThread.run(Timer.java:505)
Just for reference..
meetings = meetingService.getMeetings(date);
// meetingService is the wrapper for the DAO object. this is the successful request.
And this is how I start my request:
us.startTimer();
Which starts off the call chain, with the timer code at the top.
Edits I've made to try and fix it
So I added in a new bean tag into the applicationContext.xml file. That looks like this:
<bean id="updateTask" class="com.sis.rawfilter.domain.UpdateTask"/>
And I've added in the Autowired tag into the class for the fields:
#Autowired
private IMeetingService meetingService;
#Autowired
private IFilterMeetingService filterMeetingService;
These types are declared in the applicationContext file as:
<bean id="meetingService" class="com.sis.rawfilter.service.impl.MeetingService"/>
<bean id="filterMeetingService" class="com.sis.rawfilter.service.impl.FilterMeetingService"/>
Sample Service Class
#Transactional
public class FilterMeetingService implements IFilterMeetingService {
#Autowired
private IFilterMeetingDao filterMeetingDao;
public List<FilterMeeting> getFilterMeetings(String date) throws ParseException{
return filterMeetingDao.getFilterMeetings(date);
}
public void save(Set<String> selectedMeetings, Set<String> excludedMeetings, String date) throws ParseException{
if(excludedMeetings.size() > 0){
filterMeetingDao.remove(excludedMeetings, date);
}
if(selectedMeetings.size() > 0){
filterMeetingDao.add(selectedMeetings, date);
}
}
public void setFilterMeetingDao(IFilterMeetingDao filterMeetingDao) {
this.filterMeetingDao = filterMeetingDao;
}
}
Sample Dao Class
public class FilterMeetingDao extends BaseDao implements IFilterMeetingDao {
#SuppressWarnings("unchecked")
public List<FilterMeeting> getFilterMeetings(String date) throws ParseException{
SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATE_FORMAT);
Date startDate = sdf.parse(date);
Query query = getSession().createQuery("from FilterMeeting fm where fm.startDate = :startDate");
query.setParameter("startDate", startDate);
return query.list();
}
public void remove(Set<String> codes, String date){
Query query = getSession().createSQLQuery("delete from tbl where d = :date and c in :codes ");
query.setParameter("date", date);
query.setParameterList("codes", codes);
query.executeUpdate();
}
public void add(Set<String> codes, String date) throws ParseException{
SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATE_FORMAT);
for(String code : codes){
FilterMeeting filterMeeting = new FilterMeeting(code, sdf.parse(date), Config.getInstance().getQueue());
getSession().save(filterMeeting);
}
}
}
You are creating new object of meeting dao
new MeetingDao().getMeetings(date);
so sessionFactory object will not initialize and obviously you will get nullPointerException, you should Autowired dao.

WebAPI can't call Put method

I have the following code on server:
public class UploadController : ApiController
{
public void Put(string filename, string description)
{
...
}
public void Put()
{
...
}
and try to call it from client:
var clientDescr = new HttpClient();
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("filename", "test"));
postData.Add(new KeyValuePair<string, string>("description", "100"));
HttpContent contentDescr = new FormUrlEncodedContent(postData);
clientDescr.PutAsync("http://localhost:8758/api/upload", contentDescr).ContinueWith(
(postTask) =>
{
postTask.Result.EnsureSuccessStatusCode();
});
but this code calls second put method (without parameters). Why and how to call first put method correctly?
You have several options here:
You can either choose to pass the parameters in the query string, by just changing the URI to:
http://localhost:8758/api/upload?filename=test&description=100
or you can have Web API parse the form data for you by changing your action to look like this:
public void Put(FormDataCollection formData)
{
string fileName = formData.Get("fileName");
string description = formData.Get("description");
}
You can also choose to create a class that has a fileName and a description property and use that as your parameter and Web API should be able to bind it correctly for you.

ASP.NET MVC render Razor Partial View as String Error?

I am using this code to try and render a razor partial view as a string for the purposes of sending an email.
public static string RenderPartialToString(
string userControlPath,
object viewModel,
ControllerContext controllerContext,
TempDataDictionary tempData)
{
using (var writer = new StringWriter())
{
var viewDataDictionary = new ViewDataDictionary(viewModel);
var view = new WebFormView(controllerContext, userControlPath);
var viewContext = new ViewContext(
controllerContext,
view,
viewDataDictionary,
tempData,
writer
);
viewContext.View.Render(viewContext, writer);
return writer.GetStringBuilder().ToString();
}
}
The problem is that I get the follow error:
must derive from ViewPage, ViewPage<TModel>, ViewUserControl, or ViewUserControl<TModel>. Stack Trace: at System.Web.Mvc.WebFormView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) at .... RenderPartialToString
How would I fix that ?
Indeed, WebFormView doesn't inherit from the mentioned classes, just IView. I did a little Google research and got a prototype working. This page was the most helpful.
I created an empty MVC3 application and created the following HomeController. When I run the application, the page shows the rendered string. The resultAsString variable shows how to capture the rendering as a string.
using System;
using System.IO;
using System.Web.Mvc;
public class HomeController : Controller
{
public ActionResult Index()
{
var result = RenderPartial(this.ControllerContext, "This is #DateTime.Now right now");
var resultAsString = result.Content;
return result;
}
private ContentResult RenderPartial(ControllerContext controllerContext, string template)
{
var temporaryViewPath = string.Format("~/Views/{0}.cshtml", Guid.NewGuid());
using (var stringWriter = new StringWriter())
{
using (var fileStream = System.IO.File.Create(Server.MapPath(temporaryViewPath)))
{
using (var streamWriter = new StreamWriter(fileStream))
{
streamWriter.WriteLine(template);
streamWriter.Close();
}
fileStream.Close();
}
var razor = new RazorView(controllerContext, temporaryViewPath, null, false, null);
razor.Render(new ViewContext(controllerContext, razor, new ViewDataDictionary(), new TempDataDictionary(), stringWriter), stringWriter);
System.IO.File.Delete(Server.MapPath(temporaryViewPath));
return Content(stringWriter.ToString());
}
}
}

Resources