I try to export chart images to png or pdf with the code below.(I use Asp.Net MVC, Telerik Kendo, Inskcape)

Every user needs to have installed Inkscape software on their computers to get charts exported. I mean, if user doesn't have Inkscape, user can not get image.

So i want to control if user have Inkscape or not. If there is no installed Inkscape, i want to show exception message to related View like "Please install Inkscape to your computers"

How can i do it? With try, catch? If else? I can't get the logic about what i should.

  private string DoExport(string svgFile, KendoChartExport.Models.ExportFormat format)
        {

            var extension = format == KendoChartExport.Models.ExportFormat.PNG ? "png" : "pdf";
            var outFile = TempFileName() + "." + extension;
            var inkscape = new System.Diagnostics.Process();
            inkscape.StartInfo.FileName = INKSCAPE_PATH;
            inkscape.StartInfo.Arguments =
                String.Format("--file \"{0}\" --export-{1} \"{2}\" --export-width {3} --export-height {4}",
                              svgFile, extension, outFile, WIDTH, HEIGHT);
            inkscape.StartInfo.UseShellExecute = true;
            inkscape.Start();
            inkscape.WaitForExit();

            return outFile;
        }

I want to someting like that:

   try
            {
                 inkscape.Start();
            }
            catch (Exception)
            {

                throw ViewBag.Error = "Please Install Inkscape";
            }

Any idea to help?

I'm trying to put two partialviews together but I keep getting errors. I've got a Subject-model and a Category-model, and I've made partial views which seem to work perfectly, but when I put them together in a single view this pops up:

Error   1   'Myproject.Models.Subject' is a 'type', which is not valid in the given context

this is the only code in my view:

@{Html.RenderPartial("_CategoryPartial", Myproject.Models.Category);}
@{Html.RenderPartial("_SubjectPartial", Myproject.Models.Subject);}

I guess I will have to create a seperate viewmodel if all else fails, but I thought on checking on here first

How to dynamically render a textbox value in Asp.net web page into PDF using iTextSharp?

The text have to be placed in the PDF in the same position as the textbox in the web page, as the number of textboxes vary in different scenarios because the textboxes are contained in different FormViews. There are many FormViews in the page & only some FormViews will be datbound in some cases. So we cant set a position for each textbox. The position should be same as that in the web page.

I have done like this:

        Dim TextBox5 As TextBox = DirectCast(FormView2.FindControl("TextBox5"), TextBox)

        Dim htmlarraylist As List(Of IElement) = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(New StringReader(TextBox5.Text), Nothing)

        For Each element As IElement In htmlarraylist

            document.Add(element)

        Next

But the textbox will be added to the last of the PDF document only.

If it is to be placed at an absolute position in PDF, it can be done like this:

        Dim cb As PdfContentByte = writer.DirectContent

        cb.BeginText()

        Dim TextBox5 As TextBox = DirectCast(FormView2.FindControl("TextBox5"), TextBox)

        Dim text As String = TextBox5.Text

        cb.SetFontAndSize(bf, 8)

        cb.ShowTextAligned(1, text, 122, 474, 0)

        cb.EndText()

But both of these cant be done in my case. Please help.

I know you can alter the default behaviour of routing in Web API like this:

routes.MapHttpRoute(
    name: "ActionApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

But can you

routes.MapHttpRoute(
    name: "ActionApi",
    routeTemplate: "api/{controller}?verb={action}",
    defaults: new { action = RouteParameter.Optional }
);

I have a string like "Research Expenses: Itemize and follow <a href=" http://www.borenawards.org/boren_fellowship/budget.html" target="_blank">budget guidelines</a>(maximum $3,000)"

I want to assign that value to a sting variable.

string value= Research Expenses: Itemize and follow <a href=" http://www.borenawards.org/boren_fellowship/budget.html" 
target="_blank">budget guidelines</a>(maximum $3,000);

My need is that whatever string is passed to it I have to display the content inside a doublequotes .how to add the doublequotes?

I want to display string like "Research Expenses: Itemize and follow <a href=" http://www.borenawards.org/boren_fellowship/budget.html" target="_blank">budget guidelines</a>(maximum $3,000)".please help me

I'm a junior developer, I am going to implement run time caching in asp.net Model View Controller pattern... What should i give cache Time while using Run time caching?

I have uploaded my website in godaddy server. create a handler from where other developer can download the file. Its working fine, But it does not support resume capability. I have checked it in IDM it says server does not support resume capability, Download from beginning. I have tried code.

public class Downloader
{
public Downloader()
{
    //
    // TODO: Add constructor logic here
    //
}

public static void DownloadFile(HttpContext httpContext, string filePath)
{
    if (!IsFileExists(filePath))
    {
        httpContext.Response.StatusCode = 404;
        return;
    }

    FileInfo fileInfo = new FileInfo(filePath);

    if (fileInfo.Length > Int32.MaxValue)
    {
        httpContext.Response.StatusCode = 413;
        return;
    }

    // Get the response header information by the http request.
    HttpResponseHeader responseHeader = GetResponseHeader(httpContext.Request, fileInfo);

    if (responseHeader == null)
    {
        return;
    }

    FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

    try
    {
        SendDownloadFile(httpContext.Response, responseHeader, fileStream);
    }
    catch (HttpException ex)
    {
        httpContext.Response.StatusCode = ex.GetHttpCode();
    }
    finally
    {
        fileStream.Close();
    }
}

/// <summary>
/// Check whether the file exists.
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
private static bool IsFileExists(string filePath)
{
    bool fileExists = false;

    if (!string.IsNullOrEmpty(filePath))
    {
        if (File.Exists(filePath))
        {
            fileExists = true;
        }
    }

    return fileExists;
}

/// <summary>
/// Get the response header by the http request.
/// </summary>
/// <param name="httpRequest"></param>
/// <param name="fileInfo"></param>
/// <returns></returns>
private static HttpResponseHeader GetResponseHeader(HttpRequest httpRequest, FileInfo fileInfo)
{
    if (httpRequest == null)
    {
        return null;
    }

    if (fileInfo == null)
    {
        return null;
    }

    long startPosition = 0;
    string contentRange = "";

    string fileName = fileInfo.Name;
    long fileLength = fileInfo.Length;
    string lastUpdateTimeStr = fileInfo.LastWriteTimeUtc.ToString();

    string eTag = HttpUtility.UrlEncode(fileName, Encoding.UTF8) + " " + lastUpdateTimeStr;
    string contentDisposition = "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8).Replace("+", "%20");

    if (httpRequest.Headers["Range"] != null)
    {
        string[] range = httpRequest.Headers["Range"].Split(new char[] { '=', '-' });
        startPosition = Convert.ToInt64(range[1]);
        if (startPosition < 0 || startPosition >= fileLength)
        {
            return null;
        }
    }

    if (httpRequest.Headers["If-Range"] != null)
    {
        if (httpRequest.Headers["If-Range"].Replace("\"", "") != eTag)
        {
            startPosition = 0;
        }
    }

    string contentLength = (fileLength - startPosition).ToString();

    if (startPosition > 0)
    {
        contentRange = string.Format(" bytes {0}-{1}/{2}", startPosition, fileLength - 1, fileLength);
    }

    HttpResponseHeader responseHeader = new HttpResponseHeader();

    responseHeader.AcceptRanges = "bytes";
    responseHeader.Connection = "Keep-Alive";
    responseHeader.ContentDisposition = contentDisposition;
    responseHeader.ContentEncoding = Encoding.UTF8;
    responseHeader.ContentLength = contentLength;
    responseHeader.ContentRange = contentRange;
    responseHeader.ContentType = "application/octet-stream";
    responseHeader.Etag = eTag;
    responseHeader.LastModified = lastUpdateTimeStr;

    return responseHeader;
}

/// <summary>
/// Send the download file to the client.
/// </summary>
/// <param name="httpResponse"></param>
/// <param name="responseHeader"></param>
/// <param name="fileStream"></param>
private static void SendDownloadFile(HttpResponse httpResponse, HttpResponseHeader responseHeader, Stream fileStream)
{
    if (httpResponse == null || responseHeader == null)
    {
        return;
    }

    if (!string.IsNullOrEmpty(responseHeader.ContentRange))
    {
        httpResponse.StatusCode = 206;

        // Set the start position of the reading files.
        string[] range = responseHeader.ContentRange.Split(new char[] { ' ', '=', '-' });
        fileStream.Position = Convert.ToInt64(range[2]);
    }
    httpResponse.Clear();
    httpResponse.Buffer = false;
    httpResponse.AppendHeader("Accept-Ranges", responseHeader.AcceptRanges);
    httpResponse.AppendHeader("Connection", responseHeader.Connection);
    httpResponse.AppendHeader("Content-Disposition", responseHeader.ContentDisposition);
    httpResponse.ContentEncoding = responseHeader.ContentEncoding;
    httpResponse.AppendHeader("Content-Length", responseHeader.ContentLength);
    if (!string.IsNullOrEmpty(responseHeader.ContentRange))
    {
        httpResponse.AppendHeader("Content-Range", responseHeader.ContentRange);
    }
    httpResponse.ContentType = responseHeader.ContentType;
    httpResponse.AppendHeader("Etag", "\"" + responseHeader.Etag + "\"");
    httpResponse.AppendHeader("Last-Modified", responseHeader.LastModified);

    Byte[] buffer = new Byte[10240];
    long fileLength = Convert.ToInt64(responseHeader.ContentLength);

    // Send file to client.
    while (fileLength > 0)
    {
        if (httpResponse.IsClientConnected)
        {
            int length = fileStream.Read(buffer, 0, 10240);

            httpResponse.OutputStream.Write(buffer, 0, length);

            httpResponse.Flush();

            fileLength = fileLength - length;
        }
        else
        {
            fileLength = -1;
        }
    }
    }
  }


class HttpResponseHeader
{
   public string AcceptRanges { get; set; }
   public string Connection { get; set; }
   public string ContentDisposition { get; set; }
   public Encoding ContentEncoding { get; set; }
   public string ContentLength { get; set; }
   public string ContentRange { get; set; }
   public string ContentType { get; set; }
   public string Etag { get; set; }
   public string LastModified { get; set; }
}


using System;
using System.Web;
using System.Configuration;

public class DownloadHttpHandler : IHttpHandler {

public void ProcessRequest(HttpContext context)
{
    string filename = HttpContext.Current.Request.QueryString["f"].ToString();
    string filePath = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["CityMapFolder"] + filename);
    Downloader.DownloadFile(context, filePath);
}

public bool IsReusable
{
    get { return false; }
}

}

i want to login in php form with using curl in asp language i wrote a code

string responseText = String.Empty;

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

    request.Method = "POST";

    request.KeepAlive = true;

    request.ContinueTimeout = 500000;

    request.ContentLength = postData.Length;

    using (StreamWriter sw = new StreamWriter(request.GetRequestStream()))

    {
        sw.Write(postData);
    }

but it does'nt work . i want to insert data in that form but no data inserted with this code please help me how to insert data to form . tnx

It seems this has been asked many times, in many ways, none of which seem to fit my exact situation.

Here's a line from my _LoginPartial.cshtml file:

@Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Manage", "Account", routeValues: null, htmlAttributes: new { title = "Manage" })

See the part that says User.Identity.GetUserName()?

I want to change it to User.Identity.FirstName or User.Identity.GetFirstName().

I don't want it to say "Hello email address", but rather "Hello Bob"

My thought is that I'm simply wanting to show a new property (or method) on the Identity class. Obviously it must be more than that.

I've added the FirstName property and it is available in the AccountController.

public class ApplicationUser : IdentityUser
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

It does not get exposed in the _LoginPartial file. I want it exposed there!

Thank you for your help

Hi I am getting the following exception.Please help me to resolve this .org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.chrysler.mathapps.entity.MatlabRequest.requestedComputerList, no session or session was closed

Controller:

@RequestMapping(value = "/Request", method = RequestMethod.GET)
    public @ResponseBody String listApparoverRequest(
                                        HttpSession httpSession, 
                                        HttpServletRequest req,
                                        HttpServletResponse res,ModelMap modelMap) throws IOException {



        String json = new Gson().toJson(matlabRequestManger.getAllRequest());


        System.out.println(" MatlabRequest json  :-"+json);

        return json;
    } 

Entity Class:

@Entity
@Table(name="REQUEST")
public class MatlabRequest {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="I_REQ")
    int id;
    @Column(name="I_LOGON")
    String tid;


    @Column(name="I_LOGON_APRVR")
    String approverTid;



    @Column(name="I_LIC_TYP")
    int licenseType;    


    @Column(name="MATLB_USAGE")
    int matlabUsage;

    @Column(name="I_LIC")
    int licenseNo;

    @Column(name="N_DIR")
    String directorName="";




    @Column(name="T_REQ")
    String requestTime="";
    @Column(name="T_LAST_ASSIGN")
    String lastAssignedTime="";

    @Column(name="T_LAST_DOWNLOAD")
    String lastDownloadedTime="";
    @Column(name="T_CLOSE")
    String closedTime="";

    @Column(name="T_RELEASED")
    String releasedTime="";

    @PersistenceContext
    @OneToMany(fetch=FetchType.LAZY,mappedBy="matlabRequest")
    private Collection <RequestedComputer> requestedComputerList=new ArrayList<RequestedComputer>();

    @OneToMany(fetch=FetchType.LAZY,mappedBy="matlabRequest")
    private Collection <RequestedVersion> requestedVersionsList=new    ArrayList<RequestedVersion>();

    @OneToMany(fetch=FetchType.LAZY ,mappedBy="matlabRequest")
    private Collection<RequestedToolboxes> requestedToolboxesList=new ArrayList<RequestedToolboxes>();

 - Entity class

@Entity
@Table(name="REQ_CMPTR_INFO")
public class RequestedComputer {



    @Id
    @Column(name="N_CMPTR")
    String  computerName="";


    @Column(name="I_HOST")
    String hostId="";

    @Column(name="N_OS")
    String osName="";

    public String getOsName() {
        return osName;
    }

    public void setOsName(String osName) {
        this.osName = osName;
    }

    @Column(name="T_ASSIGN")
    String assignedDate="";


    @Column(name="T_TERMINATION")   
    String terminationTime="";

    @Column(name="T_RELEASED")
    String releasedTime="";

    @ManyToOne
    @JoinColumn(name="I_REQ")
    MatlabRequest matlabRequest;

web.xml

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

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">

  <display-name>Archetype Created Web Application</display-name>
    <welcome-file-list>
        <welcome-file>/WEB-INF/index.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>mathapps</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>mathapps</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/mathapps-servlet.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>



</web-app>


spring-servlet.xml

<?xml  version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

    <context:annotation-config />
    <context:component-scan base-package="com.chrysler.mathapps.controller" />

    <bean id="jspViewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>
    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
        p:location="/WEB-INF/jdbc.properties" />

    <bean id="dataSource"
        class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
        p:driverClassName="${jdbc.driverClassName}"
        p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
        p:password="${jdbc.password}" />


    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${jdbc.dialect}</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
    </bean>


    <bean id="objectMapper" class="com.fasterxml.jackson.databind.ObjectMapper"></bean>
    <bean id="matlabRequestDAO" class="com.chrysler.mathapps.dao.MatlabRequestDAOImpl"></bean>
    <bean id="matlabRequestManger" class="com.chrysler.mathapps.service.MatlabRequestManagerImpl"></bean>
    <bean id="toolboxesDAO" class="com.chrysler.mathapps.dao.ToolboxesDAOImpl"></bean>
    <bean id="toolboxManager" class="com.chrysler.mathapps.service.ToolboxMangerImpl"></bean>

    <bean id="computerInfoDAO" class="com.chrysler.mathapps.dao.ComputerInfoDAOImpl"></bean>
    <bean id="requestedComputerManger" class="com.chrysler.mathapps.service.RequestedComputerMangerImpl"></bean>

    <bean id="matlabVersionDAO" class="com.chrysler.mathapps.dao.MatlabVersionDAOImpl"></bean>
    <bean id="requestedMatlabVersion" class="com.chrysler.mathapps.service.RequestedMatlabVersionManagerImpl"></bean>

    <bean id="toolboxRequestedDAO" class="com.chrysler.mathapps.dao.ToolboxRequestedDAOImpl"></bean>
    <bean id="requestedToolboxManager" class="com.chrysler.mathapps.service.RequestedToolboxMangerImpl"></bean>

    <tx:annotation-driven transaction-manager="transactionManager"/>
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

</beans>

I'm new to Laravel and having trouble with subdirectories. I want to make an admin folder inside the controllers folder and so far it's working. but when I try to use Laravel's Input class it says that it couldn't find it.

My routes:

Route::group(array('prefix'=> 'admin', 'before' => 'auth.admin'), function() {

   Route::resource('/users','Admin\\UsersController');
   Route::resource('/products','Admin\\ProductsController');
   Route::resource('/categories','Admin\\CategoriesController');
   Route::resource('/orders','Admin\\OrdersController');
   Route::resource('/reviews','Admin\\ReviewsController');

});      

The Products Controller:

 <?php namespace admin;

    class ProductsController extends \BaseController {

    protected $layout = 'master';
        /**
     * Instantiate a new ProductsController instance.
     */
    public function __construct()
    {
        $this->beforeFilter('auth.admin');
    }

    /**
     * Display a listing of the resource.
     * GET /products
     *
     * @return Response
     */
    public function index()
    {
        $input = Input::all(); //here is where it finds the error

And the composer.json autoload:

"autoload": {

        "classmap": [
            "app/commands",
            "app/controllers/",
            "app/models",
            "app/database/migrations",
            "app/database/seeds",
            "app/tests/TestCase.php",
            "app/controllers/Admin"
        ]
    },

Thank you!

Edit:

I have also tried to use Input (and \Input) and it returned the "Class 'Facade' not found" error, and when I tried:

use \Illuminate\Support\Facades\Facade;
use Input;

It still did not work.

Edit 2:

Now using:

use Illuminate\Support\Facades\Input;

and returning the same error.

How can i rewrite this script using Model View Controller?
How should i include View files?

<?php
//...
$query = "SELECT SQL_CALC_FOUND_ROWS questions.question_id, questions.user_id, "
       .   "posts.post_id, posts.question_id, posts.user_id, posts.message, posts.image, posts.is_question, posts.created_at, posts.is_answer, "
       . // ...
       . "LIMIT $start, 10";
$result = mysqli_query($dbc, $query);


echo '<h2>' . $subject . '</h2>';
echo '<br />';
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {

    echo '<div class="question-container">'
       . '<div class="question-left">'
       .       '<a class="vote-up" title="This answer is useful" href="/ask/posts-nopage.php?v_pid=' . urlencode($row['post_id']) . '&amp;vote=+1&amp;qid=' . urlencode($question_id) . '"> </a>'
       .       '<div>' . $row['vote'] . '</div>'
       .       '<a class="vote-down"  title="This answer is not useful" href="/ask/posts-nopage.php?v_pid=' . urlencode($row['post_id']) . '&amp;vote=-1&amp;qid=' . urlencode($question_id) . '"> </a>'
       .      (($row['is_question'] == 0)
                 ? ((isset($_SESSION['user_id']) && $_SESSION['user_id'] == $row['user_id'])
                     ? '<a class="is-answer-' . (($row['is_answer'] == 1) ? 'yes' : 'no') . '" href="/ask/posts-nopage.php?ia_pid=' . urlencode($row['post_id']) . '&amp;ia_current=' . urlencode($row['is_answer']) . '&amp;qid=' . urlencode($question_id) . '"> </a>'
                     : '<span class="is-answer-' . (($row['is_answer'] == 1) ? 'yes' : 'no') . '"> </span>')
                 : '')
       .   '</div>'
       .   '<div class="question-right">'
       .     '<p class="post-text">'
       .        nl2br(htmlentities($row['message'])) . ((isset($row['image'])) ? '<br /><img alt="" src="_images/post/' . $row['image'] . '" />' : '')
       . //...
       .   '</div>'
       .   '</div>';

    $query_comment = "SELECT message, created_at FROM comments WHERE post_id={$row['post_id']}";
    $result_comment = mysqli_query($dbc, $query_comment);
    if ($result_comment && mysqli_num_rows($result_comment)) {
        echo '<div class="comments">';
        while ($row_comment = mysqli_fetch_array($result_comment, MYSQLI_NUM)) {
            echo '<p class="comment-text">' . htmlentities($row_comment[0]) . '</p>';
        }
        echo '</div>';
    }

    echo '</div></div>';
}
//...
?>

Does not need more details
Does not need more details
Does not need more details
Does not need more details

I'm learning to build gui applications. My current private project is working, the program is doing everything I want. But the implementation looks pretty bad and is not maintainable or extensible anymore. It is not really following MVC or other design pattern in the main parts. So I've started to rework it and would appreciate some advise.

The goal of the program: It is a monitoring tool getting the data from an external source all the time as long as the application is running. The data is displayed (some labels, text areas, an OSM map) and updated permanently. Depending on the data a button to start the recording of the data (into a file) is enabled or not. When the recording is stopped by the user (same button) some post actions are executed.

Due to lack of knowledge I have implemented two separate SwingWorkers, one to display the current data and one for the recording, started when the button is pressed (is reading the date too!). This is my main pain point. Just one data-retrieving SwingWorker must be sufficent.

So I have started to rework it. I have a gui view class. Once the gui is initialized the SwingWorker (as a gui member variable) is executed and updates the view elements. Fine. Works. But is this a nice approach? The SwingWorker is the central object. From my feeling it should not belong to the view. Other objects should also observe and use its progress. Whenever new data came in gui elements or others should get notified. So I could add several observers to the SwingWorker and call notify(myData) within the doInBackground() method.

My second, bigger issue is concerning the start-stop button to record my data. What kind of implementation approach would you suggest? My idea was to implement a PropertyChangeListener to get the button clicked action. But how can this handle/record the data from the SwingWorker and interrupt on demand? It must get notified permanently too. Or is there some other, better pattern to pulling the data on demand? Is there a nice example with a single SwingWorker and multiple independent listeners/observers?

Thanks in advance, Niels

I'm currently enjoying diving into Ember and learning a complete Front End MVC solution.

Currently, I'm a little stumped on getting data from our API as it doesn't follow the standard required by Ember's Adapter. Currently, our team are unable to change the structure of the API / JSON response due to the dependencies of third party applications.

RESTAdapter is looking for JSON like this:

{
  'episodes' : [
        {
            id : '1',
            title : 'my first title'
        }
    ]
}

Unfortunately all we get back is an array with each episode as an object, i.e. it cannot be a key with a value of array of objects.

[
    {
        id : 1,
        title : 'my first title'
    },
    {  
        id : 2,
        title : 'my second title'
    }
]

Can anyone provide assistance on how to extend DS.RESTAdapter to follow this format?

Again, our server devs cannot change the API so we have to take the JSON response as is.

Thanks

How can I redirect user after successful login to specific page. I need to do this by Authorize Attribute. In my problem I have to redirect user to page: Index/About when he/she would use specific login name, rest of users would be redirected to Index/Home.

I try this method:

public class AuthAttribute : AuthorizeAttribute
{
    private string userName;

    protected override bool AuthorizeCore(HttpContextBase filterContext)
    {
        var authorized = base.AuthorizeCore(filterContext);

        if (!authorized)
        {
            return false;
        }

        string userAuthenticated = filterContext.User.Identity.Name;
        bool specialUser = userName.Equals(userAuthenticated,    StringComparison.OrdinalIgnoreCase);

        if (specialUser)
        {
            filterContext.Items["RedirectToHomeAbout"] = true;
            return false;
        }

        return true;
    }

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);

        if (filterContext.HttpContext.Items.Contains("RedirectToHomeAbout"))
        {
            var routeValues = new RouteValueDictionary(new
            {
                controller = "Home",
                action = "About",
            });

            filterContext.Result = new RedirectToRouteResult(routeValues);
        }
        else
        {
            base.OnAuthorization(filterContext);
        }
    }

Thanks! MarQ

My MVC view has the following code -

@if(d.Listing.Port.Country.Name !=null) {...}

which returns an 'Object reference not set to an instance of an object.' error.

Both Port and Country are lazy loading properties.

Something wrong with my approach, not sure what!

regards, Guy

-

The Web API works great but I don't understand why am I getting the "no action was found on the controller that matches the request error" exception error if I changed the parameter from "long parmAccountId" to "long? parmAccountId"? (See the "?" next to long datatype).

Is there a way to make it work? Thanks..

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "MemberApi",
            routeTemplate: "WebApi/Member/{controller}/{action}/{AccountId}/{UserId}",
            defaults: new { AccountId = RouteParameter.Optional, UserId = RouteParameter.Optional }
       );
    }
}

public class DigitalLoanJacketController : ApiController
{
    [ActionName("Upload")]
    [HttpPost]
    public string Post(long? parmAccountId, long? parmUserId, Foo parmFoo)
    {
    }
}

//JQUery...
var jsonRequest = { "Id": 3, "Name": "Scott Fletcher"};

$.ajax({
    type: "POST",
    async: false, /*false, //This need to be synchronous to the client can wait for a webserver response...*/
    url: "https://localhost:44301/WebApi/Member/DigitalLoanJacket/Upload/e/83",
    data: JSON.stringify(jsonRequest),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (parmData, parmTextStatus, parmXmlHttpRequest) {
        alert("AjaxStatus: " + parmTextStatus + "\nReadyState - " + parmXmlHttpRequest.readyState + "\nStatus: " + parmXmlHttpRequest.status + "\nStatusText: " + parmXmlHttpRequest.statusText + "\nResponseText: " + parmXmlHttpRequest.responseText);
    },
    error: function (parmXmlHttpRequest, parmTextStatus, parmErrorThrown) {
        alert("AjaxStatus: " + parmTextStatus + "\nReadyState - " + parmXmlHttpRequest.readyState + "\nStatus: " + parmXmlHttpRequest.status + "\nStatusText: " + parmXmlHttpRequest.statusText + "\nResponseText: " + parmXmlHttpRequest.responseText);
    }
});

Currently looking into Identity Server's implementation from Thinktecture and was curious does somebody tried to write his own ViewService instead of default EmbeddedAssetsViewService?

I would prefer to have something MVC based that would allow to edit the pages with Razor syntax, as mostly all my applications are ASP.NET MVC, I think it would make sense to have this possibility... don't think it should be too hard, just curious if somebody already did it and could share any experience?

I tried to Google it, but didn't find anything about this...

I recently got a new laptop and did a fresh installation of Visual Studio 2013 Professional. After installation, the first thing I did was to make sure that Nuget was set to automatically download missing packages.

I'm now trying to work on the same large solution I was using before getting my new laptop, but I'm getting some strange errors that I haven't been able to resolve after many hours of research.

The most obvious symptom of the issue is that I see many errors on Razor views. They are these types of errors:

  • Feature 'lambda expression' cannot be used because it is not part of the ISO-2 C# language specification

  • Feature 'anonymous types' cannot be used because it is not part of the ISO-2 C# language specification

  • Feature 'implicitly typed local variable' cannot be used because it is not part of the ISO-2 C# language specification

  • Feature 'extension method' cannot be used because it is not part of the ISO-2 C# language specification

Another symptom is that if I try to add a new view, none of the MVC items are available: for example, no .cshtml items. However, if I create a new solution, these items are available as expected.

I updated to Visual Studio 2013 Update 3 along with the fresh installation. The solution uses MVC 4 and Razor 2. I've checked the web.config and see nothing wrong - the version of Razor and MVC I want are correct.

Despite these errors, my project builds successfully. After the build, all of the 'implicitly typed local variable' errors disappear for a few minutes, then return. Another person is working on the same solution on an old laptop and is not experiencing these issues.

I'm hoping somebody can help. I need to resolve this issue because the lack of useful Intellisense is hurting my productivity.

That is a tricky question because I want to add Html Attributes to the EditorFor() but do not want to replace the ones that was already created. Let me explain:

I have a default Editor Template for string.cshtml with the following code:

@{    
    var htmlAttributes = ViewData;
    htmlAttributes["class"] = "text-box single-line form-control";
    htmlAttributes["placeholder"] = ViewData.ModelMetadata.Watermark ?? ViewData.ModelMetadata.DisplayName;
    htmlAttributes["title"] = ViewData.ModelMetadata.Watermark ?? ViewData.ModelMetadata.DisplayName;
}
@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, htmlAttributes)

It is used to always add the following class, placeholder and title, based on the DisplayName DataAnnotation, for the Form Inputs, it is quite handy!

But the problem is that I'm having trouble adding the disable attribute for one specific Form Input with the common code:

@Html.EditorFor(x => x.Field, new { htmlAttributes = new { disabled = "" } })

When the Form Input is with a field that is not a string, it will not follow the created EditorTemplate and it will work with this exactly code, but when it is a string, the EditorTemplate replaces the Html Attributes.

Does anyone has any clue on this?

This question already has an answer here:

I am building an ASP.NET MVC website where I keep all of my localized string in a .resx resource file. However, if I try to embed any formatting or Unicode characters, I have a problem.

Example resource file [EN_US.resx]:

Key                       Value
=================================================================================
INTRO_COLLEGE             This is a <strong>really</strong> nice college&hellip;

Example view:

<p>@EN_US.INTRO_COLLEGE</p>

My problem is, any HTML formatting or special characters are literally printed as they are written in the resource file, like this:

This is a <strong>really</strong> nice college&hellip;

How can I include HTML formatting and Unicode characters in a .resx file such that they are not automatically escaped when it is printed out?