I have a .net program that lets the user select a chart from a dropdown and a data range then queries sql for the data to display the chart, everything is fine unless they pick a date range that would only return 1 value for that particular chart.

When this happens since there is only 1 point on the graph it does not display anything for line or area charts (it does work on bar and column).

i have thought about forcing the graph type to column if there is only 1 data point but was wondering if there was a setting i am missing that would allow a straight line on a line graph if there was only 1 datapoint.

well based on the idea of faking a 2nd point i came up with this that technically does what i want it to do.

this is called when there is only 1 point

 foreach (Series ser in mainChart.Series)
 {
     ser.Points.AddY(ser.Points[0].YValues[0]);

 }

I have a group of RadioButton which should have an onclick event. This onclick event (SecurityCheckedChanged) will show/hide other dividers (filled with RadioButton) based on what RadioButton was clicked.

However, SecurityCheckedChanged doesn't seem to work. I'm not sure if there is something I'm misunderstanding about onclick events when it comes to RadioButton. Or if this .is(':checked') is incorrect?

JavaScript:

//this seems to fire off fine
function pageLoad(sender, args) {
    $('#divRadioGroupKeyFormatWEP').hide();
    $('#divRadioGroupKeyFormatWPA').hide();
}

//however this doesn't seem to work.
function SecurityCheckedChanged() {
    if ($("#<%= radWEP.ClientID %>").is(':checked')) {
        $('#divRadioGroupKeyFormatWEP').show();
        $('#divRadioGroupKeyFormatWPA').hide();
    }
    else if ($("#<%= radWPA.ClientID %>").is(':checked') || $("#<%= radWPA2.ClientID %>").is(':checked')) {
        $('#divRadioGroupKeyFormatWEP').hide();
        $('#divRadioGroupKeyFormatWPA').show();
    }
    else {
        $('#divRadioGroupKeyFormatWEP').hide();
        $('#divRadioGroupKeyFormatWPA').hide();
    }
}

HTML:

<div style="text-align: left;">
    <asp:RadioButton id="radNone" Text="None" Checked="True" meta:resourcekey="radNoneRc1"
        GroupName="RadioGroupSecurity" runat="server" onclick="SecurityCheckedChanged"/>

    <asp:RadioButton id="radWEP" Text="WEP" Checked="False" meta:resourcekey="radWepRc1"
        GroupName="RadioGroupSecurity" runat="server" onclick="SecurityCheckedChanged"/>

    <asp:RadioButton id="radWPA" Text="WPA" Checked="False" meta:resourcekey="radWpaRc1"
        GroupName="RadioGroupSecurity" runat="server" onclick="SecurityCheckedChanged"/>

    <asp:RadioButton id="radWPA2" Text="WPA2" Checked="False" meta:resourcekey="radWpa2Rc1"
        GroupName="RadioGroupSecurity" runat="server" onclick="SecurityCheckedChanged"/>
</div>


<!-- show/hide these based on above -->
<div id="divRadioGroupKeyFormatWEP" style="text-align: left;">
    <asp:RadioButton id="radOpen" Text="Open" Checked="True" meta:resourcekey="radOpenRc1"
        GroupName="RadioGroupKeyFormat1" runat="server"/>
    <asp:RadioButton id="radShared" Text="Shared" Checked="False" meta:resourcekey="radSharedRc1"
        GroupName="RadioGroupKeyFormat1" runat="server"/>
</div>

<div id="divRadioGroupKeyFormatWPA" style="text-align: left;">
    <asp:RadioButton id="radTKIP" Text="TKIP" Checked="True" meta:resourcekey="radTkipRc1"
        GroupName="RadioGroupKeyFormat2" runat="server"/>
    <asp:RadioButton id="radAES" Text="AES" Checked="False" meta:resourcekey="radAesRc1"
        GroupName="RadioGroupKeyFormat2" runat="server"/>
</div>

I have added iTextSharp to "Project>...Add References" and added them to using:

using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;

I get the error code at line "GridView1.RenderControl(hw);".

How do you add a runat="server" thru Gridview and the HtmlTextWriter:

 Control 'MainContent_GridView1' of type 'GridView' must be placed inside a form tag with runat=server.

Button1_Click Code:

protected void Button1_Click(Object sender,System.EventArgs e)
    {
        string connStr = ConfigurationManager.ConnectionStrings["PDFMDF"].ConnectionString;
        DataSet ds = new DataSet();
        try
        {
            string cmdStr = "SELECT * FROM [GridviewTable];";
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                using (SqlCommand cmd = new SqlCommand(cmdStr, conn))
                {
                    conn.Open();
                    using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                    {
                        da.Fill(ds);
                        GridView1.DataSource = ds;
                        GridView1.DataBind();
                    }
                    conn.Close();
                    cmd.Dispose();
                    conn.Dispose();
                }
            }
        }
        catch  (Exception ex)
        {
            TextBox1.Text = ex.ToString();
        }

        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=this.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        GridView1.AllowPaging = false;
        GridView1.RenderControl(hw);
        StringReader sr = new StringReader(sw.ToString());
        Document PDFdoc = new Document(PageSize.A4, 10.0F, 10.0F, 10.0F, 0.0F);
        iTextSharp.text.html.simpleparser.HTMLWorker htmlparser =   new iTextSharp.text.html.simpleparser.HTMLWorker(PDFdoc);
        PdfWriter.GetInstance(PDFdoc, Response.OutputStream);
        PDFdoc.Open();
        htmlparser.Parse(sr);
        PDFdoc.Close();
        Response.Write(PDFdoc);
        Response.End();
    }

My DAT/DAL class codes are fine. In my business logic layer.. I want to validate the ID number using Regex validation.

private int idno;
    public int IDNO
    {
        get { return idno; }
        set
        {

            Regex r = new Regex("^[a-zA-Z ]+$");
            if(r.IsMatch(idno.ToString()))
                throw new Exception("Invalid length");
            idno = value;


        }

     public void AddStudent()
    {
        DAT.AddStudent(this.idno);
    }
     public DataTable ViewStudent()
    {
        return DAT.ViewStudent();
    }

Then in my presentation layer I called the Business logic layer in my Add button

protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            BIZ b = new BIZ();
            b.IDNO = int.Parse(TextBox1.Text.ToString());


            b.AddStudent();

            GridView1.DataSource = b.ViewStudent();
            GridView1.DataBind();
        }
        catch(Exception ex)
        {
            Response.Write(ex.Message);
        }
    }

The validation is always "Input string was not in a correct format." I want that the validation would be what I've written in my BLL.. I mean in my BLL it validates already if the user typed in a string but why is it not throwing the BLL exception?

I am creating a LostPassword function using the code below. When users enter their email and they get a password with link containing the token to reset. In my controller I have the GenerateTokenPassword method (under WebSecurity), but it is throwing this error:

Error: Cannot convert type 'string' to 'int' Line: var token = WebSecurity.GeneratePasswordResetToken((foundUserName).ToString(), 1440);

When I debug, I get my username in the foundUserName field and it is a string. The 1440 is the timeout on token expiration, and I am supplying an int to begin with. What int is it looking?

Any ideas what this might be?

Thanks,

Sanjeev

// POST: Account/LostPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult LostPassword(LostPasswordModel model)
{
    ApplicationUser user;
    using (var db = new MyDbContext())
    {
    var foundUserName = (db.People.Where(p => p.Email == model.Email).FirstOrDefault().UserName);
    user = UserManager.FindByName(foundUserName.ToString());
    //    user = Membership.GetUser(foundUserName);

    //Generate password token that will be used in the email link to authenticate user
    WebSecurity.InitializeDatabaseConnection("", "System.Data.SqlClient", "AspNetUsers", "Id", "UserName", false);
    var token = WebSecurity.GeneratePasswordResetToken((foundUserName).ToString(), 1440);
    // Generate the html link sent via email
    var code = UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

    string resetLink = "<a href='"
        + Url.Action("ResetPassword", "Account", new { rt = token }, "http")
        + "'>Reset Password Link</a>";

    //Email stuff
    string emailsubject = "Reset your account password.";
    string emailbody = "Please click this link to reset your account  password: " + resetLink;
    string emailfrom = "mymail@mymail.edu";
    string emailto = model.Email;


    MailMessage message = new MailMessage();
    message.To.Add(emailto);
    message.From = new MailAddress(emailfrom);
    message.Subject = emailsubject;
    message.Body = emailbody;
    message.IsBodyHtml = true;
    SmtpClient smtp = new SmtpClient();
    smtp.UseDefaultCredentials = false;
    smtp.Credentials = new System.Net.NetworkCredential("mymail", "mypass");
    smtp.Host = "smtp.gmail.com";
    smtp.Port = 587;
    smtp.EnableSsl = true;
    smtp.Send(message);

    return View();
    }
}

I have code like this in my Razor view

<script>
    var JsModel = @Html.Raw(Json.Encode(CsModel));
</script>

This works just fine. It converts the C# model received from the controller to a JS object, which is later used to populate Google Map with markers and various other stuff.

The problem is, Visual Studio is showing a big red syntax error in this line, and it's driving me insane. The code is perfectly fine, model is always non-null, and the encoding always works. But Razor parser, or perhaps even R#, I'm not sure which, trips up on it, as it seems to ignore C# code. So what it sees is just var JsModel = ; and complains.

Any way for me to tell it that it's ok? What can I do here?

How can i use the ssrs report within MVC razor application. I have downloaded MvcReportViewer 0.4.0 package from NuGet package source. what i need to do further and how i can use this package in cshtml?

I really dislike page loads, I think they detract from the user experience, so I'm trying to make my web application heavily AJAX-ified.

When the user clicks on "Add new", Javascript generates a form based on a model using Razor, with the following code:

<script type="text/javascript">

    var strNewCategoryForm = '<div><i class="glyphicon glyphicon-folder-open rightfolderpadding"></i>@using (Html.BeginForm("AddCategory", "Password", FormMethod.Post, new { @class="newcategoryform", role = "form", id="[1]" })) { @Html.AntiForgeryToken() @Html.PasswordFor(m => m.Category_ParentID, new { type = "hidden", value = "0" }) @Html.PasswordFor(m => m.CategoryName, new { type = "text" })  <span class="btn-group groupalign"><a href="#" onclick="saveNewCategory(\'#[2]\');return false;" class="btn btn-xs btn-primary"><i class="glyphicon glyphicon-save"></i>Save</a></span> }</div>';

</script>

The code works great, Razor is able to generate the form within the string, so I dont have any issues with making this work. However, for code readability and ease of development, it's not that great.

I'm still quite new to MVC and razor, so I'm just wondering, is there a better or "MVC/Razor standard" way of doing this, that I don't know about?

I understand this method of getting DB data (using foreach):

  var db = Database.Open("Connection");
  var rows = db.Query("SELECT 1 columnName,2 columnName2 FROM Table");

  foreach(var row in rows){
      var data = row.columnName;
      //or
      var data = row[0];          
  }

This works, but how do I get the data without using a foreach?

  var data = rows[0][1];

^ This doesn't work.

Basically, I am trying to figure out how to get the data without using a foreach. What would I have to do?


EDIT:

.Query() returns:

Type: System.Collections.Generic.IEnumerable

The rows returned by the SQL query.

As shown here: http://msdn.microsoft.com/en-us/library/webmatrix.data.database.query%28v=vs.111%29.aspx

In Details action of PersonController I would like to show every information about the Person object.

Initially I want only to show some info about the Person and rest will be collapsed, then I want to click a button/arrow/whatever and rest of info will expand.

Before clicking button/arrow/whatever all the data was loaded but just hidden. If I don't have to I don't want to use AJAX(I am not familiar with it).

Drawings show what I mean.


BEFORE CLICK

enter image description here


AFTER CLICK

enter image description here

Right now Details view looks like that:

@model WebApplication2.Models.Person

@{
    ViewBag.Title = "Details";
}

<h2>Details</h2>

<div>
    <h4>Person</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.FirstName)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.FirstName)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.LastName)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.LastName)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.CellNumber)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.CellNumber)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.SecondaryPhoneNumber)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.SecondaryPhoneNumber)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.Address)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Address)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.BirthDate)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.BirthDate)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.Pesel)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Pesel)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.Notes)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Notes)
        </dd>
    <!-- SOMEWHERE HERE i WOULD LIKE TO INSERT THIS PARTIALL VIEW INTO EXPANDABLE COMPONENT -->
    </dl>
</div>

I want to read the QuestionModelID and SelectedAnswerModelId in the Jquery, so that i can send a ajax call to controller. I am using strongly typed model. I have tried with submit option but that is not a valid option as my page is a partial page.

My Models
public class CheckListModel
{
  public List<QuestionModel> Questions { get; set; } // use List (easier for indexing the name attribute
  ... // other properties of model
}

public class QuestionModel
{
  public int Id { get; set; }
  public string Question { get; set; }
  public int SelectedAnswer { get; set; } // Add this
  public List<AnswerModel> Answers { get; set; }
}

public class AnswerModel
{
    public int ID { get; set; }
    public string Answer { get; set; }
}

My HTML
@model YourAssembly.CheckListModel

@using (Html.BeginForm())
{
  ....
  for (int i = 0; i < Model.Questions.Count; i++)
  {
    @Html.HiddenFor(m => m.Questions[i].ID)
    <p>@Model.Questions[i].Question</p>
    for (int j = 0; j < Model.Questions[i].Answers.Count; j++)
    {
      <div>
        @Html.RadioButtonFor(m => m.Questions[i].SelectedAnswer, Model.Questions[i].Answers[j].ID)
        <span>@Model.Questions[i].Answers[j].Answer</span>
      </div>   
    }
  }
  ....
}

I have the following code which iterates through a list of the signed in users predictions for a series of football matches:

@foreach (var scorecast in Model.Prediction.Scorecasts)
            {
                <tr>
                    @*<td><input id="fixtureid" name="fixtureid" type="text" value="@scorecast.Fixture.FixtureID" /></td>*@
                    <td align="center"><img src="@scorecast.Fixture.HomeTeam.Thumb" style="max-height:30px;max-width:30px;" /></td>
                    <td class="hidden-xs">@scorecast.Fixture.HomeTeam.Name</td>
                    <td align="center"><img src="@scorecast.Fixture.AwayTeam.Thumb" style="max-height:30px;max-width:30px;" /></td>
                    <td class="hidden-xs">@scorecast.Fixture.AwayTeam.Name</td>
                    <td>@scorecast.HomeGoals - @scorecast.AwayGoals</td>
                    <td>@Model.AdminPrediction.Scorecasts.ToList()[x].HomeGoals - @Model.AdminPrediction.Scorecasts.ToList()[x].AwayGoals </td>
                    <td>@Model.GuestPrediction.Scorecasts.ToList()[x].HomeGoals - @Model.GuestPrediction.Scorecasts.ToList()[x].AwayGoals</td>
                </tr>
            }

As you will see from the last two in the row I am attempting to call the predictions of an admin and a guest to compare with the users but I am unsure as to how I can set an iterator x using the list of scorecasts for the user

I have an extension methods for MVCs Controller class that needs to know what the current default layout file is (i.e. the value from _ViewStart.cshtml).

The code is in a library, so I only have the controller to start from. The code below basically allows any controller action to always return a PartialPage, but conditionally assigns the default layout layout (making it a full View) if it was not in response to an Ajax request (e.g. to see the entire page for debugging).

e.g.

public static void RenderMode(this Controller controller)
{
     if (!controller.Request.IsAjaxReuest())
     {
         controller.ViewBag.Layout = ????????;
     }
}

So the question is, how do you get at the default layout page value from code?

How can i use the ssrs report within MVC razor application. I have downloaded MvcReportViewer 0.4.0 package from NuGet package source. what i need to do further and how i can use this package in cshtml?

$.ajax({
        type: "GET",
        url: "getResult",
        data: "e1=" + e1,
        success: function(data) {
...
}

controller method

def getResult() {

        if (validationFailedMessage()) {
                render(template: '../exception')
    }
}

When control goes inside if loop, instead of rendering the template, it again calls getResult method. This continues for some time & then I get stackoverflow. Is rendering like this valid in ajax call or should the call go to the ajax success/error function ? I couldn't find why this is happening so I posted this exception snippet as well.

Caused by: org.codehaus.groovy.grails.web.servlet.mvc.exceptions.ControllerExecutionException: Runtime error executing action
    ... 97 more
Caused by: java.lang.reflect.InvocationTargetException
    ... 97 more
Caused by: org.codehaus.groovy.grails.web.taglib.exceptions.GrailsTagException: Error executing tag <sitemesh:wrapTitleTag>: java.lang.StackOverflowError
    at grails_app_views_AssignmentModular__exception_gsp$_run_closure1.doCall(_exception.gsp:3)
    at grails_app_views_AssignmentModular__exception_gsp.run(_exception.gsp:8)
    at BaseController$$EOnevZsu.exceptioncondition(BaseController.groovy:20)
    at grails.plugin.cache.web.filter.PageFragmentCachingFilter.doFilter(PageFragmentCachingFilter.java:200)
    at grails.plugin.cache.web.filter.AbstractFilter.doFilter(AbstractFilter.java:63)
    at student.AssignmentController$$EOneuzHF.getResult(AssignmentController.groovy:972)
    at org.apache.commons.beanutils.BeanMap.get(BeanMap.java:390)
    at org.apache.commons.beanutils.BeanMap$12.next(BeanMap.java:565)
    at org.apache.commons.collections.iterators.UnmodifiableIterator.next(UnmodifiableIterator.java:72)
    at owsoo.BaseController$$EOnevZsu.exceptioncondition(BaseController.groovy:20)
    at grails.plugin.cache.web.filter.PageFragmentCachingFilter.doFilter(PageFragmentCachingFilter.java:200)
    at grails.plugin.cache.web.filter.AbstractFilter.doFilter(AbstractFilter.java:63)
    at AssignmentController$$EOneuzHF.getResult(AssignmentController.groovy:972)
    at org.apache.commons.beanutils.BeanMap.get(BeanMap.java:390)
    at org.apache.commons.beanutils.BeanMap$12.next(BeanMap.java:565)
    at org.apache.commons.collections.iterators.UnmodifiableIterator.next(UnmodifiableIterator.java:72)
    at owsoo.BaseAssignmentController$$EOnevZsu.exceptioncondition(BaseController.groovy:20)
    at grails.plugin.cache.web.filter.PageFragmentCachingFilter.doFilter(PageFragmentCachingFilter.java:200)

I have application in C# .NET 4.0 framework. Now, My seniors asking to change it to linux format.

I don't want to change it, so they asked me the reasons.

What are the points which I can say to them ?

While I search for the reasons I mostly got that Mono-project can give cross platform. but my requirement is

please decribe what were the reasons for not changing the .NET source code to Linux format

I gone through this blog Here

While using the above concept the minification of html is done but while running i am getting error like " CS1003: Syntax error, '>' expected" and sometimes in phrases{} and in comment lines. I am using MVC4 and using js and css also Anyone there used this htmlminifier or any other solution to resolve this errors. Please help me with this.

i have recently moved my asp.net web application from 32bit to 64bit. Emails sending functionality is not working in 64bit version where it is working in 32 bit. i had configured smtp server settings successfully, but still facing the problem. Please make needful.

This question already has an answer here:

creating a login form however when comparing the username and password in database to allow access am ending up with this error.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

at this line,

SqlCommand cmd3 = new SqlCommand("Select id,Username,
                                  Password from User_data 
                                  where Username='"+UserName.Text.Trim()+"'",con);

below is my code,

protected void button1_click(Object sender, EventArgs e)
{
    SqlCommand cmd3 = new SqlCommand("Select id,Username,Password from User_data where Username='"+UserName.Text.Trim()+"'",con);

    dr = cmd3.ExecuteReader();
    dr.Read();

    string id = dr[0].ToString();
    string un=dr[1].ToString();
    string pwd= dr[2].ToString();

    dr.Close();

    con.Close();
}

Can I make an operation contract accessible on both GET & POST method? Do we have any attribute or property for it? I am able to call it on either POST with following attribute

[WebInvoke(ResponseFormat = WebMessageFormat.Json)]

or on GET with following attribute

[WebGet(ResponseFormat = WebMessageFormat.Json)]

or

[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json)]

but I want to call the operation contract on both requests. Any suggestion on how to achieve this

Thanks in advance.

I want to display the report using Crystal Report, but Its displaying me the blank Page during execution. I want Crystal report Extension or some browser plugins to display Crystal Report.Please help me