How get value from mule payload - exception

How I get value from mule payload. I am unable to get from mule payload.
ExceptionMessage{payload=ActiveMQTextMessage {commandId = 14, responseRequired = false, messageId = ID:localhost.localdomain-59898-1431596266048-1:1:5:1:1, originalDestination = null, originalTransactionId = null, producerId = ID:localhost.localdomain-59898-1431596266048-1:1:5:1, destination = queue://delivery-queue-A, transactionId = TX:ID:localhost.localdomain-59898-1431596266048-1:1:1, expiration = 0, timestamp = 1431596274660, arrival = 0, brokerInTime = 1431596274672, brokerOutTime = 1431596274700, correlationId = null, replyTo = null, persistent = true, type = null, priority = 4, groupID = null, groupSequence = 0, targetConsumerId = null, compressed = false, userID = null, content = org.apache.activemq.util.ByteSequence#3128d4c1, marshalledProperties = org.apache.activemq.util.ByteSequence#6fa7e41d, dataStructure = null, redeliveryCounter = 3, size = 0, properties = {MULE_SESSION=, MULE_ROOT_MESSAGE_ID=e33be8a0-fa1c-11e4-9365-000c294271b7, MULE_ENDPOINT=jms://delivery-queue-A, Content_Type=text/plain;charset=UTF-8, MULE_ENCODING=UTF-8}, readOnlyProperties = true, readOnlyBody = true, droppable = false, jmsXGroupFirstForConsumer = false, text = CCD150507074415642 (copy).xml====
}

You can retrieve the original payload from an org.mule.message.ExceptionMessage payload with:
#[message.payload.payload]

Please check if the message you're printing is actually a complex object or a string representation of the message, that would define the strategy for accessing the values.
For this you can log with the following expression #[payload.getClass().getName()]

First you know your payload type whether it is String or Object then try to make use of the methods on payload.

You can extract payload using #[message.payload] and value from #[message.payload.'key']

Related

Power Query (M) Get info using a function with an API

As a newbe, I have a question about Power Query (M)
I am looking for a way to extract samo info from an API result.
For starters I am doing this:
I have created a query to get the title from a task.
This works fine:
let
Source = Web.Contents(#fxGetSource() & "/tasks/IEABCDQ7KQPO5DQ4",
[Headers=[#"Authorization"=#fxGetHeader()]]),
convertToJson = Json.Document(Source),
data = convertToJson[data],
ConvertedToTable = Table.FromList(data, Splitter.SplitByNothing(), null, null, ExtraValues.Error),
ExpandedColumn1 = Table.ExpandRecordColumn(ConvertedToTable, "Column1", {"title"}),
TheTitle = Table.TransformColumnTypes(ExpandedColumn1,{{"title", type text}})
in
TheTitle
I would like to have the taskid to sit in a variable, so I created a function:
(aTask as text) as text =>
let
Source = Web.Contents(#fxGetSource() & "/tasks/" & aTask,
[Headers=[#"Authorization"=#fxGetHeader()]]),
convertToJson = Json.Document(Source),
data = convertToJson[data],
ConvertedToTable = Table.FromList(data, Splitter.SplitByNothing(), null, null, ExtraValues.Error),
ExpandedColumn1 = Table.ExpandRecordColumn(ConvertedToTable, "Column1", {"title"}),
TheTitle = Table.TransformColumnTypes(ExpandedColumn1,{{"title", type text}})
in
TheTitle
When I invoke this function ans use the taskid from above I get:
Expression Error: We cannot convert a value of type Table to type Text.
change
(aTask as text) as text =>
to
(aTask as text) as table =>

Update the inserted record in ASP.NET Web API project

In my project I am inserting an employee and as my employee is inserted my save button HTML turns to update and on the back-end I am using the same insert function for updating the employee which I just inserted, my insert functionality is working perfectly but as I attempt to update the same record it inserts a new record in database instead of updating the data against the inserted ID, how do I update the existing or currently inserted user against their respective IDs.
I do not know why my update is not working and why I am not able to update right after inserting the user, every time I try to update the user I end up inserting the user again, and how should I restrict my application from inserting similar data again and again, the insert and update button are the same, as I mentioned above that on inserting the user I am changing the inner HTML of my button from save to update and using that same button to update
Here is my complete code, please let me know If I am making any mistakes at any part of my code, all the help I get from you guys is highly appreciated
My stored procedure code:
ALTER PROCEDURE [dbo].[InsEmpOfficialDetails]
(#EmpID int = NULL,
#UserName varchar(500) = NULL,
#pass varchar(500) = NULL,
#OfficialEmailAddress varchar(500) = NULL,
#Department varchar(500) = NULL,
#RoleID int = NULL,
#Role varchar(500) = NULL,
#IsAdmin bit = NULL,
#Designation varchar(500) = NULL,
#ReportToID int = NULL,
#ReportTo varchar(500) = NULL,
#JoiningDate datetime = NULL,
#IsPermanent bit = NULL,
#DateofPermanancy datetime = NULL,
#IsActive bit = NULL,
#HiredbyReference bit = NULL,
#HiredbyReferenceName varchar(500) = NULL,
#BasicSalary int = NULL,
#CurrentPicURL nvarchar(max) = NULL
-- #CreatedBy int,
-- #CreatedOn datetime,
-- #UpdatedOn datetime,
-- #UpdatedBy int
)
AS
BEGIN
IF EXISTS (SELECT 1 FROM Employee
WHERE UserName = #UserName
AND pass = #pass
AND OfficialEmailAddress = #OfficialEmailAddress
AND Department = #Department
AND RoleID = #RoleID
AND Role = #Role
AND IsAdmin = #IsAdmin
AND Designation = #Designation
AND ReportToID = #ReportToID
AND ReportTo = #ReportTo
AND JoiningDate = #JoiningDate
AND IsPermanent = #IsPermanent
AND DateofPermanancy = #DateofPermanancy
AND IsActive = #IsActive
AND HiredbyReference = #HiredbyReference
AND HiredbyReferenceName = HiredbyReferenceName
AND BasicSalary = #BasicSalary
AND CurrentPicURL = #CurrentPicURL)
BEGIN
UPDATE Employee
SET UserName = #UserName,
pass = #pass,
OfficialEmailAddress = #OfficialEmailAddress,
Department = #Department,
RoleID = #RoleID,
Role = #Role,
IsAdmin = #IsAdmin,
Designation = #Designation,
ReportToID = #ReportToID,
ReportTo = #ReportTo,
JoiningDate = #JoiningDate,
IsPermanent = #IsPermanent,
DateofPermanancy = #DateofPermanancy,
IsActive = #IsActive,
HiredbyReference = #HiredbyReference,
HiredbyReferenceName = HiredbyReferenceName,
BasicSalary = #BasicSalary,
CurrentPicURL = #CurrentPicURL
WHERE EmpID = #EmpID
END
ELSE
BEGIN
SET NOCOUNT ON;
INSERT INTO Employee(UserName, pass,
OfficialEmailAddress,Department,
RoleID, Role, IsAdmin, Designation,
ReportToID, ReportTo, JoiningDate,
IsPermanent, DateofPermanancy, IsActive,
HiredbyReference, HiredbyReferenceName,
BasicSalary, CurrentPicURL)
VALUES (#UserName, #pass, #OfficialEmailAddress, #Department,
#RoleID, #Role, #IsAdmin, #Designation,
#ReportToID, #ReportTo, #JoiningDate,
#IsPermanent, #DateofPermanancy, #IsActive,
#HiredbyReference, #HiredbyReferenceName,
#BasicSalary, #CurrentPicURL)
SELECT SCOPE_IDENTITY();
END
END
In my HTML on top of my input fields I am storing the currently inserted user ID in a hidden field like this
<input type="hidden" class="HiddenID" />
I do not know how to use this hidden field ID for updating the User right after inserting, because as I mentioned my insert and update functions both lies on same button
My ajax code:
$('.empOfficialDetails').click(function (ev) {
ev.preventDefault();
var data = new Object();
data.UserName = $('#username').val();
data.UPassword = $('#userpass').val();
data.OfficialEmailAddress = $('#officialemail').val();
data.Departments = $('#departments :selected').text();
data.Designation = $('#designation :selected').text();
data.RoleID = $('#role').val();
data.Role = $('#role :selected').text();
data.ReportToID = $('#reportToID').val();
data.ReportTo = $('#reportTo :selected').text();
data.JoiningDate = $('#joindate').val();
data.IsAdmin = $('#isAdmin :selected').val() ? 1 : 0;
data.IsActive = $('#isActive :selected').val() ? 1 : 0;
data.IsPermanent = $('#isPermanent :selected').val() ? 1 : 0;
data.DateofPermanancy = $('#permanantdate').val();
data.HiredbyReference = $('#hiredbyRef :selected').val() ? 1 : 0;
data.HiredbyReferenceName = $('#refePersonName').val();
data.BasicSalary = $('#basicSalary').val();
data.CurrentPicURL = $('.picture').val();
//data.CurrentPicURL = $('.picture')[0].files;
if (data.UserName && data.UPassword && data.OfficialEmailAddress && data.Departments && data.Designation && data.Role && data.IsAdmin && data.IsPermanent) {
$.ajax({
url: 'http://localhost:1089/api/Employee/EmpOfficialDetails',
type: "POST",
dataType: 'json',
contentType: "application/json",
data: JSON.stringify(data),
enctype: 'multipart/form-data',
beforeSend: function () {
$("#dvRoomsLoader").show();
},
complete: function () {
$("#dvRoomsLoader").hide();
},
success: function (data) {
var ID = parseInt(data);
if (ID > 0) {
//var id = data;
$(".HiddenID").val(data);
//var id = $(".HiddenID").val();
$('#official').css('display', 'block');
$('#official').html("Employees Official details added successfully...!");
$('#official').fadeOut(25000);
$("#dvRoomsLoader").show();
$('.empOfficialDetails').html("Update <i class='fa fa-angle-right rotate-icon'></i>");
}
else {
$('#official').find("alert alert-success").addClass("alert alert-danger").remove("alert alert-success");
}
},
error: function (ex) {
alert("There was an error while submitting employee data");
alert('Error' + ex.responseXML);
alert('Error' + ex.responseText);
alert('Error' + ex.responseJSON);
alert('Error' + ex.readyState);
alert('Error' + ex.statusText);
}
});
}
return false;
});
my controller code:
public int Emp_OfficialDetails(Employee emp)
{
//SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["AmanraHRMS"].ConnectionString);
var con = DB.getDatabaseConnection();
SqlCommand com = new SqlCommand("InsEmpOfficialDetails", con);
com.CommandType = CommandType.StoredProcedure;
#region Employee Official Details Insert Code block
com.Parameters.AddWithValue("#UserName", emp.UserName);
com.Parameters.AddWithValue("#pass", emp.UPassword);
com.Parameters.AddWithValue("#OfficialEmailAddress", emp.OfficialEmailAddress);
com.Parameters.AddWithValue("#Department", emp.Departments);
com.Parameters.AddWithValue("#Role", emp.Role);
com.Parameters.AddWithValue("#IsAdmin", Convert.ToBoolean(emp.IsAdmin));
com.Parameters.AddWithValue("#Designation", emp.Designation);
com.Parameters.AddWithValue("#ReportToID", emp.ReportToID);
com.Parameters.AddWithValue("#ReportTo", emp.ReportTo);
com.Parameters.AddWithValue("#JoiningDate", Convert.ToDateTime(emp.JoiningDate));
com.Parameters.AddWithValue("#IsPermanent", Convert.ToBoolean(emp.IsPermanent));
com.Parameters.AddWithValue("#DateofPermanancy", Convert.ToDateTime(emp.DateofPermanancy));
com.Parameters.AddWithValue("#IsActive", Convert.ToBoolean(emp.IsActive));
com.Parameters.AddWithValue("#HiredbyReference", Convert.ToBoolean(emp.HiredbyReference));
com.Parameters.AddWithValue("#HiredbyReferenceName", emp.HiredbyReferenceName);
com.Parameters.AddWithValue("#BasicSalary", emp.BasicSalary);
com.Parameters.AddWithValue("#CurrentPicURL", emp.CurrentPicURL);
#endregion
//var file = emp.CurrentPicURL;
//EmployeeImage(file);
var ID = com.ExecuteScalar();
com.Clone();
return Convert.ToInt32(ID);
}
//Ajax call hit this method from AddEmployee page
[Route("api/Employee/EmpOfficialDetails")]
[HttpPost]
public int? EmpOfficialDetails(Employee emp)
{
IHttpActionResult ret;
try
{
var id = Emp_OfficialDetails(emp);
return id;
}
catch (Exception ex)
{
ret = InternalServerError(ex);
}
return null;
}
fix your hidden field
<input type="hidden" asp-for ="EmpID" id="empId" class="HiddenID" value="#Model.EmpID />
fix your stored procedure. for exist would be enough EmpID, too many parameters can give the wrong result
BEGIN
IF EXISTS (SELECT 1 FROM Employee
WHERE EmpID = #EmpID)
BEGIN
UPDATE Employee
SET UserName = #UserName,
.....
and the most important add EmpId to ajax
var data = new Object();
data.EmpID = $('#empId').val();
and action command
com.Parameters.AddWithValue("#EmpID", emp.EmpID);

Laravel - How do update a table immediately records are saved in it

In my Laravel-5.8, I have this table.
CREATE TABLE `appraisal_goal_types` (
`id` int(11) NOT NULL,
`name` varchar(200) NOT NULL,
`parent_id` int(11) DEFAULT NULL,
`max_score` int(11) DEFAULT 0,
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Then I created this controller to store record in another table.
public function store(StoreAppraisalGoalRequest $request)
{
$appraisalStartDate = Carbon::parse($request->appraisal_start_date);
$appraisalEndDate = Carbon::parse($request->appraisal_end_date);
$userCompany = Auth::user()->company_id;
$employeeId = Auth::user()->employee_id;
$identities = DB::table('appraisal_identity')->select('id','appraisal_name')->where('company_id', $userCompany)->where('is_current', 1)->first();
try {
$goal = new AppraisalGoal();
$goal->goal_type_id = $request->goal_type_id;
$goal->appraisal_identity_id = $request->appraisal_identity_id;
$goal->employee_id = $employeeId; //$request->employees_id
$goal->weighted_score = $request->weighted_score;
$goal->goal_title = $request->goal_title;
$goal->goal_description = $request->goal_description;
$goal->company_id = Auth::user()->company_id;
$goal->created_by = Auth::user()->id;
$goal->created_at = date("Y-m-d H:i:s");
$goal->is_active = 1;
if ($request->appraisal_doc != "") {
$appraisal_doc = $request->file('appraisal_doc');
$new_name = rand() . '.' . $appraisal_doc->getClientOriginalExtension();
$appraisal_doc->move(public_path('storage/documents/appraisal_goal'), $new_name);
$goal->appraisal_doc = $new_name;
}
$goal->save();
$parentids = DB::table('appraisal_goal_types')->select('parent_id')->whereNotNull('parent_id')->where('company_id', $userCompany)->where('id', $goal->goal_type_id)->first();
$parentid = $parentids->id;
$goal->update(['parent_id' => $parentid]);
}
As soon as the record is saved, I want to quickly query appraisal_goal_types
$parentids = DB::table('appraisal_goal_types')->select('parent_id')->whereNotNull('parent_id')->where('id', $goal->goal_type_id)->first();
$parentid = $parentids->id;
$goal->update(['parent_id' => $parentid]);
and update the record.
I need only one row there where the answer is true. I used the code above, but nothing is happening.
How do I resolve this?
Thank you
Try like this,
$parentids = DB::table('appraisal_goal_types')->select('parent_id')->whereNotNull('parent_id')->where('company_id', $userCompany)->where('id', $goal->goal_type_id)->first();
$parentid = $parentids->id;
$goal->parent_id = $parentid;
$goal->save();
There is an another solution like this,
$parentids = DB::table('appraisal_goal_types')->select('parent_id')->whereNotNull('parent_id')->where('company_id', $userCompany)->where('id', $goal->goal_type_id)->first();
$parentid = $parentids->id;
AppraisalGoal::where('id', $goal->id)->update(['parent_id' => $parentid]);
Both will works. And let me know if you solved the issue

Django - remove primary_key=True from an existing model?

I have a table that I've already migrated into the MySQL database and one of the fields has primary_key = True. I realized this needs to be different and I need to remove the primary_key = True. I'd like Django to create its own auto incrementing primary key fields (like it does with all models if you don't specify a primary_key).
If I simply remove the primary_key = True, Django complains because it can't auto-assign an auto-increment value to its new id field (which is now the primary key field).
What's the best way to change this one field to not have primary_key = True? This particular model doesn't have any records yet in the database, so I think I'm in a better position than if I had records in there. I'm not sure if I should just drop the table and migrate as if it's a brand new table or if I need to take some other approach?
Edit
What I actually tried:
python manage makemigrations accounting
The model in question is called Invoice and I'm wanting to change the field inv_num to not be the primary key
Django asks:
You are trying to add a non-nullable field 'id' to invoice without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows)
2) Quit, and let me add a default in models.py
Select an option:
So I select option 1, and type 1.
Django creates the migration file, so I do:
python manage migrate accounting
And Django complains with:
django.db.utils.OperationalError: (1067, "Invalid default value for 'id'")
My research indicates that this is because you can't auto-assign a value to a primary key field.
Edit 2
The Model in question:
class Invoice(models.Model):
inv_num = models.CharField(max_length = 144, primary_key = True, verbose_name = 'Invoice Number')
brokerage = models.ForeignKey(Brokerage, blank = True, null = True, verbose_name = 'Brokerage')
lot = models.ForeignKey(Lot, on_delete = models.SET_NULL, blank = True, null = True, verbose_name = "Lot")
vendor = models.ForeignKey(Vendor, on_delete = models.SET_NULL, blank = True, null = True, verbose_name = 'Bill To (Vendor)')
contact = models.ForeignKey(Contact, on_delete = models.SET_NULL, blank = True, null = True, verbose_name = 'Bill To (Contact)')
due_date = models.DateField(blank = True, null = True, verbose_name = 'Date')
fund = models.ForeignKey(Fund, on_delete = models.SET_NULL, blank = True, null = True)
org_amt = models.DecimalField(max_digits = 12, decimal_places = 2, default = 0, verbose_name = 'Original Amount of Invoice')
amtos = models.DecimalField(max_digits = 12, decimal_places = 2, default = 0, verbose_name = 'Amount OS')
is_fine = models.BooleanField(default = False)
is_reversed = models.BooleanField(default = False, verbose_name = 'Has Been Reversed')
is_paid = models.BooleanField(default = False, verbose_name = 'Is Paid')
is_locked = models.BooleanField(default = False, verbose_name = 'Is Locked')
is_archived = models.BooleanField(default = False, verbose_name = 'Is Archvied')
org_je = models.CharField(max_length = 144, blank = True, null =True, verbose_name = 'Original JE')
There are a number of other models in this Django App that have Invoice as a foreign key. But those too don't have any data in them in the database.
I wonder if I should just drop the whole app from the database, and re-migrate it in? I do have a bunch of other apps that have data I cannot simply drop though.

Assertion failure in +[NSJSONSerialization ensureObjectForKey:inDictionary:hasExpectedType:nullAllowed:]

I'm using box-ios-sdk-v2 (v1.1.0) and when I call:
[[BoxCocoaSDK sharedSDK].foldersManager folderInfoWithID:BoxAPIFolderIDRoot
requestBuilder:nil
success:folderSuccess
failure:failure];
I get an assertion failure:
*** Assertion failure in +[NSJSONSerialization ensureObjectForKey:inDictionary:hasExpectedType:nullAllowed:], ~/MyApp/Pods/box-ios-sdk-v2/BoxSDK/Categories/NSJSONSerialization+BoxAdditions.m:27
An uncaught exception was raised
+[NSJSONSerialization(BoxAdditions) ensureObjectForKey:inDictionary:hasExpectedType:nullAllowed:]: Unexpected JSON null when extracting key modified_at from dictionary {
"content_created_at" = "<null>";
"content_modified_at" = "<null>";
"created_at" = "<null>";
"created_by" = {
id = "";
login = "";
name = "";
type = user;
};
description = "";
etag = "<null>";
"folder_upload_email" = "<null>";
id = 0;
"item_collection" = {
entries = (
{
etag = 0;
id = 1092326452;
name = CSS;
"sequence_id" = 0;
type = folder;
},
{
etag = 1;
id = 680411078;
name = New;
"sequence_id" = 1;
type = folder;
},
{
etag = 2;
id = 8224096128;
name = ".apdisk";
"sequence_id" = 2;
sha1 = e8389b6e4307a798b0811cabc94144ce381b3312;
type = file;
}
);
limit = 100;
offset = 0;
order = (
{
by = type;
direction = ASC;
},
{
by = name;
direction = ASC;
}
);
"total_count" = 3;
};
"item_status" = active;
"modified_at" = "<null>";
"modified_by" = {
id = 181198661;
login = "grigutis#iu.edu";
name = "John Grigutis";
type = user;
};
name = "All Files";
"owned_by" = {
id = 181198661;
login = "grigutis#iu.edu";
name = "John Grigutis";
type = user;
};
parent = "<null>";
"path_collection" = {
entries = (
);
"total_count" = 0;
};
"purged_at" = "<null>";
"sequence_id" = "<null>";
"shared_link" = "<null>";
size = 289;
"trashed_at" = "<null>";
type = folder;
}
Is this a problem with my account (modified_at really shouldn't be null) or the SDK? If it's my account, how would I fix that?
I'm the maintainer of the Box iOS SDK. Thanks for the bug report! Root folders are special folders on Box. Root folders are "virtual folders" that don't actually exist (this explains why they always have an id of 0 across all user accounts). Because root folders (and trash folders) are virtual folders, we don't track some metadata for them, like the modified_at timestamps.
The list of fields that may be null for root/trash folders:
sequence_id
etag
created_at
modified_at
trashed_at
purged_at
content_created_at
content_modified_at
shared_link
parent
I've put together a patch that will suppress these Nulls and convert them to nil. (I didn't want to turn all of the accessors to id return type just for the special case of the root/trash folders.) https://github.com/box/box-ios-sdk-v2/pull/47
Once this commit is merged, we'll cut a bugfix release.
We should document this sort of edge case/special case behavior. I'll let our documentation team know.