I have a very simple NUnit test which is calling an asynchronous method.

Of course the test is awaiting like it should be:

    public async void Test()
    {
        var controller = new Controller(mockService.Object);

        var model = new MyObject
        {
            Address = "12.12.12.12",
            Password = "123456",
            Username = "John Foo"
        };

        var res = await controller.Add(model);
    }

When I run the test it doesn't wait for the Add method to complete, even if I tell it to do so (await)

I'd like to set a public variable that's in my BaseController from all pages/views, if possible. I have a partial view called header.cshtml that has a dropdown list full of customers and their id's. When the user selects a customer, I need to store that CustomerId value into the public variable on the BaseController. If my approach is wrong, please correct me but I need a way for a user to select a customer, then navigate to another page (that has the header view in it) and the dropdown needs to retain the customer they selected on the previous page.

Here's my BaseController:

public class BaseController : Controller
{
    private CurrentUser _currentUser;
    public CurrentUser CurrentUser { get; set; }

    protected override void Initialize(RequestContext requestContext)
    {
        base.Initialize(requestContext);

        Session.TryGetAuthenticatedValue(out _currentUser);
        CurrentUser = _currentUser;
    }

    public ActionResult SetSelectedCustomerId(int value)
    {
        CurrentUser.SelectedCustomerId = value;
        return Json(new { success = true });
    }
}

Header.cshtml:

<div class="col-md-3" style="padding-top:5px;">
    @Html.DropDownList("customers", ViewBag.CustomerList as IEnumerable<SelectListItem>,
        "--Select Customer--",
        new
        {
            @id = "ddlCustomer",
            @style = "width:390px;",
            @onchange = "javascript:SetCustomerId(this.value);",
            @class = "form-control"
        });
</div>

The part I'm missing is the ajax or other method in which to call the public action on the BaseController.

Is it possible to mark up Razor with code mirror?

I'm seeing refrences in the source code of Orchard / umbraco. But it seems I can't make it work.

I want to move my session database from my local machine into external hosting. Why? Because I do not have access to use

aspnet_regsql.ext -d DBName -S ServerName -U User -P Password -ssadd -sstype c

on the external hosting.

I tried to backup and restore. The problem is that the name of the database on the external hosting server starts with prefix, which will make the name to be different from my local machine DBName.

I want to just have 1 file that I can move to any external hosting server and the name is dynamic (means the name of the DB will be different each time I install my website).

I am considering of using custom SQL session state, but I have no knowledge of making one.

I am using:

<@Html.ActionLink("logout", "Login", "Account", routevalues:null, htmlattributes: new{@class =glyphicon glyphicon-log-out,  Id="loginLink" })

I need to check a condition whether I am reloading same page or revisiting same page(i.e when I click some link it will redirecting me to same URL but not loading entire page)

In simple term just i want to check whether my previous page and current page are same - through JavaScript. Thanks.

Ex: if (!(window.onload)) etc...

hi guys i am sorry for the title given i will tell you clearly what i need. Consider there is an registration form, a person entering his/her personal data(consider 20+ textbook for an instance..).Now he/she has completed entering and clicks OK button, now its processing meanwhile my server was working fine while processing suddenly server is down and it restarts. Here is what i want know. 1. Now what will happen to data which was entered? 2. how will my server identify my previous client? 3. where will i save the information and i don't want the client to enter the detail from the beginning again.how can i achieve this.? This was my task given to me by my manager. but i googled it, however i did not get the exact solution. can you guys help me with. Any reference in asp.net is welcomed. i have to do this task in asp.net. Please help me guys..

I am storing some data in the string on the webform1.aspx page and then displaying it to another webform (named as backend.aspx) using query-string method. But my passing string is also displaying in the url of my application. This is code of my source page

 Response.Redirect("backend.aspx?name=" + connType + "");
 //conntype is my string 

here i am retrieving on the destination page using that code

  string    ff = Request.QueryString["name"].ToString();

i have also set cookieless = false in webconfig file.

Here is snapshot of my problementer image description here

How to change databind based on dropdownlist selectedvalue inside gridview? I have tried use string and it work, how can i change the datatabind on selcted row? How I've arrived here

For practice, I am trying to display JSOn data into a datatable in my aspx webpage, but the datatable is stuck with the word processing. Turns out when I inspect the console, the error is Cannot read property 'length' of undefined

What does this error mean? how do I fix it? is this error because of my wrong approach?

What I did is, first I made a .aspx.cs file that produces the JSON string whenever it's URL is called:

[{"NickName":"Bob","LogIN":"6/7/1846 12:00:00 AM","LogOUT":"6/7/1846 12:00:00 AM"},{"NickName":"Bob","LogIN":"6/6/1846 12:00:00 AM","LogOUT":"6/6/1846 12:00:00 AM"},{"NickName":"Patrick","LogIN":"6/7/1846 12:00:00 AM","LogOUT":"6/7/1846 12:00:00 AM"},{"NickName":"Ward","LogIN":"6/7/1846 12:00:00 AM","LogOUT":"6/7/1846 12:00:00 AM"},{"NickName":"Ward","LogIN":"6/6/1846 12:00:00 AM","LogOUT":"6/6/1846 12:00:00 AM"},{"NickName":"Ward","LogIN":"6/5/1846 12:00:00 AM","LogOUT":"6/5/1846 12:00:00 AM"},{"NickName":"Krabs","LogIN":"","LogOUT":""},{"NickName":"Sandy","LogIN":"","LogOUT":""},{"NickName":"Pearl","LogIN":"","LogOUT":""}]

Then on my .aspx file where I am supposed to display the datatable, I wrote this script which is the suggested on the dataTables site:

 /*using the ajax function*/
       var tbl = $('#datatableJSONEx').DataTable({
           processing: true,
           serverSide: true,
           info: true,
           ajax: "DefaultJSONResult?THEstr=produceJSON",

           order: [[0, 'desc']],
           select: true,
           responsive: true,
           buttons: true,
           length: 10

       });

Then I added it's representation in HTML:

        <div>

            <table id="datatableJSONEx" class="display" cellspacing="0" width="100%">                    
                 <thead>
                    <tr>
                        <th>NickName</th>
                        <th>LogIN</th>
                        <th>LogOUT</th> 
                    </tr>
                </thead>
                <tfoot>
                    <tr>
                        <th>NickName</th>
                        <th>LogIN</th>
                        <th>LogOUT</th> 
                    </tr>
                </tfoot>
            </table>

        </div>

</div>

What is causing the error? When the error has been addressed, is this approach correct if I want my tables to automatically update when there are changes to the server?

I guess I'm not understanding the logic behind creating a website and adding an application.

In IIS7, I added a website. I also added a binding, say www.website.local:88.

Now I looked at how to import an asp.net project to IIS7 and I had to install "web deploy". Now I can "import" and application...

When I do, it imports into it's own folder in the site's root folder. The problem is, now I have to type www.website.local/application

The application is the website and I don't want people to have to navigate specifically to the application.

I want people to be able to navigate to www.example.local and have it serve up the application by default.

Why can't I just import an asp.net MVC site as a... site?

Thanks.

I'm modifying an older application which has a table with many rows including the following row. (first question asked on StackOverflow, so hoping it's clear)

<tr id="volumeAvailable" class="standardRow">
     <td align="right" colspan="2"><i>Volume Available for TPN/IL=</i></td>
     <td>
         <asp:TextBox ID="txtTotalFluidsLeftInfo" runat="server" style="border:None; text-align:left; color:blue; font-weight:bold;" Text="0" ReadOnly="true" CssClass="NumericTextbox" ToolTip="0" />
     </td>
</tr>

The app has a click event which prints all controls/values on the aspx page by calling cmdPrint_Click below. A new window is opened which contains the print dialog and print preview.

protected void cmdPrint_Click(object sender, EventArgs e)
    {
        try
        {
            string _url = "'./TPNForm.aspx?ID=" + hOrderId.Value + "&type=print'";
            string _target = "'_blank'";
            string _script = "window.open(" + _url + "," + _target + "," + "'status=no, menubar=yes, toolbar=no,scrollbars=1, height=400px,width=600px');";
            ClientScript.RegisterStartupScript(this.GetType(), "onclick", _script, true);
        }
        catch (Exception _ex)
        {
            throw new ApplicationException(_ex.Message);
        }
    }

I've tried adding volumeAvailable.Visible = false to the server side code to hide before displaying but the row still displays in the print window. I've also tried hiding the row by adding document.getElementById('volumeAvailable').style.display='none' but haven't been able to get this to work.

Can anybody assist on a possible way to exclude this row when calling window.open()? Thanks.


## How to return GUID/ID from stored procedure.. ##

I have a Storedprocedure. It should return GUID/ID, but After executing its returning the value either 2 or -1. I want it to return the GUID/ID only. please help me to solve this. here is the code

Stored Procedure.....

create procedure SampleAddUser1
(
@Name nvarchar(MAX),
@MailID nvarchar(MAX),
@MobileNumber varchar(12),
@Password nvarchar(MAX),
@OTPNo varchar(10),
@OTPExp datetime,
@UserID uniqueidentifier output
)
as
if(not exists(select * from tbl_UserDetails where        
MobileNumber=@MobileNumber))
begin
begin transaction
set @UserID=NEWID()
insert into
tbl_User(UserID,Name,
Password,MobileNumber,MailID)
values(@UserID,@Name,@Password,
@MobileNumber,@MailID)
insert into tbl_OTPDetails(UserId,OTPNo,OTPExp)
Values(@UserID,@OTPNo,@OTPExp)
commit transaction
end

C# Code is here.....

SqlParameter sqlParam = new SqlParameter("@UserID",
SqlDbType.UniqueIdentifier);
sqlParam.Direction = ParameterDirection.Output;
param[6] = sqlParam;
r = _obj.ExecuteNonquery("SampleAddUser", CommandType.StoredProcedure,
param.ToArray());

I'm trying to log the HTTP Response Headers of my Web API project.

The project is developed by VS2012, .NET 4.5 and ASP.NET MVC 4.

I've wrote a DelegatingHandler subclass like this:

public class LoggingHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {

        // Execute the request
        return base.SendAsync(request, cancellationToken).ContinueWith(task =>
        {
            var response = task.Result;
            return response;
        });
    }
}

However, the problem is, I can't get the header values from the response. response.Headers is an empty collection, response.Content.Headers contains nothing but a key named "Content-Type", and HttpContext.Current is null.

I've seen the code of WebAPIContrib which use the same logic to log the headers, but their code does not seem to work either.

So how should I trace the HTTP Response Headers in Web API project?

It seems that my login session (using simple membership) and cookies (verification token) are not valid after IIS server restart. This is a problem for me, if a user in the middle of a transaction then the server restart, the user has to refill the form and do it again, also it can be some code issue when the transaction is interrupted in the middle of the process.

How to make them to be still valid after server restart?

Here is my web.config:

<machineKey validationKey="EAA1686220953D8E7AA9202E10A390ABEC2AFC5259A8554CD28DA69918D5C0366033D00EF6D38B036CF57795E9F536EF2EEC33EF34C8411FE25AF05F25EDAB81"
  decryptionKey="C32AEEAED7D15C663784AD6155AC779F96D3044F80CFE914012271E70504B9E5"
  validation="SHA1" decryption="AES" />
<membership />
...
<sessionState mode="InProc" cookieless="false" timeout="2880" />
...
<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" timeout="2880" />
</authentication> 
...
<staticContent>
  <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="30.00:00:00" />
  <remove fileExtension=".woff" />
  <remove fileExtension=".woff2" />
  <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
  <mimeMap fileExtension=".woff2" mimeType="application/font-woff2" />
</staticContent>

Update

I tried to use SQLServer to store the session state. Then new problem arise, which I cannot use ViewBag because it is not Serializable.

Is there another way I can achieve this?

Can CallContext be relied upon, through-out the whole request, when using asp.net Web API?

I have read the decade-old blog post and I'm not sure it still applies (as asked there).

Assuming Thread-Agility kicks in, if I set data in a global filter, is it safe to assume it will be there through-out the request?

What's a good way when you have a structure of folders in your asp.net project as follows:

-folder 1
--web.config
--folder1.1
----web.config
----folder1.1.1
------web.config
--folder1.2
---web.config

and you want to copy a certain tag from folder1/web.config into folder1/folder1.1/web.config

Is there a better or more elegant way to have the tag from folder1/web.config take effect into a web.config from a subfolder (that lacks that tag), other than copying it?

In below datalist represents set of question's and answer.

How to insert the user selected right answer radio button value into database when the user clicks on Final submit button?

<asp:DataList ID="DataList1" runat="server" DataSourceID="AccessDataSource1" BackColor="White"  BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Horizontal" onselectedindexchanged="rd_CS_CheckedChanged">
    <FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
            <AlternatingItemStyle BackColor="#F7F7F7" />
            <ItemStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
            <SelectedItemStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
            <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
            <ItemTemplate>
               Q:
            <asp:Label ID="QLabel" runat="server" Text='<%# Eval("Q") %>' />
            <br />
                A:
                <asp:RadioButton ID="rd_CS" runat="server" GroupName="Casi" OnCheckedChanged="rd_CS_CheckedChanged" Text='<%# Eval("A") %>'></asp:RadioButton>
                <br />
                B:
                <asp:RadioButton ID="rd_CS2" runat="server" GroupName="Casi" OnCheckedChanged="rd_CS_CheckedChanged" Text='<%# Eval("B") %>'></asp:RadioButton>
                <br />
                 C:
                <asp:RadioButton ID="rd_CS3" runat="server" GroupName="Casi" OnCheckedChanged="rd_CS_CheckedChanged" Text='<%# Eval("C") %>'></asp:RadioButton>
                <br />
                 D:
                <asp:RadioButton ID="rd_CS4" runat="server" GroupName="Casi" OnCheckedChanged="rd_CS_CheckedChanged" Text='<%# Eval("D") %>'></asp:RadioButton>

                <p style="color: #FF3300">
            <asp:Label ID="Correct_AnswerLabel" runat="server" 
                Text='<%# Eval("Correct_Answer") %>' Visible="False" /></p>

    </ItemTemplate>
    <SelectedItemStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
</asp:DataList>

    <asp:AccessDataSource ID="AccessDataSource1" runat="server" 
        DataFile="~/App_Data/Quize.mdb" 
        SelectCommand="SELECT [Q],[A], [B], [C], [D], [Correct Answer] AS Correct_Answer FROM [QuizData]">
    </asp:AccessDataSource>


    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />

I am trying to move users from one OU to another in Active Directory and when I run in debug mode from my local machine everything works fine but once I push to the Test environment and try to do the same move I get

Server Error in '/' Application.

Access is denied. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.UnauthorizedAccessException: Access is denied.

ASP.NET is not authorized to access the requested resource. Consider granting access rights to the resource to the ASP.NET request identity. ASP.NET has a base process identity (typically {MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6 and IIS 7, and the configured application pool identity on IIS 7.5) that is used if the application is not impersonating. If the application is impersonating via , the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user.

To grant ASP.NET access to a file, right-click the file in File Explorer, choose "Properties" and select the Security tab. Click "Add" to add the appropriate user or group. Highlight the ASP.NET account, and check the boxes for the desired access.

Based off this information it seem like the application is using the built in IIS App Pool identity to try and login but I am specifying a UID and Password in my code:

        var principalContext = new PrincipalContext(ContextType.Domain, "site.local", "OU=Users,DC=site,DC=local", ConfigurationManager.AppSettings["ServiceAccountUser"], ConfigurationManager.AppSettings["ServiceAccountPassword"]);
        var userPrincipal = UserPrincipal.FindByIdentity(principalContext, "user.name");
        var userDirectoryEntry = (DirectoryEntry)userPrincipal.GetUnderlyingObject();
        var newDirectory = new DirectoryEntry("LDAP://OU=Users2,DC=site,DC=local");
        userDirectoryEntry.MoveTo(newDirectory);

How can I make sure it is using the supplied credentials to login and make the move of the user?

I'm creating a console application to import data to my system and I need to connect to a FortiClient SSL VPN to access the files. The problem is, FortiClient API only works with IPSEC and the latest version of FortiClient (5.4) doesn't come with any command line executable as in previous verions.

Anyone know a workaround to solve my problem?

I've been working on this since yesterday and I'm completely stumped. I'm working in VB.NET but I can understand C# if you'd prefer to answer it that way.

Basically I have items from a SQL database with IDs and parent IDs and I need to put them in a tree like so:

<ul>
    <li>Some item
        <ul>
            <li>Another item
                <ul>
                    <li>This could go forever
                        <ul>
                            <li>Still going</li>
                        </ul>
                    </li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

Currently I have a nested repeater which works but it only gets me to the second level. It looks something like this:

<asp:Repeater ID="parent" runat="server">
    <ItemTemplate>
        <ul>
            <li><span><%#Container.DataItem("Name")%></span>
                <asp:Repeater ID="child" DataSource='<%#CType(Container.DataItem, DataRowView).Row.GetChildRows("relation")%>' runat="server">
                    <ItemTemplate>
                        <ul>
                            <li><span><%#Container.DataItem("Name")%></span></li>
                        </ul>
                    </ItemTemplate>
                </asp:Repeater>
            </li>
        </ul>
    </ItemTemplate>
</asp:Repeater>

The relation is like this:

ds.Relations.Add("relation",
                 ds.Tables("Items").Columns("ID"),
                 ds.Tables("Items").Columns("ParentID"),
                 False)

I understand why it won't work because it doesn't have a template to continue the tree. So I'm trying to figure out a way around that.

I've considered writing a function to just build the string in the code behind and stick it in the html with an asp tag. I wasn't sure how to go about this while pulling the data out of the database.