How to download documents from liferay from outside application ..using liferay jsonws or any other way - liferay

Hi i am using liferay/api/secure/jsonws services to upload documents, getting documents, from a outside application , in the same way i want to download the documents also, i checked my liferay jsonws , there is no method or service which i can use for download , or i don't know about it , please suggest me a way to download documents from outside application , by using jsonws or any other way is also fine.
Edit after i got to know how to download document.
Hi I tried to download liferay document from outside application by using getURl, but every time for all document i am getting liferay login page content
i have already tried get-file-as-stream json-rpc call but that also giving me null response
the code which i have used is:
final HttpHost targetHost = new HttpHost(hostname.trim());
System.out.println(targetHost.getHostName());
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
System.out.println(creds);
final AuthScope authscope = new AuthScope(targetHost);
httpclient.getCredentialsProvider().setCredentials(authscope, creds);
final AuthCache authCache = new BasicAuthCache();
final BasicScheme basicAuth = new BasicScheme();
authCache.put(targetHost, basicAuth);
final BasicHttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
final HttpGet httpget = new HttpGet(hostname+"/documents/" + groupId + "/" + folderId + "/" + filename);
final HttpResponse response = httpclient.execute( httpget, localContext);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
final org.apache.http.HttpEntity entity = response.getEntity();
if (entity != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
entity.writeTo(baos);
return baos.toByteArray();
}
}
return null;
} finally {
httpclient.getConnectionManager().shutdown();
}
}
i am adding basic auth header will correct username and password, don't know how this login page is coming, is there any permission which i need to change or any configurations issue, please help in this.

You could use the Liferay WebDav Services to download files from your document-library. The paths to download can be inspected inside of the control-panel when clicking on a file entry (WebDAV URL toogle link). The paths usually look like: /webdav/{site-name}/document_library/{folder-name}/{file-name}
Otherwise, you could mimic the request URLs Liferay creates inside the documents-media portlet to download the file entry.
But you should take care about authentication, when your files (and folders) are not visible to guests.

Related

Acumatica - PXRedirectToFileException not redirecting in 2019R2

We're currently going through upgrading and ran into an issue where we can no longer redirect a user to one of our files. We've tried all of the different redirect methods, but for example purposes this is the easiest to show. If you use the below action and feed it a file it does nothing. However, if you change the "false" to "true" (for forcedownload) it will indeed download the file. This reinforces what we have seen with the other redirect methods. The system will not let you redirect to a URL that has .ashx in the url.
Is this an intentional change or is this a bug? We tried both 19.205.0023 and 19.207.0026
Thanks for your help =)
public PXAction<UsrDesign> viewFile;
[PXUIField(DisplayName = "View File")]
[PXButton()]
protected virtual void ViewFile ()
{
string fileName = Design.Current.ProofFile; // whatever file you want, in our case it comes from custom screen
UploadFile uploadFile = PXSelect<UploadFile, Where<UploadFile.name, Equal<Required<UploadFile.name>>>>.Select(this, fileName);
UploadFileMaintenance fileGraph = PXGraph.CreateInstance<UploadFileMaintenance>();
var file = fileGraph.GetFile((Guid)uploadFile.FileID);
throw new PXRedirectToFileException(file, false);
}

How to publish website form webapplication hosted in Azure?

need solution for website publishing form web application hosted in Azure.
I tried the following code, It create the domain but I was not able to upload the Published website.
private HttpResponseMessage CreateWebsite(CreateSiteViewModel site)
{
var cert = X509Certificate.CreateFromCertFile(Server.MapPath(site.CertPath));
string uri = string.Format("https://management.core.windows.net/{0}/services/WebSpaces/{1}/sites/", site.Subscription, site.WebSpaceName);
// A url which is looking for the right public key with
// the incomming https request
var req = (HttpWebRequest)WebRequest.Create(uri);
String dataToPost =string.Format(
#"<Site xmlns=""http://schemas.microsoft.com/windowsazure"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"">
<HostNames xmlns:a=""http://schemas.microsoft.com/2003/10/Serialization/Arrays"">
<a:string>{0}.azurewebsites.net</a:string>
</HostNames>
<Name>{0}</Name>
<WebSpaceToCreate>
<GeoRegion>{1}</GeoRegion>
<Name>{2}</Name>
<Plan>VirtualDedicatedPlan</Plan>
</WebSpaceToCreate>
</Site>", site.SiteName, site.WebSpaceGeo, site.WebSpaceName);
req.Method = "POST"; // Post method
//You can also use ContentType = "text/xml";
// with the request
req.UserAgent = "Fiddler";
req.Headers.Add("x-ms-version", "2013-08-01");
req.ClientCertificates.Add(cert);
// Attaching the Certificate To the request
// when you browse manually you get a dialogue box asking
// that whether you want to browse over a secure connection.
// this line will suppress that message
//(pragramatically saying ok to that message).
string postData = dataToPost;
var encoding = new ASCIIEncoding();
byte[] byte1 = encoding.GetBytes(postData);
// Set the content length of the string being posted.
req.ContentLength = byte1.Length;
Stream newStream = req.GetRequestStream();
newStream.Write(byte1, 0, byte1.Length);
// Close the Stream object.
newStream.Close();
var rsp = (HttpWebResponse)req.GetResponse();
var reader = new StreamReader(rsp.GetResponseStream());
String retData = reader.ReadToEnd();
req.GetRequestStream().Close();
rsp.GetResponseStream().Close();
return new HttpResponseMessage
{
StatusCode = rsp.StatusCode,
Content = new StringContent(retData)
};
}
I am not entirely sure what you try to achieve here. But if I understand correctly you want to publish a website programmatic.
You cannot do this (publish a website programmatic) with Azure Management APIs. Azure management APIs are to manage Azure services and resources. The web site content itself is not in any way Azure Service, nor an Azure resource.
If you want to programmaticly publish a website to Azure Web Site, I would suggest taking deep read into How to deploy an Azure Web site.
Out from what is mentioned there, pretty easy to automate are
Web Deploy
Repositories using GIT
MSBuild
any other that you are familiar with ...

Xamarin: Issues with transitioning between controllers and storyboard views

I realize this might come across as a very basic question, but I just downloaded Xamarin three days ago, and I've been stuck on the same issue for two days without finding a solution.
Here is what I am trying to do:
Get user input, call API, parse JSON and pass data to another controller, and change views.
Here is what I have been able to do so far: I get the user input, I call the API, I parse the response back, write the token to a file, and I want to pass the remaining data to the second controller.
This is the code I am trying:
var verifyCode = Storyboard.InstantiateViewController("verify") as VerifyCodeController;
if (verifyCode != null)
{
this.NavigationController.PushViewController(verifyCode, true);
}
My storyboard setup:
Navigation controller -> routesTo -> FirstController
I have another UI Controller View set up with the following properties set:
storyboardid: verify
restorationid: verify
and I am trying to push that controller view onto the navigation controller.
Right now this line is erroring out:
var verifyCode = Storyboard.InstantiateViewController("verify") as VerifyCodeController;
giving me this error, which I don't know what it means: Could not find an existing managed instance for this object, nor was it possible to create a new managed instance.
Am I way off in my approach?
p.s: I cannot use the ctrl drag thing like the tutorial suggests because I have an asynchronous call. And I cannot under no circumstances make it synchronous. So all the page transition has to be manual.
EDIT
to anyone requesting more code or more info:
partial void registerButton_TouchUpInside (UIButton sender)
{
phone = registrationNumber.Text;
string url = url;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create (url);
request.Method = "GET";
Console.WriteLine("Getting response...");
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
{
Console.Out.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode);
}
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string content = reader.ReadToEnd();
if (string.IsNullOrWhiteSpace(content))
{
//Console.WriteLine(text);
Console.Out.WriteLine("Response contained empty body...");
}
else
{
var json = JObject.Parse (content);
var token = json["token"];
var regCode = json["regCode"];
var aURL = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);
var filename = Path.Combine (aURL, "app.json");
File.WriteAllText(filename, "{token: '"+token+"'}");
// transition to main view. THIS IS WHERE EVERYTHING GETS MESSED UP
var verifyCode = Storyboard.InstantiateViewController("verify") as VerifyCodeController;
if (verifyCode != null)
{
this.NavigationController.PushViewController(verifyCode, true);
}
}
}
}
}
Here is all the info for every view in my storyboard:
1- Navigation controller:
- App starts there
- The root is the register pager, which is the page we are currently working on.
2- The register view.
- The root page
- class RegisterController
- No storyboard id
- No restoration id
3- The validate view
- Not connected to the navigation controller initially, but I want it to be connected eventually. Do I have to connect it either way? Through a segue?
- class VerifyCodeController
- storyboard id : verify
- restoration id : verify
If you guys need more information I'm willing to post more. I just think I posted everything relevant.

File uploading from web application to Sharepoint server

This is my first time ever with Sharepoint. Here is the scenario
I have a stand alone web application
I also have a stand alone sharepoint server.
Both are on different servers.
I need to upload a file from web application to sharepoint
I found 2 methods online,
Using the webservice provided by Sharepoint (CopyIntoItems)
Using jQuery library of Sharepoint webservice
After searching the web, I think the jQuery part will not work (you can correct me).
I am looking for a method that takes username/password and uploads a pdf file to Sharepoint server. The following is my C# code that tries to upload but ends up in error
public bool UploadFile(string file, string destination)
{
bool success = false;
CopySoapClient client = new CopySoapClient();
if (client.ClientCredentials != null)
client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
try
{
client.Open();
string filename = Path.GetFileName(file);
string destinationUrl = destination + filename;
string[] destinationUrls = { destinationUrl };
FieldInformation i1 = new FieldInformation { DisplayName = "Title", InternalName = "Title", Type = FieldType.Text, Value = filename };
FieldInformation[] info = { i1 };
CopyResult[] result;
byte[] data = File.ReadAllBytes(file);
//uint ret = client.CopyIntoItems(filename, destinationUrls, info, data, out result);
uint ret = client.CopyIntoItems(file, destinationUrls, info, data, out result);
if (result != null && result.Length > 0 && result[0].ErrorCode == 0)
success = true;
}
finally
{
if (client.State == System.ServiceModel.CommunicationState.Faulted)
client.Abort();
if (client.State != System.ServiceModel.CommunicationState.Closed)
client.Close();
}
return success;
}
I am calling the above function like this
UploadFile(#"C:\temp\uploadFile.txt", "http://spf-03:300/demo/Dokumente").ToString();
Error that i get:
Error Code: Destination Invalid
Error Message: The service method 'Copy' must be called on the same domain that contains the target URL.
There is the 3rd option with SharePoint 2010 and that is to use the Client Side object model. The client side object model a a sub set of the larger Sharepoint API, but it does cover uploading documents. Below is blog post with an example of uploading.
Upload document through client object model
As with most things in SharePoint you will need to authenticate against it the site, so find out if your site collection is forms based or claims based and then you should be able to find sample code for your situation.
Solution to the problem:
The problem was that the "security token webservice" was not working and it was giving some error when we manually ran the webservice.
The server was unable to process the request due to an internal error.
For more information about the error, either turn on
IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute
or from the configuration behavior) on the server in order to send the
exception information back to the client, or turn on tracing as per
the Microsoft .NET Framework 3.0 SDK documentation and inspect the
server trace logs.
The above exception is a generic one. To view the exact exception we enabled remote error viewing from the web.config file of the webservice(link) and saw the exact exception.
We found the solution for the exception and the service started. After that everything was working fine.

Download file with url as http://<site collection>/_layouts/DocIdRedir.aspx?ID=<doc id> using web request

I have a site collection in which Document Id feature is activated.
Documents are archived to this site collection from another site (in which Document Id is activated as well) and the only information I have about the moved file is the document id which is same between the source and the destination.
I need to download the file using web request, but my code gives '401 Unauthorised Exception'.
My code is as below:
string url = "http://<site collection>/_layouts/DocIdRedir.aspx?ID=<doc id>";
HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
request.Method = "Get";
request.PreAuthenticate = true;
var credential= new NetworkCredential(username, password, domainname);
request.Credentials = credential;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
I need to give some sort of authentication, but could not figure it out.
Any help would be greatly appreciated.
Thanks and Regards
Arjabh
Try running your code inside of a
SPSecurity.RunWithElevatedPrivileges(delegate()
{
//code goes here
});
block

Resources