mardi 4 août 2015

Can't get Control with FindControl()

I am using a MasterPage site. in default.aspx code-behind, i create many container DIV (ie. each DIV is a SQL result):

HtmlGenericControl div = new HtmlGenericControl("div");
div.Attributes.Add("id", "div_" + postid);

Then create more DIV in code behind (divBottom) programatically and add it to the container DIV, with the following controls inside it:

LinkButton lnkConfirmo = new LinkButton();
lnkConfirmo.ID = "lnkConfirmo_" + postid;
lnkConfirmo.Text = "Foo";
lnkConfirmo.Click += (sender, e) => { UpdateLabel(sender, e, postid); };

Label lblConfirms = new Label();
lblConfirms.ID = "lblConfirms_" + postid;
lblConfirms.Text = "<small><a href=\"javascript:;\">" + GetConfirmTotal(postid) + " pessoas</a> confirmam.</small>";
lblConfirms.Attributes.Add("runat", "server");

And finally add the bottom div to the container.

div.Controls.Add(divBottom);

On the UpdateLabel() method, i am not being able to change Label text when LinkButton is clicked.

    public void UpdateLabel(object sender, EventArgs e, int postid)
    {
        object ctl = (this.FindControl("ContentPlaceHolder1_lblConfirms_" + postid.ToString()) as Label);
        HtmlGenericControl ctl2 = (HtmlGenericControl)this.FindControl("ctl00").FindControl("ContentPlaceHolder1").FindControl("lblConfirms_" + postid);
        //I tried more combinations of this.
    }

I tried Label and HtmlGenericControl because Label is rendering as a span. How can i access that span to change its text, or make this an available control to be accessed? Some controls are available on this.Page.Form (such as some divs, ContentPlaceHolder, ScriptManager and many "Literal), but not the Label as it isn't being rendered as a Control, i guess.

This is the Html output:

<div id="divConfirms_24"><span id="ContentPlaceHolder1_lblConfirms_24" runat="server"><small><a href="javascript:;">190 users</a> confirmam.</small></span></div>



via Chebli Mohamed

Changing ASP.Net label's text with VB.Net

I currently have a form that has a label appear when there is an error with changing your password.

Currently there is a bug that makes a message pop up even when the change is successful that says, "Object reference not set to an instance of an object."

I'm wanting to write a test that says when the label is equal to that message to make the visibility false. I've tried:

If lblMsg.Text = "Object reference not set to an instance of an object." Then
            lblMsg.Visible = False
        End If

This, among other variations, have yet to work successfully for me.

Any idea on what other ways I can write this out to hide the label when that message occurs?



via Chebli Mohamed

How to setup a local wayback machine like that of Internet Archive?

I depend on our Government website for my research. There are some sites in those on which content and links appear and vanish on everyday basis. Their sites are terribly designed and they willfully take down some links or bury some things deep inside to make it hard for any one to find. The problem is I need to refer to something that was on the website months or years ago. Most of the time, I end up not finding it.

Is there a way to locally archive the sites and browse them like we do on wayback machine?



via Chebli Mohamed

How can I navigate to a different URL when user clicks the hyperlink in the GridView with a condition?

I am a beginner in learning asp.net. I have a column in a GridView with header name FORM ID. I want to be able to navigate to the different URL based on the part of the FORM ID.

For example,

  • Clicking on abc10001 will take us to "~/abc1.aspx?formid=abc10001"
  • Clicking on abc20001 will take us to "~/abc2.aspx?formid=abc20001"

I understand the use of the MID function like so v=MID(string,4,1) to capture the 4th value and redirect to page by determining the value v but I do not know how to apply this correctly. Please guide me. Your help is greatly appreciated.

The following is the aspx code I'm currently work on :

<asp:GridView ID="gridview1" runat="server" AutoGenerateColumns="false">           
    <columns>
        <asp:Hyperlinkfield DataTextField="formid" HeaderText="Form ID" ItemStyle-  Width="150px" 
            DataNavigateUrlFields="formid" DataNavigateUrlFormatString="~/abc1.aspx" />         
    </Columns>
</asp:GridView>



via Chebli Mohamed

ASP MVC 5 Web Application not Rendering CSS. Deployed Via Web Deploy

I deployed a MVC 5 Application via web deploy to IIS 8. It is not rendering my bootstrap.css. I'm not sure where to begin from a troubleshooting perspective as this is my first MVC 5 Deployment.

I attached my web config below

<?xml version="1.0"?>

<configuration>
  <configSections>
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
  </configSections>

  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Optimization"/>
        <add namespace="System.Web.Routing" />
        <add namespace="JCI.MW.WebFrontEnd" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>

  <appSettings>
    <add key="webpages:Enabled" value="false" />
  </appSettings>

  <system.webServer>
    <handlers>
      <remove name="BlockViewHandler"/>
      <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
    </handlers>
  </system.webServer>

  <system.web>
    <compilation>
      <assemblies>
        <add assembly="System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      </assemblies>
    </compilation>
  </system.web>
</configuration>



via Chebli Mohamed

Why is localization not working for gridvew?

Why is my localization not working with gridview ?

I have made resx files:

BoundFieldLCode.HeaderText      کد زبان 
BoundFieldText.HeaderText           متن 

and bound fields:

 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="ID">
        <Columns>
            <asp:BoundField DataField="Text" HeaderText="Text" meta:resourceKey="BoundFieldText" />
            <asp:BoundField DataField="Language" HeaderText="Language Code" meta:resourceKey="BoundFieldLCode" />
        </Columns>
    </asp:GridView>

and put this in header of page directive

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Report.aspx.cs" Inherits="_Default"  Culture="auto:en-US" UICulture="auto" %>



via Chebli Mohamed

What is the default TokenLifespan of GeneratePasswordResetTokenAsync and GenerateUserTokenAsync

I have looked everywhere and cannot seem to find out for sure what the default for each of these is.

I also need to know if there is a way to set different Lifespans for each. Thanks,



via Chebli Mohamed

Can't run asp.net app on os x with dnx . kestrel

I followed this tutorial to install tools to run asp.net on os x. I scaffolded the asp.net web application successfully, but and run all the commands the application isn't running.

macbook$ cd '/Users/macbook/Documents/Leisure/asp/webapp' ; /Users/macbook/.dnx/runtimes/dnx-mono.1.0.0-beta6/bin/dnx . kestrel
info    : [Microsoft.Framework.DependencyInjection.DataProtectionServices] User profile is available. Using '/Users/macbook/.local/share/http://ift.tt/1KG10ju' as key repository; keys will not be encrypted at rest.
Started

Everything seems fine, but when I go to localhost:5000 I get ERR_CONNECTION_REFUSED, even though kestrel is set at this url.

What's not right? how do I get my asp.net app working?



via Chebli Mohamed

Default text from .resx file disappearing from website in C#

I have a project involving a template website, that has a set of default text strings stored in a resx file, Resource.resx

I recently came across the idea of using an English language resx file, Resource.en.resx, to store text specific to each instance of the customized website. This way I can have certain pieces of text (such as addresses or other contact information) stored, while being able to easily change text for all instances of the template website. It is similar to Are resx files a suitable way to customise for different customers? except that each instance of the website has its own environment, so there is no confusion on which "version" of the text should be loaded.

However, I have been encountering a problem where the text on the page is disappearing, with the exception of the text from the Resource.en.resx file. No errors are being thrown, the areas where the text appears are just appearing as blank. This can be fixed temporarily by doing an iis reset on the website's server, but I have not been able to determine how or why this is happening.

I believe that it is a caching issue, that somehow the resx is loading "blank" values for the "missing" values in the Resource.en.resx file, even though my understanding of resx files is that any missing key should default to the text from the default file. I have a theory that the text disappears sometimes after an iis reset (which is also a method for making it reappear).

I am using C# with .Net 4.5. I am not currently changing the website's culture directly, though that is something I will be adding in the future. My methodology works most of the time, but I need to know if there is a solution to this intermittent problem, or if I will need to find another method for more easily loading text.

Has anyone encountered this before, or have any idea why it might be happening?



via Chebli Mohamed

Server updating the model on changes from other users

Imagine having a website with an input field, a text field and a button. The text field contains the sum of all inputs, from the input field. The button submits the input.

2 users loaded the page at the same time. User 1 enters "10" into the field and presses the button. How can i update the text field on user 2's screen with the new data, without reloading the whole site?

Is the best way, to make a setInterval javascript to check for changes once in a while, or is there a way, where the server could push updates to the users when the model has changed?



via Chebli Mohamed

How can i define "DisplayErrorMessage" in this case?

This is a code that I wrote for my open button ... but I have error on "DisplayErrorMessage" part. What should I write instead? or how can I define it in order not to have the error again.

protected void btnOpen_Click(object sender, EventArgs e)
{
    txtFileName.Text = txtFileName.Text.Trim();
    if (txtFileName.Text == string.Empty)
    {
        string strErrorMessage = "you did Not specify file for opening!";
        DisplayErrorMessage(strErrorMessage);
    }

    string strFileName = txtFileName.Text;
    string strRootRelativePath = "~/app_data/pageContent";
    string strRootRelativePathName =
    string.Format("{0}/{1}", strRootRelativePath, strFileName);
    string strPathName = Server.MapPath(strRootRelativePathName);

    System.IO.StreamReader ostreamReader = null;

    try
    {
        ostreamReader = new System.IO.StreamReader(strPathName, System.Text.Encoding.UTF8);
        litPageMessages.Text = ostreamReader.ReadToEnd();
    }
    catch (Exception ex)
    {
        litPageMessages.Text = ex.Message;
    }
    finally
    {
        if (ostreamReader != null)
        {
            ostreamReader.Dispose();
            ostreamReader= null;
        }
    }
}



via Chebli Mohamed

Get the "indexOf" of an ICollection in Entity Framework

I have two objects that are connected in a way such that ObjectA contains an ICollection of ObjectB. I would like to be able to determine the indexOf ObjectB in inside the ICollection<ObjectB> that is stored in ObjectA.

One of the solutions was to convert the ICollection to a list and then use the built in IndexOf. However, when multiple threads access the ICollection, in many cases, I can get the same indexOf value for multiple ObjectBs.

Question Is there any way to have a certain field (of type int) that stores the index of ObjectB inside the ICollection? If not, is there anyway to ensure that indexOf (when multiple threads attempt to access it) gives the right index (i.e. no matter of the thread)?

Possible solutions I've tried to ensure to use a new context for each look up as well as GetDatabaseValues() and Reload(). This has worked better (especially in Debug mode), but when the debug mode is turned off, the same index of value is given to more ObjectBs.



via Chebli Mohamed

Changing the color of a texbox with a table cell VB ASP.Net

I have created a textbox within a cell of a table and I am using this to take input from a user and display it on a webpage. I however cant get the background of the textbox to change when the user clicks in side the textbox, normally I would use simple CSS for this but as the textbox is inside a table cell I cant seem to be able to work out how to do this. Any Ideas on how to approach this?

I have the following VB code to generate and populate my table.

VB

 Protected Sub GenerateTable(noOfRows As Integer)
    Dim table As Table
    Dim row As TableRow
    Dim cell As TableCell
    Dim tb As TextBox
    Dim lbl As Label
    table = Table1
    table.ID = "Table1"

    For i As Integer = 1 To noOfRows Step 1
        row = New TableRow()
        For j As Integer = 0 To 1 Step 1
            cell = New TableCell()
            If j = 1 Then
                tb = New TextBox()
                tb.ID = "TextBoxRow_" & i & "Col_" & j
                cell.Controls.Add(tb)

            ElseIf j = 0 Then
                lbl = New Label()
                lbl.ID = "Label" & i
                lbl.Text = "Volume " & i
                cell.Controls.Add(lbl)
            End If
            row.Cells.Add(cell)
        Next
        table.Rows.Add(row)
    Next
    ViewState("RowsCount") = noOfRows
    Session("RowsCount") = noOfRows
End Sub

HTML

<tr>
    <td colspan="2">
        <asp:Table class="Table1" ID="Table1" runat="server"></asp:Table>

        <br />
            <asp:Button ID="btnAddVolume" class="btnVolumeBreak" runat="server"  Text="Add Volume Break"/>
    </td>
</tr>



via Chebli Mohamed

Oracle 10G Installation on Windows

I have a database: Oracle SQL Developer 3.2.20.9 an asp.net web application running locally on a pc with Windows 7 enterprise 64 bit, and to developed it I used Visual Studio 2013. Now I should connect the application with the db so I' m trying to install:

Oracle 10g ODAC and Oracle Developer Tools for Visual Studio .NET

I get this Error: "Abnormal program termination. an internal error has occured. Please provide the following files to Oracle Support: Unknown Unknown Unknown"

Could I connect the webapp in other ways? When I go to Server Explorer in Visual Studio and I choose connect to database -> add connection -> Oracle database -> .NET framework Data Provider for Oracle I get: "This provider is deprecated and should not be used. Instead, download Oracle Developer Tools for visual Studio for comprehensive integration with Oracle databases."



via Chebli Mohamed

Why doesn't the value of SPAN update

ASP.net:

<span id="lblScore" class="lblScore">Your Score is: 0</span>
<asp:Label ID="lblHiddenScore" runat="server" CssClass="lblHScore" Text="" ClientIDMode="Static"></asp:Label>

The following jquery is executed after a certain event:

$(".lblScore").text("");
$(".lblScore").text("Your Score is: " + score);
$(".lblHScore").text(score);

I can see in the front-end, the value is changing but when I view the source of the HTML, it doesn't show the changes.

I am trying to use the score value from code-behind:

string yr = lblHiddenScore.Text; //it is always ""

How can I retrieve the value from the front end to use in code-behind



via Chebli Mohamed

Self hosting request logging

With ASP.NET 5 self-hosting, is there any way to configure request logging (as a separate module) much like you can do with IIS logging?

I want to avoid having to add a dependency to Microsoft.Framework.Logging in all my controllers or to hijack a common entry/exit point (such as authentication) for logging (because I want to log the total request processing duration).



via Chebli Mohamed

Example of using ASP.NET Identity 3.0 without Entity Framework

All examples I've seen by now for ASP.NET Identity 3.0 use Entity Framework to store user-related data.

Are there any example which does not use Entity Framework and where ApplicationUser class is not derived from Microsoft.AspNet.Identity.EntityFramework.IdentityUser?

In ASP.NET Identity 2.x it was needed to implement IUser interface. It seems there is not such interface now - so we're not sure how to define User class correctly. There is almost no documentation on this subject.

Second problem is with AddIdentity call in Startup.ConfigureServices. It's pretty tied to the particular classes from Microsoft.AspNet.Identity.EntityFramework namespace and it's unclear how to register identity services without those classes.



via Chebli Mohamed

Facebook share url with query strings

I have the following problem in Sharing pages from my website through Facebook. When I try to Share a complicated URL that containing a lot of query strings and their values using Graph API or Sharer.php or Sharing button, Facebook neglects the query string and omits them. As an example Sharing this URL http://ift.tt/1IK9arH which has been shared through many ways:

1- Through Sharer.php http://ift.tt/1IhJ11X ; Generates error cause all query strings and their values are deleted after sharing.

2- Through Facebook Share Button and embedding the code in my website; Also the same problem happened.

When I debug my url using Facebook debugger ,It gives me the canonical URL without any query string.

Are there any way to share the URL link exactly as it is with its query strings and their values or a way to control the Canonical URL or og:url , Image og:Image, Title og:title, and description og:description, while Sharing any page.



via Chebli Mohamed

how to map from a ViewModel to Model

i have to model and viewModel like this

public class Estate:BaseEntity
{

    public virtual BaseInformation floorType { get; set; }

}

 public class EstateViewModel:BaseEntityViewModel
{

    public  long floorType { get; set; }

}

and i wrote the code in controller like this :

[HttpPost]
    public long save(EstateViewModel estateViewModel)
    {
        Estate entity = new Estate();
       BaseInformation bi = new BaseInformation();
       bi.id = 1;
       entity.floorType = bi;
       EstateViewModel ev = new EstateViewModel(); 
                 Mapper.CreateMap<EstateViewModel, Estate>();
                 var model = AutoMapper.Mapper.Map<EstateViewModel,Estate>(estateViewModel);

            return estateRepository.save(entity);
    }

when call the action autoMapper give an error like this : An exception of type 'AutoMapper.AutoMapperMappingException' occurred in AutoMapper.dll but was not handled in user code

please help how can fix it thanks



via Chebli Mohamed

Order of execution of fields and set/get in C#?

I am confused about the order of execution in C# regarding the setting of fields and set/get properties. Why is the value in Test2 not set when the constructor gets called while the value in Test is?

When an instance of a class is created is there some type of hidden/default "constructor" that sets the fields but does not call the setter of properties?

Does the setter get automatically called after the constructor or do I explicitly have to call it?

And finally is there good reasoning for this order of execution?

OUTPUT:

Test: 5
Test2: 0

using System.IO;
using System;

class Program
{
    static void Main()
    {
        Test test = new Test();
        Test2 test2 = new Test2();
    }
}

class Test
{
    private int x = 5;
    public Test(){
        Console.WriteLine("Test: " + x);
    }
}

class Test2
{
    private int _x;
    private int x{
        get
        {
            return _x;
        }
        set
        {
            _x = 5;
        }
    }
    public Test2(){
        Console.WriteLine("Test2: " + x);
    }
}



via Chebli Mohamed