Get local time based on coordinates - c#

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>

Related

ASP.NET MVC : completed job should go down (Sorting on Front-End page)

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

How create an AjaxToolKit control, (rating), from code-behind in C#?

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);
}

How to use web speech API in C#

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>

3 level of lists in nested view

I have these tables Pages, PageVersions and ElementsOnPageVersions.
I want to show this on a page all at once, in a collapsible kind of view.
Like this:
Page 1
Version 1
Version 2
Version 3
Version 4
Element 1
Element 2
Element 3
Page 2
Version 1
Version 2
Version 3
Version 4
Element 1
Element 2
Page 3
Version 1
Element 1
Page 4
Version 1
Element 1
I'm uncertain on what the best way to retrieve the data and easily show it in the collapsaple layout is.
I would do something like this:
Get all items, all at once. "select * from ElementsOnPageVersion e inner join PageVersions v on e.PageVersion = v.id inner join Pages p on v.PageId = p.id"
Iterate through all, and build hierachical structure of sorted list to look like the collapsaple layout. PageLists[PagesObject], PagesObject has a sorted list of PageVersionObjects, which has a sorted list of ElementObjects.
Iterate through the final PagesList list Building the page. Inside this iterating through pageversionslist showing versions for the page, and Again inside every version iterating through elementslist.
This would be the way I would do it, at this moment. But it seems too heavy, and a lot of iterating.
What would be the best way to do this?
I'd think about projecting your three different items to a single self-referencing list. Each item would need an Id, Description, and ParentId. I'd make a view model for this purpose.
public class TreeItem {
public int Id {get; set;}
public string Description {get; set;}
public int ParentId {get; set;}
}
That would allow for you to leverage either an asp:TreeView in webforms or whatever flavor of jQuery tree / treeview if you're using MVC.
i actually built something that does something very similar. i can give you the HTML source to mine but i'd need to modify the .NET code to remove company specific, proprietary information before releasing that publicly (plus convert it to C#).
unfortunately for me to modify mine to your needs, it'd be almost up to one month before i'd be able to get around to it (due to a busy week before we take a 2 week vacation). but you can look at my HTML and see what you can reuse from it. from what i understand of your request, you'd be scratching about half of my JavaScript and its functionality. but if i were in your shoes, i'd appreciate this code to use as a starter and scrap what i didn't want and maybe add something. or you may just think my code is trash and not use it at all. ;P
so here's my HTML & JavaScript so you can run with it. It does handle the collapsing and expanding of nodes tho using ul and ol lists.
<!DOCTYPE HTML>
<html>
<head><title>Oz-Med-Hist-VB</title>
<meta charset='utf-8' />
<meta http-equiv='X-UA-Compatible' content='IE=EmulateIE8' />
<style type='text/css'>
body { background: #CCC; margin-left: 1.5em; }
li { list-style-type: none; text-indent: -38px; }
.emptyGrayBox8 {
background-color: #bbb; /* checked and unchecked background color */
border: 1px solid #777; /* checked and unchecked border width & style & color */
padding: 5.5px; display: inline-block; position: relative; margin: 0 3px; margin-top: 3px;
}
.checkInsideGrayBox:after {
content: 'X';
font-size: 13px;
position: absolute;
top: -2px;
left: 1.5px;
color: #555;
}
.checkInsideGrayBoxInsideLI:after {
content: 'X';
font-size: 13px;
position: absolute;
top: -2px;
left: 39.5px;
color: #555;
}
</style>
<script>
if (navigator.userAgent.indexOf('MSIE 8.') < 0)
{
document.write(
' <style>\n' +
' .checkInsideGrayBox { left: 0.5px; }\n' +
' .checkInsideGrayBoxInsideLI:after { left: 38.5px; }\n' +
' </style>');
}
var dta =
{ 'checkedSubNodeCount--1' : 0
, 'checkedSubNodeCount--19' : 0
, 'checkedSubNodeCount--19-a': 0
, 'checkedSubNodeCount--19-b': 0
, 'checkedSubNodeCount--19-c': 0
, 'checkedSubNodeCount--22' : 0
, 'checkedSubNodeCount--24' : 0
, 'checkedSubNodeCount--25' : 0
, 'checkedSubNodeCount--144' : 0
, 'checkedSubNodeCount--1728': 0
};
function chkBox_click(id) // this gets called when user clicks on checkbox or text to right of checkbox.
{ // when checkbox becomes checked, then associated group also becomes shown.
var chkE = document.getElementById('chkBox--' + id); // CHecKBOX HTML element
var grpE = document.getElementById('grpBox--' + id); // GRouPbox HTML element (UL element)
var isChecked = chkE.checked;
if (isChecked)
{ // if user just checked the checkbox, and ...
if (grpE != null) // if an associated (sub)group exists for this checkbox, ...
{ grpE.style.display = ''; } // then expand/show the group element.
}
setLabelHtm(id);
var pid = getParentID(id); // Parent ID
if (id == null) { return; } // if parent id doesn't exist then we're done here.
// now 'pid' is parent ID of 'id'. for instance:
// when id == '19-a' then pid = '19'
// when id == '19-a-1-' then pid = '19-a'
var h = '';
var maxLoopCount = 12; // infinite loop protection :P
while (pid != null && --maxLoopCount >= 0)
{
chkE = document.getElementById('chkBox--' + pid); // CHecKBOX element *of parent*
var pKey = 'checkedSubNodeCount--' + pid; // Key for this Parent ID
if (isChecked) { ++dta[pKey]; } else { --dta[pKey]; }
setLabelHtm(pid);
if (h.length > 0) { h += '\n\n'; }
h += 'id = ' + id + ' isChecked = ' + isChecked
+ '\npid = ' + pid + ' chkE = ' + chkE
+ '\ndta[\'' + pKey + '\'] = ' + dta[pKey];
pid = getParentID(pid);
}
// alert(h);
} // function chkBox_click(id)
function chkBox_click8(id)
{
var chkE = document.getElementById('chkBox--' + id); // CHecKBOX element
var lblE = document.getElementById('chkLab--' + id); // CHecKbox LABel (HTML 'label' element for the checkbox)
if (chkE == null || lblE == null) { return; }
var isChecked = chkE.checked;
var g = Number(chkE.tag);
if (isChecked == false) { g = 3; chkE.tag = g; }
if (isChecked == true ) { g = 2; chkE.tag = g; }
alert(id + '\nisChecked = ' + isChecked + '\n.tag = ' + g);
} // function chkBox_click8(id)
function chkBox_clickIt(id)
{ var chkE = document.getElementById('chkBox--' + id); // CHecKBOX HTML element
if (chkE != null) { chkE.click(); }
} // function chkBox_clickIt(id)
function getParentID(id)
{
var pid = String(id); if (pid.length < 1) { return null; }
if (pid[pid.length - 1] == '-') { pid = pid.substr(0, pid.length - 1); }
var x = pid.lastIndexOf('-'); if (x < 0) { return null; }
pid = pid.substr(0, x); // now pid is id of parent
return pid;
} // function getParentID(id)
function hdrLab_click(id) // this will switch whether the associated group is hidden or shown
{// var chkE = document.getElementById('chkBox--' + id); // CHecKBOX HTML element
var grpE = document.getElementById('grpBox--' + id); // GRouPBOX HTML element (UL element)
if (grpE != null)
{ if (grpE.style.display == '')
{ grpE.style.display = 'none'; }
else
{ grpE.style.display = ''; }
}
setLabelHtm(id);
} // function hdrLab_click(id)
function setLabelHtm(id)
{ var grpE = document.getElementById('grpBox--' + id); // GRouPBOX HTML element (UL element)
var lblE = document.getElementById('hdrLab--' + id);
if (lblE == null) { return; }
var h = null; var suffix = '.';
if (grpE == null) { h = '<span style="visibility: hidden">+</span>'; }
else
{ var grpIsOpen = grpE.style.display == '';
h = '<b>' + (grpIsOpen ? '−' : '+') + '</b>';
}
var s = String(id);
if (s.length > 0 && s.substr(s.length - 1) == '-') { s = '•'; suffix = ''; }
else
{
var x = s.lastIndexOf('-') + 1;
if (x > 0) { s = s.substr(x); }
}
h += ' ' + s + suffix;
var cnt = dta['checkedSubNodeCount--' + id]; // CouNT of checked sub-nodes
if (cnt != null) // if this node is a parent node
{ var chkE = document.getElementById('chkBox--' + id); // CHecKBOX HTML element
if (chkE != null) { chkE.style.display = (cnt > 0) ? 'none' : ''; }
var hBeg = '<span class="emptyGrayBox8">';
var hEnd = '</span>';
if (cnt > 0) { h += hBeg + '<span class="checkInsideGrayBoxInsideLI"></span>' + hEnd; }
else if (chkE == null) { h += hBeg + hEnd; }
}
lblE.innerHTML = h;
} // function setLabelHtm(id)
function init()
{ //alert('yes');
hdrLab_click('1');
hdrLab_click('1-a');
hdrLab_click('19');
hdrLab_click('19-a');
hdrLab_click('19-a-1-');
hdrLab_click('19-a-2-');
hdrLab_click('19-b');
hdrLab_click('19-b-1-');
hdrLab_click('19-b-2-');
hdrLab_click('19-b-3-');
hdrLab_click('19-c');
hdrLab_click('19-c-1-');
hdrLab_click('19-c-2-');
hdrLab_click('19-c-3-');
hdrLab_click('22');
hdrLab_click('22-a');
hdrLab_click('22-b');
hdrLab_click('23');
hdrLab_click('24');
hdrLab_click('24-a');
hdrLab_click('24-b');
hdrLab_click('24-c');
hdrLab_click('25');
hdrLab_click('25-a-');
hdrLab_click('144');
hdrLab_click('144-a');
hdrLab_click('1728');
hdrLab_click('1728-a');
// alert(dta['checkedSubNodeCount--19-a']);
}
window.onload = init;
</script>
</head>
<body>
<ul style='list-style-type: none; margin-left: -1em'>
<li><label id='hdrLab--1' onclick='hdrLab_click("1")' tabindex='0' onkeypress='this.click(); return false;'></label><label id='txtLab--1' onclick='hdrLab_click("1")')> Test for short number '1':</label></li>
<ul id='grpBox--1'>
<li><label id='hdrLab--1-a' onclick='hdrLab_click("1-a")' onkeypress='this.click(); return false;'></label><input type='checkbox' id='chkBox--1-a' onclick='chkBox_click("1-a");' /><label id='txtLab--1-a' onclick='chkBox_clickIt("1-a")')>Test for short number '1' subitem:</label></li>
</ul>
<li><label id='hdrLab--19' onclick='hdrLab_click("19")' tabindex='0' onkeypress='this.click(); return false;'></label><label id='txtLab--19' onclick='hdrLab_click("19")')> Which fruit do you prefer?</label></li>
<ul id='grpBox--19'>
<li><label id='hdrLab--19-a' onclick='hdrLab_click("19-a")' tabindex='0' onkeypress='this.click(); return false;'></label><input type='checkbox' id='chkBox--19-a' onclick='chkBox_click("19-a");' /><label id='txtLab--19-a' onclick='chkBox_clickIt("19-a")')>Apples:</label></li>
<ul id='grpBox--19-a'>
<li><label id='hdrLab--19-a-1-' onclick='hdrLab_click("19-a-1-")' onkeypress='this.click(); return false;'></label><input type='checkbox' id='chkBox--19-a-1-' onclick='chkBox_click("19-a-1-");' /><label id='txtLab--19-a-1-' onclick='chkBox_clickIt("19-a-1-")')>Red delicious</label></li>
<li><label id='hdrLab--19-a-2-' onclick='hdrLab_click("19-a-2-")' onkeypress='this.click(); return false;'></label><input type='checkbox' id='chkBox--19-a-2-' onclick='chkBox_click("19-a-2-");' /><label id='txtLab--19-a-2-' onclick='chkBox_clickIt("19-a-2-")')>Granny smith</label></li>
</ul>
<li><label id='hdrLab--19-b' onclick='hdrLab_click("19-b")' tabindex='0' onkeypress='this.click(); return false;'></label><input type='checkbox' id='chkBox--19-b' onclick='chkBox_click("19-b");' /><label id='txtLab--19-b' onclick='chkBox_clickIt("19-b")')>Bananas:</label></li>
<ul id='grpBox--19-b'>
<li><label id='hdrLab--19-b-1-' onclick='hdrLab_click("19-b-1-")' onkeypress='this.click(); return false;'></label><input type='checkbox' id='chkBox--19-b-1-' onclick='chkBox_click("19-b-1-");' /><label id='txtLab--19-b-1-' onclick='chkBox_clickIt("19-b-1-")')>Green</label></li>
<li><label id='hdrLab--19-b-2-' onclick='hdrLab_click("19-b-2-")' onkeypress='this.click(); return false;'></label><input type='checkbox' id='chkBox--19-b-2-' onclick='chkBox_click("19-b-2-");' /><label id='txtLab--19-b-2-' onclick='chkBox_clickIt("19-b-2-")')>Yellow (ripe but not too ripe)</label></li>
<li><label id='hdrLab--19-b-3-' onclick='hdrLab_click("19-b-3-")' onkeypress='this.click(); return false;'></label><input type='checkbox' id='chkBox--19-b-3-' onclick='chkBox_click("19-b-3-");' /><label id='txtLab--19-b-3-' onclick='chkBox_clickIt("19-b-3-")')>Brown (<i>very</i> ripe)</label></li>
</ul>
<li><label id='hdrLab--19-c' onclick='hdrLab_click("19-c")' tabindex='0' onkeypress='this.click(); return false;'></label><input type='checkbox' id='chkBox--19-c' onclick='chkBox_click("19-c");' /><label id='txtLab--19-c' onclick='chkBox_clickIt("19-c")')>Juice</label></li>
<ul id='grpBox--19-c'>
<li><label id='hdrLab--19-c-1-' onclick='hdrLab_click("19-c-1-")' onkeypress='this.click(); return false;'></label><input type='checkbox' id='chkBox--19-c-1-' onclick='chkBox_click("19-c-1-");' /><label id='txtLab--19-c-1-' onclick='chkBox_clickIt("19-c-1-")')>Orange juice</label></li>
<li><label id='hdrLab--19-c-2-' onclick='hdrLab_click("19-c-2-")' onkeypress='this.click(); return false;'></label><input type='checkbox' id='chkBox--19-c-2-' onclick='chkBox_click("19-c-2-");' /><label id='txtLab--19-c-2-' onclick='chkBox_clickIt("19-c-2-")')>Grape juice</label></li>
<li><label id='hdrLab--19-c-3-' onclick='hdrLab_click("19-c-3-")' onkeypress='this.click(); return false;'></label><input type='checkbox' id='chkBox--19-c-3-' onclick='chkBox_click("19-c-3-");' /><label id='txtLab--19-c-3-' onclick='chkBox_clickIt("19-c-3-")')>Tomato juice</label></li>
</ul>
</ul>
<li><label id='hdrLab--22' onclick='hdrLab_click("22")' tabindex='0' onkeypress='this.click(); return false;'></label><label id='txtLab--22' onclick='hdrLab_click("22")')> Which juice do you prefer?</label></li>
<ul id='grpBox--22'>
<li><label id='hdrLab--22-a' onclick='hdrLab_click("22-a")' onkeypress='this.click(); return false;'></label><input type='checkbox' id='chkBox--22-a' onclick='chkBox_click("22-a");' /><label id='txtLab--22-a' onclick='chkBox_clickIt("22-a")')>Apple juice</label></li>
<li><label id='hdrLab--22-b' onclick='hdrLab_click("22-b")' onkeypress='this.click(); return false;'></label><input type='checkbox' id='chkBox--22-b' onclick='chkBox_click("22-b");' /><label id='txtLab--22-b' onclick='chkBox_clickIt("22-b")')>Orange juice</label></li>
</ul>
<li><label id='hdrLab--23' onclick='hdrLab_click("23")' onkeypress='this.click(); return false;'></label><input type='checkbox' id='chkBox--23' onclick='chkBox_click("23");' /><label id='txtLab--23' onclick='chkBox_clickIt("23")')>Single checkmark question with no subnodes</label></li>
<li><label id='hdrLab--24' onclick='hdrLab_click("24")' tabindex='0' onkeypress='this.click(); return false;'></label><label id='txtLab--24' onclick='hdrLab_click("24")')> Best OS?</label></li>
<ul id='grpBox--24'>
<li><label id='hdrLab--24-a' onclick='hdrLab_click("24-a")' onkeypress='this.click(); return false;'></label><input type='checkbox' id='chkBox--24-a' onclick='chkBox_click("24-a");' /><label id='txtLab--24-a' onclick='chkBox_clickIt("24-a")') style='color:green'>Android!</label></li>
<li><label id='hdrLab--24-b' onclick='hdrLab_click("24-b")' onkeypress='this.click(); return false;'></label><input type='checkbox' id='chkBox--24-b' onclick='chkBox_click("24-b");' /><label id='txtLab--24-b' onclick='chkBox_clickIt("24-b")') style='color:brown'>Apple</label></li>
<li><label id='hdrLab--24-c' onclick='hdrLab_click("24-c")' onkeypress='this.click(); return false;'></label><input type='checkbox' id='chkBox--24-c' onclick='chkBox_click("24-c");' /><label id='txtLab--24-c' onclick='chkBox_clickIt("24-c")')>Linux</label></li>
</ul>
<li><label id='hdrLab--25' onclick='hdrLab_click("25")' tabindex='0' onkeypress='this.click(); return false;'></label><input type='checkbox' id='chkBox--25' onclick='chkBox_click("25");' /><label id='txtLab--25' onclick='chkBox_clickIt("25")')>Check question with subnode check too.</label></li>
<ul id='grpBox--25'>
<li><label id='hdrLab--25-a-' onclick='hdrLab_click("25-a-")' onkeypress='this.click(); return false;'></label><input type='checkbox' id='chkBox--25-a-' onclick='chkBox_click("25-a-");' /><label id='txtLab--25-a-' onclick='chkBox_clickIt("25-a-")')>Sub-node check question</label></li>
</ul>
<li><label id='hdrLab--144' onclick='hdrLab_click("144")' tabindex='0' onkeypress='this.click(); return false;'></label><label id='txtLab--144' onclick='hdrLab_click("144")')> Test for 3-digit number:</label></li>
<ul id='grpBox--144'>
<li><label id='hdrLab--144-a' onclick='hdrLab_click("144-a")' onkeypress='this.click(); return false;'></label><input type='checkbox' id='chkBox--144-a' onclick='chkBox_click("144-a");' /><label id='txtLab--144-a' onclick='chkBox_clickIt("144-a")')>Test for 3-digit number subitem:</label></li>
</ul>
<li><label id='hdrLab--1728' onclick='hdrLab_click("1728")' tabindex='0' onkeypress='this.click(); return false;'></label><label id='txtLab--1728' onclick='hdrLab_click("1728")')> Test for 4-digit number:</label></li>
<ul id='grpBox--1728'>
<li><label id='hdrLab--1728-a' onclick='hdrLab_click("1728-a")' onkeypress='this.click(); return false;'></label><input type='checkbox' id='chkBox--1728-a' onclick='chkBox_click("1728-a");' /><label id='txtLab--1728-a' onclick='chkBox_clickIt("1728-a")')>Test for 4-digit number subitem:</label></li>
</ul>
</ul>
<div style='display: none'>
<script>
var ua = navigator.userAgent;
var ieVersion = null;
var ix = 0;
for (var v = 7; v <= 99; v++)
{
document.write('<!--[if IE ' + v + ']><hr />According to the conditional comment this is IE ' + v + '.<![endif]-->');
if ((ix = ua.indexOf('MSIE ' + v + '.')) >= 0)
{ ieVersion = '';
ix += 5;
while (ix < ua.length && '1234567890.'.indexOf(ua.charAt(ix)) >= 0)
{ ieVersion += ua.charAt(ix++);
} document.write('<hr />According to JavaScript, this is IE ' + ieVersion);
}
}
if (ieVersion == null)
{ document.write('<hr />According to JavaScript, this IE version could not be determined.');
} document.write('<hr />navigator.userAgent = ' + navigator.userAgent);
</script><hr />
<button id='webBtn1'>Fire an event</button>
<button id='btnHi' onclick='window.external.sayHelloFromJavaScript("Hello from JavaScript!", 5);'>Say Hello</button>
</div>
</body>
</html>
i also note that my project used a WebControl built for IE that needed to work as far back as WinXP. so i was limited in what i could use since it had to work for IE 7, but the nice thing is it works for way back to WinXP's latest working version of IE. i also care about using standards compliant code, so to my knowledge, my JavaScript also works for any standards-compliant browsers. i tested it in latest versions of Chrome and FF, and IE 10, IE 8 and IE 7.
there's still a good bit of code that's needed to generate the data into an HTML page, but this can solve half of your request.
in my .NET code, i had to build those JavaScript and HTML lists, which i can give in a few weeks.
You can use Dictionary objects to populate hierarchical data. This code sample might be helpful:
Dictionary<string, Dictionary<string, List<string>>> dictPage = new Dictionary<string, Dictionary<string, List<string>>>();
foreach (DataRow row in dt.Rows)
{
string sPageID = row["PageName"].ToString();
string sVersionID = row["VersionName"].ToString();
string sElementID = row["ElementName"].ToString();
if (!dictPage.ContainsKey(sPageID))
dictPage.Add(sPageID, new Dictionary<string, List<string>>());
if (!dictPage[sPageID].ContainsKey(sVersionID))
dictPage[sPageID].Add(sVersionID, new List<string>());
dictPage[sPageID][sVersionID].Add(sElementID);
}
I have used DataTable in this sample code, but you can use the same with SqlDataReader.
To create HTML you can do something like this:
StringBuilder sbHtmlUL = new StringBuilder();
sbHtmlUL.Append("<ul>");
foreach (var page in dictPage)
{
sbHtmlUL.Append("<li>");
sbHtmlUL.Append(page.Key);
sbHtmlUL.Append("<ul>");
foreach (var version in page.Value)
{
sbHtmlUL.Append("<li>");
sbHtmlUL.Append(version.Key);
sbHtmlUL.Append("<ul>");
foreach (var element in version.Value)
{
sbHtmlUL.Append("<li>");
sbHtmlUL.Append(element);
sbHtmlUL.Append("</li>");
}
sbHtmlUL.Append("</ul>");
sbHtmlUL.Append("</li>");
}
sbHtmlUL.Append("</ul>");
sbHtmlUL.Append("</li>");
}
sbHtmlUL.Append("</ul>");
In this process, you can also apply CSS classes, IDs or simple JavaScript to add a collapse/expand behavior.
Please note that I did not compare performance of this code with other approaches so I am not so sure about it, but it took 8ms in a test, on an average machine, to process 8000 records.

changing font size automatically

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);
});

Categories

Resources