vendredi 8 mai 2015

How to dynamically inject service into asp.net web api controller based on http request parameter using Unity

I am using Unity to inject an instance of a service into the constructor of my ASP.NET Web API controller.

In the below code, I want to inject a different implementation of IAuthenticationService based on the http request made.

Is this possible?

public class AuthenticateController : ApiController
{
    public AuthenticateController(IAuthenticationService authenticationService)
    {
    }

How can I read and play a video file from my Table in data base?

When I used to directly control the video playback,But when i read from table it's not work

My Sources :

string ss =ec.GetDs("select * from products where Product_Id='" + Request.QueryString["Product_Id"].ToString() + "'").Tables["table"].Rows[0]["product_other4"].ToString();

vd_file.InnerHtml =" < video src=\""+ss+" \" id=\"vd_file\" runat=\"server\" controls=\"controls\" width=\"400px\" height=\"300px\" /> " ;

IIS Worker Process on Windows Server 2012 Memory Limit

I have an ASP.NET 4.0 application running on IIS hosted under a Windows Server 2012 with 8 GB total physical memory.

I noticed that the IIS Worker Process size is considerably increasing as users are logging into the application and performing their tasks.

I'm really lost on how to setup this application in order to avoid memory outage or application crash.

My question is, what is the maximum size the IIS Worker Process can reach on a Windows Server 2012 with 8GB RAM?

Do you advise me to run the Application Pool in 32-bit mode or 64-bit mode?

Do you advise me to use Web Gardening (Increase the number of IIS Worker Processes) ? What are the side-effects of using this option?

Thank in advance

Simultaneous Controller function calls in ASP.net C# MVC

I'm using AJAX to get a BASE64 png image that will then be displayed on the page.

However the size of this png image maybe quite large and so the transfer time may be long.

Also on the page there are other features that use AJAX.

The problem I have is that while I'm transfering the image the other AJAX functions will not run on the controller.

VIEW

function GetImage() {
    $.ajax({
        type: "POST",
        url: "ImagesAnalysis/GetImage",
        datatype: "json",
        traditional: true,
        success: function (Data) {
           DrawImageOnCanvas(Data);
        } 
    return;
 }

function SearchFunction() {
    $.ajax({
        type: "POST",
        url: "ImagesAnalysis/SearchFunction",
        datatype: "json",
        traditional: true,
        Data: SearchString,
        success: function (Data) {
           PutResultOnScreen(Data)
        } 
    return;
 }

CONTROLLER

public int GetImage()
{
    Return Image; //BASE64 IMage string may be LARGE!!!
}

public int SearchFunction(SearchString)
{
    Return DoSearchReturnResult(SearchString);
}

The Problem I have (using MVC5 ASP.NET IIS) is SearchFunction will not run until GetImage has completed sending the image to the view.

Is there any way to be able to run search function on the controller while GetImage is still returning the image

redirect in asp.net mvc 2 controller initialize routine

I need to redirect from any controller to the login page if the session becomes null, i tried this but its not working

protected override void Initialize(System.Web.Routing.RequestContext requestContext) {
    base.Initialize(requestContext);
    if (Session["FirstName"] == null) {
        ret.msg = Resources.Resources.error_session_expired;
        ret.status = "danger";
        RedirectToAction("LogIn", "Account", new {
            area = ""
        }); // <-- i added a return in front of this, but it was red underlined
    }
}

what is the best way to do this

Cross communication between two web applications using web requests: is this close to viable?

I am using the following code to try and learn how pages post, listen and respond between one another using web requests. I begin the process by issuing a request in the first of the two procedures, intending to have the second process retrieve the request and respond back to the calling process. My calling process is receiving a blank response.

Question: Why, and how close to viable is this test?

Here's my two page load events, located in two separate web applications. Both apps are hosted on IIS:

'========================== '========================== Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim sPostURL As String = "http://localhost/DDI_TXListener_Test/Listener_Page.aspx" Dim dataToPost As String = String.Empty ' //This is the data for form posting Dim HttpWebResponse As System.Net.WebResponse = Nothing Dim StreamReader As System.IO.StreamReader = Nothing Dim respString As String = String.Empty Dim stOut As System.IO.Stream = Nothing

    dataToPost = "Name"

    Try
        Dim httpReq As System.Net.WebRequest = System.Net.WebRequest.Create(sPostURL)

        httpReq.Method = "POST"
        httpReq.ContentType = "application/x-www-form-urlencoded"
        Dim byte1 As Byte() = System.Text.Encoding.ASCII.GetBytes(dataToPost)
        httpReq.ContentLength = byte1.Length
        httpReq.Timeout = 10000

        stOut = httpReq.GetRequestStream()
        stOut.Write(byte1, 0, byte1.Length)
        stOut.Dispose()
        stOut = Nothing

        HttpWebResponse = httpReq.GetResponse()

        StreamReader = New System.IO.StreamReader(HttpWebResponse.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8"))
        respString = StreamReader.ReadToEnd()
    Catch ex As Exception
    Finally
        If Not StreamReader Is Nothing Then
            StreamReader.Dispose()
            StreamReader = Nothing
        End If
        If Not HttpWebResponse Is Nothing Then
            HttpWebResponse.Close()
            HttpWebResponse = Nothing
        End If
    End Try
    ' <asp:label> control on the html form in front of this code page
    returnedhit.Text = respString
End Sub

End Class ''==================== "'====================

And I have this as what I hope to use as the receiving/fulfilling end of the above request at:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim sPostURL As String = "http://localhost/DDI_TXRequester_Test/RequesterPage.aspx"
    Dim dataToPost As String = String.Empty ' //This is the data for form posting
    Dim HttpWebResponse As System.Net.WebResponse = Nothing
    Dim StreamReader As System.IO.StreamReader = Nothing
    Dim respString As String = String.Empty
    Dim stOut As System.IO.Stream = Nothing

    Try
        Dim httpReq As System.Net.WebRequest = System.Net.WebRequest.Create(sPostURL)

        HttpWebResponse = httpReq.GetResponse()
        StreamReader = New System.IO.StreamReader(HttpWebResponse.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8"))
        respString = StreamReader.ReadToEnd()


        If respString <> "" Then
            Dim cnt As Integer = 0
            Dim delim As Char() = {"&"c}
            Dim bodpos As Integer = InStr(respString, "<body>") + 6
            Dim respstr As String = Right$(respString, (Len(respString) - bodpos))
            Dim strArr As String() = respstr.Split(delim)
            For Each s As String In strArr
                cnt += 1
                Select Case cnt
                    Case 1
                        Session.Add("opRequested", Right$(Trim(s), (Len(Trim(s)) - 18)))
                    Case Else   '
                End Select
            Next s

            If CStr(Session("opRequested")) = "Name" Then dataToPost = "Name=Jones" Else dataToPost = "Error=Unknown Request"


            httpReq.Method = "POST"
            httpReq.ContentType = "application/x-www-form-urlencoded"
            Dim byte1 As Byte() = System.Text.Encoding.ASCII.GetBytes(dataToPost)
            httpReq.ContentLength = byte1.Length
            httpReq.Timeout = 10000

            stOut = httpReq.GetRequestStream()
            stOut.Write(byte1, 0, byte1.Length)
            stOut.Dispose()
            stOut = Nothing
        End If
    Catch ex As Exception
    Finally
        If Not stOut Is Nothing Then
            stOut.Dispose()
            stOut = Nothing
        End If
        If Not StreamReader Is Nothing Then
            StreamReader.Dispose()
            StreamReader = Nothing
        End If
        If Not HttpWebResponse Is Nothing Then
            HttpWebResponse.Close()
            HttpWebResponse = Nothing
        End If
    End Try
End Sub

calling asp.net application method from a windows service application

I wanted to access a business logic function in asp.net application from a windows service . The thing is this windows service is already being referenced in the asp.net application .

What i am looking for

Can i access an asp.net application method from windows service . Lets say there is business logic function add(int 1,int j). Can i call this add from windows service by referencing as dll or i have to create a web service and write add(int i,int j) and call this web service. ?

HttpClient posting form to a web page returns the same page

I have a page on a site designed for adding a certain entity. What I'm trying to do is to add this entity using C# HttpClient. My sequence of steps looks like this:

First I'm authenticate using the client:

public static async Task<CookieCollection> WebPortalLogin(string baseURI, string phoneNo, string pin)
    {

        var cookies = new CookieContainer();
        var handler = new HttpClientHandler()
        {
            CookieContainer = cookies
        };
        var client = new HttpClient(handler);
        var content = new FormUrlEncodedContent(new[]{
            new KeyValuePair<string,string>("page","login"),
            new KeyValuePair<string,string>("noStaticBox",""),
            new KeyValuePair<string,string>("username",phoneNo),                
            new KeyValuePair<string,string>("password",pin),
            new KeyValuePair<string,string>("login","Увійти"),
            new KeyValuePair<string,string>("_reqNo","0"),
        });

        var response = await client.PostAsync(baseURI, content);

        response.EnsureSuccessStatusCode();


        var stringResponse = response.Content.ReadAsStringAsync().Result;
        var cookieJar = cookies.GetCookies(new Uri(baseURI));
        return cookieJar;
    }

Then I send POST request to edit page with all data I want to save:

public static async Task<HttpResponseMessage> AddCar(string baseURI, string phoneNo, CookieCollection cookieJar, string carNo, string owner)
    {
        var cookieContainer = new CookieContainer();

        var client = new HttpClient(new HttpClientHandler() { CookieContainer = cookieContainer });

        var content = new FormUrlEncodedContent(new[]{
            new KeyValuePair<string,string>("carNo",carNo),
            new KeyValuePair<string,string>("userName",owner),
            new KeyValuePair<string,string>("page","carNumbers"),
            new KeyValuePair<string,string>("submit","Додати"),
            new KeyValuePair<string,string>("operation","addCar"),
            new KeyValuePair<string,string>("_reqNo","0")
        });
        cookieContainer.Add(new Uri(baseURI), cookieJar);
        var response = await client.PostAsync(baseURI, content);
        var stringResponse = response.Content.ReadAsStringAsync().Result;

        return response;
    }

However, this POST request does nothing, and in response I have this very edit page, although when I add this entity in normal way (via web site), I get empty response and entity is successfully saved. Already checked cookies - they're all right. The only thing I can think of is request headers, but successful POST has only regular ones, like Accept, Accept-Encoding etc. What are my possible mistakes and how can I get it posted? Note: all connections use HTTPS.

Angularjs With .net WebForms data in table

I am very new to angular, and trying to create my first app with .net I am trying to show data that I am getting with ajax from the DataBase. that what I ma doing: Js file: (calling it when the page is ready)

    var clients;
var url = 'handlers/http://ift.tt/1AKYW3g';
$(function () {
    $.ajax({
        type: 'POST',
        url: url,
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (msg) {
            clients = $.parseJSON(msg.d);
            alert(clients);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert("Error");
        }
    });
});
var app = angular.module('myApp', []);
app.controller('ClientsController', function ($scope, $http) {
    $scope.clients = myjson;
});

than to show it on the html file:

        <div ng-controller="ClientsController">
        search:<input type="text" ng-model="search" />
        <table>
            <tr ng-repeat="i in clients | filter:search">
                <td>
                    {{i.cid}}
                </td>
                <td>
                    {{i.name }}
                </td>
            </tr>
        </table>
    </div>

after the ajax calling I can see the Object clients so the problem is in the client side, not in the server side.

The error that I am getting is:

 Error: [ng:areq] http://ift.tt/1H6uurV
    at Error (native)
    at http://localhost:53051/js/angular/angular.min.js:6:416
    at Qb (http://localhost:53051/js/angular/angular.min.js:19:417)
    at sb (http://localhost:53051/js/angular/angular.min.js:20:1)
    at http://localhost:53051/js/angular/angular.min.js:76:95
    at http://localhost:53051/js/angular/angular.min.js:57:257
    at s (http://localhost:53051/js/angular/angular.min.js:7:408)
    at v (http://localhost:53051/js/angular/angular.min.js:57:124)
    at g (http://localhost:53051/js/angular/angular.min.js:52:9)
    at g (http://localhost:53051/js/angular/angular.min.js:52:26)

What am I doing wrong?

The error description is 'Invalid at the top level of the document.'

I'm getting following error when I calling a web service with Asp.Net.

The error description is 'Invalid at the top level of the document.'

I do not generate the xml, I'm using web reference in the Visual Studio. Looks like it's expecting

<?xml version="1.0" encoding="utf-8" ?>

But there is no way to edit Soap request and it should work I guess.

ASP.NET Development Server timing out after nth unit test run

I'm using Visual Studio 2013 to perform Unit Testing on a project. It is testing a WCF Service running ASP.NET Development Server using VS 2010. When I 'Run All' 6 Unit Tests, the first 4 pass quickly then the 5th one just times out. It's never the same unit test that times out, so I know this is not an issue with my code. If I restart the ASP.NET Development Server in the system tray and run them individually, they don't time out. This just started happening out of no where about a week ago and it's driving me insane! Any help would be appreciated.

how to configure asp.net mvc site to include a script in a particular publishing mode

We have setup three environments DEV, UAT and Live for our website built in Asp.net MVC. We need to add the google analytics script code (as below) on the live website only. How can we possibly configure this or any script so that when we publish the site in the release mode or another mode only then this script is added before the ending body tag of the _Layout view? thanks

<script>

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-xxxxxxxx-1', 'auto');
ga('send', 'pageview');

</script>

table not rendering rows ASP.NET

Does anyone know why the page is not rendering the rows in table?

Here is my code:

private void loadPhotos(DataTable dtPhotos)
        {
            int rowNumber = 0;
            foreach (DataRow row in dtPhotos.Rows) 
            {
                if (tblPhotosAfter.Rows[rowNumber].Cells.Count == 4)
                {
                    TableRow newRow = new TableRow();
                    TableCell newCell = new TableCell();
                    Image img = new Image();
                    img.ImageUrl = row["ImageName"].ToString();
                    img.Width = img.Height = 200;
                    newCell.Controls.Add(img);
                    newRow.Cells.Add(newCell);
                    tblPhotosAfter.Rows.Add(newRow);
                    rowNumber++;
                }
                else {
                    TableCell newCell = new TableCell();
                    Image img = new Image();
                    img.ImageUrl = row["ImageName"].ToString();
                    img.Width = img.Height = 200;
                    newCell.Controls.Add(img);
                    tblPhotosAfter.Rows[rowNumber].Cells.Add(newCell);
                }
            }

HTML:

<div class="row-fluid">
                        <asp:Table CssClass="table table-hover" runat="server" ID="tblPhotosAfter" >
                            <asp:TableRow>
                            </asp:TableRow> 
                        </asp:Table>
                    </div>

Debugging the code, the table has all the rows and cells, but in the page does not appear

Thanks

Edited in from comments:

calling the method loadPhotos:

 var dtPhotos = dataManager.DataTableQuery(sConn,query);
 if (dtPhotos.Rows.Count > 0) { loadPhotos(dtPhotos); } 

Update Content page Controls on Master Page Timer TIck

I have a master page it has

<asp:Timer ID="masterTimer" runat="server" Interval="1000" OnTick="masterTimer_Tick"/>
        <asp:UpdatePanel runat="server" ID="time" UpdateMode="Always" ChildrenAsTriggers="True">
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="masterTimer" EventName="Tick"/>
            </Triggers>
            <ContentTemplate>
                <asp:Label runat="server" ID="lblTime"></asp:Label>
            </ContentTemplate>
        </asp:UpdatePanel>

and in code behind i have simple

protected void masterTimer_Tick(object sender, EventArgs e)
        {
            this.lblTime.Text = DateTime.Now.ToString("ddd MMM dd yyyy h:mm:ss tt");
        }

In content page i have

Dictionary<Guid, string> data = dataClass.DataDictionary();

and then i am creating a dynamic server control of Label type. Server control has property of Text. Now my problem is, on each tick it does read the correct data means data dictionary contains updated data and it does assign it to label text property but its not displaying the updated text.

I will appreciate if somebody tells me what i need to do

Uploading a large file (up to 100gb) throught ASP.NET application

I need to somehow implement an ability to upload files through an ASP.NET application which is working withing our corporate network. The problem is those files are getting increasingly big. At the moment we're using a very generic asynchronous upload but the problem is that files are getting increasingly big and the max limit of 3.9gb per file set through maxAllowedContentLength since the max value of uint won't allow anything more. Soon files which users are suppose to upload will exceed this value and might reach up to 100gb in size.

I tried looking online for some solution to this problem but in most articles by large files people mean 1gb at best.

So is there any way to upload really large files (up to 100g) through ASP.NET MVC\WebAPI application or I need to look for alternative solutions?

Calculate Code coverage of C# selenium Test cases

I have written test case using Selenium WebDriver in c# and MSTest for Asp .net Application. Is there any tool available for calclulating code coverage of selenium test cases.

Thanks in Advance.

How to automatically wrap ASP.NET action result in JSON (and async)?

We use the following code to automatically wrap action results that do not derive from ActionResult into JSON.

// auto json wrapper
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
    var return_type = ((ReflectedActionDescriptor)filterContext.ActionDescriptor).MethodInfo.ReturnType;

    // check if the return type is an ActionResult
    if (!typeof(ActionResult).IsAssignableFrom(return_type))
    {
        // capture the result from the action
        var result = filterContext.ActionDescriptor.Execute(filterContext, filterContext.ActionParameters);
        // set the result, this means that the rest of the normal path will not be executed
        filterContext.Result = Json(result);
        // manually call OnActionExecuted
        this.OnActionExecuted(new ActionExecutedContext(ControllerContext, filterContext.ActionDescriptor, false, null));
    }
}

This means that we can quite easily use composition for returning json to our web app:

// returns json with the overview, including a list of LolCats
public object Overview()
{
    return new { name = "LolCats", list = ListLolCats() }
}

// returns a json array with lolcats
public IEnumerable<object> ListLolCats()
{
    foreach ( var cat in Db.LolCats )
        yield return new { type = cat.type };
}

Problem is that we want to move more to the async mvc pattern, and of course this won't work because our autowrapper in the OnActionExecuting method is a synchronous method.

Is there any way to have a json autowrapper like above, but one that will work with async actions?

Installing ASP.net DNX with Powershell 2.0

I am trying to get an install of ASP.Net DNX on Windows. I followed the instructions at: http://ift.tt/1ImpIqp

The problem is. when I run this, I get an error stating:

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\parsonsjm0818\Desktop>@powershell -NoProfile -ExecutionPolicy unrestric
ted -Command "&{$Branch='dev';iex ((new-object net.webclient).DownloadString('ht
tps://raw.githubusercontent.com/aspnet/Home/dev/dnvminstall.ps1'))}"
Using temporary directory: C:\Users\PARSON~1\AppData\Local\Temp\dnvminstall
Downloading DNVM.ps1 to
Downloading DNVM.cmd to
Installing DNVM
The script 'dnvm.ps1' cannot be run because it contained a "#requires" statemen
t at line 2 for Windows PowerShell version 3.0. The version required by the scr
ipt does not match the currently running version of Windows PowerShell version
2.0.
At line:1 char:191
+ [System.Threading.Thread]::CurrentThread.CurrentCulture = ''; [System.Threadi
ng.Thread]::CurrentThread.CurrentUICulture = '';$CmdPathFile='C:\Users\parsonsj
m0818\.dnx\temp-set-envvars.cmd';& <<<<  'C:\Users\PARSON~1\AppData\Local\Temp\
dnvminstall\dnvm.ps1' setup
    + CategoryInfo          : ResourceUnavailable: (dnvm.ps1:String) [], Scrip
   tRequiresException
    + FullyQualifiedErrorId : ScriptRequiresUnmatchedPSVersion


C:\Users\parsonsjm0818\Desktop>

Can I install the DNX with only Powershell 2.0 or do I have to upgrade to 3.0?

How to retrieve the selected rows from ASP.NET Form DataGrid

I'm developing new features for an old project developped in ASP.Net Forms/VB.Net and .Net 3.5, one of this features is a batch operation which consists of letting user select multiple rows from a DataGrid (lets say it is GridA) the he press a button to start the operation, the server should display the list of selected items in another grid (lets say its GridB) in a Modal Popup (I'm using ModalPopupExtender from AjaxToolkit) the user should the fill some informations on the popup and then validate the operation using the 'Validate' Button.

So, To implement the row selection I added a TemplateColumn that display a checkbox like this:

<asp:TemplateColumn>
  <HeaderStyle HorizontalAlign="Center"></HeaderStyle>
  <ItemStyle HorizontalAlign="Center"></ItemStyle>
  <HeaderTemplate>
    <asp:CheckBox ID="SelectAll" runat="server" />
  </HeaderTemplate>
  <ItemTemplate>
    <asp:CheckBox ID="ItemSelector" runat="server" />
  </ItemTemplate>
</asp:TemplateColumn>

The DataGrid (GridA) is bound to a dataset retrieved directly from the database.

My question is how to get the list of the selected items (on the server side) from the GridA after the user press the button 'Start' that starts the operation ?

If you have other suggestions on how to implement this scenario, your ideas are welcome :-)

How can I render an entire sitemap in script as a list, reading both title and url?

My objective is to render the full web.sitemap as a nested unordered list. By full, I mean to produce the entire sitemap from root to all descendants. This list must contain the title and url of each node.

This process is useful when your website is a Windows Authenticated network and you need to create a navigation list with secuirty trimming by Active Directory role.

Context -- This is an asp.net 4.0 webpage using Visual Studio 2010. I use strict = true and explicit = true.

Background & What I've done so far

This page http://ift.tt/1AKOj0o shows an example of how to generate a sitemap based on "current node," but I want to generate a full sitemap from the root to all children.

The URL gave me the inspiration to set up a recursive function, but my problem is while I can get the node titles I am unable to get the node URL to accompany it.

Update (5/7/2015): I learned that I was missing a critical piece of code necessary to get the URL of the "current" node. The ordered list emphasizes the new additions, and I'm posting my refreshed code.

I have discovered that while I can get two levels deep from the root node, I am not going any further, which leads me to believe that the recursion script is not defined correctly.

*This goes in the LoadMe sub *

  1. Dim node As SiteMapNode -- this variable is defined before the while loop and represents the "current" node in the while loop.
  2. node = CType(rootNodesChildrenEnumerator.Current, SiteMapNode) -- the node value is updated each pass through the while loop
  3. node.Url -- this is how to read the URL of the "current" node

*This goes in the List_Childnodes function *

  1. Dim node As SiteMapNode
  2. node = CType(childNodesEnumerator.Current, SiteMapNode)
  3. sb.Append(childNodesEnumerator.Current.ToString())

Here is the full (updated) code.

Thank you for any ideas you can provide in improving the recursion and ideas to make the code syntax better.

<%@ Page Title="Sitemap Test" Language="VB" MasterPageFile="~/MasterPage.master" Strict="true" Explicit="true" %>

<script runat="server">
Private Sub LoadMe(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim sb As New StringBuilder
    ' Examine the RootNode, and navigate the SiteMap relative to it.
    sb.Append("<ul>")
    sb.Append("<li><a href=""" & Page.ResolveClientUrl(SiteMap.RootNode.Url) & """>" & SiteMap.RootNode.Title & "</a></li>")

    ' What nodes are children of the RootNode?
    If (SiteMap.RootNode.HasChildNodes) Then
        Dim rootNodesChildrenEnumerator As IEnumerator = SiteMap.RootNode.ChildNodes.GetEnumerator()
        Dim node As SiteMapNode
        While (rootNodesChildrenEnumerator.MoveNext())
            node = CType(rootNodesChildrenEnumerator.Current, SiteMapNode)
            sb.Append("<li><a href=""" & node.Url & """>" & rootNodesChildrenEnumerator.Current.ToString() & "</a></li>")
            sb.Append(List_Childnodes(CType(rootNodesChildrenEnumerator.Current, SiteMapNode)))
        End While
    End If
    sb.Append("</ul>")

    lblSitemap.Text = sb.ToString
End Sub

Function List_Childnodes(Current_Node As SiteMapNode) As String
    Dim sb As New StringBuilder

    ' What nodes are children of the function parameter?
    If (Current_Node.HasChildNodes) Then
        Dim childNodesEnumerator As IEnumerator = Current_Node.ChildNodes.GetEnumerator()

        sb.Append("<ul>")
        Dim node As SiteMapNode
        While (childNodesEnumerator.MoveNext())
            ' Prints the Title of each node.
            node  = CType(childNodesEnumerator.Current, SiteMapNode)
            sb.Append("<li>")
            sb.Append("<a href=""" & node.Url & """>")
            sb.Append(childNodesEnumerator.Current.ToString())
            sb.Append("</a>")
            sb.Append("</li>")

            ' Because I didn't get all children, I tried calling the same function here
            '   to see if I could get all child descendents.


            ' this didn't work
            List_Childnodes(node)

        End While
        sb.Append("</ul>")
    End If

    Return sb.ToString
End Function

</script>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<h1>Sitemap Test</h1>
<p>The <var>LoadMe</var> sub runs on Me.Load and recursively calls all children. The root node is manually moved into the first level for user convenience.</p>
<h2>Sitemap tree</h2>
<asp:Label ID="lblSitemap" runat="server" Text="Label"></asp:Label>

Data is not updating into database

I want to update the values of textboxes into my database the code doesnot show any syntax error and redirects easily to the page im redirecting but still database is not updating the new data in it.. please resolve this issue it would be appreciated thankyou.

        conn.Open();
        string str_id = Session["userid"].ToString();
        int id;
        id = Convert.ToInt32(str_id);
        id = Int32.Parse(str_id);

        string updatequery = "Update empdata set fname='" + updatename.Text + "',education='" + updateeducation.Text + "',position='" + updateposition.Text + "',email='" + updateemail.Text + "',address='" + updateaddress.Text + "',contact='" + updatecontact.Text + "',account='" + updateaccount.Text + "',postal='" + updatepostal.Text + "',password = '" + updatepwd.Text + "' Where id = '" +id.ToString()+ "'";
        SqlCommand updateinfo = new SqlCommand(updatequery, conn);
        updateinfo.ExecuteNonQuery();
        updateinfo.Dispose();
        updationmessage.Text="<p style='color:green;'>Information updated successfully</p>";

How to delete an item from this listbox?

I have a listbox where i need to be able to remove individual RegimeItems. These RegimItems belong to a specific user, but as they are right now the listbox shows them for specific user, so i don't know if i need to state that in the code. Currently it is showing no error however it does not return the listbox with the remaining RegimeItems, nor does it actually update the database with the changes.

Update: i am getting a null reference exception atmodel.RequestedSelected on the line foreach (int selected in model.RequestedSelected) in RemoveExercises.

Controller

    [HttpGet]
    public ActionResult ExerciseIndex(int? id, UserExerciseViewModel vmodel)
        {
            User user = db.Users.Find(id);
            UserExerciseViewModel model = new UserExerciseViewModel { AvailableExercises = GetAllExercises(), RequestedExercises = ChosenExercises(user, vmodel) };
            user.RegimeItems = model.RequestedExercises;
            return View(model);
        }
        [HttpPost]
        public ActionResult ExerciseIndex(UserExerciseViewModel model, string add, string remove, string send, int id, RegimeItem regimeItem)
        {
            User user = db.Users.Find(id);
            user.RegimeItems = model.RequestedExercises;
            RestoreSavedState(model);
            if (!string.IsNullOrEmpty(add))
                AddExercises(model, id);
            else if (!string.IsNullOrEmpty(remove))
                RemoveExercises(model, id);              
            SaveState(model);
            return View(model);
        }

        void SaveState(UserExerciseViewModel model)
        {
            model.SavedRequested = string.Join(",", model.RequestedExercises.Select(p => p.RegimeItemID.ToString()).ToArray());
            model.AvailableExercises = GetAllExercises().ToList();
        }

        void RemoveExercises(UserExerciseViewModel model, int id)
        {
            foreach (int selected in model.RequestedSelected)
        {
            RegimeItem item = model.RequestedExercises.FirstOrDefault(i => i.RegimeItemID == selected);
            if (item != null)
            {
                User user = db.Users.Find(id);
                user.RegimeItems.Remove(item);
            }
            RedirectToAction("ExerciseIndex");
        }

        void RestoreSavedState(UserExerciseViewModel model)
        {
            model.RequestedExercises = new List<RegimeItem>();

            //get the previously stored items
            if (!string.IsNullOrEmpty(model.SavedRequested))
            {
                string[] exIds = model.SavedRequested.Split(',');
                var exercises = GetAllExercises().Where(p => exIds.Contains(p.ExerciseID.ToString()));
                model.AvailableExercises.AddRange(exercises);
            }
        }

private List<Exercise> GetAllExercises()
        {
            return db.Exercises.ToList();
        }

        private List<RegimeItem> ChosenExercises(User user, UserExerciseViewModel model)
        {
            return db.Users
            .Where(u => u.UserID == user.UserID)
            .SelectMany(u => u.RegimeItems)
            .ToList();
        }

Models

 public class User
    {
        public int UserID { get; set; }
        public ICollection<RegimeItem> RegimeItems { get; set; }
        public User()
        {
            this.RegimeItems = new List<RegimeItem>();
        } 
    }
    public class RegimeItem
    {
        public int RegimeItemID { get; set; }
        public Exercise RegimeExercise { get; set; }
    }

ViewModel

public class UserExerciseViewModel
{
    public List<Exercise> AvailableExercises { get; set; }
    public List<RegimeItem> RequestedExercises { get; set; }
    public int? SelectedExercise { get; set; }
    public int[] AvailableSelected { get; set; }
    public int[] RequestedSelected { get; set; }
    public string SavedRequested { get; set; }
}

View(Segment only)

      <input type="submit" name="remove"
             id="remove" value="<<" />
  </td>
  <td valign="top">
      @Html.ListBoxFor(model => model.RequestedExercises, new MultiSelectList(Model.RequestedExercises, "RegimeItemID", "RegimeExercise.Name", Model.RequestedSelected))
  </td>

ViewBag does not show new line

I want to show text on two separate lines for the page header:

@section featured {
    <section class="featured">
        <div class="content-wrapper">
            <hgroup class="title">
                <h1>@ViewBag.Message</h1>
            </hgroup>
        </div>
    </section>
}

I have the following code in controller:

public ActionResult Login(string returnUrl)
{
    StringBuilder sb = new StringBuilder();
    sb.Append("Web Security Administration Portal");
    sb.AppendLine();
    sb.AppendLine();
    sb.Append("Services, Inc. - SSOAdmin v2.00");
    ViewBag.ReturnUrl = returnUrl;
    ViewBag.Message = sb.ToString();
    return View();
}

ViewBag does not show new line. When viewing source code of generated html, looks like that two strings are on separated lines, but when page is rendered, lines are not separated.

I tried to use sb.Append(Environment.NewLine) and sb.Append(Text{0}, Environment.NewLIne) as well. Does not help here.

What can be wrong here?

sending asp.net notification from one user to another

NEED HELP

i am developing a medicine prescription system.in this system when a new patient is added in the system notification will be send to the specific doctor.

outbound web requests fail when made from IIS sites using shared IP address

  • IIS 7.5 / Windows Server 2008 R2
  • Multiple IIS sites bound to the same IP address, using host names.
  • Inbound traffic to sites working fine.
  • Outbound web requests made by the back-end site code fail. Remote site returns 404 (NotFound).
  • Verified via a network trace that the traffic is making it to the remove server.
  • Same requests work fine if done from a site using a dedicated IP address (i.e. not shared w/ any other sites).

Anyone have any ideas on how to make this work or what could be going wrong?

Network trace on hosting server:

Successful request from site w/ non-shared IP address:

No.     Time            Source                Destination           Protocol Info
   6366 15:54:35.590463 192.168.1.76          173.194.77.121        HTTP     GET /key/value/one/two HTTP/1.1 
   6369 15:54:35.599879 173.194.77.121        192.168.1.76          TCP      http > 55407 [ACK] Seq=1 Ack=110 Win=344 Len=0
   6370 15:54:35.621587 173.194.77.121        192.168.1.76          HTTP     HTTP/1.1 200 OK  (application/json)
   6608 15:54:35.815774 192.168.1.76          173.194.77.121        TCP      55407 > http [ACK] Seq=110 Ack=357 Win=509 Len=0

Failed request from site using a shared IP address:

No.     Time            Source                Destination           Protocol Info
   9720 15:54:39.244192 192.168.1.80          173.194.77.121        HTTP     GET /key/value/one/two HTTP/1.1 
   9760 15:54:39.256958 173.194.77.121        192.168.1.80          TCP      [TCP segment of a reassembled PDU]
   9761 15:54:39.256962 173.194.77.121        192.168.1.80          HTTP     HTTP/1.1 404 Not Found  (text/html)
   9762 15:54:39.257027 192.168.1.80          173.194.77.121        TCP      55438 > http [ACK] Seq=212 Ack=1676 Win=512 Len=0

Code:

public static HttpWebRequest CreateWebRequest(string url, string method = "GET", string referer = null, string contentType = null, int timeout = 100000, string authentication = null, string bindToIpAddress = null, string host = null)
{
    var request = (HttpWebRequest)WebRequest.Create(url);

    if (!string.IsNullOrWhiteSpace(bindToIpAddress))
    {
        IPAddress bindIp;
        if (!IPAddress.TryParse(bindToIpAddress, out bindIp))
        {
            throw new ArgumentException("bindToIpAddress");
        }

        request.ServicePoint.BindIPEndPointDelegate = ((sp, rep, rc) =>
        {
            return new IPEndPoint(bindIp, 0);
        });
    }

    request.Accept = "*/*";
    request.ContentType = contentType;
    request.Referer = referer;
    request.Method = method;
    request.Timeout = timeout;

    if (!string.IsNullOrWhiteSpace(host))
    {
        request.Host = host;
    }

    return request;
}

string GetData()
{
    try
    {
        string result;

        var request = CreateWebRequest("http://ift.tt/1pLXQ3d", 
                                       "GET", 
                                       "somedomain.com", 
                                       timeout: (10 * 1000), 
                                       bindToIpAddress: "192.168.27.133" /*site IP*/);

        request.Accept = "application/json";

        using (var response = request.GetResponse())
        {
            using (var sr = new StreamReader(response.GetResponseStream()))
            {
                result = sr.ReadToEnd();
            }
        }

        return result;
    }
    catch (Exception ex)
    {
        return null;
    }
}

issue in AjaxControlToolKit 0x800a138f - JavaScript runtime error

i installed AjaxControlToolKit 15.1 to use it with my asp.net website i include it in the web.config as assembly

<add assembly="AjaxControlToolkit" />

i define it as a control with tagname

<add assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagPrefix="cc1" />

this is the piece of code in my aspx page where i use elemnts of the toolkit

<cc1:TabContainer ID="TabContainer1" runat="server" ActiveTabIndex="1"
TabStripPlacement="TopRight" Width="23%" Font-Size="Large">
    <cc1:TabPanel ID="TabPanel2" runat="server" HeaderText="menu" >
    </cc1:TabPanel></cc1:TabContainer>

my website works properly, but when i navigate out of the page with ajax control it gives me this error

Unhandled exception at line 1, column 56851 in http://localhost:6159/bundles/MsAjaxJs?v=c42ygB2U07n37m_Sfa8ZbLGVu4Rr2gsBo7MvUEnJeZ81

0x800a138f - JavaScript runtime error: Unable to get property 'length' of undefined or null reference

and this error occurs exactly here

$removeHandler(element, name, events[name]);

here is the code

   removeHandlers: function(element, events) {
    // Removes a set of event handlers from an element
    // This is NOT the same as $clearHandlers which removes all delegates
    // from a DomElement. This rather removes select delegates 
    // from a specified element and has a matching signature as $addHandlers
    // "element" - the element to modify
    // "events" - the template object that contains event names and delegates

    for (var name in events) {
        $removeHandler(element, name, events[name]);
    }
},

what to do please?

I'm in need of example of ASP.NET Web API 2 application interacting with XML file where this file is data source

In http://ift.tt/1DwfKuA there is a nice example of how to create Web API 2 application interacting with MS SQL Server database tables. But where can I get similar example where XML file used as data source instead of SQL Server database tables. Give me a reference to that example please.

Authenticate a USER in Asp.net MVC 5 without password

I want to authenticate a user with only user name and no password. My application does not have any user management data and I just want to create Identity with user details so that I can use it in the application.

I tried to copy the SingInAsync method to put this up

    private async Task InitializeUser()
    {
        var user = new ApplicationUser();
        user.Id = "abcd";
        user.UserName = "abcd";

        AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
        var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
        AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, identity);
    }

But it tells me and error - that user ID cannot be found. Is there someway I can just authenticate the user by username and assign the Identity with some details??

Using System.Windows.Media.Imaging in MVC results in "The operation completed successfully" error

We're using WPF libraries to resize images that are uploaded to an MVC action, and we periodically get an error that says "The operation completed successfully". The error happens on the "new DrawingVisual()" line in the below code.

public static BitmapFrame ResizeWithExcess(this BitmapFrame photo, int width, int height)
        {
            double dpiX = photo.DpiX == 0 ? 96 : photo.DpiX;
            double dpiY = photo.DpiY == 0 ? 96 : photo.DpiY;

            var targetVisual = new DrawingVisual();
            using (var targetContext = targetVisual.RenderOpen())
            {
                targetContext.DrawRectangle(Brushes.White, null, new Rect(0, 0, width * 96 / dpiX, height * 96 / dpiY));
                var x = ((width - (photo.Width * dpiX / 96)) / 2) * 96 / dpiX;
                var y = ((height - (photo.Height * dpiY / 96)) / 2) * 96 / dpiY;
                var w = photo.Width;
                var h = photo.Height;
                targetContext.DrawImage(photo, new Rect(x, y, w, h));
                targetContext.Close();
            }


            var target = new RenderTargetBitmap(width, height, dpiX, dpiY, PixelFormats.Default);
            target.Render(targetVisual);

            var targetFrame = BitmapFrame.Create(target);
            if (targetVisual.Dispatcher != null) targetVisual.Dispatcher.InvokeShutdown();
            return targetFrame;
        } 

The number of handles for the w3wp process, according to task manager, is something around 35k when this happens. The number of threads is around 270, and "GDI" is 0. I've tried forcing the dispatcher to initiate shutdown after the BitmapFrame.Create(target), and also added GC code, but none of these seem to make a difference. Right now the only solution is to recycle the app pool.

I've done some Googling and mostly what I've seen is for WPF apps that are desktop apps, or WPF XAML controls. Please note that if you'd like to see any of the code that calls this method, I can provide it. I'm basically using several tasks to have many resized versions created at one time, and I'm using "await" to watch for them to complete. I've also tried disposing the task, and that didn't seem to do anything at all.

Thanks.

EDIT: We've also seen an error that says "Not enough storage is available to process this command" occur sometimes immediately before the stream of "The operation completed successfully" errors.

Xamarin + ASP WebAPI + ASP MVC - which architecture is best?

I'm not found answer for my question - and opened this topic.

So I want develop project.

Database:

Or Couchbase or SQL Server (right now it is not important, but I think it will be Couchbase)

Website:

Asp .NET MVC + Angular etc. - Simple Website

Web Api:

ASP .NET WebAPI

**Mobile Application (This is hard side for me)**

I'm a good C# developer - it's a reason why I want write Application by Xamarin. If its bad idea - tell me (and tell me WHY IS BAD IDEA)

if is good framework, I have a few question: 1) How work with API 2) Or I need write for each platform(iOS, Android, WP) - service (like WCF) = (3 services?)

3) Which way better for Authentication (I want give to user option Registration by FB, Google, What's Up, etc...)

I dont know, maybe you can give me links for good topics, or same question here (I'm not found) Or maybe you can give me a name of good course on Lynda or plularsight?

Thank you.

I have a requirement which requires a custom week picker control to be used. The intention is to make the user [on hold]

I have a requirement which requires a custom week picker control to be used. The intention is to make the user able to pick dates which falls in sets of weeks. Ideally, I need a drop down like control which is capable of listing options like below for the current year. I am assuming there will be some way to write custom scripts to attain this.

Jan 1-7 Jan 8-14 Jan 15-21 Jan 22-28

I think my requirement was unclear, sorry for that. This is what I require. 1. I need a dropdown user control. 2. I need it to be used to pick dates like a datepicker control. 3. But instead of showing the calendar, I should be able to list out week values like below in my dropdown. I have attached a picture also on what it should like look actually.

Chose a date
Jan 1-7
Jan 8-14
Jan 15-21
Jan 22-28

Screehshot URL - http://ift.tt/1GTswFR

ASP.NET web application 'Could not load the assembly 'App_Web_'

I am trying to deploy my first ASP.NET web application.

So far I have gone to Build > Publish Web Site > Publish to file system and it has created my web application, packaging the .cs files into the bin directory in a number of .dlls. I have then copied this output to my web server

When developing on my local machine everything has been in the same directory, on the web server my web application is in a sub directory so root/myApplication.

My web.config in the root directory looks like this:

<system.web>
<customErrors mode="Off"/>
 <compilation batch="false" targetFramework="4.5" />
  <httpRuntime targetFramework="4.5" />

  <roleManager enabled="false" defaultProvider="MyRoles">
    <providers>
      <clear />
      <add name="MyRoles"
           type="MtManagementRoles"
           connectionStringName="ControlConnection" 
           applicationName="/myApplication"/>
    </providers>
  </roleManager>

  <authentication mode="Forms">
    <forms loginUrl="myApplication/login.aspx" defaultUrl="myApplication/Home.aspx" name="ControlAuthentication" timeout="30" />
  </authentication>
</system.web>

Whenever I access any .aspx page from my application on the web server I get the following error.

 Could not load the assembly 'App_Web_15jywomu'. Make sure that it is compiled before accessing the page.
<%@ page language="C#" autoeventwireup="true" inherits="Home, App_Web_15jywomu" %>

I have seen a number of other similar questions but none had a clear solution. I have noticed in the bin folder created by publishing the site through visual studio, there are two 'Compiled files'. inside these files it mentions virtual file paths. This file path matches my solution name and folder from the visual studio project but not the web server directories. Is this also an issue?

<preserve resultType="6" virtualPath="/WebTest/App_Code/" hash="2c00728f" filehash="" flags="140000" assembly="App_Code" />

Asp panel visible setting not changing

I'm trying to change the visible setting of a panel with a button click. I need the second panel become visible when the button at the bottom of first panel is clicked.

<asp:Content ID="Content3" ContentPlaceHolderID="cphContent" runat="Server">
<asp:Panel ID="pnl1" runat="server">
    <asp:GridView ID="gv1" runat="server" AutoGenerateColumns="False" CellPadding="0"
        AllowSorting="True" CssClass="grid" Visible="true">
        <Columns>
            //gv1 columns here
        </Columns>
    </asp:GridView>
    <asp:Button ID="btnModAdd" class="btn btn-primary" runat="server" Text="Ekle" OnClick="btnModAdd_Click">
    </asp:Button>
    <br />
    <div class="dataTables_paginate" id="example_info">
        <uc1:PagingControl ID="pcBottom" runat="server" PagingPosition="Top" />
    </div>
</asp:Panel>
<br />
<asp:Panel ID="pnl2" runat="server" Visible="false">
    <asp:GridView ID="gv2" runat="server" AutoGenerateColumns="False" CellPadding="0"
        AllowSorting="True" CssClass="grid" Visible="true">
        <Columns>
            //gv2 columns here..
        </Columns>
    </asp:GridView>
</asp:Panel>

And this is C# code of the button, quite simple.

public void btnModAdd_Click(object sender, EventArgs e)
{
    pnl2.Visible = true;
}

I can't understand what I'm missing to see here...

How to validate a form so if a field is missing or not correctly filled in the form will return false

I have the following form in my ASP.net page:

<asp:UpdatePanel runat="server" ClientIDMode="Static" ID="upReg" UpdateMode="Conditional">
        <ContentTemplate>
            <div class="dvHolder hidOverflow clearfix">
                <input id="txtFirst" type="text" name="login" value="" placeholder="First Name" runat="server" />
                <asp:Label Text="" runat="server" ID="lblRFName" CssClass="lblStyle" />
            </div>
            <div class="dvHolder hidOverflow clearfix">
                <input id="txtLast" type="text" name="login" value="" placeholder="Last Name" runat="server" />
                <asp:Label Text="" runat="server" ID="lblRLName" CssClass="lblStyle" />
            </div>
            <div class="dvHolder hidOverflow clearfix">
                <input id="txtEmail" type="text" name="login" value="" placeholder="Email Address" runat="server" />
                <asp:Label Text="" runat="server" ID="lblREmail" CssClass="lblStyle" />
            </div>
            <div class="dvHolder hidOverflow clearfix">
                <input id="txtUser" type="text" name="login" value="" placeholder="Username" runat="server" />
                <asp:Label Text="" runat="server" ID="lblRUser" CssClass="lblStyle" />
            </div>
            <div class="dvHolder hidOverflow clearfix">
                <input id="txtPass" type="password" name="login" value="" placeholder="Password" runat="server" />
                <asp:Label Text="" runat="server" ID="lblRPass" CssClass="lblStyle" />
            </div>
            <div class="dvHolder hidOverflow clearfix">
                <input id="txtPassC" type="password" name="login" value="" placeholder="Confirm Password" runat="server" />
                <asp:Label Text="" runat="server" ID="lblRPassC" CssClass="lblStyle" />
            </div>
            <div class="dvHolder hidOverflow clearfix setTextRight">
                <asp:Button ID="btnRegister" ClientIDMode="Static" runat="server" Text="Register" OnClick="btnRegister_Click" />
                <asp:Label runat="server" Text="" ID="lblSuccess" ClientIDMode="Static" />
            </div>
        </ContentTemplate>
    </asp:UpdatePanel>
</div>

Code-behind:

public void btnRegister_Click(object sender, EventArgs e)
{
    if (txtFirst.Value == "")
    {
        lblRFName.Text = "Please enter your first name";
        blnFrmComplete = false;
    }
    else
    {
        lblRFName.Text = "";
        blnFrmComplete = true;
    }
    if (txtLast.Value == "")
    {
        lblRLName.Text = "Please enter your last name";
        blnFrmComplete = false;
    }
    else
    {
        lblRLName.Text = "";
        blnFrmComplete = true;
    }
    if (txtEmail.Value == "")
    {
        lblREmail.Text = "Please enter your email address";
        blnFrmComplete = false;
    }
    else
    {
        if (!(IsValidEmail(txtEmail.Value)))
        {
            lblREmail.Text = "Please enter a valid email address";
            blnFrmComplete = false;
        }
        else
        {
            if (UserExistsWithEmail()) //function to check if email account already exists
            {
                lblREmail.Text = "The email already has an account";
                blnFrmComplete = false;
            }
            else
            {
                lblREmail.Text = "";
                blnFrmComplete = true;
            }
        }
    }
    if (txtUser.Value == "")
    {
        lblRUser.Text = "Please enter a desired username";
        blnFrmComplete = false;
    }
    else
    {
        if (UserExistsWithUsername()) //function to check if username already exists
        {

        }
        else
        {
            lblRUser.Text = "";
            blnFrmComplete = true;
        }
    }
    if (txtPass.Value == "")
    {
        lblRPass.Text = "Please enter a password";
        blnFrmComplete = false;
    }
    else
    {
        if (txtPassC.Value != "" && txtPass.Value == txtPassC.Value)
        {
            lblRPass.Text = "";
            blnFrmComplete = true;
        }
        else
        {
            lblRPass.Text = "Password do not match";
            blnFrmComplete = false;
        }
    }
    if (txtPassC.Value == "")
    {
        if (txtPass.Value != "")
        {
            lblRPassC.Text = "Please confirm your password";
            blnFrmComplete = false;
        }
        else
        {
            lblRPassC.Text = "Please enter your confirmed password";
            blnFrmComplete = false;
        }
    }
    else
    {
        if (txtPass.Value != "" || txtPass.Value == txtPassC.Value)
        {
            lblRPassC.Text = "";
            blnFrmComplete = true;
        }
        else
        {
            lblRPassC.Text = "Confirm password do not match";
            blnFrmComplete = false;
        }
    }

    if (blnFrmComplete == true)
    {
        CreateNewUser();
    }
    upReg.Update();
}

The issue I am having is because it is going sequential, if I am missing the email address but the password is correct it will return true.

How can I modify the code, so if any of the field is either missing or not properly filled in, blnFrmComplete will be false and the rest of the code won't be checked.

Summing duplicate values while reading in data

I am reading in 5000 rows of data from a stream as follows from top to bottom and store it in a new CSV file.

ProductCode |Name   | Type  | Price
ABC | Shoe  | Trainers  | 3.99
ABC | Shoe  | Trainers  | 4.99
ABC | Shoe  | Trainers  | 5.99 
ABC | Shoe  | Heels | 3.99
ABC | Shoe  | Heels | 4.99
ABC | Shoe  | Heels | 5.99
...

Instead of having duplicate entries, I want the CSV to have one row but with the Price summed:

ProductCode |Name   | Type  | Price
ABC | Shoe  | Trainers  | 14.97
ABC | Shoe  | Heels | 14.97

I store each row as a Product:

public class Product
    {
        public string ProductCode { get; set; }
        public string Name { get; set; }
        public string Type { get; set; }
        public string Price { get; set; }
    }

After reading the data from the stream I end up with an IEnumerable<Product>.

My code is then:

string fileName = Path.Combine(directory, string.Format("{0}.csv", name));            
var results = Parse(stream).ToList(); //Parse returns IEnumerable<Product>
if (results.Any())
            {
                using (var streamWriter = File.CreateText(fileName))
                {
                    //writes the header line out
                    streamWriter.WriteLine("{0},{1}", header, name);

                    results.ForEach(p => { streamWriter.WriteLine(_parser.ConvertToOutputFormat(p)); });
                    streamWriter.Flush();
                    streamWriter.Close();
                }

                Optional<string> newFileName = Optional.Of(SharpZipWrapper.ZipFile(fileName, RepositoryDirectory));
                //cleanup
                File.Delete(fileName);
                return newFileName;
            }

I don't want to go through the 5000 rows again to remove the duplicates but would like to check if the entry already exists before I add it to the csv file.

What is the most efficient way to do this?

Kendo DateTimePicker Culture Doesn't work Asp.net MVC

I have a kendo data picker to display the date, I want to have the date information in French for that I used the efficient script in my layout page like bellow:

<script>
        kendo.Culture("fr-FR");
    </script>
    <script src="~/Scripts/kendo/culture/kendo.fr-FR.js"></script>
    <script src="~/Scripts/kendo/kendo.tooltip.min.js"></script>
</script>

I even add the globalize script but even that the culture doesn’t change:

![<script type="text/javascript" src="~/scripts/globalize/globalize.js"></script>
    <script type="text/javascript" src="~/scripts/globalize/cultures/globalize.culture.fr-FR.js"></script>][1]

enter image description here This my kendo datapicker image:

@chxzy here is my kendo datapicker

 @(Html.Kendo().DatePickerFor(m => m./****).Events(e => e.Open("onOpen")).Footer("Today - #=kendo.toString(data, 'd') #").MonthTemplate("# if ($.inArray(+data.date, birthdays) != -1) { #" +
                                     "<div class=\"birthday\"></div>" +
                                 "# } #" +
                                 "#= data.value #")
                   .HtmlAttributes(new { @class = "form-control" })
                           .Culture("fr-FR")
    )

and here is my script code:

var today = new Date(),
    birthdays = [
        +new Date(today.getFullYear(), today.getMonth(), 11),
        +new Date(today.getFullYear(), today.getMonth() + 1, 6),
        +new Date(today.getFullYear(), today.getMonth() + 1, 27),
        +new Date(today.getFullYear(), today.getMonth() - 1, 3),
        +new Date(today.getFullYear(), today.getMonth() - 2, 22)
    ];

function onOpen() {
    var dateViewCalendar = this.dateView.calendar;
    if (dateViewCalendar) {
        dateViewCalendar.element.width(340);
    }
};

How Do I configure the correct authentication in IIS

Here's my scenario.

I have 2 virtual web applications. WebApp1 uses windows based authentication with impersonation turned on. WebApp2 is used simply as a launching point to stream a file back to the user. For the sake of focusing on the problem I'm trying to solve, let's just say we can't put this functionality in WebApp1.

We would like to have a link in WebApp1 call this 'service' (which is just really an aspx page) such that if the a user clicks this link in WebApp1, it launches this page in WebApp2 and not have to provide authentication. However, we want to avoid anyone going to webapp2 directly.

Key questions (focus on quick turn around):

  1. Are there any settings we could do in IIS to make this happen (like host based authentication)
  2. We could develop clever ways such as passing authentication tokens as parameters and have the two webapps do proper handshake, but again, if all we had was just a link to call this service and pass in basic paramters needed by WebApp2, what's the quickest way?

globalization in asp to change language french,urdu, english to dropdown list

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="amenities.aspx.cs" Inherits="amenities"%>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" Runat="Server" >

    <div>

        Change Language
    
       <br />
   <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" >
       <asp:ListItem Value="en-US">English</asp:ListItem>
       <asp:ListItem Value="ur">Urdu</asp:ListItem>
       <asp:ListItem Value="fr">French</asp:ListItem>
        </asp:DropDownList>
    </div>
 
    <div>
        <img src="Images/2.jpg" style="position:relative;top:20px; height:300px;" />
        <p style="position:relative;left:454px; top: -300px; width: 619px;"><asp:Label ID="Label2" runat="server" BackColor="<%$ Resources:Resource, BColor %>" ForeColor="<%$ Resources:Resource, FColor %>" Text="<%$ Resources:Resource, Text %>" ></asp:Label></p>


        <br /><img src="Images/3.jpg" style="position:relative; height:305px; top: -120px; left: 2px;" />
        <p style="position:relative;left:456px; top: -443px; width: 619px; bottom: 2332px;"><asp:Label ID="Label1" runat="server" Text="Label"></asp:Label></p>


        <br/><img src="Images/4.jpg" style="position:relative;top:-180px; height:330px; left: 5px; width: 450px;" />
        <p style="position:relative; top: -530px; left: 460px; width: 617px;">The spectacular happens at all of our hotels and resorts in 80 countries across six continents. Let us find the one that’s right for you. The five-star international Islamabad Marriott Hotel is located at the foot steps of the famous Margalla Hills and is within close proximity to Rawal Lake, the town centre, President & Prime Minister Houses, Ministry of Foreign Affairs, Senate, Parliament House, Foreign Missions, World Bank, Government Offices, corporate sector, Print and Electronic media offices etc. The Hotel is a favourite rendezvous of politicians, diplomats, businessmen and movers and shakers of the country. Owing to the perfect location of the hotel, it hardly takes half an hour to commute between the Hotel, the Islamabad International Airport and the places of interests.</p>


        <br/><img src="Images/5.jpg" style="position:relative; top: -372px; left: 488px; width: 587px; height: 249px;" />
        <p style="position:relative; top: -638px; left: 1px; width: 481px;">The all-day dining restaurant offers an extensive selection of international & local flavors on a la carte menu but also buffet available for breakfast,lunch,hi-tea and dinner.The restaurant is popular for business lunches,casual dinners and Sunday Brunch</p>
         
        <br/><img src="Images/6.jpg" style="position:relative; top: -424px; left: 485px; height: 276px; width: 590px;" />
        <p style="position:relative; top: -718px; left: 2px; width: 478px;">A truly authentic Japenese Restaurant. As you dine with us you will not only savour the sumptous flavour but also the spectacular design that actually makes you feel that you are actually in Japan. Sakura is made to capture your heart and soul imagination. Jason's steakhouse concept is centered around exceptionally high quality food and warm elegent atmosphere. we serve best steak available and uncompromising quality.Two Private Rooms, both with the capacity of 04-persons.</p>
        
         </div>       
   </asp:Content>

I am trying to use globalization in asp. I have created three resource files, fr,ur and resource. Languages are changing through selecting through drop down list, but I have to change other language too on the same page using drop down list.
box1 language changed, but how to change box2 language?
I have problems in resource file how to put 2 3 and 4 text in same resource fr resource file and how to link with it a label each resource file with a different label.

http://ift.tt/1cf7tFC please see the screenshot http://ift.tt/1zRahE8 resource file screenshot

CSHTML file outside Views folder

I have an ASP.NET MVC project and I want to put CSHTML files outside of Views Folder. While I can do so easily by adding the CSHTML files in my desired folder, I am not able to render partial view result from these files.

The folder structure I currently have is roughly as follows: Root | |--Templates | |---Welcome.cshtml | |--Views | |---

I'm using the below syntax from one of the controller actions

    public ActionResult Welcome()
    {
        return PartialView("Welcome");
    }

However, doing so, razor is not able to locate the Welcome.cshtml. I have read about using a custom view engine to change the default search location etc. etc. but wondering if this just can be solved by addition configuration.

asp.net SERVER_NAME returns wrong domain name

Can anyone explain me how the asp.net/iis gets SERVER_NAME variable ? The problem appears when we change our production domain name. The backend code returns old value by calling the following method Request.ServerVariables["SERVER_NAME"] . Could it be related to DNS update ?

How to retrieve which radio button within a LI is selected

<ul class="ulGroup" runat="server" id="ulGroup">
    <li>
        <input type="radio" name="grouptype" id="rdGroup1" class="css-checkbox" value="Group 1" checked="checked" runat="server" />
        <label for="rdGroup1" class="css-label radGroup1">Group 1</label>
    </li>
    <li>
        <input type="radio" name="grouptype" id="rdGroup2" class="css-checkbox" value="Group 2" runat="server" />
        <label for="rdGroup2" class="css-label radGroup1">Group 2</label>
    </li>
    <li>
        <input type="radio" name="grouptype" id="rdGroup3" class="css-checkbox" value="Group 3" runat="server" />
        <label for="rdGroup3" class="css-label radGroup1">Group 3</label>
    </li>
    <li>
        <input type="radio" name="grouptype" id="rdGroup4" class="css-checkbox" value="Group 4" runat="server" />
        <label for="rdGroup4" class="css-label radGroup1">Group 4</label>
    </li>
</ul>

How do I retrieve which li radio button is selected from code-behind.

When I run the code, I get the following error:

Parser Error Message: Cannot create an object of type 'System.Boolean' from its string representation 'checked' for the 'Checked' property.

using (SqlConnection sc = new SqlConnection(gloString))
{
    using (SqlCommand qSave = new SqlCommand())
    {
        qSave.Connection = sc;
        qSave.CommandType = CommandType.Text;
        qSave.CommandText = @"INSERT INTO [db1].[dbo].[tbl1] (FirstName, LastName, EmailAddress, UN, UP, DietGroup) VALUES (@FirstName, @LastName, @EmailAddress, @UN, @UP, @DietGroup)";
        qSave.Parameters.AddWithValue("@FirstName", txtFirst.Value);
        qSave.Parameters.AddWithValue("@LastName", txtLast.Value);
        qSave.Parameters.AddWithValue("@EmailAddress", txtEmail.Value);
        qSave.Parameters.AddWithValue("@UN", txtUser.Value);
        qSave.Parameters.AddWithValue("@UP", txtPass.Value);
        qSave.Parameters.AddWithValue("@DietGroup", rdGroup1.Checked); //Instead of rdGroup1.Checked, I would like to get which of the four radio is checked
    }
}

Ajax in .NET for form editing

I have a form where user can create a complex object. When click on "Add action", then an Ajax call is made in JS, and I use a partialview as return, then I show it as accordion in the form and all is OK for that creation form.

Now, I want to make the same form but for editing, so I have my basic form that works well, but I'm like blocked for the edit form, especially for the partiaviews called by pressing the "Add action" button ...

In the Edit Form, I have a List that contains all the data of each "add action", How can I handle/load/show this in the view?

Can I make one include of the partialView (and passing data) by only using C#?

here is what I've did:

Finally, this is my ajax call from Create JS:

    var x = 0; // problem count
    // method called when user click on add problem
    $(".add_action_button").click(function (event) {
        event.preventDefault();

        // ajax call to partial with prefix
        var prefix = "actionList[" + x + "]";
        $.ajax({
            url: "@Url.Action("AddAction", "Home")",
            cache: false,
            type: "GET",
            dataType: "html",
            traditional: true,
            data: { prefix: prefix, accordioncounter: x + 1 },
            success: function (result) {
                // lot of stuff
            }
        });
    });

AddAction Controller:

public ActionResult AddAction(string prefix, int accordioncounter)
        {
            ViewBag.Prefix = prefix;
            ViewBag.accordioncounter = accordioncounter;

            return PartialView("_AddAction", new ActionViewModel());
        }

_AddAction View:

@model MyModel.ActionViewModel

@{
    if (!string.IsNullOrEmpty(ViewBag.Prefix))
    {
        ViewData.TemplateInfo.HtmlFieldPrefix = ViewBag.Prefix;
    }
}
...

And I have this object in my model from my Edit view:

public List<ActionViewModel> actionList { get; set; }

Thanks in advance for your help :-)

Searching with a dropdown list in asp.net MVC

I'm new to ASP.NET MVC. I want to use selected items from my dropdownlist to search my database table. The dropdownlist was generated from a BOL model which automatically binds to the view.

Below are my code snippet

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BLL;
using BOL;

namespace DentiCareApp.Areas.Admin.Controllers
{
    [AllowAnonymous]
    public class GenerateInvoiceController : Controller
    {
        private TreatmentBs objBs;

        public GenerateInvoiceController()
        {
                objBs = new TreatmentBs();
        }
        // GET: Admin/GenerateInvoice
        public ActionResult Index(string CompanyID)
        {
            DentiCareEntities db = new DentiCareEntities();
            ViewBag.CompanyId = new SelectList(db.Companies, "CompanyId", "CompanyName");

            if (CompanyID == null)
            {
                return View();
            }
            else
            {
                return View(db.Treatments.Where(x => x.Company == CompanyID.Take(50)));
            }
            //return View();
        }

Also below is the interface of view.

enter image description here

Secondly, I also want the search result to appear on the same page. How do I do this? If I create a separate action for this, I will need to create a separate view for it. Can partial view be used? If so how?

PostAsJsonAsync returning null

I am currently posting a json string to an API to receive an object containing various values.

This is the json string i am posting:

{"SomeProperty":1,"DimensionOne":4,"DimensionTwo":6,"IdNumber":0}

Now I don't have issues with the Json string itself because I've tested this string in Fiddler going to the api, and it works perfectly fine, returning all the values I need.

The only difference between what I am doing and what Fiddler is doing is that I am going from the script to a WebService that posts to the API.

Here is the code I am using for the WebService:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class WebService1 : System.Web.Services.WebService
{
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public ObjectType Relay(string json)
    {
        const string url = "https://api.com";
        var client = new HttpClient {BaseAddress = new Uri(url)};

        client.DefaultRequestHeaders.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var response = client.PostAsJsonAsync("api/v1/GetObject", json).Result;

        if (response.IsSuccessStatusCode)
        {
            var objectRequest = Task.FromResult(response.Content.ReadAsStringAsync());
            return JsonConvert.DeserializeObject<ObjectType>(objectRequest.Result.Result);
        }

        return null;
    }
}

So far it has only returned null (obviously because response.IsSuccessStatusCode is not TRUE)

But when I comment out the if brackets and remove the return null, it gives me an empty object when I should be receiving data. All the inputs are correct.

I'm wondering if I should be using a method other than PostAsJsonAsync, or if there is anything else I should be doing to the json string or json header.

Again, the json string is in correct format as it worked with Fiddler and has previously worked when going directly from the website to the API (without a WebService).

I'd appreciate any suggestions. Thanks in advance.

Access Database Unchanged

I'm trying to add comments to a database. I'm starting with an Access database to be sure I have the code correct before going to the next step. The two files I'm using are Comments.aspx and the code file Comments.aspx.vb.

Here's what I have so far. The contents of Comments.aspx are:

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Comments.aspx.vb" Inherits="Comments" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://ift.tt/15udxSm    transitional.dtd">
<html xmlns="http://ift.tt/lH0Osb">
<head runat="server">
    <title>Leave Your Comments</title>
    <style type="text/css">
        .style2 { width: 250px; }
        .style3 { color: #793300; }
    </style>
</head>

<body>
    <form id="frmComments" runat="server">
    <div style="text-align: center">
        <h1 class="style3">Please leave your comments below.</h1>
 <table align="center">
        <tr><td class="style3"> 
            First Name : </td>
            <td class="style2"> 
                <asp:TextBox ID="txtFName" runat="server" Width="250px"></asp:TextBox></td> </tr>
        <tr> <td class="style3"> 
            Last Name : </td>
            <td class="style2"> 
            <asp:TextBox ID="txtLName" runat="server" Width="250px"></asp:TextBox></td></tr>
        <tr> <td class="style3"> 
            E-Mail : </td>
            <td class="style2">
            <asp:TextBox ID="txtEmail" runat="server" Width="250px"></asp:TextBox></td></tr>
        <tr> <td class="style3"> Comments :&nbsp; </td>
            <td class="style2"> 
            <asp:TextBox ID="txtComments" runat="server" TextMode = "MultiLine" Height="60px"   Width="250px"></asp:TextBox></td></tr> 
</table>
    <br /><asp:ImageButton ID="btnContactUs" runat="server" Height="50px"
                ImageUrl="~/Images/Dark_Continue.gif" />
    </div>
    </form>
</body>
</html>

The contents of Comments.aspx.vb are:

Imports System.Data.OleDb

Partial Class Comments
  Inherits System.Web.UI.Page
  Private Property FNameParam As Object
  Private Property LNameParam As Object
  Private Property CommentsParam As Object
  Private Property EMailParam As OleDbParameter

Sub ImageButtonRun_Click(ByVal sender As Object, ByVal e As EventArgs)
   Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=/Test.mdb"

   Dim dbConnection As New OleDbConnection(ConnectionStringSettings)
      dbConnection.Open()
   Dim commandString As String = "INSERT INTO Contacts(FName, LName, EMail, Comments) " & _
    "Values(@FName, @LName, @EMail, @Comments)"

   Dim dbCommand As New OleDbCommand(commandString, dbConnection)

   Dim FNameParam As New OleDbParameter("@FName", OleDbType.VarChar, 50)
      FNameParam.Value = txtFName.Text
      dbCommand.Parameters.Add(FNameParam)

   Dim LNameParam As New OleDbParameter("@LName", OleDbType.VarChar, 50)
      LNameParam.Value = txtLName.Text
      dbCommand.Parameters.Add(LNameParam)

   Dim EMailParam As New OleDbParameter("@EMail", OleDbType.VarChar, 255)
      EMailParam.Value = txtEmail.Text
      dbCommand.Parameters.Add(EMailParam)

   Dim CommentsParam As New OleDbParameter("@Comments", OleDbType.VarChar, 255)
      CommentsParam.Value = txtComments.Text
      dbCommand.Parameters.Add(CommentsParam)

  dbCommand.ExecuteNonQuery()
     dbConnection.Close()
End Sub

Private Function ConnectionStringSettings() As String
    Throw New NotImplementedException
End Function

End Class

Absolutely nothing at all happens after I fill in the form and click the image button. Most of what I've read points me in this direction' but it's obviously wrong. Please help.

Stored Procedure not execute as expected

I have written following stored procedure

CREATE procedure [dbo].[findUSerID]
    @Column_name varchar(50),
    @TR_ID int
AS
    DECLARE @sql nvarchar(max) = 'SELECT ' +@Column_name+ ' 
                                  FROM Transfer_TB 
                                  WHERE TID =' + CAST(@TR_ID AS VARCHAR(10))

    EXEC sp_executesql @sql

Table definition :

CREATE TABLE [dbo].[Transfer_TB]
(
    [TID] [int] NULL,
    [ABC] [varchar](20) NULL,
    [XYZ] [varchar](50) NULL,
    [LMN] [varchar](50) NULL,
    [PQR] [varchar](50) NULL,
)

But it does not return the proper output.

Like I have called it from my asp page code for that using n tier architecture.

public string check_validID(string branch,int trId)
{
    string user_Br_ID;
    clsBranch_TB objbr = new clsBranch_TB();
    clsUserTB objuser = new clsUserTB();
    objuser.User_Branch = 'XYZ';
    objuser.Extra_Int = 32;

    DataSet ds = clsAdminLogic.findUSerID(objuser);

    if (ds.Tables[0].Rows.Count == 0)
    {
        user_Br_ID = clsAdminLogic.getno_of_Emp(objbr);
    }
    else 
    {
        user_Br_ID = ds.Tables[0].Rows[0][0].ToString();
    }

    return user_Br_ID;
}

 public static DataSet findUSerID(clsUserTB objuser)
 {
        DataSet ds = DataAccessLayer.clsLogs.findUSerID(objuser);
        return ds;
 }

 public static DataSet findUSerID(clsUserTB objuser)
 {
     SqlParameter[] param = {
                              new SqlParameter("@TR_ID",objuser.Extra_Int),
                              new SqlParameter("@Column_name",objuser.User_Branch)
                            };
     DataSet ds = DataAccessLayer.SqlHelper.FillDataNewRJ(
                     DataAccessLayer.clsDataAccessLayer.con.ConnectionString.ToString(),
                     CommandType.StoredProcedure, "findUSerID", (param)
            );
     return ds;
}

As it executes it, there is value present in database, but still it enters into else part of that function.

Please help me and guide if something wrong in above code

Default C# ASP.NET nav bar resizing issue

I am new to ASP so I am still trying to find me way around. I am running into a problem where the default nav bar that came with the project is resizing over the content if I change the width of the window.

Default Project meaning: In VS13 create a new ASP.NET Web Forms project. The Navigation that comes as a template with that project is what I stared with. Simply add a few more links to the default and you can see the resizing issue I am having.

I can't figure out how to change the padding of the content when the top nav bar resizes.

Examples:

Before: enter image description here

After: enter image description here

How do I stop this from happening?

Edit: Code from Site.Master

<form runat="server">
        <asp:ScriptManager runat="server">
            <Scripts>
                <%--To learn more about bundling scripts in ScriptManager see http://ift.tt/1eMOMJk --%>
                <%--Framework Scripts--%>
                <asp:ScriptReference Name="MsAjaxBundle" />
                <asp:ScriptReference Name="jquery" />
                <asp:ScriptReference Name="bootstrap" />
                <asp:ScriptReference Name="respond" />
                <asp:ScriptReference Name="WebForms.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebForms.js" />
                <asp:ScriptReference Name="WebUIValidation.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebUIValidation.js" />
                <asp:ScriptReference Name="MenuStandards.js" Assembly="System.Web" Path="~/Scripts/WebForms/MenuStandards.js" />
                <asp:ScriptReference Name="GridView.js" Assembly="System.Web" Path="~/Scripts/WebForms/GridView.js" />
                <asp:ScriptReference Name="DetailsView.js" Assembly="System.Web" Path="~/Scripts/WebForms/DetailsView.js" />
                <asp:ScriptReference Name="TreeView.js" Assembly="System.Web" Path="~/Scripts/WebForms/TreeView.js" />
                <asp:ScriptReference Name="WebParts.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebParts.js" />
                <asp:ScriptReference Name="Focus.js" Assembly="System.Web" Path="~/Scripts/WebForms/Focus.js" />
                <asp:ScriptReference Name="WebFormsBundle" />
                <%--Site Scripts--%>
            </Scripts>
        </asp:ScriptManager>

        <div class="navbar navbar-inverse navbar-fixed-top">
            <div class="container">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    <a class="navbar-brand" runat="server" href="~/">Winded Warriors</a>
                </div>
                <div class="navbar-collapse collapse">
                    <ul class="nav navbar-nav">
                        <li><a runat="server" href="~/">Home</a></li>
                        <li><a runat="server" href="~/Players">Players</a></li>
                        <li><a runat="server" href="~/Stats">Stats</a></li>
                        <li><a runat="server" href="~/MatchHistory">Match History</a></li>
                        <li><a runat="server" href="~/Schedule">Schedule</a></li>
                        <li><a runat="server" href="~/Photos">Photos</a></li>
                        <li><a href="http://ift.tt/1EnMM0R"><img src="http://ift.tt/1JTGtK7" height="16"></a> </li>
                        <li><a href="https://www.youtube.com/channel/UCudcTnN9fHNLigUTvmGv_Fg"><img src="http://ift.tt/1EnMM0T" height="16"></a></li>
                    </ul>
                </div>
            </div>
        </div>
        <!-- why doesnt this not space correctly???? -->
        <div class="container body-content">
            <asp:ContentPlaceHolder ID="MainContent" runat="server">
            </asp:ContentPlaceHolder>
            <hr />
            <footer>
                <p>&copy; <%: DateTime.Now.Year %> - Winded Warriors Soccer</p>
            </footer>
        </div>
    </form>

How do I manipulate WebGrids?

I'm using ASP.NET and the MVC pattern. I have the following code which I use to style the columns:

<div id="grid">
    @grid.GetHtml(columns: grid.Columns(
            grid.Column("Amount", "Amount", canSort: true, style: "column"),
            grid.Column("ShelfLife", "ShelfLife", canSort: true, style: "column"),
            grid.Column("Size", "Size", canSort: true, style: "column"),
            grid.Column("Type", "Type", canSort: true, style: "column"),
            grid.Column("Unit", "Unit", canSort: true, style: "column")
    ))
</div>

I use the following code to load the data for the grid:

@{
    ViewBag.Title = "ListView";
    Layout = "~/Views/Shared/_Layout.cshtml";
    var grid = new WebGrid(Model, defaultSort: "null");
}

It's probably a long and trivial way of doing this... but I'd like to know how I can manipulate what's in the grid? For example, I'd like to add a button for every row. I'd also like to recolour every second row. How would I do this? Thanks in advance.

does Session free memory when User Close Browser in ASp.NET?

As per my knowledge I know we have 2 types of Session.First is in-proc and another is out-proc. So my question is when User close his browser , does it free session memory from Server too or not?

Thanks, Parveen.

Javascript not loading when using HttpContext.Current.Response.WriteFile

I am opening PDF file in my aspx page using HttpContext.Current.Response.WriteFile(). My problem is I have some script in same page and it is not triggering.

<script type="text/javascript">
    $(document).ready(function () {
        alert("in");
    });
</script>