Right now the controller servlet seems to handle dispatching correctly, so far as I can tell, in that it dispatches to a specified JSP. It uses an instance of MyToken, kept in the session, to track the session. The controller dispatches to different JSP's depending on booleans of the MyToken instance.

I've put all the JSP's in WEB-INF so that only the controller servlet is exposed -- preferably, all requests/responses go through the servlet.

The intention is to use the MyToken object as a session bean.

How does a JSP access such a session bean with EL? The login.jsp page needs set the name value for the bean, and then dispatch back to the controller.

Can that be done with EL? Or, is it only possible to access a session bean with the JSTL?

It's intended as MVC, sans a framework -- just a very simple login with a simple bean for storing simple user data. A properties file contains a list of valid users which the token credentials are checked against.

Controller servlet:

package net.bounceme.dur.servlets;

import filter.PropertiesReader;
import java.io.IOException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/controller")
public class Controller extends HttpServlet {

    private static final Logger log = Logger.getLogger(Controller.class.getName());

    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        log.info("controller processing request..");
        String jsp = dispatcherLogic(request.getSession());
        request.getRequestDispatcher("/WEB-INF/" + jsp).forward(request, response);
    }

    private String dispatcherLogic(HttpSession session) {
        Properties properties = PropertiesReader.getProps();
        MyToken token = (MyToken) session.getAttribute("token");
        if (token != null) {
            token.setAuthenticated(properties.containsValue(token.getName()));
        } else {
            token = new MyToken();
        }
        log.info(token.toString());
        session.setAttribute("token", token);
        if (token.isAuthenticated()) {
            return "success.jsp";
        } else {
            if (token.isAttemptedLogin()) {
                return "fail.jsp";
            } else {
                return "login.jsp";
            }
        }
    }

    private String dispatcherLogic0(HttpSession session) {
        Map<String, String> p = PropertiesReader.getPropsAsMap();
        Enumeration<String> names = session.getAttributeNames();
        for (String s : Collections.list(names)) {
            log.info(s);
        }
        MyToken t = (MyToken) session.getAttribute("token");
        for (String s : p.keySet()) {
            //  t.getName() = p.containsValue(s);
        }
        return "hello.jsp";  //always to hello page for now
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "controller";
    }
}


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>login</title>
    </head>
    <body>
        <form name="bar" action="controller" method="POST">
            name <input type="text" name="username" value="Jim" size='20' />
            <p>
                <input type="submit">
            </p>
        </form>
    </body>
</html>

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <filter>
        <filter-name>AuthenticateFilter</filter-name>
        <filter-class>filter.AuthenticateFilter</filter-class>
        <init-param>
            <param-name>Name</param-name>
            <param-value>Value</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>AuthenticateFilter</filter-name>
        <url-pattern>/foo.jsp</url-pattern>
    </filter-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
    <jsp-config>
        <jsp-property-group>
            <description>all</description>
            <display-name>all</display-name>
            <url-pattern>/*</url-pattern>
            <scripting-invalid>true</scripting-invalid>
        </jsp-property-group>
    </jsp-config>
</web-app>

token for login credentials:

package net.bounceme.dur.servlets;

import java.util.logging.Logger;

public class MyToken {//should probably be immutable...

    private static Logger log = Logger.getLogger(MyToken.class.getName());

    private String name = "nemo";
    private String role = "captain";
    private String password = "abc";
    private boolean authenticated = false;  //remove down the road?
    private boolean attemptedLogin = false;  //remove down the road?

    public MyToken() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public boolean isAuthenticated() {
        return authenticated;
    }

    public void setAuthenticated(boolean authenticated) {
        this.authenticated = authenticated;
    }

    public boolean isAttemptedLogin() {
        return attemptedLogin;
    }

    public void setAttemptedLogin(boolean attemptedLogin) {
        this.attemptedLogin = attemptedLogin;
    }

    @Override
    public String toString() {
        return name + authenticated + attemptedLogin;
    }
}

For very simple MVC with JSP and servlet, what's the functionality of a filter?

There's a controller servlet in the example below, and then each JSP presents, I suppose, a different view. The servlet interacts mostly with the model, a properties file with a list of users. However, login.jsp will mutate the token, which is a session bean.

I realize that generally Spring, or facelets, or some other framework would come into play -- I'm just feeling my way.

It's a correct usage of filters for the servlet to use the filter? I'm not sure how a filter would come into play here -- except that the "logic" of which JSP to dispatch to could maybe be extracted from the controller servlet and exist on its own in the filter...?

The JSP's wouldn't need access to the filter, since all dispatching is done through the servlet(?).

servlet:

package net.bounceme.dur.servlets;

import filter.PropertiesReader;
import java.io.IOException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/controller")
public class Controller extends HttpServlet {

    private static final Logger log = Logger.getLogger(Controller.class.getName());

    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        log.info("controller processing request..");
        String jsp = dispatcherLogic(request.getSession());
        request.getRequestDispatcher("/WEB-INF/" + jsp).forward(request, response);
    }

    private String dispatcherLogic(HttpSession session) {
        Properties properties = PropertiesReader.getProps();
        MyToken token = (MyToken) session.getAttribute("token");
        if (token != null) {
            token.setAuthenticated(properties.containsValue(token.getName()));
        } else {
            token = new MyToken();
        }
        log.info(token.toString());
        session.setAttribute("token", token);
        if (token.isAuthenticated()) {
            return "success.jsp";
        } else {
            if (token.isAttemptedLogin()) {
                return "fail.jsp";
            } else {
                return "login.jsp";
            }
        }
    }

    private String dispatcherLogic0(HttpSession session) {
        Map<String, String> p = PropertiesReader.getPropsAsMap();
        Enumeration<String> names = session.getAttributeNames();
        for (String s : Collections.list(names)) {
            log.info(s);
        }
        MyToken t = (MyToken) session.getAttribute("token");
        for (String s : p.keySet()) {
            //  t.getName() = p.containsValue(s);
        }
        return "hello.jsp";  //always to hello page for now
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "controller";
    }
}

filter:

package net.bounceme.dur.filter;

import filter.PropertiesReader;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Properties;
import java.util.logging.Logger;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class AuthenticateFilter implements Filter {

    private static final Logger log = Logger.getLogger(AuthenticateFilter.class.getName());
    private FilterConfig filterConfig = null;

    public AuthenticateFilter() {
    }

    private void doBeforeProcessing(ServletRequest request, ServletResponse response) throws IOException, ServletException {
        log.info("do before processing..");
    }

    private void doAfterProcessing(ServletRequest request, ServletResponse response) throws IOException, ServletException {
        log.info("do after processing");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        log.info("do filter");
    }

    public FilterConfig getFilterConfig() {
        return (this.filterConfig);
    }

    public void setFilterConfig(FilterConfig filterConfig) {
        this.filterConfig = filterConfig;
    }

    @Override
    public void destroy() {
    }

    private void props() {
        log.info("properties file:");
        Properties properties = PropertiesReader.getProps();
        StringBuilder sb = new StringBuilder();
        for (String key : properties.stringPropertyNames()) {
            String value = properties.getProperty(key);
            sb.append("\n" + key + " => " + value);
        }
        log.info(sb.toString());
    }

    @Override
    public void init(FilterConfig filterConfig) {
        log.info("init");

        this.filterConfig = filterConfig;
        if (filterConfig != null) {
            log.info("SessionCheckFilter:Initializing filter");
        } else {
            log.warning("null filterConfig");
        }

        props();

    }

    @Override
    public String toString() {
        if (filterConfig == null) {
            return ("SessionCheckFilter()");
        }
        StringBuilder sb = new StringBuilder("SessionCheckFilter(");
        sb.append(filterConfig);
        sb.append(")");
        return (sb.toString());
    }

    private void sendProcessingError(Throwable t, ServletResponse response) {
        log.info("send processing error");
        String stackTrace = getStackTrace(t);

        if (stackTrace != null && !stackTrace.equals("")) {
            try {
                response.setContentType("text/html");
                try (PrintStream ps = new PrintStream(response.getOutputStream()); PrintWriter pw = new PrintWriter(ps)) {
                    pw.print("<html>\n<head>\n<title>Error</title>\n</head>\n<body>\n"); //NOI18N
                    pw.print("<h1>The resource did not process correctly</h1>\n<pre>\n");
                    pw.print(stackTrace);
                    pw.print("</pre></body>\n</html>"); //NOI18N
                }
                response.getOutputStream().close();
            } catch (Exception ex) {
            }
        } else {
            try {
                try (PrintStream ps = new PrintStream(response.getOutputStream())) {
                    t.printStackTrace(ps);
                }
                response.getOutputStream().close();
            } catch (Exception ex) {
            }
        }
    }

    public static String getStackTrace(Throwable t) {
        String stackTrace = null;
        try {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            t.printStackTrace(pw);
            pw.close();
            sw.close();
            stackTrace = sw.getBuffer().toString();
        } catch (Exception ex) {
        }
        log.warning(stackTrace);
        return stackTrace;
    }

}

login token:

package net.bounceme.dur.servlets;

import java.util.logging.Logger;

public class MyToken {//should probably be immutable...

    private static Logger log = Logger.getLogger(MyToken.class.getName());

    private String name = "nemo";
    private String role = "captain";
    private String password = "abc";
    private boolean authenticated = false;
    private boolean attemptedLogin = false;

    public MyToken() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public boolean isAuthenticated() {
        return authenticated;
    }

    public void setAuthenticated(boolean authenticated) {
        this.authenticated = authenticated;
    }

    public boolean isAttemptedLogin() {
        return attemptedLogin;
    }

    public void setAttemptedLogin(boolean attemptedLogin) {
        this.attemptedLogin = attemptedLogin;
    }

    @Override
    public String toString() {
        return name + authenticated + attemptedLogin;
    }
}

Currently, my application can track whenever user has logged in or out. The logging out activity is saved to database because User simply click a button. However, I would be interested in how to implement something similar but when user's ticket is no longer valid, either because it's been removed or expired.

I would like to handle any event (if possible) that is fired whenever user is no longer valid.

Is it possible to implement anything like this?

Cheers!

I have created a web service which works fine and i have also added the webservice to my android app project in xamarin studio but i dont know how i can call my web service to work on my android app. I want to insert data into the remote database from my android app.

here is my webservice code

[WebMethod]
public string insertData(string title, string coment)
{
    string Message;

    SqlConnection con = new SqlConnection(connectionString);
    SqlCommand cmd = new SqlCommand("INSERT INTO Header (title, coment) 
                    VALUES (@title, @coment)", con);

    cmd.Parameters.Add("@title", SqlDbType.NVarChar, 50).Value = title;
    cmd.Parameters.Add("@coment", SqlDbType.NVarChar, 50).Value = coment;

    con.Open();
    int result = cmd.ExecuteNonQuery();
    if (result == 1)
    {
        Message = " Details inserted successfully";
    }
    else
    {
        Message =" Details not inserted successfully";
    }
    con.Close();
    return Message;

}

also here is my android layout

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/backgd"
    android:minWidth="25px"
    android:minHeight="25px">
    <TextView
        android:text=""
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView1" />
    <TextView
        android:text=""
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView1" />
    <TextView
        android:text=""
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView1" />
    <TextView
        android:text="Title"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView1" />
    <EditText
        android:inputType="textPersonName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText1"
        android:background="#ffffffff" />

    <TextView
        android:text="Comment"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView1" />
    <EditText
        android:inputType="textPersonName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText1"
        android:background="#ffffffff" />
    <Button
        android:text="Insert"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button1" />
</LinearLayout>

I've added the webservice to my project which gives me a reference.cs code but i dont understand how to use it. can you help with how i can make the text filled data to be inserted into my remote database through my webservce. thanks

function Search_Gridview(strKey, strGV) {
    var strData = strKey.value.toLowerCase().split(" ");
    var tblData = document.getElementById(strGV);
    var rowData;
    for (var i = 1; i < tblData.rows.length; i++) {
        rowData = tblData.rows[i].innerHTML;
        var styleDisplay = 'none';
        for (var j = 0; j < strData.length; j++) {
            if (rowData.toLowerCase().indexOf(strData[j]) >= 0)
                styleDisplay = '';
            else {
                styleDisplay = 'none';
                break;
            }
        }
        tblData.rows[i].style.display = styleDisplay;
    }
}    

in the grid I wrote this code but it is search only for one page in grid view I want it in all grid view pages

and then in textbox I use

          <asp:TextBox ID="txtsearch" runat="server" onkeyup="Search_Gridview(this, 'GridView1')"></asp:TextBox>

i have a jqgrid.I need to add a shape(like circle ) into jqgrid cell and fill that circle with color .

I have an asp.net form that looks something like this...

<asp:Panel ID="PanelForm" runat="server" >
    <asp:FormView ID="FormView1" runat="server" >
        <asp:EditItemTemplate>
            <asp:FormView ID="FormView2" runat="server" >
                <InsertItemTemplate>
                    <asp:TextBox ID="myControl" runat="server" />
                </InsertItemTemplate>
            </asp:FormView>
        </asp:EditItemTemplate>
    </asp:FormView>
</asp:Panel>

I want to set the text of a TextBox called "myControl" to "myText".

The code below results in t = null which throws an "Object reference not set to an instance of an object." error.

FormView fv2 = (FormView)FormView1.FindControl("FormView2");
fv2.ChangeMode(FormViewMode.Insert);
TextBox t = (TextBox)fv2.FindControl("myControl");
t.Text = "myText";

How to update this TextBox from the code behind?

I am using OnRowDataBound to automatically add a link button to my grid view that looks like this. The problem I am having is setting the command argument.

<asp:LinkButton ID = "lnkDelete" Text = "Delete" CommandArgument = '<%# Eval("Value") %>' runat = "server" OnClick = "DeleteFile" />

Below is the code that adds the links. I set the command argument to Eval("Value") but that doesn't work. Here is a link to the original code that I'm trying to change so it is dynamic.

protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        LinkButton lnkView = new LinkButton();
        lnkView.ID = "lnkDelete";
        lnkView.Text = "Delete";
        lnkView.Click += DeleteFile;
        lnkView.CommandArgument = Eval("Value");
        e.Row.Cells[1].Controls.Add(lnkView);
    }

Hi There so basically Im trying to create an interactive staff sheet so when the user fills it out and they need to add another row them click another button and it generates a new dropdown list which contains staff names for them to select. So far when you click the button it does generate a new dropdown list with the same values however I need it to create another each time its clicked and this is my code.

Dim ctrl As Control
        Dim i As Integer = 0
        Dim DDlist As String
        Dim Con As SqlConnection
        Dim cmd As SqlCommand

    For Each ctrl In form1.Controls
        If (ctrl.GetType() Is GetType(DropDownList)) Then
            i = i + 1
        End If
    Next

    i = i + 1


    Dim MyDDL = New DropDownList
    MyDDL.ID = "DropDownList" + i.ToString

    Dim cmdstring As String = "SELECT * FROM [Staff Table]"
    Con = New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\YellowDoor.mdf;Integrated Security=True;User Instance=True")
    cmd = New SqlCommand(cmdstring, Con)
    cmd.Connection.Open()

    Dim ddlValues As SqlDataReader
    ddlValues = cmd.ExecuteReader()

    MyDDL.DataSource = ddlValues
    MyDDL.DataValueField = "StaffID"
    MyDDL.DataTextField = "FullName"
    MyDDL.DataBind()

    cmd.Connection.Close()

    form1.Controls.Add(MyDDL)

Any suggestions??

Could you please help in figuring out the versions supported by Fortify for .net2010 Windows 32 bit as well as 64.

Thanks in Advance

I want to publish the asp.net(web Application), when i click the button(Button_Click) Event.

As per below MSBuild script successfully published using VS2008 comment prompt at Run as administrator.

Note: msbuild D:\Test.sln /p:DeployOnBuild=true /p:OutDir= D:\Test_Publish_Folder\

how to call the above msbuild command using c# in Button_Click event?

I have two separated projects "MyWeb" and "MyAPI", MyWEB is a one-page site with one controller and one view, it is based on the knockout MVVM and ajax requests to the MyAPI web application, this two projects are contains in different apppools. I had integrated the MiniProfiler with MyWEB site and it is worked good, but I can see only first load results of Home page and then all data is loading from MyAPI web app. So, I need to integrate MiniProfiler with MyAPI project that I had the ability to see miniprofiler results on page of MyWEB site. I know that MiniProfiler send ajax requests for getting results, but I'm not understand why this requests are working only with the same domain. For example MyWEB is in domaint http://mywebsite.com and I send requests to MyAPI in domain http://mywebapi.com/api, also this two projects can be placed on two different computers. So, what I have in this time

MyWEB global.asax

public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            MiniProfilerEF6.Initialize();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AreaRegistration.RegisterAllAreas();
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_EndRequest()
        {

        }
    }

MyAPI global.asax

public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            MiniProfilerEF6.Initialize();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            AreaRegistration.RegisterAllAreas();
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            if (Request.IsLocal)
            {
                MiniProfiler.Start();
            }
        }

        protected void Application_EndRequest()
        {
            MiniProfiler.Stop();
        }
    }

MyAPI web.config handlers

<handlers>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
      <remove name="MiniProfiler"/>
      <add name="MiniProfiler" path="mini-profiler-resources/*" verb="*" type="System.Web.Routing.UrlRoutingModule" resourceType="Unspecified" preCondition="integratedMode" />
    </handlers>

We are trying to play large videos (30MB) using asp.net. The code we are using is:

System.IO.Stream iStream = null;
byte[] buffer = new Byte[10000];
int length;
long dataToRead;


context.Response.Buffer = false;
context.Response.BufferOutput = false;
context.Response.Clear();
iStream = new System.IO.FileStream(myPath, System.IO.FileMode.Open,  System.IO.FileAccess.Read, System.IO.FileShare.Read);
dataToRead = iStream.Length;
context.Response.ContentType = "video/mp4";
context.Response.AddHeader("Content-Length", iStream.Length.ToString(System.Globalization.CultureInfo.InvariantCulture));
                               //Write the file.
while (dataToRead > 0)
{
   // Verify that the client is connected.
   if (context.Response.IsClientConnected)
   {
       // Read the data in buffer.
       length = iStream.Read(buffer, 0, 10000);

       // Write the data to the current output stream.
       context.Response.OutputStream.Write(buffer, 0, length);

       // Flush the data to the HTML output.

       context.Response.Flush();

       buffer = new Byte[10000];
       dataToRead = dataToRead - length;
   }
   else
   {
       //prevent infinite loop if user disconnects
       dataToRead = -1;
   }`enter code here`
}
context.Response.OutputStream.Flush();

The issue is, it will take long time to play the video. The response is not quick. Please help us how to resolve this.

    [HttpPut]
    [Route("contacts/{id}")]
    [RequirePermission(ResourceType.Contact, BasePermission.Update, RouteAttribute.GetCustomAttribute(), id)]
    public void A(ContactContext context, [FromUri] string id, [FromBody] ContactPreferencesModel data)
    {
              ....
    }

In the 3rd line, I'd like to use the {id} of the 2nd line. Is it possible to get it? Thx a lot!

So i ran into a little problem and i am having a hard time understanding what I should do to get the result I want/need.

So my application is supposed to show the route a certain object made in the last 2 hours. When the user loads the app they see several points scattered through out the map and when they click on one of those objects the route it made in the last 2 hours is shown, and a table I have is supposed to be updated with those coordinates. Now I make the call to fill the partial view when I get all the locations the object went to in the controller method.

this is how I start all of this

(I am using openlayers 3 but it is irrelevant to this question)

$.ajax({
          type: "GET",
          url: '/Controller/GetRoutes',
          dataType: "json",
          success: function (result) {
                alert('Added');
              
                var layerLines = new ol.layer.Vector({
                    source: new ol.source.Vector({
                        features: [
                            new ol.Feature({
                                geometry: new ol.geom.LineString(routes, 'XY'),
                                name: 'Line'
                            })
                        ]
                    })
                });

                         
                map.addLayer(layerLines);             
            

          },
          error: function (xhr, ajaxOptions, thrownError) {
              //some errror, some show err msg to user and log the error  
              alert(xhr.responseText);
  
          }
      });

So as you can see from this code the method GetRoutes() is going to be responsible for getting the information on where the object has been to.

This is the controller (I omitted most of the code thats responsible for drawing the actual routes since its quite a bit chunky)

 [HttpGet]
    public JsonResult GetRoutes()
    {

    var lastpoints = get an arraylist with all the points I want

   var name = get the name of the object 

    RouteInformation(lastPoints,name);

    return Json(lastPoints, JsonRequestBehavior.AllowGet);

    }

I know I should probably change something here but i do not know what. The method that gives me the last points is not mine, but I am required to use it so I have no other choice but to accept the arrayList it returns to me.

this is the RouteInformation method

 public ActionResult RouteInformation(ArrayList routeList, string name )
       {

           List<ObjPoint> routes = routeList.OfType<ObjPoint>().ToList();

           List<ObjRoute> objRoutes = new List<ObjRoute>();

           objRoutes.Add(new ObjRoute()
                         {

                             name = name,
                             ObjPoints = routes
                          });

           return PartialView("RouteDetailsView", objRoutes);
       }

My issue is updating/refreshing that table, I have it in a partial view but I have no idea on what I have to do in order update that table with the information I want to display (i can get that information I just canĀ“t seem to show it).

ObjPoint is composed of latitude,longitude, date, time.

This is the ObjRoute model

 public class ObjRoute
{
    public string name { get; set; }
    public  List<ObjPoint> ObjPoints { get; set; }      

}

And now the Views ...

this is how the "main view" calls the partial view

<div> 
@Html.Partial("routeDetailsView")
</div>

And this is my partial view

@model webVesselTracker.Models.ObjRoute

@{
    ViewBag.Title = "RouteDetailsView";
    Layout = "~/Views/Shared/_Layout.cshtml";
}


<div>

    <table id="routeTable" class="table">
        <tr>
            
            <th>
               Name
            </th>
            <th>
                Latitude
            </th>
			<th>
                Longitude
            </th>
         
            <th></th>
        </tr>       

@if (Model != null) {

    foreach (var item in Model.ObjPoints)
    {
        
            <tr>				  
                <td>                  
                    @Html.DisplayFor(modelItem => item.Latitude)
                </td>
				<td>                  
                    @Html.DisplayFor(modelItem => item.Longitude)
                </td>      				
               
            </tr>
}
}

else
{
    <tr>
        <td>
          No object has been selected, please select one
        </td>

    </tr>
}
    </table>

</div>

Now I know I could probably do this by adding some sort of json request in the js file and from there on build the table, but I would like to know how to do this with Razor and where I have gone wrong in the code/logic. Am I supposed to add some ajax elsewhere?

So to summarize this:

-User sees points. 
-User clicks point to see the route it made. 
-App draws the route and then sends the route information to a method  table so it can be added to the table
the user can see that information

Thank you for your time and if I missed something please point it out so I can fix or explain it better.

I'm using identity 2.1.0 in ASP.NET MVC 5 application, and I have pages for admin to work (create/edit/delete user) with some custom user properties I defined. However I need to store a list of values in one field. How can I achieve this by using identity, and how to show this on a web page ?

I have a web application which is having an asmx web service holding some web methods. Those are being called through jQuery ajax method to get data or do various operations.

I want it to be accessed by only my web application and no other ways to call the web methods and this should be a fully secured one.

Can any body suggest on what are the security threats might affect my web methods and how i can protect them from those threats ?

Any suggestions are appreciated.

My model property is like this

    [DisplayFormat(DataFormatString = "{0:MMM dd, yyyy}"), DisplayName("Procedure Effective From"),
     DataType(DataType.Date)]
    public DateTime ProcedureEffectiveFrom { get; set; }

And in view

     @Html.TextBoxFor(model => model.ProcedureEffectiveFrom, new { @class = "form-control date-picker" })
  @Html.ValidationMessageFor(model => model.ProcedureEffectiveFrom)

And I am expecting an output like this

1/27/2015

But the output is

1/27/2015 10:40:45 AM

Can anyone point out what I am doing wrong?

I get this problem whenever I save the changes I made when changing the roles of a user:

An exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll but was not handled in user code. Additional information: The ViewData item that has the key 'URole' is of type 'System.Int32' but must be of type 'IEnumerable

These are the codes of my GET and POST Edit

// GET: /AccountAdmin/Edit/5

public ActionResult Edit(int id)
{

    Account account = db.Accounts.Find(id);
    if (account == null)
    {
        return HttpNotFound();
    }
    RoleDropDownList(account.URole);
    return View(account);
}

//
// POST: /AccountAdmin/Edit/5

[HttpPost]
public ActionResult Edit(Account account)
{
    try
    {

        if (ModelState.IsValid)
        {
            db.Entry(account).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        RoleDropDownList(account.URole);
        return View(account);
    }
    catch (Exception ex)
    {

        return View(account);
    }
}
 private void RoleDropDownList(object selectedRole = null)
    {
        var q = from a in db.Roles
                orderby a.RoleID
                select a;
        ViewBag.URole = new SelectList(q, "RoleID", "UserRole", selectedRole);
    }

And this is the Edit View

 @model MvcApplication3.Models.Account

    @ViewBag.Title = "Edit";

    <h2>Edit</h2>

    @using (Html.BeginForm()) {
        @Html.ValidationSummary(true)

    <fieldset>
        <legend>Account</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.AccID)
        </div>
        <div class="editor-field">
            @Html.DisplayFor(model => model.AccID)
            @Html.ValidationMessageFor(model => model.AccID)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.UName)
        </div>
        <div class="editor-field">
            @Html.DisplayFor(model => model.UName)
            @Html.ValidationMessageFor(model => model.UName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Pword)
        </div>
        <div class="editor-field">
            @Html.DisplayFor(model => model.Pword)
            @Html.ValidationMessageFor(model => model.Pword)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.FName)
        </div>
        <div class="editor-field">
            @Html.DisplayFor(model => model.FName)
            @Html.ValidationMessageFor(model => model.FName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.LName)
        </div>
        <div class="editor-field">
            @Html.DisplayFor(model => model.LName)
            @Html.ValidationMessageFor(model => model.LName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.URole, "Role")
        </div>
        <div class="editor-field">
            @Html.DropDownList("URole", String.Empty)
            @Html.ValidationMessageFor(model => model.URole)
        </div>

        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}

    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>

        @section Scripts{
            <script src="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/bundles/jqueryval")"></script>
        }

What could be the problem? Thanks in advance!

When I declare a text box in view page the below error will appear

 The type arguments for method 'System.Web.Mvc.Html.InputExtensions.TextBoxFor<TModel,TProperty>(System.Web.Mvc.HtmlHelper<TModel>, 
System.Linq.Expressions.Expression<System.Func<TModel,TProperty>>)'
 cannot be inferred from the usage. Try specifying the type arguments
 explicitly

even I included

<compilation debug="true" targetFramework="4.0">
  <!-- ... -->
</compilation>

this in webconfig file but the same error shows . ............ my code

 @Html.TextBoxFor(x => x.Entity, new { @id = "Entityname" })

//.......... model

public string Entity { set; get; }

//......... //.............. .cshtml page

  @model BOSSNew.Models.NewQuantifierM
    @using Omnex.OmnEwIMSSuite.Helpermethod;
    @{Layout = "../Shared/_Layout.cshtml";}
    <div class="breadCrumbHolder">
        @{Html.RenderAction("BreadCrumb", "Base", new { menulist = new string[] { "Quantifier", "New Quantifier" }, CurrentURL = new string[] { "#", "#" } });}
    </div>
    <div class="divContentPane">
        <div class="contentPaneHead">
            <span class="contentPaneTitle">Users Details </span>
        </div>
        <table class="ClsTable ClsPad0">
            <tr class="even">
                <th>@LabelHelper.GetLabel("THLentity", 3)
                </th>
                <td>
                    @Html.TextBoxFor(x => x.Entity, new { @id = "Entityname" })
                    <img title="" id="selectentit" style="margin: 5px" onclick="getentity('txtentity','optentity')"
                        alt="" src="../../../EwIMS.Controls/Themes/EwIMS-Theme/images/entity.png">
                </td>
            </tr>
     </table>
    </div>

//.............

Any idea ?

Any help will be appreciated

So I have a model

public class test
{
    private List<int> _abc;

    public List<int> abc
    {
        get { return _abc; }
        set { _abc = value; }
    }
}

My partial page:

@model List<int>

//do something with model

My main page :

@model somenamespace.test

@Html.Partial("~/Views/Test/partial.cshtml", model.abc)

But I got this error when trying to access the page :

The model item passed into the dictionary is of type , but this dictionary requires a model item of type 'System.Collections.Generic.List`1[System.Int32]'.

I'm confused because my partial view accept list of integer and I pass property with list of integer as datatype, anything wrong with my code?

Any help will be appreciated and sorry for bad english.