I get "access denied" when I submit a job in Azure - azure

I upload a video in one asp.net page, save the asset in a session variable, and then in another asp.net page, I use that asset to hopefully encode the video (using azure media services calls). The I get an error when I submit the encoding job (with job.submit). It says that access is denied, and the type of exception is: system.security.cryptography.cryptographicException.
I'm wondering if the reason is that I create a context in the new page?
Here is the code from page #1:
Dim mediaServicesAccountName As String = ConfigurationManager.AppSettings("accountname")
Dim mediaServicesAccountKey As String = ConfigurationManager.AppSettings("accountkey")
Dim mediaCloud As New CloudMediaContext(mediaServicesAccountName, mediaServicesAccountKey)
Dim assetOptions As New AssetCreationOptions()
asset = mediaCloud.Assets.Create(Filename, assetOptions)
Session("azureasset") = asset
Dim assetFile As IAssetFile = asset.AssetFiles.Create(Filename)
Session("assetFile") = assetFile
Here is the code from page #2:
Sub Page_Load
Dim asset As IAsset
asset = CType(Session("azureasset"), IAsset)
Dim assetname As String
assetname = asset.Name ' just for debugging
_context = New CloudMediaContext(_accountName, _accountKey)
CreateEncodingJob(asset)
End Sub
Private Function CreateEncodingJob(asset As IAsset) As IJob
Dim job As IJob = _context.Jobs.Create("My encoding job")
Dim processor As IMediaProcessor = GetLatestMediaProcessorByName("Windows Azure Media Encoder")
Dim task As ITask = job.Tasks.AddNew("My encoding task", processor, "H264 Broadband 720p", Microsoft.WindowsAzure.MediaServices.Client.TaskOptions.ProtectedConfiguration)
task.InputAssets.Add(asset)
' Add an output asset to contain the results of the job.
' This output is specified as AssetCreationOptions.None, which
' means the output asset is not encrypted.
task.OutputAssets.AddNew("Output asset", AssetCreationOptions.None)
' Use the following event handler to check job progress.
Dim ev As New EventHandler(AddressOf StateChanged)
AddHandler job.StateChanged, AddressOf StateChanged
' Launch the job.
job.Submit()
Thanks

I would suggest to only keep AssetID in your session. Then get the IAsset reference from the CloudMediaContext once you create it. Use a code similar to this (C#):
//var assetId = [Get this from Session, not the entire Asset object]
var asset = _context.Assets.Where(x => x.Id.Equals(assetId)).FirstOrDefault();
// no configure the job with this asset..
My best bet goes to the fact that indeed you create the CloudMediaContext again, and the reference to the asset is lost. Your new instance of Media Context does not know anything about this asset object you have in your session.

Related

Generating a document link coming from another form (Web)

I'm trying to generate document links from another form using a button I created (in pass through below). Upon clicking the button, an agent must run and document link/s should be generated, and the current form should still be in edit mode (web).
Here are the issues:
1. I am unable to generate document link/s coming from another form through the view. The key is PeopleID, the current document has the computed field which should match with another form.
2. When I click on the button, it redirects me to the agent page and says that the agent is done running (non-verbatim). It should still be on the current document (current page, only that the document link/s should be generated).
Below is the code I use on the form (in pass-through) for the button and JS function to run agent.
<input type="button" value="Generate Link" onclick="javascript:runAgent();">
<script language="JavaScript">
function runAgent() {
var path = document.forms[0].BaseLink.value; // BaseLink is the prefix url.
var completeUrl = path + '(GenerateDoc)?OpenAgent&UNID=' + document.forms[0].UniqueID.value;
self.location.href = completeUrl;
}
</script>
After this, I have a rich text field named "DocumentLink", computed.
For the agent code, here it is:
Dim session As New NotesSession
Dim db as NotesDatabase
Dim curDoc as NotesDocument
Dim difDoc as NotesDocument
Dim view as NotesView
Dim rtitem as NotesRichTextItem
Dim peopleID as String
Set db = session.currentDatabase
thisDocumentID = Right$(session.DocumentContext.query_string(0),32)
Set curDoc = db.GetDocumentByUNID(thisDocumentID) //For some reason I am not getting anything here.
Set view = db.GetView("MyView")
peopleID = curDoc.PeopleID(0)
Set difDoc = view.GetDOcumentByKey(peopleID,true)
If Not difDoc Is Nothing Then
Set rtitem = curDOc.GetFirstItem("DocumentLink")
rtitem.values = ""
Call rtitem.AppendDocLink(difDoc,"Link to other form")
Call curDoc.Save(True,False)
End If
Appreciate your help.
There are several issues with what you are doing.
First: The self.location.href = completeUrl; line in Javascript will redirect the browser to the agent which has no relationship to the currently selected or open document. Alternatives to this approach would be using AJAX techniques from jQuery or other framework to run your agent asynchronously. If you have not saved the current document then there might not be a UNID on the Query String using your current approach.
Second: You should put the PeopleId on the query string also so that the agent can read it. The agent should then parse the Query_String_Decoded to get the two elements UNID and PeopleId.
Third: your agent is not generating any output. You should use PRINT statements in the LotusSctipt to create some feedback. You can also create JavaScript Tags and calls to calls to redirect back to the original page/document.

Is it possible to group function calls in VBA?

I have a function that looks something like:
Public Function GetData(DataType As String) As String
Dim Client As New WebClient
Client.BaseUrl = "http://url/to/get/data"
Dim Response As New WebResponse
Set Response = Client.GetJson(DataType)
GetInstruments = Response.Data("data")
End Function
It's a simple HTTP GET that returns a value based on an argument.
My problem is that I'm trying to execute this function for many different cells at once in Excel (i.e. =GetData(A$1)) that leads to hundreds of HTTP calls which is very slow.
Is there a way that in VBA that I am able to intercept function calls so I can then make a single and quick HTTP call and then return all the data at once?
You can use global variables in a module to cache and reuse alread downloaded data.
First easy to digest example using simple Collection:
Private someCollection As Collection
Public Function GetData() As Integer
' Make sure that data is already read/created
If someCollection Is Nothing Then
' If we didn't get any data, then get it
Set someCollection = New Collection
someCollection.Add (1)
End If
' Get data :)
GetData = someCollection(1)
End Function
Now, applying this logic to your problem you could do:
Private Response As WebResponse
Public Function GetData(DataType As String) As String
' You can alter check to see if URL has changed.
' In order to do that just store URL in some global variable
If Response Is Nothing Then
Dim Client As New WebClient
Client.BaseUrl = "http://url/to/get/data"
Set Response = Client.GetJson(DataType)
End If
GetInstruments = Response.Data("data")
End Function
Of course, all this code goes into module.

How to give public access to files under webcontent in lotus domino

I have a domino application with XPages that i want to be public. So, i set in the ACL the "Default" to Depositor level with read public documents option, so as to make it public.
When i want to use an image resource i go to its properties security tab and i enable the "available to public access users" checkbox.
Now, I want to use font-awesome in my application and i have font-awesome's folder with its subfolders and files under webcontent folder.
How can i make them public? (in a non-public app, font-awesome works normally with font-awesome's folder under webcontent folder)
I simply created an agent to set the flag. You can get the code below. I use it for an Angular app that I have added to the NSF.
HTH
/John
Edit:
Code inserted directly here:
Option Public
Option DeclareSub Initialize
Const APP_DIR = “app/”
Const FN_PUBLICACCESS = “$PublicAccess”
Const FLAG_TRUE = “1”
Dim sess As New NotesSession
Dim db As NotesDatabase
Dim nc As NotesNoteCollection
Set db = sess.currentDatabase
Set nc = db.CreateNoteCollection(False)
Call nc.SelectAllDesignElements(True)
Call nc.BuildCollection
Dim d1 As Long
Dim d2 As Long
Dim title As String
Dim flagsExt As String
Dim noteid As String
Dim nextid As String
Dim i As Long
Dim doc As NotesDocument
noteid = nc.Getfirstnoteid()
For i = 1 To nc.Count
‘get the next note ID before removing any notes
nextid = nc.GetNextNoteId(noteid)
Set doc = db.GetDocumentByID(noteid)
title = doc.GetItemValue(“$title”)(0)
flagsExt = doc.GetItemValue(“$flagsExt”)(0)
If LCase(flagsExt) = “w” And Left(LCase(title),Len(APP_DIR)) = LCase(APP_DIR) Then
d1 = d1 + 1
If Not doc.Getitemvalue(FN_PUBLICACCESS)(0) = FLAG_TRUE Then
d2 = d2 + 1
Call doc.replaceItemValue(FN_PUBLICACCESS,FLAG_TRUE)
Call doc.save(True, False)
Print title & ” – set to allow public access read”
End If
End If
noteid = nextid
Next
Print nc.count & ” design elements checked. “ & d1 & ” elements found in ‘” & APP_DIR & “‘ and “ & d2 & ” updated to give public access”
End Sub
They still get registered as design notes inside the NSF (which is why they're picking up the default visibility), so I think the only real option is to run an agent to update their visibility, explicitly. Sven Hasselbach has blogged about this topic a couple times (at least on interacting with items in the WebContent folder, programmatically) and is worth reading. Ultimately, I try to put these sorts of public agnostic, common resources into my Domino /Data/domino/html/ path, so as to have it always public (that path is always publicly visible), and available to be set in a theme .
[Update]
See the link Per Henrik Lausten posted in the comments to the Q for details.
[/Update]

Office 365 - multitenant application constantly gives unauthorized

For some reason the following code gives an unauthorized exception, can anyone tell me what i'm doing wrong?
In the screenshot below you can find the contents of "theToken", which has been received through Office365 and saved in a database ( 1 minute before excecution)
Async Function CalendarDemo() As System.Threading.Tasks.Task(Of ActionResult)
Dim tokenData = UserTokenService.GetToken(HttpContext.User.Identity.Name)
Dim theToken = tokenData.ReadItems(0)
Dim myCalendars As List(Of ViewModels.Office365.MyCalendar) = New List(Of ViewModels.Office365.MyCalendar)
Try
Dim accessToken As Func(Of String) = Function() As String
Return theToken.AccessToken
End Function
Dim discClient As New DiscoveryClient(New Uri("https://api.office.com/discovery/v1.0/me/"), accessToken)
Dim dcr = Await discClient.DiscoverCapabilityAsync("Calendar") 'This is where the code breaks, the code worked in the past. Till i split up the authorization and the fetching of the Calendar
ViewBag.ResourceId = dcr.ServiceResourceId
Dim exClient As New OutlookServicesClient(dcr.ServiceEndpointUri, Function()
Return Helpers.Office365Helpers.ReturnStringAsAsync(theToken.AccessToken)
End Function)
Dim calendarResults = Await exClient.[Me].Events.ExecuteAsync()
Dim calenderResults = Await exClient.Me.Calendar.Events.ExecuteAsync()
Do
Dim calendars = calendarResults.CurrentPage
For Each calendar In calendars
Dim newCalendar = New ViewModels.Office365.MyCalendar(calendar)
myCalendars.Add(newCalendar)
Next
calendarResults = Await calendarResults.GetNextPageAsync()
Loop While calendarResults IsNot Nothing
Catch exception As AdalException
' handle token acquisition failure
If exception.ErrorCode = AdalError.FailedToAcquireTokenSilently Then
'authContext.TokenCache.Clear()
'Redirect naar login of refresh token
ViewBag.ErrorMessage = "AuthorizationRequired"
End If
Catch exception As DiscoveryFailedException
End Try
Return View(myCalendars)
End Function
The exception is : "Exception of type ' Microsoft.Office365.Discovery.DiscoveryFailedException' was thrown." - and the ErrorCode is 'Unauthorized'
According to the answer below, i changed the following code:
Dim exClient As New OutlookServicesClient(New Uri("https://outlook.office365.com/api/v1.0/"), Function()
Return Helpers.Office365Helpers.ReturnStringAsAsync(theToken.AccessToken)
End Function)
Dim calendarResults = Await exClient.[Me].Events.Take(10).ExecuteAsync()
Where my helper is :
Public Module Office365Helpers
Public Async Function ReturnStringAsAsync(ToReturnString As String) As System.Threading.Tasks.Task(Of String)
Return Await System.Threading.Tasks.Task.Delay(1).ContinueWith(Function(dl) ToReturnString)
End Function
End Module
But it doesn't return any value when it's loading.. It's like the api call is in a continuous loop.
Identitical question but shorter:
I have a Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache, how can i query the Microsoft Calendar API using the DLL's and vb.net to get the data.
In the ODataException, in the response, you can view the header values.
There is an error there that explains my fault, it said something in the lines of : "Inconsistent resource". Which could be true. I found out that i didn't use https://outlook.office365.com/api/v1.0/ when requesting the token. But used it when requesting data.
So i received invalid tokens for what i tried to do.
Your resource should be https://api.office.com/discovery/ for calling the Discovery service. However, since you're calling the Calendar API, you could just skip discovery. The endpoint is fixed at https://outlook.office365.com/api/v1.0/.
If you get stuck, try the .NET tutorial on https://dev.outlook.com.

Load/save documents to SFTP Linux server with VB.NET

So I am using Visual Studio 2013 (Community)
And so far I've build a program that can create files using textboxes and so forth.
It saves to XML, and hopefully reads from XML (Even if I am getting access denied)
The time has come for the Application to talk to a server, where all the files will be saved, and read from.
The server is a Linux Server Edition (Latest) and its up and running fine.
I want my application to connect to it, log in, and then just list and read files from the server.
So far, it does this a bit.
Private Sub Loginbutton_Click(sender As Object, e As EventArgs) Handles Loginbutton.Click
Dim mySessionOptions As New SessionOptions
With mySessionOptions
.Protocol = Protocol.Sftp
.HostName = "192.168.0.247"
.UserName = "username" - these are default on purpose
.Password = "password"
.SshHostKeyFingerprint = "ssh-rsa 2048 [Hidden]"
End With
Using mySession As Session = New Session
' Connect
mySession.Open(mySessionOptions)
End Using
Form1.Show()
Me.Close()
End Sub
That works like a charm, and it moves on.
Once Form1 is loaded, its showing me the correct files from the server folder..
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For Each i As String In Directory.GetFiles("\\192.168.0.247\Database")
Objectlist1.Items.Add(Path.GetFileName(i))
Next
Objectlist1.Refresh()
End Sub
And when I save files to it
Private Sub Savebutton_Click(sender As Object, e As EventArgs) Handles Savebutton.Click
If IO.File.Exists(Pholderbox.Text) = False Then
Dim settings As New XmlWriterSettings()
settings.Indent = True
Dim XmlWrt As XmlWriter = XmlWriter.Create("\\192.168.0.247\Database\" + Pholderbox.Text, settings)
With XmlWrt
All of that, works as intended.
I want to mention that the folder in Question, or "Share" in question on the server, is password protected, and the username and password are inserted in the Login Code (Temporary)
My problem comes here when I doubleclick the file (activate) to READ it.
Private Sub Objectlist1_ItemActivate(sender As Object, e As EventArgs) Handles Objectlist1.ItemActivate
Caseworker.Show()
Me.Objectlist1.MultiSelect = False
Dim selectedListViewItem As String
selectedListViewItem = Me.Objectlist1.SelectedItems.Item(0).ToString
Const basepath As String = "\\192.168.0.247\Database"
Dim xmlpath = IO.Path.Combine(basepath, Objectlist1.SelectedItems.Item(0).Text)
If (IO.File.Exists(xmlpath)) Then
Dim document As XmlReader = New XmlTextReader(basepath)
Dim mySessionOptions As New SessionOptions
While (document.Read())
' - This little bugger screams out everytime
' "An unhandled exception of type 'System.UnauthorizedAccessException' occurred in System.Xml.dll
' Additional information: Access to the path '\\192.168.0.247\Database' is denied."
What in the world is wrong here? I would assume since it can list the content of that folder, and for testing I gave EVERYONE Full access to that folder (User, Group, Other) FULL Access on Linux (0777)
I put it like that to test if it would help.
This might be out of your expertize, as it involves the library WinSCP and is in fact a Linux Server.
Being that its only the "Read XML" feature that denies it, I must be very close?
I see that very many suggest other Third Party libraries, the best for me, would be a solution in plain VB.NET if possible.
You are combining SFTP login with an access to a remote resource via UNC path. This cannot work. Either use the SFTP only (what you can use WinSCP .NET assembly for) or login to the remote (Samba?) server, so that you can use UNC paths only.
An SFTP solution follows. I do not know VB.NET, so excuse mistakes in syntax. Also note, that you need to make the mySession global, so that you can access it from other functions.
Loading list of remote files:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For Each i As RemoteFileInfo In mySession.ListDirectory("/Database").Files
Objectlist1.Items.Add(i.Name)
Next
Objectlist1.Refresh()
End Sub
Reference: https://winscp.net/eng/docs/library_session_listdirectory
Saving:
Private Sub Savebutton_Click(sender As Object, e As EventArgs) Handles Savebutton.Click
Dim settings As New XmlWriterSettings()
settings.Indent = True
Dim TempPath As String = IO.Path.Combine(IO.Path.GetTempPath, Pholderbox.Text);
Dim XmlWrt As XmlWriter = XmlWriter.Create(TempPath , settings)
With XmlWrt
End With
mySession.PutFiles(TempPath, "/Database/").Check()
End Sub
Reference: https://winscp.net/eng/docs/library_session_putfiles
Loading:
Private Sub Objectlist1_ItemActivate(sender As Object, e As EventArgs) Handles Objectlist1.ItemActivate Caseworker.Show()
Me.Objectlist1.MultiSelect = False
Dim selectedListViewItem As String
selectedListViewItem = Me.Objectlist1.SelectedItems.Item(0).ToString
Dim xmlpath = IO.Path.Combine(IO.Path.GetTempPath, Objectlist1.SelectedItems.Item(0).Text)
mySession.GetFiles("/Database/" + Objectlist1.SelectedItems.Item(0).Text, xmlpath).Check();
If (IO.File.Exists(xmlpath)) Then
Dim document As XmlReader = New XmlTextReader(basepath)
Dim mySessionOptions As New SessionOptions
While (document.Read())
Reference: https://winscp.net/eng/docs/library_session_getfiles

Resources