Is there an asp.net mvc app generator that generates models/views/controllers from the database. I know there's a built-in asp.net mvc scaffolding. But what I exactly want is; Pages will be rendered from a configuration file like xml or json. I want to specify the filters, load query or client side validations.

What is html.Raw() ? Can it be used to display special characters?

I'm using VS2012 and Razor. In my cshtml-file I have the following : enter image description here

As you can see the "@model" and other codeblocks aren't displaying in yellow. I'm also missing the intellisense.

What am I forgetting?

I have some troubles with the textbox or my brain. I can't understand what's the reason of unedittable textbox. I mean, i have listview with 3 columns:"Name","Code","Binding". By clicking on the "Name", the first and the second column become editable. After my edit, i push button "Save"...and nothing is happened. Can't understand such a simple thing. Why it's not working? Sorry for mistakes, i'm here for the 1st time

<asp:Content ID="ContentMain" ContentPlaceHolderID="centerContent" runat="server">
    <asp:Panel ID="i_ListContainer" runat="server" HorizontalAlign="Center">
        <asp:ListView ID="CpzListView" runat="server" DataKeyNames="id" InsertItemPosition="FirstItem"
            OnItemCreated="i_UserLV_ItemCreated" OnItemInserted="i_UserLV_ItemInserted" OnItemEditing="i_UserLV_ItemEditing"
            OnItemInserting="i_UserLV_ItemInserting" OnItemUpdated="i_UserLV_ItemUpdated"
            OnItemUpdating="i_UserLV_ItemUpdating">
            <LayoutTemplate>
                <table cellpadding="0" cellspacing="0" class="mGrid">
                    <th style="width: 150px">
                        Name
                    </th>
                    <th style="width: 150px">
                        Code
                    </th>
                    <th style="width: 50px">
                        Binding
                    </th>
                    </thead>
                    <tbody>
                        <asp:PlaceHolder runat="server" ID="itemPlaceholder" />
                    </tbody>
                </table>
            </LayoutTemplate>
            <ItemTemplate>
                <tr>
                    <td>
                        <asp:LinkButton ID="i_viewEditLB" runat="server" CommandName="Edit" Text='<%#Bind("cpzname") %>' />
                    </td>
                    <td>
                        <asp:Label ID="i_viewUserFioLabel" runat="server" Text='<%#Bind("code") %>' />
                    </td>
                    <td style="text-align: center; width: 80px">
                        <a href='<%# GetUrl(Eval("cpzname"), Eval("code"))%>'>Bindindg</a>
                    </td>
                </tr>
            </ItemTemplate>
            <InsertItemTemplate>
            </InsertItemTemplate>
            <EditItemTemplate>
                <tr>
                    <td>
                        <asp:TextBox ID="tbCpzName" runat="server" Text='<%# Bind("cpzname") %>'></asp:TextBox>
                    </td>
                    <td>
                        <asp:TextBox ID="tbCpzCode" runat="server" Text='<%# Bind("code") %>'></asp:TextBox>
                    </td>
                    <td>
                        <asp:LinkButton ID="lbSave" runat="server" CommandName="Update" Text="Save" />
                    </td>
                </tr>
            </EditItemTemplate>
        </asp:ListView>
    </asp:Panel>
</asp:Content>

Here is the c# code, hope you'll help me.

    namespace WebApplication2.MemberPages
{
        protected void Page_Load(object sender, EventArgs e)
        {
            UpdateBinding();
        }

        private void UpdateBinding()
        {
            DataTable dt = AOneConnectDB.ExecuteQuery("select id, cpzname, code from cpz");
            if (dt == null) return;

            CpzListView.DataSource = dt;
            CpzListView.DataBind();
        }

        protected void i_UserLV_ItemCanceling(object sender, ListViewCancelEventArgs e)
        {
            CpzListView.EditIndex = -1;
            UpdateBinding();
        }

        private string GetValue(users key)
        {
            return CpzListView.Items.Count > 0 ? CpzListView.SelectedDataKey[key.ToString()].ToString() : string.Empty;
        }

        protected void i_UserLV_ItemEditing(object sender, ListViewEditEventArgs e)
        {
            CpzListView.EditIndex = e.NewEditIndex;
            CpzListView.SelectedIndex = e.NewEditIndex;
            UpdateBinding();
        }

        protected void i_UserLV_ItemInserted(object sender, ListViewInsertedEventArgs e)
        {
            // must empty
        }

        private string ControlValue(string controlName, ListViewItem item)
        {
            object c = item.FindControl(controlName);
            if (c is TextBox) return (c as TextBox).Text;
            if (c is CheckBox) return (c as CheckBox).Checked ? ADataBase.TRUE : ADataBase.FALSE;
            if (c is DropDownList) return (c as DropDownList).SelectedValue;
            return null;
        }

        protected void i_UserLV_ItemUpdated(object sender, ListViewUpdatedEventArgs e)
        {
            // must empty
        }

        protected void i_UserLV_ItemUpdating(object sender, ListViewUpdateEventArgs e)
        {
            if (CpzListView.SelectedDataKey != null && !string.IsNullOrEmpty(CpzListView.SelectedDataKey["id"].ToString()))
            {
                var cpzId = CpzListView.SelectedDataKey["id"];
                var cpzName = ControlValue("tbCpzName", CpzListView.EditItem);
                var cpzCode = ControlValue("tbCpzCode", CpzListView.EditItem);
                string updateCpzQuery = string.Format(@"update cpz c
                                            set c.cpzname = {0}
                                            and c.code = {1}
                                            where c.id = {2}", cpzName, cpzCode, cpzId);
                if (AOneConnectDB.ExecuteNonQuery(updateCpzQuery))
                {
                    AGUI.ShowMessage(MessageType.Success, "CPZ Modified.");
                }
            }
        }

        protected void i_UserLV_ItemCreated(object sender, ListViewItemEventArgs e)
        {
            // must empty
        }

    }
}

I am new to consuming WCF services from ASP.net websites. I have been working with AP.net websites for some time. Now, I have a challenging situation. I need to access WCF services from asp.net websites. My actual requirement is to read the incoming clients' IP address. From reading the tutorials, I was able to consume the WCF services from asp.net websites.

Suppose I have a WCF service LoginMethod(userid,password,ip) where ip is taken from http message header, how is it possible to read the HTTP message header at the WCF Service ?

I need to make one utility which can do the conversion for the .cmp file to .png or .jpg format file.

Sample .cmp file: https://docs.google.com/a/meditab.com/file/d/0B9yqWUFZO4qhd3BySHZLaGxBRXJReXlDWWRzbXVlNUM1Vm9Z/edit

for the .cmp file it is certainly very hard to find article related to .cmp file operations. Here i am listing what I have tried so far:

  1. Image compression/ Re-Compression
  2. http://bringerp.free.fr/RE/Phantasie/spriteViewer.php5#CMP spriteviewer c# code

if you need any further information from my end please comment below.

2 days i've been working on this now and no matter what I try I simply cant get it to work.

What i'm trying to do is get a Review Page of a Ordering System to grab data from a database and change the text of the labels to the corresponding fields in the DB. Obviously I have to have it so that it only uses the current logged in users username not the first one in the DB (i'm using the asp.net membership database).

Here is the code from the page behind (I want it to display on-load):

protected void Page_Load(object sender, EventArgs e)
    {
string username1 = User.Identity.Name;
        CheckUser.InsertParameters.Add("@username", username1);
        string readsql = "SELECT title, gname, sname, dob, address, suburb, postcode, dayphone, email FROM users WHERE username = @username";
        using (SqlConnection myConnection = new SqlConnection(strConnString))
        {

            myConnection.Open();

            SqlCommand myCommand = new SqlCommand(readsql, myConnection);
            SqlDataReader reader = myCommand.ExecuteReader();
            myCommand.ExecuteNonQuery();
            reader.Read();
            Label2.Text = reader["title"].ToString();
            Label3.Text = reader["gname"].ToString();
            Label4.Text = reader["sname"].ToString();
            Label5.Text = reader.GetDateTime(reader.GetOrdinal("dob")).ToString();
            Label6.Text = reader["address"].ToString();
            Label7.Text = reader["suburb"].ToString();
            Label18.Text = reader["postcode"].ToString();
            Label8.Text = reader["dayphone"].ToString();
            Label9.Text = reader["email"].ToString();
            reader.Close();
            myConnection.Close();
        }

And this is the ASPX page itself:

<asp:SqlDataSource ID="CheckUser" runat="server" ConnectionString="<%$ConnectionStrings: Database %>" 
     SelectCommand ="SELECT title, gname, sname, dob, address, suburb, postcode, dayphone, email FROM users WHERE username = @username" ProviderName="<%$ ConnectionStrings:Database.ProviderName %>"></asp:SqlDataSource>

I've tried so many variations of this but nothing seems to work. Keep getting Scaler Variable error for @username.

Any ideas on what's going wrong?

Hi respected developers, I am trying to develop a sample movie ticket booking application.When a seat (image button) is selected, the color has to change and when it is de-selected the color has to regain its normal position i.e.,white or no color.Can anybody take me to the right path.When seat image is selected. But it shows turning of seat into blue up to 1 second and getting back to its normal position.

imagebuttonSeat1.Backcolor=System.Drawing.Color.Blue;

I am trying to implement clean url in my asp.net website.

when I try home all images are loaded properly, but if I pass parameter home/logout than images are not loaded properly.

I am not able to call web services after implementing clean url.

This is the code I have written in mu global.asax

RouteTable.Routes.MapPageRoute("home", "home/{logout}", "~/default.aspx"); RouteTable.Routes.MapPageRoute("freeDelivery", "freeDelivery", "~/freeDelivery.aspx");

I designed a ASP.net Webforms site that uses Watin to scrap data from another website.

Everything worked fine when I was using Visual Studio locally. However when I deployed the code to an actually server, Watin didnt work.

Here is what I've done so far: - Edited my COM Security (Launch and Activation Permissions) to allow Everyone full access. - Installed the Watin DLsLs in the GAC. - Set my IIS Application Poll User to myself. - Set the 'createInNewProcess' flag to true in my C# code for Watin.

When I go the the Event Viewer for the server, the message I get is :

An unhandled exception occurred and the process was terminated.

Application ID: /LM/W3SVC/3/ROOT

Process ID: 3888

**Exception: WatiN.Core.Exceptions.BrowserNotFoundException**

**Message: Could not find an IE window matching constraint: Timeout while waiting to attach to newly created instance of IE.. Search expired after '30' seconds.**

At this point I'm stuck. I feel like the issue has something to do with Watin trying to create a window for a desktop program, but not having an actually desktop to run from since its being called by the IIS server.

Anybody got any ideas? I wrote a lot of code already thinking this would work since it did work locally.

Thanks in advanced! (Ugghhh so frustrating!)

Angular seems so elegant but when I try and send this $http request I get a 500 error.

    $scope.UpdateOrganization = function (organization) {
        var jsonOrg = JSON.stringify(organization);

        var url = 'Organization/UpdateOrganization/' + organization.ActorId;

        $http({
            method: 'PUT',
            url: url,
            data: jsonOrg,
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).success(function (data, status) {
        }).error(function (data, status) {
        });
    }

On the receiving end, I am using an MVC controller. The method is like this:

    // PUT: api/Organization/guid
    [HttpPut]
    public string UpdateOrganization(Guid id, Organization organization)
    {

    }

Basically, I want the C# controller to receive the Angular PUT. However, the failure has something to do with the data: jsonOrg in the $http call.

Just to clarify, I have also tried $http.put() with no success. I must be doing something wrong.

VS2013 Update3, .Net 4.5, MVC, IIS 7

I created a new mvc project. Tested from VS and it works. From IIs, I created a folder in wwwroot, and made it an application. Add app pool with .net 4.0. Enabled windows authentication and disabled Anonymous authentication. Set service account in app pool and webapp. From VS I deploy to IIS with default settings (which is NOT precompile) (using File System) Site works fine on IIS. But… If deploy with the precompile setting clicked on. Web site fails with 403 error. Tried various combinations and get never get the precompiled to work. Always works when non-precompiled.

I'm out of ideas and looking for help

I am unable to create an instance using PDFLibrary in C#.

The dll lives at c:/the project directory/lib/DebenuPDFLibraryDLL1016.dll

I generate the path and also tried hard coding it.

var dllPath = AppDomain.CurrentDomain.BaseDirectory + "Lib\\DebenuPDFLibraryDLL1016.dll";

This method assumes SysWOW or System32 dirs.

PDFLibrary QP = new PDFLibrary("DebenuPDFLibraryDLL1016.dll");

Also attempted with this:

PDFLibrary QP = new PDFLibrary(dllPath);

I've included the import file: DebenuPDFLibraryDLL1016.cs Inside the constructor, dll.dllHandle is always 0. The object is never instantiated. This is the part inside the DebenuPDFLibraryDLL1016.cs file that creates the dll instance.

    public PDFLibrary(string dllFileName)
    {
        dll = new DLL(dllFileName);
        if (dll.dllHandle != IntPtr.Zero)
        {
            instanceID = dll.DebenuPDFLibraryCreateLibrary();
            dll.RegisterForShutdown(instanceID);
        }
        else
        {
            dll = null;
        }
    }

Does anyone know why this would happen aside from having the wrong location of the dll? I have uninstalled / reinstalled the quick pdf data a few times.

Based on their documentation it should live in the SysWOW or System32 folders based on your application needs.

I think the issue is the dll and the server has the site set to the incorrect application type. I will try to change that next.

i want to add dynamic fields into a list of items that are contained in a IEnumerable in a model class.

I followed this tutorial where they say that you can put

$("#addItem").click(function() {
    $.ajax({
       url: this.href,
       cache: false,
       success: function(html) { $("#editorRows").append(html); }
   });
    return false;
});

But when i post the form , the new added rows are not considered as part of the model. I am sure is because the names of the fields has their own id and name attributes , so they have to follow a pattern like the original ones(not added by js). Can you suggest a way to do that? Any tutorial? Any help? I am lost. Many thanks!! I will mark as answer the best answer

Suppose we have the following controller code and default to Home/Index and i have a domain www.abc.com.

How to i configure to make www.abc.com/home and www.abc.com/home/index as 404 page

 public HomeController : Controller {
        public ActionResult Index() {
        }
    }

Also suppose I have controller like this, I assume that user can access it following way. www.abc.com/home/index/1 or using query string www.abc.com/home/index/?id = 1. I would like to display 404 page for this url: www.abc.com/home/index/?id = 1. How can this be done?

public HomeController : Controller {
        public ActionResult Index(string id) {
        }
    }

I don't know how to use razor syntax in Javascript. I want to make Html.ListBoxFor with items from my model. I used to use:

@Html.ListBoxFor(x => x.TagIdList, (MultiSelectList)ViewBag.Tags, new { @class = "chzn-select", data_placeholder = "Tags..." })

As you see I want also use chzn-select class, to have better layout.

For now, I just have this code above in HTML as plain text, but I want have there things from my model.

Any ideas?

There is my code in ASP.NET MVC:

@model Generator.Models.ExamModel

@{
    ViewBag.Title = "Generate";
}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    <script src="@Url.Content("~/Multiple_chosen/chosen.jquery.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/ListOfTags.js")" type="text/javascript"></script>
    <script >    
        $(".chzn-select").chosen();
    </script>
}

<link href="@Url.Content("~/Multiple_chosen/chosen.css")" rel="stylesheet" type="text/css" />

<h1>@ViewBag.Title</h1>
<h2>@ViewBag.Message</h2>

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

    <fieldset>
        <legend>Generate</legend>


        <div class="editor-label">Numbers</div>
        <div class="editor-field" id="NumberOfModels">
            @Html.EditorFor(model => model.NumberOfQuestions)
        </div>

        <div class="editor-label">Tags</div>
        <div id="itemsmodel"></div>
        <br>

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

And there is javascript file:

var models = document.getElementById("NumberOfQuestions");
var modelsTable = document.getElementById("itemsmodel");

models.addEventListener("change", drawModels, false);

function drawModels() {
    var modelsNum = parseInt(models.value);
    var curModels = modelsTable.childElementCount;

    if (modelsNum > curModels) {
        var delta = modelsNum - curModels;
        for (var i = 0; i < delta; i++) {
            var input = document.createElement("div");
            input.className = "editor-field";
            input.innerHTML = "@Html.ListBoxFor(x => x.TagIdList, (MultiSelectList)ViewBag.Tags, new { @class = \"chzn-select\", data_placeholder = \"Tags...\" })";
            modelsTable.appendChild(input);
        }
    } else {
        while (modelsTable.childElementCount > modelsNum) {
            modelsTable.removeChild(modelsTable.lastChild);
        }
    }
}

drawModels();

Afternoon.

I need help trying to add my Windows Login Name and the Current Date into my Current Database from a form in my cshtml file. Please bare in mind im pretty new to this... I've only started understanding HTML.

The Tools Im using: WebMatrix 3, Firefox

Name of the database is: sweep hazmat library.sdf

Table name is:kl1explosiv

Heres the code:

enter code here
{
    var db = Database.Open("sweep hazmat library");


    var ASIN = "";
    var description = "";
    var dateadded = "";
    var addedby = "";



    if(IsPost){

            //read ASIN.
            ASIN = Request["ASIN"];
            if (ASIN.IsEmpty()){
                Validation.Equals("ASIN", "A Article is needed here");
            }
            //read description.
            description = Request["description"];
            if (description.IsEmpty()){
                Validation.Equals("description", "a description is required");
            }
            //figure out how to add date automatically.
            dateadded = Request["DateTime.Now"];

            addedby = ;
            var SQLINSERT =
                "INSERT INTO kl1explosiv (ASIN, description, dateadded){Values (@0, @1, @datetime.now )";
            db.Execute(SQLINSERT, ASIN, description, dateadded, addedby);
            Response.Redirect("~/EntsorgungsTabelle.cshtml");

}

<html>
<head>

</head>

<body>
<h2>Add an Article</h2>
<form method="post">
<fieldset>
<p><label for="ASIN">Title:</label>
<input type="text" name="ASIN" value="@Request.Form["ASIN"]" />
@Html.ValidationMessage("ASIN")
</p>

<p><label for="description">beschreibung:</label>
<input type="text" name="description" value="@description" />
 @Html.ValidationMessage("description")
</p>

<p><input type="datetime-local" name="Dateadded" value="@dateadded" />  
</p>
<p><input type="submit" name="buttonSubmit" value="Add an Article" /></p>
</fieldset>
</form> 
</body>
</html>    

I am trying to use @Html.DropDownListFor to add selections to multiple drop down lists.

View

  for (int i = 0; i < Model.questions.Count(); i++)
{
        <fieldset>
            <legend>Questions</legend>

            <div class="editor-label">
                @Html.DisplayFor(model=>model.questions[i].Question)

            </div>
            <div class="editor-field">    
               @Html.DropDownListFor(model => model.answers[i].Answers, new SelectList(Model.hold[i]))
            </div>  
            <hr />
        </fieldset>
}

This iterates through all the questions in my Model and displays the question. The drop down box is used for the user to select answers to that question. Since the number of questions and answers to those questions are dynamically created by the admin user I can not simply make static lists and insert them into the Drop Down List.

Controller

  public ActionResult Index()
    {
        //get the list of questions from db
        var q = (from questions in db.questions select questions).ToList();
        var answersList = (from answer in db.answers select answer).ToList();
        List<List<string>> aList = SplitAnswers();

        QAViewModel qa = new QAViewModel{questions = q, hold = aList, questionAnswers = answersList};

        return View(qa);
    }

   public List<List<string>> SplitAnswers()
   {
       List<List<string>> aList = new List<List<string>>();
       List<string> populate = new List<string>();
       var answersList = (from answer in db.answers select answer).ToList();
       var q = (from questions in db.questions select questions).ToList();

       //Group answers by questionId to use in the view
       for (int i = 0; i < q.Count(); i++)
       {
           for (int x = 0; x < answersList.Count(); x++)
           {
               if (answersList[x].QuestionsId == q[i].Qid)
               {
                   populate.Add(answersList[x].answer);
               }
           }
           aList.Insert(i, populate);
       }

       System.Diagnostics.Debug.WriteLine("test" + aList[1]);
       return aList;
   }

I'm using a aList (of type List<List<string>>) so that i can store populate (of type List<string>) at each element of aList. However, each drop down list ends up showing all the elements of aList.

I am not sure if I am misusing List<List<string>> or if I am somehow adding all the elements of populate at every element of aList.

UPDATE

By changing the index of Model.hold in @Html.DropDownListFor(model => model.answers[i].Answers, new SelectList(Model.hold[1])) I can see that each element of this list holds all the answers.

I have two asp.net sites. one is like domain.com and the second is sub.domain.com. The domain.com sets aspxauth cookies on login and removes it (via expiration date in the past) on logout. The cookie domain is ".domain.com" so it's available on both side. sub.domain.com is passive about cookies and just tries to read the cookies and authenticate user if cookie was found.

The problem. After some period of time the browser gets the second ASPXAuth cookies with the "domain.com" (without ".") domain - so log out doesn't work since only first (".domain.com") cookie is removed.

Config is

<authentication mode="Forms">
  <forms loginUrl="~/account/login" timeout="2880" domain=".domain.com"/>
</authentication>

Set cookie

public static void SetAuthCookie(IUserPrincipal principal, DateTime expiration)
    {
        var ticket = new FormsAuthenticationTicket(1, principal.Identity.Name, DateTime.Now, expiration, false,
            principal.SessionId, FormsAuthentication.FormsCookiePath);

        var encTicket = FormsAuthentication.Encrypt(ticket);
        var response = HttpContext.Current.Response;

        if (response.Cookies[FormsAuthentication.FormsCookieName] != null)
        {
            response.Cookies.Remove(FormsAuthentication.FormsCookieName);
        }

        var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)
        {
            Expires = expiration,
            Secure = FormsAuthentication.RequireSSL,
        };
        response.Cookies.Set(cookie);
    }

Remove cookie

 public static void SignOut()
    {
        SetContextPrincipal(null);
        FormsAuthentication.SignOut();
    }

With the sharepoint API you can only return 500 items for every search, however for some specific report I am doing I need to return all results, so that in a page (webpart), they can export it to excel.

I have the do while logic already in place, but I am not sure how to concatenate/merge/join the resultfs of each iteration in a bigger datatable.

max Nr of rows is 9000.

The code I have is as follows, but missing the important part which is my question actually

 int k = 0;
                int batchsize = 500;
                int nrofRecords = 0;
                int index = default(int);
                using (new DocBoxMonitoredScope("KQLUtilities.ExecuteKQL"))
                {
                    do
                    {
                        index = k * batchsize;
                        keywordQuery.RowLimit = batchsize;
                        keywordQuery.StartRow = index;
                        resultTableCollection = new SearchExecutor().ExecuteQuery(keywordQuery);
                        nrofRecords += resultTableCollection[0].RowCount;                       

                    } while (nrofRecords == batchsize);
                }

Hi I am using a reportviewer control in visual studio 2012 and I want to reset the datasource of the report viewer, but I can't figure out the right name value combination: The Datasource in my .rdlc is "RF" and the Dataset in the .rdlc is "dsTotalOrderCalls" I have an Objectdatasource ID: "odsSales" and a type name: "RapidFire.RFTableAdapters.USP_TOTAL_ORDERCALLSTableAdapter" that is referring to a table adeapter in an .xsd (dataset) that is calling a stored procedure called "USP_TOTAL_ORDERCALLS" and returning a data table called: "USP_TOTAL_ORDERCALLSDataTable"

When I try to open a new instance of the reportdatasource ie, rv_SalesSC.LocalReport.DataSources.Add(new ReportDataSource("dsTotalOrdersCalls", odsSalesSC));

I receive an error message saying: Cannot create a connection to data source 'RF'

Can someone help me understand what values go into instantiating a new reportdatasource object? Thank you!!!