I have a gridview which is accessed from another page. First page sends an Id as a request parameter to a SP so the grid gets populated.

But other pages than the first page of grid comes blank because the aforementioned Id is not sent with page changes.

We use a custom pagination without any PageIndex change function but I have some "addparameter" and other request manipulation functions.

I'm trying to send the Id to other pages too but I can't get it persist on postbacks. I tried to set a viewstate variable with the first coming request parameter of Id and make it persist through postbacks. I used a session variable before but I was told not to use it again and to do it request parameters. When I try the viewstate variable, first time it comes right but then it becomes 0 on other pages too because the request parameter gets sent as null to other pages (checked when I assigned the viewstate parameter assignation) and each pageload sets the viewstate to 0.

What is the correct way of doing this? How can I keep the first coming request parameter and send it as a request parameter again with each new page?

Assigning the request parameter to viewstate (apparently wrong approach)

public int FirmaId
            if (ViewState["FirmaId"] == null)
                ViewState["FirmaId"] = Convert.ToInt32(Request["FirmaId"]);
            return (int)ViewState["FirmaId"]; 
        set { ViewState["FirmaId"] = value; }

page load and grid binds (only relevant parts)

protected void Page_Load(object sender, EventArgs e)
        if (!Page.IsPostBack)
            if (Convert.ToInt32(Request["Page"]) > 1)
                //int FirmaId = Convert.ToInt32(Request["FirmaId"]);
                pcBottom.AddCustomParameter("FirmaId=" + FirmaId);

            if (!string.IsNullOrEmpty(Request["FirmaId"]))

                trFirmaAdi.Visible = false;
                fldImport.Visible = true;
                fdlFirmaSecim.Visible = true;
                tdIslemFirma.Visible = true;

                DataRow dr = FirmaDB.Firma_Get(Convert.ToInt32(Request["FirmaId"])).Tables[0].Rows[0];
                string adi = dr["adi"].ToString();
                string vergino = dr["vergiNo"].ToString();
                lblIslemFirmaAdi.Text = adi;
                lblIslemFirmaVergiNo.Text = vergino;

                //OnayFirmaId = Convert.ToInt32(Request["FirmaId"]);
                //fsFirma_Select(fsFirma, null);

            DataRow db = AdminDB.FirmaArac_Get_Count().Tables[0].Rows[0];
            string cekici = db["Adet"].ToString();
            DataRow dt = AdminDB.FirmaArac_Get_Count().Tables[0].Rows[1];
            string dorse = dt["Adet"].ToString();
            lblCount.Text = "Toplam çekici:" + cekici + "-" + "Toplam dorse" + dorse;


    #region Parameters
    private int _pageRowCount = 500;
    //private int _currentPageIndex = 1;
    public int CurrentPageIndex
        get { return pcBottom.CurrentPageId; }
        set { pcBottom.CurrentPageId = value; }

    #endregion Parameters

    private void BindFirmaAracList(bool KeepLabel)
        int FirmaId = 0;
        if (!string.IsNullOrEmpty((string)Request["FirmaId"]))
            FirmaId = Convert.ToInt32(Request["FirmaId"]);

        string firmaadi = (txtSearchFirmaAdi.Text == string.Empty ? null : txtSearchFirmaAdi.Text);
        string plakano = (txtSearchPlakaNo.Text == string.Empty ? null : txtSearchPlakaNo.Text);

        int TotalCount;
        int Start = (CurrentPageIndex - 1) * _pageRowCount;

        //Request["Start"] = Start;

        DataSet ds = AdminDB.FirmaArac_List(
            FirmaId, firmaadi, Convert.ToInt32(cmbSearchAracTipi.SelectedValue), plakano, Convert.ToInt32(drpApproved.SelectedValue)
            , Start, _pageRowCount, out TotalCount);
        gvFirmaAracList.DataSource = ds;

        int intTotalCount;
        int intCurrentCount;

        intTotalCount = TotalCount == -1 ? 0 : TotalCount;
        intCurrentCount = ds.Tables[0].Rows.Count - 1;

        pcBottom.TotalRowCount = intTotalCount;
        pcBottom.PageRowCount = _pageRowCount;
        pcBottom.CurrentRowCount = intCurrentCount;

        int p = Convert.ToInt32(Request["Page"]);
        //if (Convert.ToInt32(Request["Page"]) > 0)
        //    pcBottom.AddCustomParameter("FirmaId=" + FirmaId);


        pcBottom.Visible = intTotalCount > 0;

How do you get your every link displayed of website Google search results page?

enter image description here

I am trying to take number of variables from my database with a where condition but I get an error like

'LINQ to Entities does not recognize the method 'Int32 Parse(System.String)' method'.

Here is my code:

var tickets = (from a in user.TicketTable where a.HandlerId == int.Parse(Session["emp"].ToString()) && a.Done == true select a.TicketId);
int count = 0;
foreach (var n in tickets) 
lblDone.Text = count.ToString();

I tried other methods to convert my session to int but they all gave the same result.

Not sure why it's behaving like this but when I try and make my button group the width of the column it splits. Here is the code:

<div class="row">   
  <div class="col-md-3">...</div>
  <div class="col-md-3">...</div>
  <div class="col-md-6">      
    <div class="row">
      <div class="col-md-7" >
        <div class="input-group">
          <asp:TextBox ID="TextBox1" CssClass="form-control" Text="Search for..." runat="server"></asp:TextBox>
          <span class="input-group-btn">
            <asp:Button ID="Button1" runat="server" Text="Search" CssClass="btn btn-primary" />              

This is how it looks (only the furthest most right textbox & button): enter image description here

That's fine, however, if I try and increase the <div class="col-md-7"> to <div class="col-md-12"> so it takes up the whole width of the col-md-6 it displays like this:

enter image description here

Why isn't the input-group keeping my textbox and button intact? Any value above 7 causes this. Must be making a silly error.

From server side, I defined a new boolean value and set it into <input> tag, but browser couldn't detect it.

@{ var isAuthor = false; }
<input type="hidden" value="@isAuthor" />

After compiling, the result was: <input type="hidden"></input>

But, when I tried to convert isAuthor to a string, it should work:

@{ var isAuthor = false; }
<input type="hidden" value="@isAuthor.ToString()" />

Result: <input type="hidden" value="false"></input>

Why? Did I miss something?

I am new to asp.net mvc 5. I have designed a form that have a field

  @Html.LabelFor(model => model.Id, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => @ViewData["id"] })
                @Html.ValidationMessageFor(model => model.Id)

what i need is to call a function from my controller wherever a value is increased or decreased in my if field.

I want get HttpContext.Current.Request.AnonymousID of users in Razor and then send it to an action in a controller in this way:

 app.controller('loginController', function ($http, $scope, $location, $rootScope) {
    $scope.login = function () {

        //Send Anonymous to UserLogin action
        $http.post("/Accounts/UserLogin?anonymous="+AnonymousId, $scope.model).success(function (response) {
            $scope.message = response;

            window.location = '/';
            $rootScope.ShowSpinner = false;

Is there any way to do this?

I use crystal report formula fields like:

enter image description here

and i set indentation to 0:

enter image description here

but when i get PDF file in client i receive this: enter image description here

crystal report set indentation(margin) from left automatically, also i set indentation Equuleus 0 Thanks!

I am currently making an online coding compiler similar to Google Docs. So, it will basically allow multiple users to write code and the other users can see that code updated in real time. However, I do not know how to make the webpages (that will have the same url) update each other in real time. Any suggestions are appreciated!

I am trying to create a routing rule that allows me to use


instead of


to access a page. I currently have a routing rule that successfully removes index when accessing a page. How do I apply the same concept to this?

    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

I am trying to publish my ASP.NET 5 MVC6 application to godaddy server from Visual Studio 2015. I have imported publish profile from my server and I am able to validate the connection, however when I publish my app I have the following error:


Web deployment task failed. (Connected to the remote computer ("XXXXXXX") using the Web Management Service, but could not authorize. Make sure that you are using the correct user name and password, that the site you are connecting to exists, and that the credentials represent a user who has permissions to access the site.

The credentials are valid, I can publish VS2013 sample project from VS2015, but I can not publish VS2015 sample project as well as my app from VS2015 with the same credentials.

The user is an admin on the server.

I'm trying to download files from a service that URL does not contains filename.

using (var client = new WebClient())
      foreach (var document in links)
         client.Encoding = Encoding.GetEncoding("windows-1251");
         client.OpenRead(new Uri(document.ProxyPath));
         var header_contentDisposition = client.ResponseHeaders["content-disposition"];
         ContentDisposition disposition = new ContentDisposition(header_contentDisposition);
         var fileName = disposition.FileName //this line throws exception

I try above code to fetch filename. header_contentDisposition string contains at filename key below string. attachment; filename=anex_2418689_подÑвеÑждение.pdf

Service that I consume is hosting in Russia. I suspected code-page confusions. They say we encode headers UTF-8.

EDIT I also tried UTF-8 encoder

client.Encoder = Encoding.UTF8

AsP.NET MVC 4 application runs in Debian Squeeze Linux using Mono. Controller creates pdf file from html using code below.

How to print pdf file to Samsung printer connected to server ? It there some executable which can used for this ?

       public class Test: Controller {
        public ActionResult Print()
            return new ContentResult() { Content = "OK" };

        void PrintOrderVormiga()
    StringBuilder sb = new StringBuilder();
    sb.Insert(0, " test ", 500);
            pdf = ConvertHtmlToPDF("<html><body>" +sb.Tostring()+ "</body></html>");
            var doc = new PrintDocument();
            doc.PrinterSettings.PrinterName = "Samsung ML-331x Series";
            doc.PrintPage += new PrintPageEventHandler(ProvideContent);
            pageHeight = doc.DefaultPageSettings.PaperSize.Height;

        byte [] pdf;

        void ProvideContent(object sender, PrintPageEventArgs e)
          ?? of to print this.pdf contents as pdf ?

        static byte[] ConvertHtmlToPDF(string html)
            string programm = "wkhtmltopdf";
            var p = new Process
                StartInfo =
                    CreateNoWindow = true,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    RedirectStandardInput = true,
                    UseShellExecute = false,
                    FileName = Environment.OSVersion.Platform == PlatformID.Win32NT ?
                @"C:\Program Files\wkhtmltopdf\bin\" + programm + ".exe" : "/usr/bin/" + programm

            p.StartInfo.Arguments += " - -";
            using (var stream = p.StandardInput)
                byte[] ibuffer = System.Text.Encoding.UTF8.GetBytes(html);
                stream.BaseStream.Write(ibuffer, 0, ibuffer.Length);

            var buffer = new byte[32768];
            byte[] file;
            using (var ms = new MemoryStream())
                while (true)
                    var read = p.StandardOutput.BaseStream.Read(buffer, 0, buffer.Length);
                    if (read <= 0)
                    ms.Write(buffer, 0, read);
                file = ms.ToArray();
            var returnCode = p.ExitCode;
            return file;


I am using ARR on IIS 8.5 with a URL rewrite pointing to a server farm. The backend web sites run on the same machine, but on different ports, i.e. 8102. Some of the backing web site nodes send emails for email confirmation and those mails contain an activation link that has a wrong port in it (host name is correct). The link has the same port which the web site instance has. But that is a problem since the link is then broken. In the code I am using to generate the link:

Url.Action("ConfirmMail", "Account",
                new { userId = user.Id, code = UserManager.GeneratePasswordResetTokenAsync(user.Id)},
                protocol: Request.Url.Scheme);

So the link the users get is https://correct_hostname:8102/Account/ConfirmMail?..... The correct link should be https://correct_hostname/Account/ConfirmMail?..... or https://correct_hostname:443/Account/ConfirmMail?.....

Any ideas how to make it work?

I'm trying to hide ssn or other sensitive information in a textbox. I created a custom user control (.ascx)

<span class="mask-wrapper">
   <asp:TextBox ID="txtMasked" TextMode="Password" runat="server"></asp:TextBox>
   <asp:LinkButton ID="lnk" runat="server" CssClass="linkbutton btn-link" ToolTip="Show" >Show</asp:LinkButton>

<script type="text/javascript">
   $('#' + '<% = lnk.ClientID%>').click(function (e) {
    if ($('#' + '<% = txtMasked.ClientID%>').attr('type') === 'password') {

        $('#' + '<% = txtMasked.ClientID%>').attr('type', 'text');
        $(this).prop('title', 'Hide');
    else {
        $('#' + '<% = txtMasked.ClientID%>').attr('type', 'password');
        $(this).prop('title', 'Show');
    return false;

var show = function (ev) {
    $('#' + '<% = txtMasked.ClientID%>').attr('type', 'text');
    $('#' + '<% = lnk.ClientID%>').text('Hide');
    $('#' + '<% = lnk.ClientID%>').prop('title', 'Hide');
     hide = function (ev) {
         $('#' + '<% = txtMasked.ClientID%>').attr('type', 'password');
         $('#' + '<% = lnk.ClientID%>').text('Show');
         $('#' + '<% = lnk.ClientID%>').prop('title', 'Show');

   $('#' + '<% = txtMasked.ClientID%>').focus(show);
   $('#' + '<% = txtMasked.ClientID%>').blur(hide);

    Public Class MaskedBox
    Inherits System.Web.UI.UserControl
    Implements INamingContainer

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
       txtMasked.Attributes("value") = Me.Text
    End Sub

    ''' <summary>
    ''' Gets or sets the text.
    ''' </summary>
    ''' <value>
    ''' The text.
    ''' </value>
     Public Property Text() As String
            Return txtMasked.Text
        End Get
        Set(value As String)
            txtMasked.Text = value
            txtMasked.Attributes("value") = value
        End Set
    End Property

End Class

The problem I'm having now is that existing textbox values can't be delete, it returns on post back. The is as a result of storing the value in: attribute('value'). I need to store this value so the password field don't lose its value on postback

I don't know how to resolve this, can someone point me to the right direction.

I know it is better to mask the value on the server side, but I have been told to do this for now.


Element 'RequiredFieldValidator' is not a known element this can occur if compilation error in web site or web config file is missing.

I tried many ways adding line in web config file. Is there any other solution.

I have following code:

applicationmodel.CurrentState = (ApplicationStateEnum) 0;

where applicationmodel.CurrentState is of Type ApplicationStateEnum. What I was expecting after this code is executed is that CurrentState should represent the 0th value of the Enum. But it still represents numeric value 0 and when I send this object to Razor view engine, it is still displayed is 0 numeric value.

Any idea on what I may be doing wrong?

I thought app_code folder was there so that the razor knows where to look for classes and the likes but it seems I still need to add @using.

What's the purpose of app_code folder then?

When calling a view which displays properties for ASP.NET's ApplicationUser class which I have extended, I receive the below error when the code tries to render a line where I dive into a ApplicationUser class:

@model BaseballStatTracker.Models.ApplicationUser

@foreach (var stats in Model.GameStatistics)
            @Html.DisplayFor(modelItem => stat.Game.GameTime)


Error Upon Rendering "Game" Navigation Properties

Any property accessed from within the "Game" property causes the error, and Razor gives no indication that there is a problem when editing the view. Just accessing regular properties on the GameStatistics works without issue.

I have two contexts; the standard ApplicationDbContext and my GamesContext which houses both the Game and GameStatistics entities. I have overridden the OnModelCreating method on the GamesContext per the following:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
            modelBuilder.Entity<Game>().HasKey(i => i.GameId);
            modelBuilder.Entity<Game>().HasOptional(i => i.HomeTeam).WithMany(i => i.HomeGames).HasForeignKey(i => i.HomeTeamId);
            modelBuilder.Entity<Game>().HasOptional(i => i.AwayTeam).WithMany(i => i.AwayGames).HasForeignKey(i => i.AwayTeamId);
            modelBuilder.Entity<Game>().HasOptional(i => i.Diamond).WithMany(i => i.Games).HasForeignKey(i => i.DiamondId);

            modelBuilder.Entity<GameStatistics>().HasKey(i => i.GameStatisticsId);
            modelBuilder.Entity<GameStatistics>().HasRequired(i => i.Game).WithMany(i => i.GameStatistics).HasForeignKey(i => i.GameId);
            modelBuilder.Entity<GameStatistics>().HasRequired(i => i.Player).WithMany(i => i.GameStatistics).HasForeignKey(i => i.PlayerId);

The ApplicationUser, Game and GameStatistics classes look like the following:


public class ApplicationUser : IdentityUser
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;

        [Display(Name = "First Name")]
        [StringLength(155, ErrorMessage = "First Name can only be max 155 characters in length.")]
        public string FirstName { get; set; }

        [Display(Name = "Last Name")]
        [StringLength(155, ErrorMessage = "Last Name can only be max 155 characters in length.")]
        public string LastName { get; set; }

        [Display(Name = "Full Name")]
        public string FullName
                return FirstName + " " + LastName;

        [Display(Name = "Player Number")]
        public int PlayerNumber { get; set; }

        [Display(Name = "Team")]
        public virtual Guid TeamId { get; set; }
        public virtual Team Team { get; set; }

        public virtual ICollection<GameStatistics> GameStatistics { get; set; }


public class Game
        public Guid GameId { get; set; }

        public string GameName { get
                return AwayTeam.Name + " @ " + HomeTeam.Name + ", " + GameDate.Value.Date.ToLongDateString();
            } }

        [Display(Name = "Game Date")]
        public DateTime? GameDate { get; set; }

        [Display(Name = "Game Time")]
        public DateTime? GameTime { get; set; }

        [Display(Name = "Game Location")]
        public virtual Guid? DiamondId { get; set; }
        public virtual Diamond Diamond { get; set; }

        [Display(Name = "Home Team")]
        public virtual Guid? HomeTeamId { get; set; }
        public virtual Team HomeTeam { get; set; }

        [Display(Name = "Away Team")]
        public virtual Guid? AwayTeamId { get; set; }
        public virtual Team AwayTeam { get; set; }

        public virtual ICollection<GameStatistics> GameStatistics { get; set; }


public class GameStatistics
        public Guid GameStatisticsId { get; set; }

        public Guid GameId { get; set; }
        public virtual Game Game { get; set; }

        public string PlayerId { get; set; }
        public virtual ApplicationUser Player { get; set; }

        public int AtBats { get; set; }

        public int Hits { get; set; }

        public int Walks { get; set; }

I have tried redoing the OnModelCreate method but I can't see what I have done wrong with the Game<-GameStatistics relationship. Any help would be much appreciated. Thank you in advance -

I have a table Customer which is having foreign key constraint of CustomerType(CustomerTypeId).

Now using EntityFramework when I try to insert record in Customer table I get an error saying

Cannot add or update a child row: a foreign key constraint fails ("Event"."Customer", CONSTRAINT "customer_ibfk_2" FOREIGN KEY ("CustomerTypeId") REFERENCES "CustomerType" ("CustomerTypeId"))

While researching on this error, I found that in MySQL database it is case sensitive and because of that I am getting this error.

Is there any possible solution to ignore case sensitivity in MYSQL ?

I am a very beginner in coding, changing career and doing self learning+enrolled to a self funded course to get into programming. I posted some similar question earlier but now I have more bigger issue in my code! It was partially working until I mess it up :(.. I have a form which the user will fill then store it into Microsoft Access database, when it was working the first detailed user entered was perfectly stored into my table but second deatiled it skipped the first field (firstname in my case) and stored the firstname to Surname(my second field) basically every time it was skiping one field and starting from the following field ( Hope I am clear!) .. Now that I changed my code, It keeps giving me Syntax error and I checked different tutorials and different syntax ( they all use different syntax) but this error is VERY persistant!

Please, help me.. below is mycode

Imports System.Data.OleDb

Public Class FirstCode
    Inherits System.Web.UI.Page
    Dim provider As String
    Dim dataFile As String
    Dim connString As String
    Dim myConnection As OleDbConnection = New OleDbConnection

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    End Sub

    Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles save.Click
        provider = "Provider= Microsoft.ACE.OLEDB.15.0;Data Source = "
        dataFile = "C:\Users\Data.accdb"
        connString = provider & dataFile
        myConnection.ConnectionString = connString
        Dim str As String

        str = "INSERT INTO RegisterList (FirstName,Surname,Email,Location,ZipCode,Num,[Password]) + VALUES (@FirstName,@Surname,@Email,@Location,@ZipCode,@Num,@Pass)"

        str = " Insert into RegisterList (FirstName) Values(@FirstName)"
        str = " Insert into RegisterList (Surname) Values(@Surname)"
        str = " Insert into RegisterList (Email) Values(@Email)"
        str = " Insert into RegisterList (Location) Values(@Location)"
        str = " Insert into RegisterList (ZipCode) Values(@ZipCode)"
        str = " Insert into RegisterList (Num) Values(@Num)"
        str = " Insert into RegisterList (Password) Values(@Pass)"

        Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
        cmd.Parameters.AddWithValue("@FirstName", TextBox2.Text)
        cmd.Parameters.AddWithValue("@Surname", TextBox3.Text)
        cmd.Parameters.AddWithValue("@Email", TextBox3.Text)
        cmd.Parameters.AddWithValue("@Location", DropDownList1.Text)
        cmd.Parameters.AddWithValue("@CourtName", TextBox4.Text)
        cmd.Parameters.AddWithValue("@Homecare", TextBox5.Text)
        cmd.Parameters.AddWithValue("@Pass", TextBox6.Text)


    End Sub

    Protected Sub Button1_Click1(sender As Object, e As EventArgs) Handles Button1.Click

    End Sub
End Class