I'm pretty new to C# and MVC coding. I'm making a booking application and I'm using DayPilotMonth for a calendar. I'm using the following code in my view:
#Html.DayPilotMonth("dpm", new DayPilotMonthConfig
{
BackendUrl = Url.Content("~/Home/Backend"),
TimeRangeSelectedHandling = DayPilot.Web.Mvc.Events.Month.TimeRangeSelectedHandlingType.JavaScript,
TimeRangeSelectedJavaScript = "document.location='Bokabord2?startingtime={0}';"})
According to someone on DayPilot the {0} in TimeRangeSelectedJavaScript gives the clicked date in DateTime format.
Now when I'm trying to use the 'startingtime' in my controller nothing works. It seems like the value is always null and I can't find a way to convert it. This is the code I have been trying to use:
public ActionResult Bokabord2(DateTime? startingtime)
{
DateTime startingTime;
if (Session["InloggatId"] != null)
{
if (Request.QueryString["startingtime"] != null)
{
startingTime = Convert.ToDateTime(Request.QueryString["startingtime"]);
ViewBag.Message2 = startingtime;
}
else
{
ViewBag.Message2 = "Error";
}
return View();
}
else
{
return RedirectToAction("Login", "Account");
}
}
When I run the application the error message always shows up at the Convert.ToDateTime line and says something about string not able to convert to DateTime.
Thanks in advance
Regards Philip
protected void builtyLinkButton_click(object sender, EventArgs e)
{
LinkButton lnk = (LinkButton)sender;
GridViewRow row = (GridViewRow)lnk.NamingContainer;
Label l1 = (Label)row.FindControl("Lbl_id");
Response.Redirect("Loading_request.aspx?Id=" + (l1.Text) + "&Date=" + (DateTime.Now.ToString()));
}
I just got it to work. The problem was in the View.
I had to change
TimeRangeSelectedJavaScript = "document.location='Bokabord2?startingtime={0}';"
To:
TimeRangeSelectedJavaScript = "document.location='Bokabord2?startingtime=' + start;"
Now it sends a string with the selected date to the controller. There is very little information about the functions of DayPilotMonth on their website, hence why I couldn't find anything about it. Thanks all.
Related
How can I get the value of an HTML element with CefSharp?
I know how to do with this default WebBrowser Control:
Dim Elem As HtmlElement = WebBrowser1.Document.GetElementByID("id")
But I didn't find anything similar for CefSharp. The main reason I am using CefSharp is because part of the website is using iframes to store the source and default WebBrowser doesn't support it. Also, does CefSharp have an option to InvokeMember or similar call?
I'm using the latest release of CefSharp by the way.
There is a really good example of how to do this in their FAQ.
https://github.com/cefsharp/CefSharp/wiki/Frequently-asked-questions#2-how-do-you-call-a-javascript-method-that-return-a-result
Here is the code for the lazy. Pretty self explanatory and it worked well for me.
string script = string.Format("document.getElementById('startMonth').value;");
browser.EvaluateScriptAsync(script).ContinueWith(x =>
{
var response = x.Result;
if (response.Success && response.Result != null)
{
var startDate = response.Result;
//startDate is the value of a HTML element.
}
});
this is the only way that worked for me, version 57.0.0.0..
((CefSharp.Wpf.ChromiumWebBrowser)chromeBrowser).FrameLoadEnd += Browser_FrameLoadEnd;
....
async void Browser_FrameLoadEnd(object sender, CefSharp.FrameLoadEndEventArgs e)
{
Console.WriteLine("cef-"+e.Url);
if (e.Frame.IsMain)
{
string HTML = await e.Frame.GetSourceAsync();
Console.WriteLine(HTML);
}
}
This worked for me. You can modify it by yourself.
private async void TEST()
{
string script = "document.getElementsByClassName('glass')[0]['firstElementChild']['firstChild']['wholeText']";
JavascriptResponse response = await browser.EvaluateScriptAsync(script);
label1.Text = response.Result.ToString();
}
Maybe this can do your job.
private async void TEST()
{
string script = "Document.GetElementByID('id').value";
JavascriptResponse response = await browser.EvaluateScriptAsync(script);
string resultS = response.Result.ToString(); // whatever you need
}
With CefSharp,you can get elements' value by javascript.
For example,
m_browser.ExecuteScriptAsync("document.GetElementById('id1');");
About javascript,you can learn it from w3s.
And I think you should read this passage.
Have fun.
string script = #"document.getElementById('id_element').style;";
browser.EvaluateScriptAsync(script).ContinueWith(x=> {
var response = x.Result;
if (response.Success && response.Result != null)
{
System.Dynamic.ExpandoObject abc = (System.Dynamic.ExpandoObject)response.Result;
foreach (KeyValuePair<string,object> item in abc)
{
string key = item.Key.ToString();
string value = item.Value.ToString();
}
}
});
It working for me.
i have a big problem and i need your help. i'm trying send to url parameters to generate the pdf file with the library winnovative. when trying the first time I have no problems and generates pdf but if I want to get the pdf again this gives me error because the parameters in url they are sent and fail to request and falls when so finally assign to generate the pdf file.
I have attached the code for review:
public override void Pagina_PrimeraCarga(object sender, EventArgs e)
{
string datosRequest = Request.QueryString["DATOS"];
char delimitadores = ';';
string[] datos = datosRequest.Split(delimitadores);
imgBanco.Attributes.Add("ImageUrl", "~/App_Themes/Imagenes/Logo.gif");
System.DateTime fecha = new System.DateTime(2014, 12, 17);
lblDia.Text = Convert.ToString(fecha.Day);
lblMes.Text = Convert.ToString(fecha.Month);
lblAno.Text = Convert.ToString(fecha.Year);
string rutEmpresa = datos[3];
int rut = Convert.ToInt32(rutEmpresa);
string rutRes = rut.ToString("N0", CultureInfo.InvariantCulture).Replace(",", ".");
rutRes = rutRes + "-" + datos[4];
lblOficina.Text = "OFICINA: " + datos[0];
lblNombreTitular.Text = "NOMBRE TITULAR: " + datos[1];
lblRut.Text = "R.U.T.: " + rutRes;
lblDireccion.Text = "DIRECCION: " + datos[2];
lblFono.Text = "FONO: " + datos[5];
}
P.D: my apologies for my bad English but my native language is Spanish
P.D.2: Thanks to everyone who could help me in this case
I think that your problem is that after postBack your query string will be empty. Try this
add hiddenfield
<asp:HiddenField runat="server" ID="hidden1" />
then in your pageLoad
if (!IsPostBack)
{
string datosRequest = Request.QueryString["DATOS"];
if(datosRequest != null)
{
//do something
hidden1.Value = datosRequest ;
}
}
else
{
datosRequest = hidden1.Value;
}
I have solved the problem. I was thinking a bit and detects when passed a second time to obtain the pdf that was creating the cookie to be passed to the other form was created and therefore did not pass the data. for this reason I had to add 2 lines but my code for closing the pdf this server delete the cookie and when consulted again remove the client:
Response.Cookies.Clear ();
myCookie.Expires = DateTime.Now.AddDays (1D);
Here What I am trying to do, my employer want to be able to be able do 301 redirect with regex expression with the alias in Sitecore so the way I am trying to implement this is like this!
a singleline text field
with a checkbox to tell sitecore it will be a regex expression I am a noob in .NET and Sitecore how can I implement this ? here a exemple http://postimg.org/image/lwr524hkn/
I need help the exemple of redirect I want handle is like this, this is a exemple of the redirect I want to do it could be product at the place of solution.
exemple.com/en/solution/platform-features to
exemple.com/en/platform-features
I base the code from http://www.cmssource.co.uk/blog/2011/December/modifying-sitecore-alias-to-append-custom-query-strings-via-301-redirect this is for query string I want to use regex expression.
namespace helloworld.Website.SC.Common
{
public class AliasResolver : Sitecore.Pipelines.HttpRequest.AliasResolver
{
// Beginning of the Methods
public new void Process(HttpRequestArgs args)
{
Assert.ArgumentNotNull(args, "args");
if (!Settings.AliasesActive)
{
Tracer.Warning("Aliases in AliasResolver are not active.");
}
else
{
Sitecore.Data.Database database = Context.Database;
if (database == null)
{
Tracer.Warning("There is no context in the AliasResolver.");
}
else
{
{
Profiler.StartOperation("Resolve virgin alias pipeline.");
Item item = ItemManager.GetItem(FileUtil.MakePath("/sitecore/system/aliases", args.LocalPath, '/'), Language.Current, Sitecore.Data.Version.First, database, SecurityCheck.Disable);
if (item != null)
{
//Alias existis (now we have the alias item)
if (item.Fields["Regular Expressions"] != null)
{
if (!String.IsNullOrEmpty(item.Fields["Regular Expressions"].Value) && !args.Url.QueryString.Contains("aproc"))
{
var reg = new Regex(#"(?<Begin>([^/]*/){2})[^/]*/(?<End>.*)");
var match = reg.Match(#"exemple.com/en/solution/platform-features");
var result = match.Groups["Begin"].Value + match.Groups["End"].Value;
}
}
}
Profiler.EndOperation();
}
catch (Exception ex)
{
Log.Error("Had a problem in the VirginAliasResolver. Error: " + ex.Message, this);
}
}
}
}
///<summary>
/// Once a match is found and we have a Sitecore Item, we can send the 301 response.
///</summary>
private static void SendResponse(string redirectToUrl, HttpRequestArgs args)
{
args.Context.Response.Status = "301 Moved Permanently";
args.Context.Response.StatusCode = 301;
args.Context.Response.AddHeader("Location", redirectToUrl);
args.Context.Response.End();
}
}
}
PS: I know they have module for this but my employer want it done that way and I am reaching for help since it's been a week I'm trying to add this feature
So if I understand correctly, you do not want to select an Alias by path:
Item item = ItemManager.GetItem(FileUtil.MakePath("/sitecore/system/aliases", args.LocalPath, '/'), Language.Current, Sitecore.Data.Version.First, database, SecurityCheck.Disable);
But rather find an Alias comparing a Regex field to the Url. I have not tested this, but it could be someting like:
var originalUrl = HttpContext.Current.Request.Url;
var allAliases = Sitecore.Context.Database.SelectItems("/sitecore/system/aliases//*");
var foundAlias = allAliases.FirstOrDefault( alias =>
!string.IsNullOrEmpty(alias["Regular Expressions"]) &&
Regex.IsMatch(HttpContext.Current.Request.Url.ToString(), alias["Regular Expressions"]));
Then, if foundAlias != null, you can retrieve the url and redirect like you do in your private SendResponse function.
var linkField = (LinkField)foundAlias.Fields["linked item"];
var targetUrl = linkField.Url;
using (new SecurityDisabler())
{
if (string.IsNullOrEmpty(targetUrl) && linkField.TargetItem != null)
targetUrl = LinkManager.GetItemUrl(linkField.TargetItem);
}
SendResponse(targetUrl, args);
Again, I have not tested this so don't shoot me if it needs some corrections, but this should help you get on your way.
I'm trying to use a cookie to store an integer value for a switch.
private int LessonSlideNum;
I get:
FormatException Input string was not in a correct format
on this line:
LessonSlideNum = Convert.ToInt32(testCookie.Value);
or this one:
LessonSlideNum = Int.Parse(testCookie.Value);
when I use this code:
protected void Page_Load(object sender, EventArgs e)
{
HttpCookie testCookie = Request.Cookies["TestCookie"];
if (testCookie == null)
{
testCookie = new HttpCookie("TestCookie");
testCookie.Path = "~/App_Data/Cookies";
Response.Cookies.Add(testCookie);
}
else
{
LessonSlideNum = Convert.ToInt32(testCookie.Value);
}
Response.Cookies.Add(testCookie);
}
It seems that VS is expecting something in DateTime format. Could someone please help me out here? Thanks :)
The error was that I had no values in the actual cookie. Thanks Ali Shahrokhi! Still, I find it strange that the line:
if(testCookie == null)
didn't catch this error...
I'm a student of programming and decided to make a simple program to practice.
It's a simple form, with name, date of birth, address etc, and it's being saved in a text file (I know there are easier ways, but I want to learn all of them and started with this one =) )
I have a button to search, by name, if the person is already saved and, if yes, it's supposed to fill the form with the data.
Here's an example of how it's saved:
38b7aa1f-0afb-4fe5-a8f6-40fe953eb1ca;Cindy;22/07/2005;111.111.111-11;22.222.222-2;33333-333;Testes;2112;05;Testando;Testadora;SP;cindy#gmail.com;(44)44444-4444;(55)55555-5555;True;True;Rose;26/05/1950;666.666.666-66;77.777.777-7
So, the name (Cindy) would be in and index[1] of an array.
The problem is this error: index was outside the bounds of the array
At this line: if (linha[1] == txtboxNome.Text)
I've searched on internet and kinda understood the problem, but still don't know how to fix it.
Can anybody help me, please?
How can I load my form properly?
Here's an print to help you "see" the program. Don't worry abou the layout, a few things get opacity 0 when running =)
http://i.imgur.com/jze16Pz.jpg
Thanks in advance =)
private void pesquisarNovoBtn_Click(object sender, RoutedEventArgs e)
{
var filePath = #"E:\Programação\WPF ConsultorioDentista\WPF ConsultorioDentista\bin\Debug\Pacientes.txt";
string[] resultado = null;
using (var abrirPacientes = System.IO.File.OpenText(filePath))
{
string lerPacientes = abrirPacientes.ReadLine();
while (lerPacientes != null)
{
var linha = lerPacientes.Split(';');
if (linha[1] == txtboxNome.Text)
{
resultado = linha;
break;
}
lerPacientes = abrirPacientes.ReadLine();
}
if (resultado == null)
{
MessageBox.Show("Paciente não encontrado.");
}
else
{
txtboxNome.Text = resultado[1];
txtboxData.Text = resultado[2];
txtboxCPF.Text = resultado[3];
txtboxRG.Text = resultado[4];
txtboxCEP.Text = resultado[5];
txtboxEndereco.Text = resultado[6];
txtboxNumero.Text = resultado[7];
txtboxCompl.Text = resultado[8];
txtboxBairro.Text = resultado[9];
txtboxCidade.Text = resultado[10];
txtboxUF.Text = resultado[11];
txtboxEmail.Text = resultado[12];
txtboxCel.Text = resultado[13];
txtboxTelRes.Text = resultado[14];
//checkBoxClinico.IsChecked = resultado[15];
//checkBoxOrto.IsChecked = resultado[16];
txtboxNomeResp.Text = resultado[17];
txtboxNascResp.Text = resultado[18];
txtboxCPFResp.Text = resultado[19];
txtboxRGResp.Text = resultado[20];
}
abrirPacientes.Close();
}
This is where you need to "Step Through" the application. Set a Breakpoint (F9) on the If STatement :
if (linha[1] == txtboxNome.Text)
{
resultado = linha;
break;
}
And mouse over to look at the values contained in the linha array.
Most likely you have a header in the first row of your file and it's not splitting.