Retrieveing video/audio duration using WindowsAPICodecPack and Shell - azure

I have the following code to retrieve the duration of a video uploaded:
HttpPostedFileBase postedFileCopy = postedFile;
postedFileCopy.InputStream.Position = 0;
Stream stream = postedFile.InputStream;
LocalResource tempDirectory = RoleEnvironment.GetLocalResource("TempZipDirectory");
postedFile.SaveAs(tempDirectory.RootPath + #"\" + postedFile.FileName);
ShellFile so = ShellFile.FromFilePath(tempDirectory.RootPath + #"\" + postedFile.FileName);
string durationString;
double nanoseconds;
double.TryParse(so.Properties.System.Media.Duration.Value.ToString(),out nanoseconds);
if (nanoseconds > 0)
{
int totalSeconds = (int)Math.Round((nanoseconds / 10000000), 0);
int seconds = totalSeconds % 60;
int minutes = totalSeconds / 60;
int hour = totalSeconds / (60 * 60);
durationString = "" + hour + ":" + minutes + ":" + seconds;
}
else
{
System.Diagnostics.EventLog.WriteEntry("Application", "BLANK DURATION STRING", System.Diagnostics.EventLogEntryType.Error);
durationString = "00:00:00";
}
This works as expected on localhost but when put up to Azure storage it does not seem to be able to retrieve the details of the file. The
postedFile.SaveAs(tempDirectory.RootPath + #"\" + postedFile.FileName);
saves the upload to the directory so i can grab these details but no matter what i try I cant seem to get the nanoseconds returned when the storage is on azure. This is a deployed MVC application and the tempdirectory is stored on the C:/ drive of the server.

The code you refer is using native (Shell) functions. As AzureWebSites is running as a high-density shared environment, your code runs into non-full-trust mode. Calls to native functions is restricted in Azure Web Sites, even if you scale to reserved mode instances.
UPDATE
The only way to get application executed under FULL TRUST is to use Web Role (for web projects) or Worker Role (for background tasks).
Read more about cloud services here.

Related

How can Create timedown

I wanna to create a timedown with mongoose and excited an function at the end of time.
I have a quiz and I wanna at the end of time logout from quiz page. code implemented with nodejs
You can try this:
// Set the date we're counting down to
var countDownDate = new Date("Jan 5, 2022 15:37:25").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
<p id="demo"></p>
This is an example of js timedown for js/dom.
and you can easily change the document.getElementById() by any var you want.
I would say to create a token (jwt) including the timestamp of the quiz starts on the server, user_id, and quiz_id and pass it to the client application. Then you might tick the timer in the ejs app itself using the native js function setInterval() and can automatically trigger an exit from the quiz page when ticker time reaches the quiz expiry time.
For each answer submission, you may pass that token created on quiz initiation to the server alongside submission details, so that server can validate whether that token is still valid to use (based on the quiz expiry time). So by the time expires, the server will no longer accept answers for that particular quiz since the token gets expired.
You may include the business logic based on your needs, this is a more generic answer for your generic question. (This might not be the best way of implementing a quiz, but this works with minimal server requests.)

How to prevent Execution usage limit in scheduled scripts

I am using the scheduled script which will create the custom records based on criteria. every time when the schedule script runs it should create approx. 100,000 records but the script is timing out after creating 5000 or 10000 records. I am using the below script to prevent the script execution usage limit but even with this also the script is not working. can any one please suggest some thing or provide any information. any suggestions are welcome and highly appreciated.
In my for loop iam using the below script. with this below script included the scheduled script is able to create up to 5000 or 10000 records only.
if (nlapiGetContext().getRemainingUsage() <= 0 && (i+1) < results.length )
{
var stateMain = nlapiYieldScript();
}
If you are going to reschedule using the nlapiYieldScript mechanism, then you also need to use nlapiSetRecoveryPoint at the point where you wish the script to resume. See the Help documentation for each of these methods, as well as the page titled Setting Recovery Points in Scheduled Scripts
Be aware that nlapiSetRecoveryPoint uses 100 governance units, so you will need to account for this in your getRemainingUsage check.
#rajesh, you are only checking the remaining usage. Also do check for execution time limit, which is 1 hour for any scheduled script. Something like below snippet-
var checkIfYieldOrContinue = function(startTime) {
var endTime = new Date().getTime();
var timeElapsed = (endTime * 0.001) - (startTime * 0.001);
if (nlapiGetContext().getRemainingUsage() < 3000 ||
timeElapsed > 3500) { //3500 secs
nlapiLogExecution('AUDIT', 'Remaining Usage: ' + nlapiGetContext().getRemainingUsage() + '. Time elapsed: ' + timeElapsed);
startTime = new Date().getTime();
var yieldStatus = nlapiYieldScript();
nlapiLogExecution('AUDIT', 'script yielded.' + yieldStatus.status);
nlapiLogExecution('AUDIT', 'script yielded reason.' + yieldStatus.reason);
nlapiLogExecution('AUDIT', 'script yielded information.' + yieldStatus.information);
}
};
Inside your for loop, you can call this method like-
var startTime = new Date();
if ((i+1) < results.length ) {
//do your operations here and then...
checkIfYieldOrContinue(startTime);
}
I have a script that lets you process an array like a forEach. The script checks each iteration and calculates the maximum usage and yields when there is not enough usage left to cover the max.
Head over to https://github.com/BKnights/KotN-Netsuite and download simpleBatch.js

RDP to call an EXE file, not the whole desktop

I have used this code to implement RDP.
This works fine but now I want to implement a system , that will call a particular EXE file from the server. Not the whole desktop.
Any idea how can I implement this?
Process rdcProcess = new Process();
rdcProcess.StartInfo.FileName = Environment.ExpandEnvironmentVariables(#"%SystemRoot%\system32\cmdkey.exe");
rdcProcess.StartInfo.Arguments = "/generic:TERMSRV/192.168.0.16 /user:" +Saltlake1" + " /pass:" + "saltlake#1234";
rdcProcess.Start();
rdcProcess.StartInfo.FileName = Environment.ExpandEnvironmentVariables(#"%SystemRoot%\system32\mstsc.exe");
rdcProcess.StartInfo.Arguments = "/v " + "192.168.0.16";
rdcProcess.Start();

How to publish a countdown via gmail status?

Please is it possible to publish a countdown in my gmail status?
Like "01:44:15:23" and its decrements continually.
Found a good article to share:
Google Talk uses XMPP then if you can connect using an XMPP client to your Google account you can use the client instead of Google talk.
The whole mechanism is too simple (Used the Smack XMPP Library because it is simple and serves me well):
Login.
Calculate difference between now and the targeted date.
Send the presence
Login
import org.jivesoftware.smack.XMPPConnection;
public void connect() {
XMPPConnection connection = new XMPPConnection(server); //Server is gmail.com for Google Talk.
connection.connect();
connection.login(username, password); //Username and password.
}
Calculate difference between now and the targeted date
This process is done using Java Calendar and Date objects:
import java.util.Calendar;
import java.util.Date;
{
Calendar calendar1 = Calendar.getInstance();
Date d = new Date();
calendar1.setTime(d);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(endLine); //End line is the date we're counting to.
long milliseconds1 = calendar1.getTimeInMillis();
long milliseconds2 = calendar2.getTimeInMillis();
long diff = milliseconds2 - milliseconds1;
long diffDays = diff / (24 * 60 * 60 * 1000);
diff = diff % (24 * 60 * 60 * 1000);
long diffHours = diff / (60 * 60 * 1000);
diff = diff % (60 * 60 * 1000);
long diffMinutes = diff / (60 * 1000);
diff = diff % (60 * 1000);
}
This code calculates the difference between the two dates in days, hours and minutes.
Send the presence
After calculating the difference all we have to do is to send the presence:
import org.jivesoftware.smack.packet.Presence;
{
String remaining = Long.toString(diffDays) + " day(s), " + Long.toString(diffHours) + " hour(s), " + Long.toString(diffMinutes) + " minute(s) " + message; //Message is usually: Until "something".
Presence presence = new Presence(Presence.Type.available);
presence.setStatus(remaining);
presence.setPriority(24); //Highest priority in Google Talk
presence.setMode(presenceMode); //This is one of XMPP modes (Available, Chat, DND, Away, XA).
connection.sendPacket(presence);
}
After this point people will see your new status instead of the one in Google Talk. (Notice that you won’t be able to see the change inside Google Talk but rest assured it is changed.f you wanna make sure it is changed ask one of your friends to tell you your status).
Its very simple just download status-counter.jar from here and write a script file
java -jar /root/status-counter.jar -status SF -username username#gmail.com -password XXXXXX -datetime 2013-03-21T16:00:00+02:00 -type hours -decimals 0
and write a cron to do the job
*/5 * * * * /path/script.sh > /dev/null
this updates your status every 5 minutes. More details can be found here.

How to validate local VM clock with NTP on Windows Azure?

NTP (Network Time Protocol) is basically the de-facto standard to adjust setup server clocks. I have already raised a question about the expectations in terms of native clock accuracy on Windows Azure. Here comes a slightly different one: how I can validate the current clock reliability with NTP? The catch is that UDP is not available on Windows Azure (only TCP), and it seems there is no TCP implementation available of NTP (although the discussion is nearly one decade old).
Any take?
Assuming that UDP outgoing packets are still blocked by Azure (I'm surprised/disappointed this is still the case!) then maybe you could drop down to a TCP service with less resolution such as TIME or DAYTIME - see descriptions of both on http://www.nist.gov/pml/div688/grp40/its.cfm - you would obviously need to measure the length of time your network call took in order to be sure the answer coming back is sufficiently accurate for you.
Joannes and Stuart: You are correct that Windows Azure roles (Web, Worker, and VM Roles) do not support hosting of UDP endpoints currently. However, NTP support is already included by default on Windows Azure role VMs, currently configured by default to synch the clock against server time.windows.com once a week (evidence here - search for "time service").
You can tweak a registry setting in a Startup Task if a weekly sync is not frequent enough.
HTH!
I'm a bit surprised by your answer about udp while i'm actually connect to NTP server from my azure web role to serve our JS client synchronization.
This is working fine...
Note the azure web role time is a lot different thant the NTP one ( actually 30s ahead !! ). However, the NTP time is nearly the same as my local machine synchronized with time.microsoft.com
{"network":"2013-07-16T18:18:25.9558581Z","server":"2013-07-16T18:18:52.5415999Z"}
Here the code i use :
static uint SwapEndianness(ulong x)
{
return (uint)(((x & 0x000000ff) << 24) +
((x & 0x0000ff00) << 8) +
((x & 0x00ff0000) >> 8) +
((x & 0xff000000) >> 24));
}
static DateTime Update(string server)
{
// NTP message size - 16 bytes of the digest (RFC 2030)
var ntpData = new byte[48];
//Setting the Leap Indicator, Version Number and Mode values
ntpData[0] = 0x1B; //LI = 0 (no warning), VN = 3 (IPv4 only), Mode = 3 (Client Mode)
var addresses = Dns.GetHostEntry(server).AddressList;
//The UDP port number assigned to NTP is 123
var ipEndPoint = new IPEndPoint(addresses[0], NTPPort);
//NTP uses UDP
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Connect(ipEndPoint);
socket.Send(ntpData);
DateTime l_now = DateTime.UtcNow;
socket.Receive(ntpData);
socket.Close();
//Offset to get to the "Transmit Timestamp" field (time at which the reply
//departed the server for the client, in 64-bit timestamp format."
const byte serverReplyTime = 40;
//Get the seconds part
ulong intPart = BitConverter.ToUInt32(ntpData, serverReplyTime);
//Get the seconds fraction
ulong fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 4);
//Convert From big-endian to little-endian
intPart = SwapEndianness(intPart);
fractPart = SwapEndianness(fractPart);
var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
//**UTC** time
var l_networkTime = (new DateTime(_epocBaseTicks, DateTimeKind.Utc)).AddMilliseconds((long)milliseconds);
_networkTimeDelta = l_networkTime.Ticks - l_now.Ticks ;
return l_networkTime;
}
Hope this help.

Resources