This is a html file which contains web speech API code. I want convert this to a web service and hope use it as a reference in windows forms application in c#. I have no idea how to do that and if someone can give some instructions to do that it will be grateful.
Thank you!
<!DOCTYPE html>
<meta charset="utf-8">
<title>Voice To Text</title>
<style>
* {
font-family: Verdana, Arial, sans-serif;
}
a:link {
color:#000;
text-decoration: none;
}
a:visited {
color:#000;
}
a:hover {
color:#33F;
}
.button {
background: -webkit-linear-gradient(top,#008dfd 0,#0370ea 100%);
border: 1px solid #076bd2;
border-radius: 3px;
color: #fff;
display: none;
font-size: 13px;
font-weight: bold;
line-height: 1.3;
padding: 8px 25px;
text-align: center;
text-shadow: 1px 1px 1px #076bd2;
letter-spacing: normal;
}
.center {
padding: 10px;
text-align: center;
}
.final {
color: black;
padding-right: 3px;
}
.interim {
color: gray;
}
.info {
font-size: 14px;
text-align: center;
color: #777;
display: none;
}
.right {
float: right;
}
.sidebyside {
display: inline-block;
width: 45%;
min-height: 40px;
text-align: left;
vertical-align: top;
}
#headline {
font-size: 40px;
font-weight: 300;
}
#info {
font-size: 20px;
text-align: center;
color: #777;
visibility: hidden;
}
#results {
font-size: 14px;
font-weight: bold;
border: 1px solid #ddd;
padding: 15px;
text-align: left;
min-height: 150px;
}
#start_button {
border: 0;
background-color:transparent;
padding: 0;
}
</style>
<h1 class="center" id="headline">
<a href="http://dvcs.w3.org/hg/speech-api/raw-file/tip/speechapi.html">
Web Speech API</a> Demonstration</h1>
<div id="info">
<p id="info_start">Click on the microphone icon and begin speaking.</p>
<p id="info_speak_now">Speak now.</p>
<p id="info_no_speech">No speech was detected. You may need to adjust your
<a href="//support.google.com/chrome/bin/answer.py?hl=en&answer=1407892">
microphone settings</a>.</p>
<p id="info_no_microphone" style="display:none">
No microphone was found. Ensure that a microphone is installed and that
<a href="//support.google.com/chrome/bin/answer.py?hl=en&answer=1407892">
microphone settings</a> are configured correctly.</p>
<p id="info_allow">Click the "Allow" button above to enable your microphone.</p>
<p id="info_denied">Permission to use microphone was denied.</p>
<p id="info_blocked">Permission to use microphone is blocked. To change,
go to chrome://settings/contentExceptions#media-stream</p>
<p id="info_upgrade">Web Speech API is not supported by this browser.
Upgrade to Chrome
version 25 or later.</p>
</div>
<div class="right">
<button id="start_button" onclick="startButton(event)">
<img id="start_img" src="mic.gif" alt="Start"></button>
</div>
<div id="results">
<span id="final_span" class="final"></span>
<span id="interim_span" class="interim"></span>
<p>
</div>
<div class="center">
<div class="sidebyside" style="text-align:right">
<button id="copy_button" class="button" onclick="copyButton()">
Copy and Paste</button>
<div id="copy_info" class="info">
Press Control-C to copy text.<br>(Command-C on Mac.)
</div>
</div>
<div class="sidebyside">
<button id="email_button" class="button" onclick="emailButton()">
Create Email</button>
<div id="email_info" class="info">
Text sent to default email application.<br>
(See chrome://settings/handlers to change.)
</div>
</div>
<p>
<div id="div_language">
<select id="select_language" onchange="updateCountry()"></select>
<select id="select_dialect"></select>
</div>
</div>
<script>
var langs =
[['Afrikaans', ['af-ZA']],
['Bahasa Indonesia',['id-ID']],
['Bahasa Melayu', ['ms-MY']],
['Català', ['ca-ES']],
['Čeština', ['cs-CZ']],
['Deutsch', ['de-DE']],
['English', ['en-AU', 'Australia'],
['en-CA', 'Canada'],
['en-IN', 'India'],
['en-NZ', 'New Zealand'],
['en-ZA', 'South Africa'],
['en-GB', 'United Kingdom'],
['en-US', 'United States']],
['Español', ['es-AR', 'Argentina'],
['es-BO', 'Bolivia'],
['es-CL', 'Chile'],
['es-CO', 'Colombia'],
['es-CR', 'Costa Rica'],
['es-EC', 'Ecuador'],
['es-SV', 'El Salvador'],
['es-ES', 'España'],
['es-US', 'Estados Unidos'],
['es-GT', 'Guatemala'],
['es-HN', 'Honduras'],
['es-MX', 'México'],
['es-NI', 'Nicaragua'],
['es-PA', 'Panamá'],
['es-PY', 'Paraguay'],
['es-PE', 'Perú'],
['es-PR', 'Puerto Rico'],
['es-DO', 'República Dominicana'],
['es-UY', 'Uruguay'],
['es-VE', 'Venezuela']],
['Euskara', ['eu-ES']],
['Français', ['fr-FR']],
['Galego', ['gl-ES']],
['Hrvatski', ['hr_HR']],
['IsiZulu', ['zu-ZA']],
['Íslenska', ['is-IS']],
['Italiano', ['it-IT', 'Italia'],
['it-CH', 'Svizzera']],
['Magyar', ['hu-HU']],
['Nederlands', ['nl-NL']],
['Norsk bokmål', ['nb-NO']],
['Polski', ['pl-PL']],
['Português', ['pt-BR', 'Brasil'],
['pt-PT', 'Portugal']],
['Română', ['ro-RO']],
['Slovenčina', ['sk-SK']],
['Suomi', ['fi-FI']],
['Svenska', ['sv-SE']],
['Türkçe', ['tr-TR']],
['български', ['bg-BG']],
['Pусский', ['ru-RU']],
['Српски', ['sr-RS']],
['한국어', ['ko-KR']],
['中文', ['cmn-Hans-CN', '普通话 (中国大陆)'],
['cmn-Hans-HK', '普通话 (香港)'],
['cmn-Hant-TW', '中文 (台灣)'],
['yue-Hant-HK', '粵語 (香港)']],
['日本語', ['ja-JP']],
['Lingua latīna', ['la']]];
for (var i = 0; i < langs.length; i++) {
select_language.options[i] = new Option(langs[i][0], i);
}
select_language.selectedIndex = 6;
updateCountry();
select_dialect.selectedIndex = 6;
showInfo('info_start');
function updateCountry() {
for (var i = select_dialect.options.length - 1; i >= 0; i--) {
select_dialect.remove(i);
}
var list = langs[select_language.selectedIndex];
for (var i = 1; i < list.length; i++) {
select_dialect.options.add(new Option(list[i][1], list[i][0]));
}
select_dialect.style.visibility = list[1].length == 1 ? 'hidden' : 'visible';
}
var create_email = false;
var final_transcript = '';
var recognizing = false;
var ignore_onend;
var start_timestamp;
if (!('webkitSpeechRecognition' in window)) {
upgrade();
} else {
start_button.style.display = 'inline-block';
var recognition = new webkitSpeechRecognition();
recognition.continuous = true;
recognition.interimResults = true;
recognition.onstart = function() {
recognizing = true;
showInfo('info_speak_now');
start_img.src = 'mic-animate.gif';
};
recognition.onerror = function(event) {
if (event.error == 'no-speech') {
start_img.src = 'mic.gif';
showInfo('info_no_speech');
ignore_onend = true;
}
if (event.error == 'audio-capture') {
start_img.src = 'mic.gif';
showInfo('info_no_microphone');
ignore_onend = true;
}
if (event.error == 'not-allowed') {
if (event.timeStamp - start_timestamp < 100) {
showInfo('info_blocked');
} else {
showInfo('info_denied');
}
ignore_onend = true;
}
};
recognition.onend = function() {
recognizing = false;
if (ignore_onend) {
return;
}
start_img.src = 'mic.gif';
if (!final_transcript) {
showInfo('info_start');
return;
}
showInfo('');
if (window.getSelection) {
window.getSelection().removeAllRanges();
var range = document.createRange();
range.selectNode(document.getElementById('final_span'));
window.getSelection().addRange(range);
}
if (create_email) {
create_email = false;
createEmail();
}
};
recognition.onresult = function(event) {
var interim_transcript = '';
for (var i = event.resultIndex; i < event.results.length; ++i) {
if (event.results[i].isFinal) {
final_transcript += event.results[i][0].transcript;
} else {
interim_transcript += event.results[i][0].transcript;
}
}
final_transcript = capitalize(final_transcript);
final_span.innerHTML = linebreak(final_transcript);
interim_span.innerHTML = linebreak(interim_transcript);
if (final_transcript || interim_transcript) {
showButtons('inline-block');
}
};
}
function upgrade() {
start_button.style.visibility = 'hidden';
showInfo('info_upgrade');
}
var two_line = /\n\n/g;
var one_line = /\n/g;
function linebreak(s) {
return s.replace(two_line, '<p></p>').replace(one_line, '<br>');
}
var first_char = /\S/;
function capitalize(s) {
return s.replace(first_char, function(m) { return m.toUpperCase(); });
}
function createEmail() {
var n = final_transcript.indexOf('\n');
if (n < 0 || n >= 80) {
n = 40 + final_transcript.substring(40).indexOf(' ');
}
var subject = encodeURI(final_transcript.substring(0, n));
var body = encodeURI(final_transcript.substring(n + 1));
window.location.href = 'mailto:?subject=' + subject + '&body=' + body;
}
function copyButton() {
if (recognizing) {
recognizing = false;
recognition.stop();
}
copy_button.style.display = 'none';
copy_info.style.display = 'inline-block';
showInfo('');
}
function emailButton() {
if (recognizing) {
create_email = true;
recognizing = false;
recognition.stop();
} else {
createEmail();
}
email_button.style.display = 'none';
email_info.style.display = 'inline-block';
showInfo('');
}
function startButton(event) {
if (recognizing) {
recognition.stop();
return;
}
final_transcript = '';
recognition.lang = select_dialect.value;
recognition.start();
ignore_onend = false;
final_span.innerHTML = '';
interim_span.innerHTML = '';
start_img.src = 'mic-slash.gif';
showInfo('info_allow');
showButtons('none');
start_timestamp = event.timeStamp;
}
function showInfo(s) {
if (s) {
for (var child = info.firstChild; child; child = child.nextSibling) {
if (child.style) {
child.style.display = child.id == s ? 'inline' : 'none';
}
}
info.style.visibility = 'visible';
} else {
info.style.visibility = 'hidden';
}
}
var current_style;
function showButtons(style) {
if (style == current_style) {
return;
}
current_style = style;
copy_button.style.display = style;
email_button.style.display = style;
copy_info.style.display = 'none';
email_info.style.display = 'none';
}
</script>
Related
Model
public class Jobs
{
public List<string> JobNames { get; set; }
}
Controllers
public class HomeController : Controller
{
public static List<string> sorteddailyreports= new List<string>();
static Jobs jobnames;
public static List<string> dailyreports = new List<string>();
public ActionResult GetJobs()
{
jobnames =new Jobs();
dailyreports = new List<string> { "M2I|0705","FGI|1220","SDI|0100" };
sorteddailyreports=dailyreports.ToList().OrderBy(x=> x.Split('|')[1].Trim()).ToList();
jobnames.JobNames = sorteddailyreports;
return View(jobnames);
}
public static int IsJobRan(string job)
{
int completed = 0;
if (true) //some condition
{
completed = 1;
}
else
{
completed = -1;
}
return completed;
}
}
View
#model WebApplication1.Models.Jobs
<body>
#foreach(string jobdetails in Model.JobNames)
{
string job = jobdetails.Split('|')[0].Trim();
string runtime = jobdetails.Split('|')[1].Trim();
string fruntime = runtime.Substring(0, 2) + ":" + runtime.Substring(2, 2);
if (WebApplication1.Controllers.HomeController.IsJobRan(jobdetails)==1)
{
<tr>
#Html.Label(job)
</tr>
<tr>
#Html.Label(fruntime)
</tr>
}
<br />
}
</body>
I am expecting in view if the method return 1 it means jobs completed then completed job should go down and if the method returns other than 1 the job is sorted on the basis of runtime.
For example: if M2I job runs successfully and returns 1, then the Output which I am expecting in view. Completed Job M2I should go down and other jobs like SDI and FGI are sorted on the basis of runtime.
SDI 0100
FGI 1220
M2I 0705
Code which I am trying but didn't get the desired result
sorteddailyreports = dailyreports.ToList()
.OrderBy(x => x.Split('|')[1].Trim())
.ToList();
Please amend the code, I am new in Asp.net MVC Thanks in advance.
I am trying Generic Move method for moving the Completed List to last on the Front End page.
Add this logic in Controller to move completed list to last index still not able to get sorting on front end. call this method in view still Not sure this Move method is a workable solution for sorting at front end.
public static void Move(List<string> list, int newIndex, int oldIndex)
{
var item = list[oldIndex];
list.RemoveAt(oldIndex);
if (newIndex > oldIndex) newIndex--;
list.Insert(newIndex, item);
}
You can check the Front-end gif picture first.
And the code here.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>css3 dynamic</title>
</head>
<style>
*{
margin: 0;
padding: 0;
box-sizing: border-box;
list-style: none;
font-size: 12px;
}
.box{
width: 600px;
height: 500px;
margin: 100px auto;
}
.skill {
width: 100%;
list-style: none;
}
.skill li {
position: relative;
margin-bottom: 25px;
}
.skill li .expand-box{
width: 100%;
margin-top: 20px;
margin-bottom: 10px;
height: 15px;
border-radius: 3px;
border: 1px solid #092c99;
position: relative;
}
.skill li em:first-child {
position: absolute;
top: -15px;
left: 0;
}
.skill li em:last-child {
position: absolute;
top: -15px;
right: 0;
}
.expand {
height: 13px;
margin: 0;
top: 0;
background: #2187e7;
position: absolute;
border-radius: 3px;
box-shadow: 0px 0px 10px 1px rgba(0, 198, 255, 0.4);
}
</style>
<body>
<div class="box">
<ul class="skill" id="chart"></ul>
</div>
<script src="https://code.jquery.com/jquery-3.6.3.js" integrity="sha256-nQLuAZGRRcILA+6dMBOvcRh5Pe310sBpanc6+QBmyVM=" crossorigin="anonymous"></script>
<script>
$(document).ready(function(){
let listdata = [
{"data1":"Job 1","data2":54},
{"data1":"Job 2","data2":3},
{"data1":"Job 3","data2":12},
{"data1":"Job 4","data2":65},
{"data1":"Job 5","data2":3}
];
const compareData2 = (arrayItemA, arrayItemB) => {
if (arrayItemA.data2 < arrayItemB.data2) {
return 1
}
if (arrayItemA.data2 > arrayItemB.data2) {
return -1
}
return 0
}
const objectComparisonCallback = (arrayItemA, arrayItemB) => {
// first sort by data2
return compareData2(arrayItemA, arrayItemB)
}
listdata.sort(objectComparisonCallback)
loadData(listdata);
var job3 = setInterval(function(){
//find Job3
const index = listdata.findIndex(object => {
return object.data1 === "Job 3";
}); // 👉️ 1
if (index !== -1) {
if(listdata[index].data2< 100){
listdata[index].data2 += 1;
$('#chart').empty();
listdata.sort(objectComparisonCallback);
loadData(listdata);
//clear all the css style about the .animations2
$(".animations"+index).css("width",listdata[index].data2+"%")
}
else{
console.log("Job 3 COMPLETED!");
clearInterval(job3);
}
}
}, 100);
})
function loadData(listdata){
let _html = '';
let len = listdata.length;
if(len > 0){
for(let i = 0; i < len; i++){
_html += '<li>';
_html += '<em>'+listdata[i]['data1']+'</em>';
_html += '<div class="expand-box"><span class="expand animations'+i+'"></span></div>';
_html += '<em>'+listdata[i]['data2']+'%</em>';
_html += '</li>';
let newStyle=document.styleSheets[0];
newStyle.insertRule(
".animations"+i+" { " +
"width: "+listdata[i]['data2']+"%;" +
"-moz-animation:animations"+i+" 0s ease-out;" +
"-webkit-animation:animations"+i+" 0s ease-out;" +
"}", 0);
newStyle.insertRule(
"#keyframes animations"+i+"{ " +
"0% { width: 0; } " +
"100% { width:"+listdata[i]['data2']+" % }" +
"}",0);
$('#chart').html(_html);
}
}else{
$('#chart').html('No Data');
}
}
</script>
</body>
</html>
You should learn the signalr in asp.net core.
The use of Signalr can carry out real-time communication very well, and the background task execution process can be sent to the front-end page through websocket in real time. You can implement the sorting of the front-end pages according to your needs.
Here is a complete sample code, you can refer to the blog to realize your needs.
Communicate the status of a background job with SignalR
I am creating dinamically controls from code-behind, such as textbox, checkboxlist, radiobuttonlist, etc etc... and adding them in a placeholder inside a repeater, in order to create a dynamic survey from a template-user-made, the questions of the survey I want 'em to be created from code-behind, but if there's any other way for creating dynamically the controls, could you guys guide me with a specific topic or show me a code-example?
I was thinking something like..
AjaxControlToolkit.Rating rateThing = new AjaxControlToolkit.Rating();
rateThing.CurrentRating = 3;
rateThing.MaxRating = 5;
rateThing.StarCssClass = "ratingStar";
rateThing.WaitingStarCssClass = "savedRatingStar";
rateThing.FilledStarCssClass = "filledRatingStar";
rateThing.EmptyStarCssClass = "emptyRatingStar";
rateThing.ID = "rateThing" + IdPregunta.Value;
rateThing.Visible = true;
placeholder.Controls.Add(rateThing);
but it doesn't render ...
P.D. I already added the images the example need in the css to create the stars of the control, tried reading about rating in MS with this rating ajaxtoolkit stuff and with other stuff without success :(
EDITED: Never got figured it out so I choose for an RadioButtonList for creating the control in codebehind then using CSS and JS/JQuery for creating the real pseudocontrol of rating
You could use this as a guide for the codebehind
RadioButtonList rblEscala = new RadioButtonList();
rblEscala.ID = "rblRes" + IdPregunta.Value;
rblEscala.CssClass = "input-sm form-control col-sm-12 star-cb-group";
rblEscala.Style.Add("height", "auto !important;");
for (int i = 5; i >= 1; i--)
{
rblEscala.Items.Add(new ListItem("☆", i.ToString()));
}
rblEscala.RepeatDirection = RepeatDirection.Horizontal;
placeholder.Controls.Add(rblEscala);
In the front use this link as reference: https://codepen.io/anon/pen/PKxQYY
I'll free my code so you can use it, as a base for your custom rating
hehehe
For the CodeBehind try using a PlaceHolder and using this:
RadioButtonList rblEscala = new RadioButtonList();
rblEscala.ID = "rblRes";
rblEscala.CssClass = "star-cb-group";
rblEscala.Style.Add("height", "auto !important;");
for (int i = 5; i >= 1; i--)
{
//rblEscala.Items.Add(new ListItem(i.ToString(), i.ToString()));
rblEscala.Items.Add(new ListItem("☆", i.ToString()));
}
rblEscala.RepeatDirection = RepeatDirection.Horizontal;
placeholder.Controls.Add(rblEscala);
For CSS Use this:
.star-cb-group {
/* remove inline-block whitespace */
font-size: 0;
/* flip the order so we can use the + and ~ combinators */
unicode-bidi: bidi-override;
direction: rtl;
/* the hidden clearer */
}
.star-cb-group tbody {
float: left;
}
.star-cb-group * {
font-size: 2.5rem;
}
.star-cb-group input {
display: none;
background: none;
}
.star-cb-group label {
background: none !important;
padding-left: 5px !important;
height: auto !important;
}
.star-cb-group input + label {
color: #888;
}
.star-cb-group input:checked + label {
color: #e52;
}
For JS/Jquery I added this:
try {
$(".star-cb-group input").change(function () {
//$(this).next().text("★");
var inputs = $(this).parent().parent().children().children("input");
var bandera = false;
inputs.each(function () {
if ($(this).is(':checked') || bandera) {
$(this).next().text("★");
$(this).next().css("color", "#e52");
$(this).next().css("font-weight", "Bold !important");
bandera = true;
} else {
$(this).next().text("☆");
$(this).next().css("color", "#888");
$(this).next().css("font-weight", "normal !important");
}
});
});
} catch (err2) {
console.log(err2);
}
I am programming an application that should give the local time based on the coordinates (lat&long) that you give it.
I only know of 2 methods to do that:
1st: Get the TimeZone Name, and then find its local time.
2nd: Use the Google API and receive the time as an offset and UTC not Local.
I decided to use the 1st method because seemed easier, so I decided to use the GeoTimeZone to get the Time Zone... Problem is that then I don´t know how to get the local time on that TimeZone... Here´s the code I wrote to get the TimeZone name.
string tz = TimeZoneLookup.GetTimeZone(lat, lon).Result;
variables lat & lon are of course the coordinates.
Thank you!
Edit: My question is how can I get the LocalTime on that TimeZone?
Here's my solution. It works offline (so no call to an api). It's fast and the packages are widely used and available on Nuget.
string tzIana = TimeZoneLookup.GetTimeZone(lat, lng).Result;
TimeZoneInfo tzInfo = TZConvert.GetTimeZoneInfo(tzIana);
DateTimeOffset convertedTime = TimeZoneInfo.ConvertTime(DateTimeOffset.UtcNow, tzInfo);
You can do it using Google api for identifying current timezone.
.Net Fiddle example:
public class Program
{
public static DateTime GetLocalDateTime(double latitude, double longitude, DateTime utcDate)
{
var client = new RestClient("https://maps.googleapis.com");
var request = new RestRequest("maps/api/timezone/json", Method.GET);
request.AddParameter("location", latitude + "," + longitude);
request.AddParameter("timestamp", utcDate.ToTimestamp());
request.AddParameter("sensor", "false");
var response = client.Execute<GoogleTimeZone>(request);
return utcDate.AddSeconds(response.Data.rawOffset + response.Data.dstOffset);
}
public static void Main()
{
var myDateTime = GetLocalDateTime(33.8323, -117.8803, DateTime.UtcNow);
Console.WriteLine(myDateTime.ToString());
}
}
public class GoogleTimeZone
{
public double dstOffset { get; set; }
public double rawOffset { get; set; }
public string status { get; set; }
public string timeZoneId { get; set; }
public string timeZoneName { get; set; }
}
public static class ExtensionMethods
{
public static double ToTimestamp(this DateTime date)
{
DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
TimeSpan diff = date.ToUniversalTime() - origin;
return Math.Floor(diff.TotalSeconds);
}
}
And then you can easily use your GetLocalDateTime(double latitude, double longitude, DateTime utcDate) method as it was shown in the example above:
public static void Main()
{
var myDateTime = GetLocalDateTime(33.8323, -117.8803, DateTime.UtcNow);
Console.WriteLine(myDateTime.ToString());
}
Finally this is how I fixed it, I needed to use the TimeZoneDb livery which traduces the IANA TimeZone to the Microsoft Format, so this is the code to do it:
string tz1 = TimeZoneLookup.GetTimeZone(lat, lon).Result;
var timeZoneDbUseCases = new TimeZoneDbUseCases();
var allTimeZones = timeZoneDbUseCases.GetAllTimeZones();
var timeZone = timeZoneDbUseCases.GetTimeZoneWithIanaId(tz1);
var timeZone1 = TimeZoneInfo.FindSystemTimeZoneById(timeZone.MicrosoftId);
var localTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, timeZone1);
Thanks to anyone who helped, both the solutions helped me a lot and maybe without them I couldn´t achieve it.
Thank you very much!!
You can convert current UTC time to local time using the following code:
var tz = "Eastern Standard Time"; // local time zone
var timeZone = TimeZoneInfo.FindSystemTimeZoneById(tz);
var localTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, timeZone);
//Console.WriteLine(localTime.ToString("G"));
//Console.ReadLine();
here my solution based on mixed solutions. Need RestSharp and NodaTime (both from nuget)
private static string WindowsToIana(string windowsZoneId)
{
if (windowsZoneId.Equals("UTC", StringComparison.Ordinal))
return "Etc/UTC";
var tzdbSource = NodaTime.TimeZones.TzdbDateTimeZoneSource.Default;
var tzi = TimeZoneInfo.FindSystemTimeZoneById(windowsZoneId);
if (tzi == null) return null;
var tzid = tzdbSource.MapTimeZoneId(tzi);
if (tzid == null) return null;
return tzdbSource.CanonicalIdMap[tzid];
}
private static string IanaToWindows(string ianaZoneId)
{
var utcZones = new[] { "Etc/UTC", "Etc/UCT", "Etc/GMT" };
if (utcZones.Contains(ianaZoneId, StringComparer.Ordinal))
return "UTC";
var tzdbSource = NodaTime.TimeZones.TzdbDateTimeZoneSource.Default;
// resolve any link, since the CLDR doesn't necessarily use canonical IDs
var links = tzdbSource.CanonicalIdMap
.Where(x => x.Value.Equals(ianaZoneId, StringComparison.Ordinal))
.Select(x => x.Key);
// resolve canonical zones, and include original zone as well
var possibleZones = tzdbSource.CanonicalIdMap.ContainsKey(ianaZoneId)
? links.Concat(new[] { tzdbSource.CanonicalIdMap[ianaZoneId], ianaZoneId })
: links;
// map the windows zone
var mappings = tzdbSource.WindowsMapping.MapZones;
var item = mappings.FirstOrDefault(x => x.TzdbIds.Any(possibleZones.Contains));
if (item == null) return null;
return item.WindowsId;
}
private static string GetIanaTimeZone(double latitude, double longitude, DateTime date)
{
RestClient client;
string location;
RestRequest request;
RestResponse response;
TimeSpan time_since_midnight_1970;
double time_stamp;
string time_zone = "";
try
{
const string GOOGLE_API = "https://maps.googleapis.com";
const string GOOGLE_TIMEZONE_REQUEST = "maps/api/timezone/xml";
client = new RestClient(GOOGLE_API);
request = new RestRequest(GOOGLE_TIMEZONE_REQUEST,
Method.GET);
location = String.Format("{0},{1}",
latitude.ToString(CultureInfo.InvariantCulture),
longitude.ToString(CultureInfo.InvariantCulture));
DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
time_since_midnight_1970 = date - origin;
time_stamp = Math.Floor(time_since_midnight_1970.TotalSeconds);
request.AddParameter("location", location);
request.AddParameter("timestamp", time_stamp);
request.AddParameter("sensor", "false");
//request.AddParameter("key", yourgooglekey);
response = (RestResponse)client.Execute(request);
if (response.StatusDescription.Equals("OK"))
{
XmlNode node;
XmlDocument xml_document = new XmlDocument();
xml_document.LoadXml(response.Content);
node = xml_document.SelectSingleNode(
"/TimeZoneResponse/time_zone_id");
if (node != null)
{
time_zone = node.InnerText;
}
else
{
}
}
else
{
}
}
catch (Exception ex)
{
}
return time_zone;
}
public static DateTime? GetDateTimeFromCoordinates(DateTime? utc, double? latitude, double? longitude)
{
if (utc == null || latitude == null || longitude == null)
return null;
try
{
string iana_timezone = GetIanaTimeZone((double)latitude, (double)longitude, (DateTime)utc);
if (string.IsNullOrWhiteSpace(iana_timezone))
return null;
string time_zone = IanaToWindows(iana_timezone);
TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById(time_zone);
DateTime date = TimeZoneInfo.ConvertTimeFromUtc((DateTime)utc, tz);
return date;
}
catch (Exception ex)
{
return null;
}
}
}
static void Main(string[] args)
{
double latitude = -11.2026920;
double longitude = 17.8738870;
DateTime uct = DateTime.UtcNow;
DateTime? ret = GetDateTimeFromCoordinates(utc,latitude,longitude);
}
function jsonpRequest(url, data)
{
let params = "";
for (let key in data)
{
if (data.hasOwnProperty(key))
{
if (params.length == 0)
{
params += "?";
}
else
{
params += "&";
}
let encodedKey = encodeURIComponent(key);
let encodedValue = encodeURIComponent(data[key]);
params += encodedKey + "=" + encodedValue;
}
}
let script = document.createElement('script');
script.src = url + params;
document.body.appendChild(script);
}
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
let lat_ini=[]; let lon_ini=[];
function showPosition(position) {
lat_ini= position.coords.latitude;
lon_ini= position.coords.longitude;
}
////delay time between lines
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
///////
function getGMT()
{
getfinalGMT()
getLocation()
async function sample() {
await sleep(2000);
let lat_str=lat_ini.toString();
let lng_str=" "+lon_ini.toString();
let url = "https://api.opencagedata.com/geocode/v1/json";
let data = {
callback: "displayGMT",
q: lat_str + lng_str,
key: "fac4471073a347019196c1291e6a97d7"
}
jsonpRequest(url, data)
}
sample();
}
let your_GMT=[];
function displayGMT(data)
{
your_GMT=(Number(data.results[0].annotations.timezone.offset_string))
console.log(your_GMT)
}
/////
function getfinalGMT()
{
let lat=document.getElementById("lat_id").value; let lng=document.getElementById("lng_id").value;
let lat_str=lat.toString();
let lng_str=" "+lng.toString();
let url = "https://api.opencagedata.com/geocode/v1/json";
let data = {
callback: "displayfinalGMT",
q: lat + lng_str,
key: "fac4471073a347019196c1291e6a97d7"
}
jsonpRequest(url, data)
}
let final_GMT=[];
function displayfinalGMT(data)
{
final_GMT=(Number(data.results[0].annotations.timezone.offset_string))
console.log(final_GMT)
}
/////clock
const hourHand = document.querySelector('[data-hour-hand]')
const minuteHand = document.querySelector('[data-minute-hand]')
const secondHand = document.querySelector('[data-second-hand]')
let dif_overall=[];
function setClock() {
let gmt_diff=Number(your_GMT-final_GMT)/100
if (gmt_diff>12){
dif_overall=gmt_diff-12
}
else{
dif_overall=gmt_diff
}
console.log(dif_overall)
const currentDate = new Date()
const secondsRatio = currentDate.getSeconds() / 60
const minutesRatio = (secondsRatio + currentDate.getMinutes()) / 60
const hoursRatio = (minutesRatio + currentDate.getHours() - dif_overall ) / 12
setRotation(secondHand, secondsRatio)
setRotation(minuteHand, minutesRatio)
setRotation(hourHand, hoursRatio)
}
function setRotation(element, rotationRatio) {
element.style.setProperty('--rotation', rotationRatio * 360)
}
function activate_clock(){
setClock()
setInterval(setClock, 1000)
}
*, *::after, *::before {
box-sizing: border-box;
}
body {
background: linear-gradient(to right, hsl(200, 100%, 50%), hsl(175, 100%, 50%));
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
overflow: hidden;
}
.clock {
width: 200px;
height: 200px;
background-color: rgba(255, 255, 255, .8);
border-radius: 50%;
border: 2px solid black;
position: relative;
}
.clock .number {
--rotation: 0;
position: absolute;
width: 100%;
height: 100%;
text-align: center;
transform: rotate(var(--rotation));
font-size: 1.5rem;
}
.clock .number1 { --rotation: 30deg; }
.clock .number2 { --rotation: 60deg; }
.clock .number3 { --rotation: 90deg; }
.clock .number4 { --rotation: 120deg; }
.clock .number5 { --rotation: 150deg; }
.clock .number6 { --rotation: 180deg; }
.clock .number7 { --rotation: 210deg; }
.clock .number8 { --rotation: 240deg; }
.clock .number9 { --rotation: 270deg; }
.clock .number10 { --rotation: 300deg; }
.clock .number11 { --rotation: 330deg; }
.clock .hand {
--rotation: 0;
position: absolute;
bottom: 50%;
left: 50%;
border: 1px solid white;
border-top-left-radius: 10px;
border-top-right-radius: 10px;
transform-origin: bottom;
z-index: 10;
transform: translateX(-50%) rotate(calc(var(--rotation) * 1deg));
}
.clock::after {
content: '';
position: absolute;
background-color: black;
z-index: 11;
width: 15px;
height: 15px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
border-radius: 50%;
}
.clock .hand.second {
width: 3px;
height: 45%;
background-color: red;
}
.clock .hand.minute {
width: 7px;
height: 40%;
background-color: black;
}
.clock .hand.hour {
width: 10px;
height: 35%;
background-color: black;
}
/* Background Styles Only */
#import url('https://fonts.googleapis.com/css?family=Raleway');
* {
font-family: Raleway;
}
.side-links {
position: absolute;
top: 15px;
right: 15px;
}
.side-link {
display: flex;
align-items: center;
justify-content: center;
text-decoration: none;
margin-bottom: 10px;
color: white;
width: 180px;
padding: 10px 0;
border-radius: 10px;
}
.side-link-youtube {
background-color: red;
}
.side-link-twitter {
background-color: #1DA1F2;
}
.side-link-github {
background-color: #6e5494;
}
.side-link-text {
margin-left: 10px;
font-size: 18px;
}
.side-link-icon {
color: white;
font-size: 30px;
}
<input type="text" id="lat_id" placeholder="lat"><br><br>
<input type="text" id="lng_id" placeholder="lng"><br><br>
<button class="text" onClick="getLocation()">Location</button>
<button class="text" onClick="getGMT()"> GMT</button>
<button class="text" onClick="activate_clock()"> Activate</button>
<div class="clock">
<div class="hand hour" data-hour-hand></div>
<div class="hand minute" data-minute-hand></div>
<div class="hand second" data-second-hand></div>
<div class="number number1">1</div>
<div class="number number2">2</div>
<div class="number number3">3</div>
<div class="number number4">4</div>
<div class="number number5">5</div>
<div class="number number6">6</div>
<div class="number number7">7</div>
<div class="number number8">8</div>
<div class="number number9">9</div>
<div class="number number10">10</div>
<div class="number number11">11</div>
<div class="number number12">12</div>
</div>
I have an asp.net mvc application with razor view's engine. I need to store the values of a list passed as a model in my view by using javascript
#section logout {
<a href='#Url.Action("Retour", "Client")'><img src="~/Content/images/home-icon.png" /></a>
<img src="~/Content/images/images.jpg" style="width:37px; height:37px" />
}
#Json.Encode(Model.Get_List_Tache());
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="~/Content/jquery.treeview.css" />
<script src="~/Content/jquery.cookie.js" type="text/javascript"></script>
<script src="~/Content/jquery.treeview.js" type="text/javascript"></script>
<script type="text/javascript" src="~/Content/demo.js"></script>
<!-- partie calendrier-->
<link rel="stylesheet" href="~/Scripts/Calendar/theme.css" />
<link href="~/Scripts/Calendar/fullcalendar.css" rel="stylesheet" />
<link href="~/Scripts/Calendar/fullcalendar.print.css" rel="stylesheet" media="print" />
<script src="~/Scripts/Calendar/fullcalendar.min.js"></script>
<style>
body
{
background-color:#eee;
}
#tree {
background-color:#eee;
}
.affaire {
color:black;
font-size: 16px;
}
.tache {
color:black;
font-size: 12px;
}
.projet {
color:blue;
font-size: 20px;
}
.sequence {
color:blue;
font-size: 13px;
}
#calendar {
width: 700px;
margin: 0 auto;
}
</style>
<script>
$(document).ready(function () {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var titles= Json.Parse(Model.Get_List_Tache());
$('#calendar').fullCalendar({
theme: true,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
events: [
{
id: 999,
title: titles[0],
start: new Date(y, m, d - 3, 16, 0),
allDay: false
}
]
});
});
</script>
</head>
<body>
<table><tr><td style="width:200px;display:block;margin-top:80px;" id="tree">
<ul id="red" style="width: 100%; display:block;width:100%;margin-top:0%">
#for (int i = 0; i < Model.Get_List_Projet().Count; i++)
{
<li><span class="projet">Projet : #Model.Get_List_Projet()[#i].Description</span>
<br />
<br />
<ul>
#for (int j = 0; j < Model.Get_List_Affaire_By_Projet(Model.Get_List_Projet()[#i].Id_projet).Count; j++)
{
int id_affaire = #Model.Get_List_Affaire_By_Projet(Model.Get_List_Projet()[#i].Id_projet)[#j].Id_affaire;
<li><span class="affaire"> #Model.Get_List_Affaire_By_Projet(Model.Get_List_Projet()[#i].Id_projet)[#j].Affaire_description</span>
<br />
<br />
<ul>
#for (int k = 0; k < #Model.Get_List_Sequence_By_Affaire(id_affaire).Count; k++)
{
int id_sequence = #Model.Get_List_Sequence_By_Affaire(id_affaire)[k].Id_séquence;
<li><span class="sequence">#Model.Get_List_Sequence_By_Affaire(id_affaire)[k].Sequence_description </span>
<ul>
#for (int t = 0; t < #Model.Get_List_Tache_By_Sequence(id_sequence).Count; t++)
{
int id_tache = #Model.Get_List_Tache_By_Sequence(id_sequence)[t].Id_tache;
<li><span class="tache">Tache : #Html.ActionLink((string)#Model.Get_List_Tache_By_Sequence(id_sequence)[t].Tache_description, "GererTache", new { id = id_tache })</span></li>
}
<li>#Html.ActionLink("AjouterTache", "AjouterTache", new { id = id_affaire }) </li>
<li>#Html.ActionLink("GérerSéquence", "GererSequence", new { id = id_sequence }) </li>
</ul>
</li>
}
#for (int g = 0; g < #Model.Get_List_Tache_By_Affaire(id_affaire).Count; g++)
{
int id_task = #Model.Get_List_Tache_By_Affaire(id_affaire)[g].Id_tache;
<li><span class="tache">Tache: #Html.ActionLink((string)#Model.Get_List_Tache_By_Affaire(id_affaire)[g].Tache_description, "GererTache", new { id = id_task })</span>
</li>
}
</ul>
<ul><li>#Html.ActionLink("AjouterSéquence", "AjouterSéquence", new { id = id_affaire }) </li>
<li>#Html.ActionLink("AjouterTache", "AjouterTache", new { id = id_affaire }) </li>
<li>#Html.ActionLink("Gérer cette affaire", "GererAffaire", new { id = id_affaire }) </li>
</ul>
</li>
}
</ul>
</li>
}
<br />
</ul>
</td> <td >
<div id='calendar'></div>
</td>
</tr>
</table>
<a href='#Url.Action("Choice", "Travail")'>Retour</a>
</body>
</html>
But i don't know how can i pass from server side to client side, to pass from a C# List to Javascript table.
So i need suggestions to do this task
You need to wrap your code in a loop, consider something like this:
var someArray = []
#for (int i=0; i < this.Model.myArray.length; i++)
{
someArray.push([{ Prop = this.Model.myArray[i].someProp . . . } ]);
}
Alternatively you could add a property to your model, eg.
public class MyModel
{
public string SerialisedData {
get {
return string.Format("[{ name = {0}, someProp = {1} ...... }]", this.Name, this.someProp .....);
}
}
}
But remember to escape quotes.
I have 3 paragraphs of text on a page...I want to change the font size of the paragraphs after every 3 seconds....is this possible?
What i want is when the page loads para 1 is 10px and para 2 is 8px and then after 3 seconds para 2 is 10px and para 1 is 8px.
I mean like using an update panel or something? js ...any way?
You can use the setInterval method to run a function at an interval:
CSS:
#para1 { font-szie: 10px; }
#para2 { font-szie: 8px; }
#para3 { font-szie: 8px; }
HTML:
<p id="para1">asdf</p>
<p id="para2">asdf</p>
<p id="para3">asdf</p>
Javascript:
window.onload = function(){
var current = 0;
var ids = ['para1', 'para2', 'para3'];
window.setInterval(function(){
current = (current + 1) % 3;
for (var i = 0; i < ids.length; i++) {
document.getElementById(ids[i]).style.fontSize = (i == current ? '10px' : '8px');
}
}, 3000);
};
Try this:
<div>
<p id="p1">Para1 </p>
<p id="p2">Para2 </p>
</div>
$(function() {
var pa1 = 20, pa2 = 8, pa3;
$('#p1').css('fontSize', pa1);
$('#p2').css('fontSize', pa2);
function fstyle() {
pa3 = pa1;
pa1 = pa2;
pa2 = pa3;
$('#p1').css('fontSize', pa1);
$('#p2').css('fontSize', pa2);
}
setInterval(fstyle, 3000);
});