Rendering a child page in a parent page - c1-cms

is it possible to render a specific page in a razor function. I tried #RenderPage but i cant figure out the path. Are there any built in functions to accomplish this?
Thanks Johan

Not really a C1 specific approach, but personally my best approach has been to just make a separate web-request for the page in question, parse out the html and render it.
This code can serve as an example, its a 1:1 of what i'm using. As you can see the trick is to find the element that wraps your content, in my example its the element inside that has an id equals to ContentColumnInner
public static string GetContentFromPage(Guid pageId)
{
var DomainName = HttpContext.Current.Request.Url.Authority;
var Uri = String.Format("http://{0}/page({1})", DomainName, pageId);
var request = WebRequest.Create(Uri);
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
using (var response = (HttpWebResponse)request.GetResponseWithoutException())
{
if (response.StatusCode != HttpStatusCode.OK)
{
LogError("StatusCode: " + response.StatusCode);
return null;
}
// Get the stream containing content returned by the server.
using (var responseStream = response.GetResponseStream())
{
if (responseStream == null)
{
LogError("ResponseStream is null");
return null;
}
// Open the stream using a StreamReader for easy access.
using (var stream = new StreamReader(responseStream))
{
// Read the content.
var responseFromServer = stream.ReadToEnd();
var beforeBodyStartIndex = responseFromServer.IndexOf("<body", StringComparison.Ordinal);
var afterBodyEndIndex = responseFromServer.LastIndexOf("</body>", StringComparison.Ordinal) + 7;
var body = responseFromServer.Substring(beforeBodyStartIndex, afterBodyEndIndex - beforeBodyStartIndex);
try
{
var xmlDocument = XElement.Parse(body);
var content = xmlDocument.Descendants().FirstOrDefault(o => o.Attribute("id") != null && o.Attribute("id").Value.EndsWith("ContentColumnInner"));
if (content == null || !content.HasElements)
{
return null;
}
var reader = content.CreateReader();
reader.MoveToContent();
return reader.ReadInnerXml();
}
catch (XmlException ex)
{
LogError("Error parsing xml: " + ex.Message);
return null;
}
}
}
}
}

Related

Save UIImage as jpg File in Photo Library Directory in Xamarin.iOS

As I know this is Simple Approch to save it in a Photo Library. But It can save with custom filename.
var someImage = UIImage.FromFile("someImage.jpg");
someImage.SaveToPhotosAlbum((image, error) => {
var o = image as UIImage;
Console.WriteLine("error:" + error);
})
But I want to save it with filename.jpg in the Photo Library.
I try so much code but nothing is getting help to me.
Code 1 :
var imageName = "/" + dicomId.ToString() + ".jpg";
var documentsDirectory = Environment.GetFolderPath
(Environment.SpecialFolder.Personal);
string jpgFilename = System.IO.Path.Combine(documentsDirectory, imageName); // hardcoded filename, overwritten each time
NSData imgData = dicomImage.AsJPEG();
NSError err = null;
if (imgData.Save(jpgFilename, false, out err))
{
Console.WriteLine("saved as " + jpgFilename);
}
else
{
Console.WriteLine("NOT saved as " + jpgFilename + " because" + err.LocalizedDescription);
}
This code part goes to if condition but it can not save the Image.
Code 2 :
If using this part of Code
var documentsDirectoryPath = NSSearchPath.GetDirectories(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User, true)[0];
It give you don't have permission to save image.
I try lots of thing on google and SO but nothing could help to me.
Edit :
info.plist
Any Help would be Appreciated.
How about using UIImage.SaveToPhotosAlbum()?
Usage is something like:
image.SaveToPhotosAlbum((uiImage, nsError) =>
{
if (nsError != null)
// do something about the error..
else
// image should be saved
});
Make sure that you have requested permissions before you try to save.
PHPhotoLibrary.RequestAuthorization(status =>
{
switch (status)
{
case PHAuthorizationStatus.Restricted:
case PHAuthorizationStatus.Denied:
// nope you don't have permission
break;
case PHAuthorizationStatus.Authorized:
// yep it is ok to save
break;
}
});
Edit: if you want more control, you need to use PHPhotosLibrary, which is an awful API...
var library = PHPhotoLibrary.SharedPhotoLibrary;
var albumName = "MyPhotos";
var fetchOptions = new PHFetchOptions();
fetchOptions.Predicate = NSPredicate.FromFormat($"title = {albumName}");
var assetsCollections = PHAssetCollection.FetchAssetCollections(
PHAssetCollectionType.Album, PHAssetCollectionSubtype.Any, fetchOptions);
var collection = assetsCollections.firstObject as PHAssetCollection;
library.PerformChanges(() => {
var options = new PHAssetResourceCreationOptions();
options.OriginalFilename = "filename.jpg";
var createRequest = PHAssetCreationRequest.CreationRequestForAsset();
createRequest.AddResource(PHAssetResourceType.FullSizePhoto, image.AsJPEG(1), options);
// if you want to save to specific album... otherwise just remove these three lines
var placeholder = createRequest.PlaceholderForCreatedAsset;
var albumChangeRequest = PHAssetCollectionChangeRequest.ChangeRequest(collection);
albumChangeRequest.AddAssets(new PHObject[] { placeholder });
},
(ok, error) => {
if (error != null)
{
// someone set up us the bomb
}
});

Making workable JSON file with Angularjs1

I have file that looks like this when I navigate to my local host server
URL:
http://localhost:9000/read/lol.json
And output looks like this:
"{\n \"firstName\" : \"Vladimir\"\n}\n"
Now, what I want is to read this file, so I made service in angular:
.service('messageService', ['$resource', function($resource){
this.getMessage = function(firstName) {
var gmList = $resource("read/lol.json");
return gmList.get({
firstName : firstName
});
};
}]);
and my controller.js
.controller('messageService', function(messageService){
this.firstName = messageService.firstName;
this.messageResult = messageService.getMessage(this.firstName);
});
Finally, my html file
<div data-ng-controller="messageService as mService">
<p>This is new controller: </p>
<div >
<ul data-ng-repeat="w in mService.messageResult">
<li>{{w.firstName}}</li>
</ul>
</div>
EDIT! This is how I got my output when i go to /read/lol.json
Its in java, to be precise, Play Framework.
public Result getFileContent(String filename) throws IOException {
String publicFolder = _appEnvironment.rootPath().getAbsolutePath().concat(folder);
String result = "";
FileReader in = null;
BufferedReader br = null;
File dataFile = new File(publicFolder + filename);
try {
in = new FileReader(dataFile);
br = new BufferedReader(in);
String line;
while ((line = br.readLine()) != null) {
result = result.concat(line).concat("\n");
}
} finally {
if (in != null) {
in.close();
}
if (br != null) {
br.close();
}
}
return ok(Json.toJson(result));
}
Thats it. I feel something needs to be done to ignore those \n and .
When I load my page, I get empty list (dots and nothing in that list, just dots).
However, when I look in console, my lol.json file has status 200. I GET that file but cant get anything from it (object).
What is the problem?
Make use of JSON.parse. The code is below:
var data=JSON.parse("{\n \"firstName\" : \"Vladimir\"\n}\n"
);
console.log(data.firstName);
It would convert the string to javascript object format. And to get value of firstname, just log data.firstname.

Get an image of a vbhtml view as a byte array and save it to an oracle database

I need help on an mvc application in vb.net. In general terms I need to receive an image through the view and get it to work on the controller. I need to do this to convert the image to a byte array and save it to an oracle database. So my idea is to get the image and in the controller to convert it to a byte array or maybe there is some way to get the image already as a byte array and pass that array to the controller to save it to the database.
something like this its my View :
<div class="span11">
<div class="span4" id="depnac">
#Html.LabelFor(Function(m) m.DepNacPER)
#Html.DropDownListFor(Function(m) m.DepNacPER, Model.DepNacPER, New With {.class = "form-control"})
</div>
and this is my Model :
<Display(Name:="Region of birth")>
<Required(ErrorMessage:="you must select a option")>
Property DepNacPER As SelectList
I'm working on an ASP.NET Core app right now that uploads images. The image comes through to the controller via the request as a Stream. I'm then creating an Image object from that Stream but you could just read the data from it directly. That said, you might want to try to create an Image object to confirm that the data does represent a valid image.
Here's some relevant code from the view's script:
function uploadImage()
{
// This is a file upload control in a hidden div.
var image = $("#imageFile");
if (image[0].files.length > 0)
{
var formData = new FormData();
formData.append(image[0].files[0].name, image[0].files[0]);
var xhr = new XMLHttpRequest();
xhr.open("POST", "#Url.Content("~/events/uploadimage")");
xhr.send(formData);
xhr.onreadystatechange = function ()
{
if (xhr.readyState === 4 && xhr.status === 200)
{
var response = JSON.parse(xhr.responseText);
if (response.saveSuccessful)
{
// ...
} else
{
window.location.replace("#Url.Content("~/error")");
}
}
}
xhr.onerror = function(err, result)
{
alert("Error: " + err.responseText);
}
}
}
I'm in the process of replacing that code with some jQuery that does the heavy lifting but haven't got that far yet.
Here's some relevant code from the action:
[HttpPost]
public IActionResult UploadImage()
{
var requestForm = Request.Form;
StringValues tempImageFileNames;
string tempImageFileName = null;
string imageUrl = null;
var saveSuccessful = true;
var requestFiles = requestForm.Files;
if (requestFiles.Count > 0)
{
// A file has been uploaded.
var file = requestFiles[0];
using (var stream = file.OpenReadStream())
{
try
{
using (var originalImage = System.Drawing.Image.FromStream(stream))
{
// Do whatever you like with the Image here.
}
}
catch (Exception)
{
saveSuccessful = false;
}
}
}
if (saveSuccessful)
{
return Json(new {saveSuccessful, tempImageFileName, imageUrl});
}
else
{
return Json(new {saveSuccessful});
}
}
Sorry, it didn't occur to me at first that you're after VB code and this is C#. Hopefully you can still get the idea and I'll take the hit if someone dislikes the answer.

Uploading CustomData with ng-file-upload and WebApi

I am trying to upload a file along with some metadata to a WebApi Service that I have created with ng-file-upload and Angular. I am getting the file name and bytes as expected, but I am not able to get the metadata I am passing as well. Here is what I am doing on the Angular side
Upload.upload({
url: '/api/FileStorage/AddContent' + location.search,
data: {file: files, year: vm.year }
})
And the WebApi side
var streamProvider = new CustomMultipartFileStreamProvider();
IEnumerable<HttpContent> parts = null;
Task.Factory
.StartNew(() => parts = Request.Content.ReadAsMultipartAsync(streamProvider).Result.Contents,
CancellationToken.None,
TaskCreationOptions.LongRunning, // guarantees separate thread
TaskScheduler.Default)
.Wait();
var customData = streamProvider.CustomData;
Here I am using a MultiStreamProvider to get the file, here is the meat of that provider
public override Task ExecutePostProcessingAsync()
{
foreach (var file in Contents)
{
var parameters = file.Headers.ContentDisposition.Parameters;
var filename = GetNameHeaderValue(parameters, "filename");
var year = GetNameHeaderValue(parameters, "year");
}
return base.ExecutePostProcessingAsync();
}
I am able to get filename without issue, but am never able to get the year. Here is the value in the debugger when I am looking at the parameters variable
As you can see, the name is "name" and the value is "year" when I would expect the name to be "year" and value to be "2016" or whatever I am passing in. What am I doing wrong here and how do I get the metadata included in the same call to the Api?
We use a similar approach with ng-file-upload and WebAPI. To get the values out of the form data, we weren't able to use GetNameHeaderValue. We had to do some manual parsing. We decided to use modified version of what was posted at http://conficient.wordpress.com/2013/07/22/async-file-uploads-with-mvc-webapi-and-bootstrap/ to dynamically take a form and unload it to a strongly-typed Model. But basically, here's what it does in the ExecutePostProcessingAsync method:
public override async Task ExecutePostProcessingAsync()
{
var formData = new FormCollection();
for (int index = 0; index < Contents.Count; index++)
{
ContentDispositionHeaderValue contentDisposition = headers.ContentDisposition;
if (contentDisposition != null)
{
HttpContent formContent = Contents[index];
string formFieldName = UnquoteToken(contentDisposition.Name) ?? String.Empty;
// Read the contents as string data and add to form data
string formFieldValue = await formContent.ReadAsStringAsync();
formData.Add(formFieldName, formFieldValue);
}
//For your case
var filename = formData["filename"];
var year = formData["year"];
This is the UnquoteToken method this uses:
private static string UnquoteToken(string token)
{
if (String.IsNullOrWhiteSpace(token))
{
return token;
}
if (token.StartsWith("\"", StringComparison.Ordinal) && token.EndsWith("\"", StringComparison.Ordinal) && token.Length > 1)
{
return token.Substring(1, token.Length - 2);
}
return token;
}

Use array to add new entry in model in asp.net mvc

I'm using asp.net mvc 4 and Entity Framework 6 to make a website where I can store data in MSSQL database. I want to make a function where it'll make a copy of an entry with different id. I want to put those copied values in an array and push it to the model to make the back-end processing faster. But I'm not sure how to do it.
Here are my codes:
public ActionResult FlatCopy(FlManagement FlTable, int FlId = 0)
{
var getOwner = rentdb.OwnerRegs.Where(a => a.username == User.Identity.Name).FirstOrDefault();
var getId = getOwner.serial;
var getLimit = getOwner.limit;
var getPosted = getOwner.posted;
FlInfo model = FlTable.Flats;
if (ModelState.IsValid)
{
if (getLimit != 0)
{
try
{
getOwner.limit = getLimit - 1;
getOwner.posted = getPosted + 1;
var dbPost = rentdb.FlatInfoes.Where(p => p.serial == FlId).FirstOrDefault();
if (dbPost == null)
{
TempData["flat_edit_fail"] = "Error! Information update failed!";
return RedirectToAction("FlatManager", new { FlPanelId = "AllFl" });
}
model.flatno = "Copy of " + dbPost.flatno;
model.type = dbPost.type;
model.owner_id = getId;
model.t_id = 0;
model.t_name = "N/A";
model.t_phone = "N/A";
model.basic = dbPost.basic;
model.electric = dbPost.electric;
model.gas = dbPost.gas;
model.water = dbPost.water;
model.total = dbPost.total;
model.advancerent = dbPost.advancerent;
model.currency = dbPost.currency;
model.title = dbPost.title;
model.status = "N/A";
db.FlatInfoes.Add(model);
db.SaveChanges();
TempData["success"] = "Information Added Successfully!";
return RedirectToAction("FlManager", new { FlPanelId = "AllFl" });
}
catch
{
TempData["fail"] = "Error! Please Provide Valid Information.";
return RedirectToAction("FlManager", new { FlPanelId = "AllFl" });
}
}
else
{
TempData["fail"] = "You've reached your post limit!";
return RedirectToAction("FlManager", new { FlPanelId = "AllFl" });
}
}
else
{
TempData["fail"] = "Error! Please Provide Valid Information.";
return RedirectToAction("FlManager", new { FlPanelId = "AllFl" });
}
}
How can I put the values in an array and push the array in model to add a new entry?
You could detach the entity from the DbContext then re-add it to the EntityCollection.
rentdb.Entry(dbPost).State = EntityState.Detached;
rentdb.FlatInfoes.Add(dbPost);
solution 2:(is better)
var model = new FlInfo();
rentdb.FlatInfoes.Add(model);
var sourceValues = rentdb.Entry(dbPost).CurrentValues;
rentdb.Entry(model).CurrentValues.SetValues(sourceValues);
rentdb.SaveChanges();

Resources