samedi 25 avril 2015

STRUGGLING IN CRYSTAL REPORT MARGIN


i have a task to print id, it should print 4 data in every page, it looks like 2 rows 2 columns, the paper that i'm using has 4 id embedded in every column, I've managed to achieve it using the "section expert", however when i move the black rectangle inside the white rectangle using the margins in page setup, height in rpt, and section expert, the black object goes to different directions, are there any code that would make the black object follow a single direction? anyone here encountered this problem?

it's really hard because i have to print it using printToprinter to see the result.

http://ift.tt/1bGiNuE


Membership.GetUser -> Membership doesn't contain a definition for 'GetUser'. What I missed?


MembershipUser newUser = Membership.GetUser(CreateUserWizard1.UserName);

A red line under GetUser and when I hover over it, a message appears:

Membership doesn't contain a definition for 'GetUser'

When I click the small dash below GetUser I found:

Generate method stub for 'GetUser' in 'Membership

What I missed?

ASPX:

<asp:CreateUserWizard ID="CreateUserWizard1" runat="server" OnCreatedUser="CreateUserWizard1_CreatedUser" >
    <WizardSteps>
        <asp:CreateUserWizardStep ID="CreateUserWizardStep1" runat="server">
        </asp:CreateUserWizardStep>
        <asp:CompleteWizardStep ID="CompleteWizardStep1" runat="server">
        </asp:CompleteWizardStep>
    </WizardSteps>
</asp:CreateUserWizard>

Code behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

public partial class SignUp : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
    {
        MembershipUser newUser = Membership.GetUser(CreateUserWizard1.UserName);
        Guid newUserId = (Guid)newUser.ProviderUserKey;
    }
}


vnext (asp .net 5.0) and oracle


I created a vnext solution in visual studio ultimate 2015 CTP version 14.0.22609.0 D14REL and in the package manager I added the oracle managed driver.

Install-Package odp.net.managed

then in my config.json

"Data": {
        "DefaultConnection": {
            "ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=aspnet5-vnext-237fb18c-c414-44a8-8771-e02d4719d1dc;Trusted_Connection=True;MultipleActiveResultSets=true"
        },
        "hr": {
            "ConnectionString": "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SID=mydatabase))); User Id=hr; Password=xxxxxxx;", "providerName":"oracle.manaagedatacess.client"
        }

    },

when I attempted to use it in a class

using System;
using Oracle.ManagedDataAccess.Client;
using System.Configuration;

namespace vnext.Models
{
    internal class dataHelper
    {
        OracleConnection cn = new OracleConnection(ConfigurationManager.ConnectionStrings["hr"].ConnectionString);
    }
}

lots of compile errors such as the type or namespace Oracle, Configuration, and OracleConnection could not be found are you missing an assembly reference? project vnext asp.net Core 5.0


How to customize CreateUserWizard to get UserId and UserName values?


I am using Membership provider to deal with user registration and logging to the website. This Membership provider is part of a package comes through:

Install-Package Microsoft.AspNet.Providers

I have two ASPX pages one has a CreateUserWizard control and the other has a Login control. The registration and logging is working correctly.

I have defined Profile properties in the web.config file:

<profile defaultProvider="DefaultProfileProvider">
  <properties>
    <add name="Id" type="System.Guid" />
    <add name="UserName"/>
  </properties>

What I am trying to is to be able to take the UserId and UserName values on registration of the user, and store them to Profile.Id and Profile.UserName respectively.

How to customize the CreateUserWizard to achieve this?.

My try:
When you show CreateUserWizard on the browser. You can see a button named "Create User", so I thought it is a good place to extend on and add code to take the required values. So I clicked the small arrow on CreateUserWizard and choose Customize Create User Setup, but the editable template doesn't include the corresponding button of "Create User".

So what is the possible way to achieve that?


Display nested gridview


I have a nested GridView with 4 levels, when i click in "+" to show child GridView i make request to database to download data of current row, every thing work well for me, the only problem i have is in design, all the child GridView display in column of its parent GridView this is how it looks:

Parent GridView enter image description here

First Child gridView enter image description here

here is my aspx code:

    <asp:UpdatePanel ID="upNestedGridView" runat="server" UpdateMode="Conditional">
       <ContentTemplate>
          <asp:GridView ID="gvCostCenters" runat="server" ....>
           <Columns>
             <asp:TemplateField>
               <ItemTemplate>
                 <asp:ImageButton ID="imgShowAccountingPlan" runat="server" OnClick="Show_Hide_AccountingPlansGrid" .../>
                    <asp:Panel ID="pnlAccountingPlan" runat="server" Visible="false" Style="position: relative">
                        <asp:GridView ID="gvAccountingPlans" runat="server" AutoGenerateColumns="false"....">
                          <Columns>
                             <asp:TemplateField>                                 
                                <ItemTemplate>
                                   <asp:ImageButton ID="imgShowPrograms" runat="server" OnClick="Show_Hide_ProgramsGrid" .../>
                                   <asp:Panel ID="pnlPrograms" runat="server" Visible="false" Style="position: relative">
                                       <asp:GridView ID="gvPrograms" runat="server" AutoGenerateColumns="false" ...>
                                            <Columns>
                                                <asp:TemplateField>
                                                    <ItemTemplate>
                                                        <asp:ImageButton ID="imgShowProjects" runat="server" OnClick="Show_Hide_ProjectsGrid" ..../>
                                                        <asp:Panel ID="pnlProjects" runat="server" Visible="false" Style="position: relative">
                                                            <asp:GridView ID="gvProject" runat="server" ....>
                                                                .....
                                                            </asp:GridView>
                                                        </asp:Panel>
                                                    </ItemTemplate>
                                                </asp:TemplateField>                                                                              
                                                <asp:BoundField DataField="Label" HeaderText="البند " ItemStyle-HorizontalAlign="Right" />
                                                ....
                                            </Columns>
                                        </asp:GridView>
                                    </asp:Panel>
                                </ItemTemplate>
                             </asp:TemplateField>                                                          
                             <asp:BoundField DataField="NumAccountingPlan" HeaderText="الخطة المحاسبية " ItemStyle-HorizontalAlign="Right" />
                             ...
                         </Columns>
                    </asp:GridView>
                 </asp:Panel>
            </ItemTemplate>
         </asp:TemplateField>
         ...
        <asp:BoundField DataField="OperatingExpenses" HeaderText="المصروفات التشغيلية" DataFormatString="{0:#,##0.00;(#,##0.00);0}" />
    </Columns>
</asp:GridView>

my jquery code:

<script type="text/javascript">
    $(function () {
        $("[src*=minus]").each(function () {
            $(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>");
            $(this).next().remove()
        });
    });
</script>

My code C#:

protected void Show_Hide_AccountingPlansGrid(object sender, EventArgs e)
    {
        try
        {
            ServiceClass service = new ServiceClass();
            ImageButton imgShowHide = (sender as ImageButton);
            GridViewRow row = (imgShowHide.NamingContainer as GridViewRow);
            if (imgShowHide.CommandArgument == "Show")
            {

                _budget = service.GetBudgetById(int.Parse(hfIdBudget.Value));
                row.FindControl("pnlAccountingPlan").Visible = true;
                imgShowHide.CommandArgument = "Hide";
                imgShowHide.ImageUrl = "/Content/img/minus.gif";
                string idCostCenter = gvCostCenters.DataKeys[row.RowIndex].Value.ToString();
                GridView gvAccountingPlans = row.FindControl("gvAccountingPlans") as GridView;
                //gvAccountingPlans.ToolTip = costCenterId;
                gvAccountingPlans.DataSource = AccountingPlanData(int.Parse(hfIdUser.Value), int.Parse(hfIdBudget.Value), int.Parse(idCostCenter));
                gvAccountingPlans.DataBind();

            }
            else
            {
                row.FindControl("pnlAccountingPlan").Visible = false;
                imgShowHide.CommandArgument = "Show";
                imgShowHide.ImageUrl = "/Content/img/plus.gif";
            }
        }
        catch (Exception ex) { GlobalHelpers.Trace(ex); }
    }

I notice that when i delete the UpdatePanel the first child GridView display well, but the others no. How can i do to display all childs GridView well?

I'm sorry for my bad english


How to set Startdate is Today in cc2:CalendarExtender?


<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" 
                                                             TagPrefix="cc2" %>
<asp:TextBox ID="txtngaydat" runat="server"></asp:TextBox>
<cc2:CalendarExtender ID="CalNgayDat" TargetControlID="txtngaydat" 
                       PopupButtonID="ibtCal" runat="server"></cc2:CalendarExtender>

Any help would be highly appreciated, Thanks in advance,


Asp.net Add identity user from backend


I am developing Asp.net web application in visual studio 2013.

I have a requirement to add new ApplicationUsers from backend (SSMS trigger)? Any stored procedure?

In other words, is there any option to do the following from SQL Server trigger that I am doing from C# right now?

ApplicationUserManager::Create
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
            var signInManager = Context.GetOwinContext().Get<ApplicationSignInManager>();
            var user = new ApplicationUser() { UserName = Email.Text, Email = Email.Text };
            IdentityResult result = manager.Create(user, Password.Text);

Best regards,


Need to Get data value prior to binding to row in listview


I have a ListView object in asp.net (C#) where I also have a ListView_ItemDataBound() method that is populated using a sqlDataSource.

In some cases, I would like to be able to insert a row in the ListView prior to the current record being bound. I.e., as the rows are being populated, I need to be able to read the value that is about to be bound and then insert a "header" row mid stream before the current row of data is added to the ListView. In the case of the ItemDataBound event, the data seems to be already bound to the control so the rows being added are actually one ListView row too late for me to do anything.

ListView_ItemDataBound()
{
    System.Data.DataRowView rowView = e.Item.DataItem as System.Data.DataRowView;


 //Psuedo code of what I'd like
 //if rowView["some_field"]==123 then insert row prior to this row being bound
    }

I'm relatively new to asp.net and come from a classic asp background so maybe I'm thinking and going about this all wrong. Any suggestions would be appreciated.


How can I toggle a css class automatically on mobile view?


I would like to automatically toggle an asp.net control (Textbox) class when a user opens the website on mobile.

I tried the following code it works to get the screen size automatically. but now I want to change or add a new class to the textbox which sets the Textbox width to 100%.

Javascript code

<script type="text/javascript">
window.onload = function () { responsiveFn(); }
function responsiveFn() {
width = $(window).width();
height = $(window).height();

if (width <= 470)
{
var cntltxtInput = document.getElementById(<%=TextBox1.ClientID %>);
cntltxtInput.setAttribute("class", "mobMini");
document.getElementById('widthID').innerHTML += "This is an Iphone S";
}
}
</script>

Asp.net C#

<asp:TextBox ID="TextBox1" runat="server"  ></asp:Textbox>

Css Class

<style type="text/css">
.mobMini {
width:100%;
}
</style>

Any ideas?


Updating database gives "The multi-part identifier could not be bound." Error


Im trying to update the BookingID in the CounselorDB table. Its previously null. cID is a String that contains the predefined CounselorID.

The error im getting is The multi-part identifier "x" could not be bound. x being the cID.

Thank you.

 using (SqlConnection connection = new SqlConnection(connectionString))
    {
        String sql = string.Format("UPDATE CounselorDB SET BookingID = @BookingID WHERE CounselorID = " + cID);
        SqlCommand cmd = new SqlCommand(sql, connection);
        cmd.CommandType = CommandType.Text;
        cmd.Connection = connection;
        cmd.Parameters.AddWithValue("@BookingID", getBookingID());
        connection.Open();
        cmd.ExecuteNonQuery();
    }


I am new to Asp.net, How to program that Admin is able to change the text of content pages (Different Sections) in active-admin asp.net dashboard?


Admin be able to change the text of different sections like highlighted ones[1 http://ift.tt/1HFddG6]


Struggling with Object Reference Null Exception ASP.NET


I am having issues with DataTable.

I am trying to create a simple cart but it's not passing all the information to the Cart page when I click Add Cart.

<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl='<%# ResolveUrl(Eval("Image").ToString()) %>'/>
    </div>
    <div>
        <b>
            <asp:Label ID="IDLABEL" runat="server" Text='<%# Eval("jumperID") %>'></asp:Label><br />
            <asp:Label ID="NameLabel" runat="server" Text='<%# Eval("Name") %>'></asp:Label><br />
            <asp:Label ID="TypeLabel" runat="server" Text='<%# Eval("Type") %>'></asp:Label> <br />
        </b></div>
    <div style="clear: right;">
        Our Price: £<%# Eval("Price") %></div>
    <asp:TextBox ID="txtQty" runat="server" Text="1" CssClass="QtyTextBox"></asp:TextBox>
    <div class="cell1">
        <asp:Button ID="btnCart" runat="server" Text="Add to Cart" CommandArgument='<%# Eval("jumperID") %>' OnClick="btnCart_Click"/></div>

When I click the add button it should pass information: jumperid, jumpername, type, quantity and price

However I get the error, and it highlights string JumperName...

"Object Reference not set"

string jumperID = Convert.ToInt32((((Button)sender).CommandArgument)).ToString();
string JumperName = ((Label)listView.FindControl("NameLabel")).Text;
string Type = ((Label)listView.FindControl("TypeLabel")).Text;
string Qty = ((TextBox)listView.FindControl("txtQty")).Text;

if (Session["Cart"] != null)
{
    DataTable dt = (DataTable)Session["Cart"];
    dt.Rows.Add(jumperID);
    dt.Rows.Add(JumperName);
    dt.Rows.Add(Type);
    dt.Rows.Add(Qty);
    Session["Cart"] = dt;
    Response.Redirect("MyCart.aspx");
}
else {
    DataTable dt = new DataTable();
    dt.Columns.Add(("jumperID"),typeof(string));
    dt.Rows.Add(jumperID);
    dt.Rows.Add(JumperName);
    dt.Rows.Add(Type);
    dt.Rows.Add(Qty);
    Session["Cart"] = dt;
    Response.Redirect("MyCart.aspx");
}

Please help me I've been stuck on it for a week now


How to get ip address in Managed C++


Can someone give a example how to obtain the ip address in Managed C++.
I have several examples in C# but didn't found code in C++.
This is the code in C# :
string strIPAddress = string.Empty;
strIPAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];


Error: SignalRRouteExtension.Mapconnection is obsolete. use MapSignalR in Owin Startup class


I am developing a ASP.NET MVC application with ASP.NET SignalR. But i am getting error and couldn't find how to solve this. This is my global.asax class and I am getting error at here when i started the project:

 public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start(object sender, EventArgs e)
    {
        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);

        //This is what I added and this is where i am getting the error.
        RouteTable.Routes.MapConnection<NfcConnection>("echo", "/echo");
    }
}

And my connection class like at the bottom

public class NfcConnection : PersistentConnection
{
    protected override Task OnConnected(IRequest request, string connectionId)
    {
        string msg = string.Format(
            "A new user {0} has just joined. (ID: {1})",
            request.QueryString["name"], connectionId);
        return Connection.Broadcast(msg);
    }

    protected override Task OnReceived(IRequest request, string connectionId, string data)
    {

        string msg = string.Format(
            "{0}: {1}", request.QueryString["name"], data);
        return Connection.Broadcast(msg);
    }
}

This is the part that will broadcast the data which coming from the client. And also my startup class for owin is like that;

 public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.MapSignalR();
    }

}

When i start the project this line

RouteTable.Routes.MapConnection<NfcConnection>("echo", "/echo");

giving me this error;

Error'System.Web.Routing.SignalRRouteExtensions.MapConnection<T>(System.Web.Routing.RouteCollection, string, string)' is obsolete: 'Use IAppBuilder.MapSignalR<TConnection> in an Owin Startup class.

How can i solve this?


Contains Method doesnt work


 String emailID = Session["New"].ToString();
        string usertype = returnQuery("select userType from Registration where email = '" + lblEmail.Text + "'");
        if (usertype.Contains("Student"))
        {         
            Response.Redirect("Profile.aspx?email=" + emailID.ToString());
        }
        else if (usertype.Contains("Company"))
        { 
            Response.Redirect("CompanyProfile.aspx?email=" + emailID.ToString());
        }
        else if(usertype.Contains("Admin"))
        {
            Response.Redirect("AdminProfile.aspx?email=" + emailID.ToString());
        }
        else
            Response.Write("Error");

I want to compare the UserType if it is Student I want to redirect him to srudent profile etc. But it always gets to the last else statement and Writes an Error the returnQuery method works well because it returns Student value.


Title case in C# using split()


I am writing a simple program that lets the user input a sentence and it gets converted to title case. The first letter in each word is made capital. When it runs I don't get any errors, but it doesn't convert. Can someone let me know what I am missing? Thanks in advance!

This is my .cs file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
 {
    protected void Page_Load(object sender, EventArgs e)
 {
    if (Page.IsPostBack)
    {
        Page.Validate();
        if (!Page.IsValid)
        {
            string sentence = phrase.Text;
            String[] sentenceArray = sentence.Split(' ');
            for (int i = 0; i < sentenceArray.Length; i++)
            {
                sentenceArray[i] = sentenceArray[i].Substring(0,      1).ToUpper() + sentenceArray[i].Substring(1).ToLower();
            }
            phrase.Text = String.Join(" ", sentenceArray);
        }
    }
  }
  }

If needed here is the HTML code:

<html xmlns="http://ift.tt/lH0Osb">
<head runat="server">
    <title>Convert to Title Case</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <p>
        Enter a phrase and click the Title Case button.</p>
        <p>
            <asp:TextBox ID="phrase" runat="server" /> <asp:RequiredFieldValidator ID="letterValidator"
                runat="server" ErrorMessage="Required field" ControlToValidate="phrase" />
        </p>
        <p>
            <asp:HiddenField ID="progress" runat="server" Value="**********" />
            <asp:Button ID="convertToTitleCase" runat="server" Text="Title Case" />
        </p>
    
    </div>
    </form>
</body>
</html>

Multiple dbContexts in ASP.NET vNext and EF7


I'm trying to get along with building web systems with ASP.NET vNext using MVC 6 and EF7. I'm looking at this tutorial: http://ift.tt/1xcKRJH

On the page you'll see how to add a dbContext to a project and it's registered in the startup file like this:

        // Register Entity Framework
        services.AddEntityFramework(Configuration)
            .AddSqlServer()
            .AddDbContext<MoviesAppContext>();

And the context class looks like this:

public class MoviesAppContext:DbContext
{

    public DbSet<Movie> Movies { get; set; }

}

It all works good, but now I'm in need of adding an additional DbContext. Though I don't know how to register this additional context so that it will be used by EF and possible to use in my project.

Let's say I've created a new context like this:

public class MyNewSuper:DbContext
{

    public DbSet<Model1> Model1 { get; set; }
    public DbSet<Model2> Model2 { get; set; }

}

How do I go ahead to register it for use in my project then?


map static files to alternate path


So I have a MVC website at this location on disk: C:\MyApp\Applications\1.0.0.0, however I have static resources in a shared location like: C:\OtherApps\myapp\css\site.css

How can I intercept requests for static files to my MVC app and map the path to this alternate resources location? I have an IHttpHandler that I can apply to specific paths, but I want to do this for all static files (things that don't match an MVC route).

note: nothing is serving resources from the alternate location, so a rewrite will not work.


Using EF and other Dapper ORM in same project - drawbacks


I am about to start a new project and I have a little dillema. App require asp identity for security and dapper as orm. My plan is to use default asp web app template with identity that use entity framework and for all business data access use dapper. This means that I will use dapper sometimes to get something from identity tables also (like username for some user).

Another approach is to change identity to use dapper but I think that I am not skilled enough to do that and this probably would be bad for project later.

So what could be drawbacks for architecting app like this?


ASP.NET Access to Path "something" is denied. (and most of solutions here didn't work)


I am trying to upload a file, an image, to a folder in the server called images, when i click the button to upload it, after it passes ImageUpload.SaveAs(Path) i get an exception "Access to Path "any path here" is denied, now i tried editing the security tab of the folder and gave permission to NETWORK SERVICE, i tried giving permission to IIS AppPool\DefaultAppPool, still not working. i also enabled ASP.NET Impersonation in the iis manager as some other people said, still same error.


ASP.NET MVC5: live loaded partial view doesn't load dynamic Javascript reference


My goal is to refresh a partial View containing an interactive world map. I have a Controller action

public JavaScriptResult DynMap(int id, List<int> relevantCountries = null){}

which returns the map data as JavaScriptResult.

I call this Javascript in my Partial View "MapSite" with

<script src="/JS/DynMap/@ViewBag.GameRoomID"></script>

The Partial View "MapSite"

public ActionResult MapSite(int id)
{
   ViewBag.GameRoomID = id;
   return PartialView("MapSite");
}

is rendered into my main page like this:

<td id="map">
    @{Html.RenderAction("MapSite", "JS");}
</td>

That works perfectly fine! But if I want to render MapSite again at runtime (with new values) like this: $('#map').load('/JS/MapSite/4')(4 is static for testing), the Partial View comes without the DynMap Javascript.

Is this a bug? Isn't it possible to load external Javascript this way "live"? It even hits the breakpoint inside the Controller DynMap method, but the map is empty, because the DynMap values are missing.


update sql in asp.net


what's the error on this when i run it it's give me this error ""String or binary data would be truncated. The statement has been terminated."" it's update by using ID that i take it from Drop Down list

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string constr = "Data Source=YAZAN-PC ; initial Catalog=Elder ; user = sa ; pwd =yazan7;";
        SqlConnection con = new SqlConnection(constr);
        string sql = "Select * from Users;";
        con.Open();
        SqlDataAdapter da = new SqlDataAdapter(sql, con);
        DataTable dt = new DataTable();
        da.Fill(dt);
        con.Close();
        DataRow dr = dt.NewRow();
        dr["ID"] = "0";

        dt.Rows.InsertAt(dr, 0);
        ddlID.DataSource = dt;

        ddlID.DataValueField = "ID";
        ddlID.DataBind();
    }
}

protected void btnUpdate_Click(object sender, EventArgs e)
{
    string constr = "Data Source = YAZAN-PC ;" +
                   "initial catalog = Elder;" +
                   "user = sa ; pwd = yazan7;";
    SqlConnection con = new SqlConnection(constr);
    string Sql =
    "Update Users Set Name=@Name , Gender=@Gender , Email=@Email ,UserType=@UserType, BirthDate=@BirthDate , Password=@Password, RePassword=@RePassword where ID=@ID;";
   con.Open();
    SqlCommand cmd = new SqlCommand(Sql, con);

    cmd.Parameters.AddWithValue("@Name", txtName.Text);
    cmd.Parameters.AddWithValue("@Gender", rblGender.SelectedValue);
    cmd.Parameters.AddWithValue("@Email", txtEmail.Text);
    cmd.Parameters.AddWithValue("@UserType", rblUserType.SelectedValue);
    cmd.Parameters.AddWithValue("@BirthDate", txtBirthDate.Text);
    cmd.Parameters.AddWithValue("@Password", txtPassword.Text);
    cmd.Parameters.AddWithValue("@RePassword", txtRePassword.Text);
    cmd.ExecuteNonQuery();
    con.Close();
}


Adding SelectListItem manually to SelectList to use in DropDownListFor


When I create a SelecList I wish to be able to add SelecListItem's manually and to do this I use this code:

List<SelectListItem> Provinces = new List<SelectListItem>();
Provinces.Add(new SelectListItem() { Text = "Northern Cape", Value = "NC" });
Provinces.Add(new SelectListItem() { Text = "Free State", Value = "FS" });
Provinces.Add(new SelectListItem() { Text = "Western Cape", Value = "WC" });

SelectList lstProvinces = new SelectList(Provinces);

Instead of this :

var lstProvinces = new SelectList(new[] { "Northern Cape", "Free State", "Western Cape" });

After I created the SelectList, I pass it to the DropDownListFor via the ViewBag :

Html.DropDownListFor(m => m.StartPointProvince, (SelectList)ViewBag.Provinces)

However when I create the SelectList using the first method, it doesn't work - It adds the 3 values to the dropdown list, but all the values display as: Code *screenshot of output

However when I use the second method, it works fine. I wish to use the first method because i want to be able to specify the Text AND value of each item.


Gridview generate extra column on left


I am using asp.net c#.I have following code this code is working fine.But problem is gridview generate one extra column on left.

   <asp:GridView Width="96%"   CssClass="grdclass" ID="grd"  runat="server" AutoGenerateColumns="False" DataKeyNames="STAT_ID"   >
                    <AlternatingRowStyle BackColor="#FFCC99" />
                    <Columns>
                <asp:TemplateField>
          <HeaderTemplate>
                <th scope="col">الهاتف</th>

          </HeaderTemplate> 
          <ItemTemplate>
            <td class="row_style">
                <div class="row_style">
                                   <%#Eval("PHONE_Num") %>
                                </div>

            </td>


          </ItemTemplate>
        </asp:TemplateField>

                    </Columns>
                    <EmptyDataTemplate>No Record Found</EmptyDataTemplate>
                    <HeaderStyle BackColor="Aquamarine" />
                    <RowStyle BackColor="#FFFFCC" />
                </asp:GridView>

Please check above code and guide me where is the mistake or how can i get rid of this problem.


how to get regex for twillio cell number in c#


I am working on c# project.I need to send sms on cell number via twillio service for account validation.So I need to validate cell Number of Twillio So What regex maybe useful for twillio cell number validation Thanks in Advance.


which connection string vs2013 and azure with EF and OAuth


I have searched the web and can't seem to find a direct, correct or current answer to this question.

"which connection string vs2013 and azure with EF and OAuth"

I am using Visual Studio 2013 Professional and creating a web forms application using SQL server. Existing DB's....

The question is I have 3 connection strings.....

1) The (DEFAULT) local database (*.mdf) that comes with a new project in VS2013. 2) The (AZURE_DB) actual AZURE connection string. 3) A tcp: connection string. Which is still local and ok for testing.....

* ALL 3 WORK and I can access all 3 without problem. *

Using the DEFAULT-LOCAL DB did copy up to Azure the table changes I made, adding and altering... Originally.

However in testing I am not getting on the AZURE SQL database the user data from a localhost login. So there doesn't seem to be a sync. Which is ok, I can point to any connection string as the default connection string. So just using the AZURE connection string would work. And it did until....

I introduced Entity Frameworks for user administration. After reviewing several MSDN demos and elsewhere, all that required a tweak or assumption using vs2013 with all the updates.

I got the "/" yellow screen application failure on my default aspx page where it references Hello, <%: Context.User.Identity.GetUserName() %> on the site master page for the user display in the menubar.

I have deleted, rebuilt my application several times and as soon as I get to implementing EF/OAuth, I get the yellow screen failure or a 404 error, depending on the many ways I have tried implementing this.

So I have 3 connection strings and I am assuming part of the error is the strings. But have read about issues with the Role Modeler.

So is there a definitive, use only 1 string as some have suggested to resolve the issue and if so which one, obviously the local db isn't going to help my application out in the real world.

It would seem the transport control protocol would be a logical upload path but not as fast and reliable as just connecting to the AZURE connection string and remove all other references.

I have an existing database. I want to use OAuth. I am using webforms but could move(learn) to MVC as most of the "current" demos show using MVC over webforms.

My Connection strings are as follows:

DEFAULT: Data Source=(LocalDb)\v11.0;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False

AZURE: Server=tcp:********.database.windows.net,1433;Database=****_DB;User ID=*****@******;Password={your_password_here};Trusted_Connection=False;Encrypt=True;Connection Timeout=30;

TCP: Data Source=tcp:*********.database.windows.net,1433;Initial Catalog=****_db;Integrated Security=False;User ID=****@****;Password=********;Connect Timeout=30;Encrypt=True;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False

FWIW: The "logical" choice appears to be to use the AZURE connection string and drop all the rest. Then delete the VS references in web.config to the local db's.....

But I have worked and reworked on this for too long and frustration with this seemingly simple issue is getting the better of me.

Thanks in advance.


Problems with the site.master page


How to change the length of the the nav-bar of site.master. As the number of items on the top bar increase the page over shadows the content below.


Why do I get a 'System.ArgumentOutOfRangeException' when setting the Text for a row cell?


Using a number of queries, as shown in the code below, I get the following exception:

An exception of type 'System.ArgumentOutOfRangeException' - Specified argument was out of the range of valid values

on this line:

e.Row.Cells[3].Text = count;

What could be the problem? I tried countless different things, but I can't get it working. I am a novice at this.

SqlConnection conn;
conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=" + Server.MapPath("~\\App_Data\\ForumDB.mdf") + ";Integrated Security=True;User Instance=True");
conn.Open();
SqlCommand comm;
comm = new SqlCommand("SELECT COUNT(ThreadId) FROM [Threads] WHERE [TopicId] = @TopicId", conn);
SqlCommand comm2;
comm2 = new SqlCommand("SELECT MAX(PostedDate) FROM [Threads] WHERE [TopicId] = @TopicId", conn);
SqlCommand comm3;
comm3 = new SqlCommand("SELECT PostedBy FROM Threads WHERE PostedDate=(SELECT MAX(PostedDate) FROM [Threads] WHERE [TopicId] = @TopicId", conn);

//FOR COMMAND1 CMD
comm.Parameters.Add("@TopicId", System.Data.SqlDbType.Int, 10, "TopicId");
comm.Parameters["@TopicId"].Value = e.Row.Cells[0].Text;
string count = (comm.ExecuteScalar().ToString());
e.Row.Cells[3].Text = count;

//FOR COMMAND2 CMD1
comm2.Parameters.Add("@TopicId", System.Data.SqlDbType.Int, 10, "TopicId");
comm2.Parameters["@TopicId"].Value = e.Row.Cells[0].Text;
string count1 = (comm2.ExecuteScalar().ToString());
e.Row.Cells[4].Text = count1;

//for command3 cmd2
comm3.Parameters.Add("@TopicId", System.Data.SqlDbType.Int, 10, "TopicId");
comm3.Parameters["@TopicId"].Value = e.Row.Cells[0].Text;
if (comm3.ExecuteScalar() != null)
{
    count2 = (comm3.ExecuteScalar().ToString());
}
conn.close();

/


Accessing and checking values of dynamic controls ASP.NET


I have a scenario. following is the code:

Home.aspx

protected void Button1_Click(object sender, EventArgs e)
{
    try
        {
            if (!String.IsNullOrEmpty(txtbox_query.Text.Trim()))
                {
                    if (isTrue)
                        {
                            // To do statements
                        }
                        else
                        {
                            List<RequestAndResponse.Parameter> parameters = request.getParameter(txtbox_query.Text.Trim(), sourcePath, parameterValue);
                            Session["Data"] = parameters;
                            Response.Redirect("Result.aspx",false);
                        }

                    }

    }
        catch (Exception error)
        {
                Response.Write(error.Message);
        }
}

Result.aspx

protected void Page_Load(object sender, EventArgs e)
{
    parameters = (List<RequestAndResponse.Parameter>)Session["Data"];
        ContentPlaceHolder content = (ContentPlaceHolder)this.Form.FindControl("MainContent");
        for (int j = 1; j <= _arrViewState; j++)
        {
            string _id = j.ToString();
                TextBox txtfname = new TextBox();
                txtfname.ID = "TextBox_" + _id + "_";
                txtfname.Width = 160;
                txtfname.Text = parameters[(j - 1)].Value.ToUpper();
                txtfname.Attributes.Add("style", "color:#015D84;font-weight:bold;font-size:12px;padding:10px;");
                txtfname.EnableViewState = true;
                content.Controls.Add(txtfname);
                content.Controls.Add(new LiteralControl("<br/>"));
        }
        Button btnSubmit = new Button();
        btnSubmit.ID = "btnSubmit";
        btnSubmit.Text = "Submit";
        btnSubmit.Click += new System.EventHandler(btnSubmit_click);
        btnSubmit.Enabled = false;
        content.Controls.Add(btnSubmit);
}

protected void btnSubmit_click(object sender, EventArgs e)
{
    // How to find the dynamically created textbox
}

Now How to find the dynamically created controls I know the basic like:

Form.FindControl("TextBox ID");

But here i dont know the textbox id and also i even dont know how many textbox will be their as it totally depends on user input i.e. from 2 TO N textboxes What i want is on bttn_Click i will fetch the text from all the textboxes How will i achieve this. Also i want to check if all Textbox is empty or not on bttn_Click


Show/Hide Single Row in ASP.NET Repeater


I'm having trouble showing just a single row inside a repeater. I have all of them expanding correctly, but my efforts to show just that row have not worked out well.

 <asp:Repeater ID="rptPlayers" runat="server" OnItemDataBound="DataBound_ItemDataBoundEvent">
            <HeaderTemplate>
                <thead>
                    <tr>

                        <th>Name</th>

                        <th>Profile Approved?</th>
                        <th>Playing in <%: DateTime.Now.Year %>?</th>
                        <th>Roommate</th>
                        <th>Manage</th>
                    </tr>
                </thead>
            </HeaderTemplate>
            <ItemTemplate>
                <tbody>
                    <tr>
                        <td><a href="#" class="show_hide"><%# Eval("FirstName") %>&nbsp;<%# Eval("LastName") %></a></td>
                        <td style="display: none"><%# Eval("PlayerEmail") %></td>
                        <td>
                            <asp:CheckBox ID="chkApproved" runat="server" Checked='<%# Eval("ProfileApproved") %>' /></td>
                        <td>

                            <asp:CheckBox ID="chkPlayingCurrentYear" runat="server" Checked='<%# Eval("PlayingCurrentYear") %>' /></td>
                        <td>

                            <asp:DropDownList ID="ddlRoommate" runat="server" AppendDataBoundItems="True"></asp:DropDownList>&nbsp;
                            <asp:LinkButton ID="lnkAssign" runat="server" OnClick="AssignPlayer"></asp:LinkButton></td>
                        <td>
                            <asp:PlaceHolder ID="AdminActions" runat="server"></asp:PlaceHolder>
                            <p class="text-danger">
                                <asp:LinkButton ID="lnkApproveProfile" runat="server" OnClick="ApprovePlayer"></asp:LinkButton>
                                <asp:LinkButton ID="lnkConfirm" runat="server" OnClick="ConfirmPlayer"></asp:LinkButton>
                            </p>
                        </td>
                        <td style="display: none">
                            <asp:Literal ID="ltUserId" runat="server" Text='<%# Eval("PlayerId") %>'></asp:Literal></td>
                    </tr>
                    <tr>
                        <td colspan="6">
                            <div class="slidingDiv">
                                Fill this space with really interesting content. <a href="#" class="show_hide">hide</a>
                            </div>
                        </td>
                    </tr>
                </tbody>
            </ItemTemplate>
        </asp:Repeater>

This is my current jQuery, what am I missing to just toggle a single row?

 <script type="text/javascript">
    $(document).ready(function () {
        $("div.slidingDiv").hide();
         $(".show_hide").show();
        $('.show_hide').click(function () {
            $(".slidingDiv").slideToggle();
           // $(this).next('div.slidingDiv').eq(0).slideToggle(800);


        });
    });
</script>


Run JavaScript from C# ASP.NET


I'm trying to run a javascript function from the code behind in C#. I looked at many resourses on internet but so far no luck. This does not even work with a very simple sample code that I have:

Code behind:

  protected void Button2_Click(object sender, EventArgs e)
  {
       ScriptManager.RegisterStartupScript(this,GetType(),"a","a();", true);
  }

In my aspx file:

 <script type="text/javascript">
         function a()
         {
             var i = 0;

         }
  </script>

When I run this I get :

0x800a1391 - JavaScript runtime error: 'a' is undefined

Note :

Also tried :

  • ScriptManager.RegisterStartupScript(this,GetType(),"a","a()", true);
  • ScriptManager.RegisterStartupScript(this,GetType(),"a","a", true);

Still getting the same error.


tag refreshes my asp.net page


I have an tag within my listview to direct the user to the profile page

<a class="btn btn-sm btn-default" href="profile.aspx?ID=<%# Eval("ownerID") %>"></a>

The profile page works as I can load it myself. However when I hover over the tag it shows the the correct link that it'll be directed to, but when I click on it, it just refreshes the current page, I've used the tag the same way in different pages and it works but for some reason it does not work here.

What could be the reason why?


Azure SQL Database Clearing or Reseting?


I have created a basic .NET C# web application with role, user and group authentication. The code is almost entirely pulled from this tutorial here:

http://ift.tt/1IWmWFk

This code appears to be working by many people in the online community, however something is going wrong and I'm trying to figure out what that is.

I have run through the code several times and can't seem to find an error. I am storing the connection to my Azure SQL Database in the Web.config file in the app, and it seems to be working. I am able to create, edit and delete users, roles and groups and see those changes in the database, but after an hour when I revisit the app it is like the SQL Database has restored itself to a previous version and reset, or dumped all my data. Everything is gone.

Has anyone else ran into a similar issue with the free Azure account?


need to prepare email with body and body will contain graph


I have a asp.net MVC 3 web application, where in some page I am showing a bar chart.

Now user is asking a "mailto" kind of link in that page and on clicking of that link, email client should open, where TO, Subject & Body will fill automatically and the bar chart should appear in body.

I know there is limitation of "mailto", we can prepare body with simple text like below, but is there any workaround to put graph within email body?

<A HREF="mailto:help@webcodehelpers.com?Subject=Help&Body=Hello%20%22Name%22%0A%0AWe%20are%20very%20happy%20for%20visiting%20our%20website%20webcodehelpers.com%20portal%2C%20which%20is%20providing%20useful%20information%20%2C%20code%20snippets%20and%20live%20examples.%0A%0AWe%20also%20providing%20Interview%20tip%20to%20all%20the%20freshers%20in%20web%20development%20and%20experienced%20people%20also%0A%0A%0AThanks%2C%0AWebCodeHelpers.com%20Team">Check Mail</A>


OnClick not firing in UserControl when button is clicked


I have a master page. In the master page I have a UserControl for the footer. In the footer I have a button that is not firing OnClick. During debugging I see the function being called by OnClick, btnSignup_Click, is not getting hit. I can't seem to figure out where the mistake in my code is.

master.master

<%@ Master Language="C#" AutoEventWireup="true" Inherits="master" Codebehind="master.master.cs" %>
<%@ Register TagPrefix="xyz" TagName="Footer" Src="~/controls/footer.ascx" %>


<xyz:Footer ID="Footer" runat="server" />

footer.ascx

<%@ Control Language="C#" AutoEventWireup="true" Inherits="footer" Codebehind="footer.ascx.cs"  %>

<div>
     <asp:TextBox ID="fName" runat="server"></asp:TextBox>
     <asp:RequiredFieldValidator ID="RequiredFieldValidatorfName"  ValidationGroup="validationSignup" Display="Static" ControlToValidate="fName" ErrorMessage="First Name required" runat="server"></asp:RequiredFieldValidator>
</div>

<div class="button">
    <asp:Button ID="btnSignup"  CommandName="Button" runat="server" ValidationGroup="validationSignup" Text="Signup"  HeaderText="Please fill in all required fields before continuing." OnClick="btnSignup_Click"/>
</div>

<div class="validationSummary">                 
    <asp:ValidationSummary ID="ValidationSummary"   ValidationGroup="validationSignup" runat="server"></asp:ValidationSummary>
</div>

footer.ascx.cs

public partial class templates_site_footer : BaseUserControl
{       
    protected void Page_Load(object sender, EventArgs e)
    {
        btnSignup.Click += new EventHandler(btnSignup_Click);
    }
    protected void btnSignup_Click(object sender, EventArgs e)
    {       
        if (!Page.IsValid)
            return;

        // code to execute after button is clicked
    }
}


Add a event on cshtml page load


How can i do It? The event is used to popolate the form element calling a ext.net direct method placed in the controller. Please help me is very urgent. Thanks in advance. Simone


C# MVC5 @Html.EnumDropDownListFor loses selection on "postback"


MVC5 EF6

I have a Product. A product can have multiple Titles, A title has a Type which is an Enum.

I am working on the Create View for a Product - The Model is the Product

View:

            @for (int x = 0; x < Model.ProdTitles.Count; x++)
            {                    
                <tr>
                    <td>
                        @Html.TextBoxFor(model => model.ProdTitles.ToArray()[x].Title, new { @class = "form-control" })
                        @Html.ValidationMessageFor(model => model.ProdTitles.ToArray()[x].Title, "", new { @class = "text-danger" })
                    </td>
                    <td>
                        @Html.EnumDropDownListFor(model => model.ProdTitles.ToArray()[x].TitleTypeID, new { @class = "form-control" })
                    </td>
                    <td>
                        @Html.EnumDropDownListFor(model => model.ProdTitles.ToArray()[x].CultureID, new { @class = "form-control" })
                    </td>
                </tr>
            }

In the Controller - when I create a product to return to the view, I create one title for each title type and add it to the product. The view displays everything as I expect.

Working as required

When I hit the Create button, the product and the titles are returned to the controller as expected and I validate the titles (different validation depending on the type). I add any errors to the ModelState and therefore, ModelState.IsValid is false.

I return back to the View return View(product); Debugging this product, all the titles are in the product and they all still have their correct types but the View now displays the first Enum in the list, for all titles and not the one that is actually in the model!

Showing first enum for all titles

If I change the EnumDropDown to a text box, the correct type is displayed, so the model is definitely correct:

proves model has the correct type

I'm not sure why this is happening and I hope someone can suggest a fix? Is it a bug in the C:\Users\Rick\Desktop\C.png? or am I doing something wrong?


Error asp.net webformapplication in line string price = sdr.GetInt32("Mobile_price").ToString();


Error 1 The best overloaded method match for 'System.Data.Common.DbDataReader.GetInt32(int)' has some invalid arguments

Error 2 Argument1 : cannot convert from 'string' to 'int'

string price = sdr.GetInt32("Mobile_price").ToString();


.Net MVC 4 CAS Authentication


I need to authenticate User from a central CAS. The assumption are these:

  1. The UserId for authentication is in a Request Header
  2. The roles for authorization are given by a web service.
  3. The application must cache the authorization phase.

I've tried this:

In the Global.asax:

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
    {
        const string SiteMinderHeaderToken = "SM_USER";
        if (HttpContext.Current.User == null || !HttpContext.Current.User.Identity.IsAuthenticated)
        {

            var userSSO = HttpContext.Current.Request.Headers[SiteMinderHeaderToken];
            GenericIdentity webIdentity = new GenericIdentity(userSSO, "SiteMinder");

            string[] roles = { "ROLE1", "ROLE2" };
            GenericPrincipal principal = new GenericPrincipal(webIdentity, roles);
            HttpContext.Current.User = principal;



            // System.Web.Security.FormsAuthentication.SetAuthCookie(userSSO, true);

        }
    }

In the Web.config

<authentication mode="None"   />
<authorization>
  <deny users="?" />
</authorization>

The problem is that for every request, the HttpContext.Current.User is always null, and every time all the authentication and authorization phase are done.

If I uncomment

System.Web.Security.FormsAuthentication.SetAuthCookie(userSSO, true);

All is fine, after the first request the User is authenticated.

My questions are:

  1. Is it correct to call System.Web.Security.FormsAuthentication.SetAuthCookie even if there isn't FormAuthentication?
  2. Is there a way to do it better?
  3. Are there some security issues doing this way?

Thanks


Accessing database from android app using ASP.net


I'm using this tutorial to establish a connection between my android app to MS database 1.http://ift.tt/1nLn2ZH

2.http://ift.tt/13uVEal

I downloaded everything, did basically everything it says.. Now, everything works till I press Register button in the registration activity layout, nothing happens actually, it shows no errors nothing.. but it directs to next activity which means that it is ok.. but when i check the database nothing is added!

I used both emulators: the android studio emulator and genymotion.. and I checked the url strings for both emulators and they work fine in their broswers

How can I track the program when it goes out from the android studio so I can know where is the error?

Register.java

package hamadk.car_care;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.support.v4.app.NavUtils;
import android.annotation.TargetApi;
import android.os.Build;

public class Register extends Activity {

    EditText regName, regPhone, regPassword, regEmail;
    Button btnCreateUser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        // Show the Up button in the action bar.
//        setupActionBar();

        regName =(EditText) findViewById(R.id.reg_name);
        regPhone = (EditText) findViewById(R.id.reg_phone);
        regPassword = (EditText) findViewById(R.id.reg_password);
        regEmail = (EditText) findViewById(R.id.reg_email);
        btnCreateUser=(Button) findViewById(R.id.btn_createuser);

        btnCreateUser.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                String name, password, email;
                int phonenumber;

                name = regName.getText().toString();
                phonenumber = Integer.parseInt(regPhone.getText().toString()) ;
                password = regPassword.getText().toString();
                email = regEmail.getText().toString();

                UserDetailsTable userDetail = new UserDetailsTable(name,
                        phonenumber, password, email);

                new AsyncCreateUser().execute(userDetail);

            }
        });

    }

    protected class AsyncCreateUser extends
            AsyncTask<UserDetailsTable, Void, Void> {

        @Override
        protected Void doInBackground(UserDetailsTable... params) {

            RestAPI api = new RestAPI();
            try {

                api.CreateNewAccount(params[0].getName(),
                        params[0].getPhoneNumber(), params[0].getPassword(),
                        params[0].getEmail());


            } catch (Exception e) {
                // TODO Auto-generated catch block
                Log.d("AsyncCreateUser", e.getMessage());

            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {

            Intent i = new Intent(Register.this, MainActivity.class);
            startActivity(i);
        }

    }

    /**
     * Set up the {@link android.app.ActionBar}, if the API is available.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void setupActionBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            getActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_register, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                // This ID represents the Home or Up button. In the case of this
                // activity, the Up button is shown. Use NavUtils to allow users
                // to navigate up one level in the application structure. For
                // more details, see the Navigation pattern on Android Design:
                //
                // http://ift.tt/1c7OZSR
                //
                NavUtils.navigateUpFromSameTask(this);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

}

RestAPI.java

/* JSON API for android appliation */
package hamadk.car_care;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
import org.json.JSONArray;

public class RestAPI {
    private final String urlString = "http://ift.tt/1IVX1xz";

    private static String convertStreamToUTF8String(InputStream stream) throws IOException {
        String result = "";
        StringBuilder sb = new StringBuilder();
        try {
            InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
            char[] buffer = new char[4096];
            int readedChars = 0;
            while (readedChars != -1) {
                readedChars = reader.read(buffer);
                if (readedChars > 0)
                    sb.append(buffer, 0, readedChars);
            }
            result = sb.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }


    private String load(String contents) throws IOException {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setRequestMethod("POST");
        conn.setConnectTimeout(60000);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        OutputStreamWriter w = new OutputStreamWriter(conn.getOutputStream());
        w.write(contents);
        w.flush();
        InputStream istream = conn.getInputStream();
        String result = convertStreamToUTF8String(istream);
        return result;
    }


    private Object mapObject(Object o) {
        Object finalValue = null;
        if (o.getClass() == String.class) {
            finalValue = o;
        }
        else if (Number.class.isInstance(o)) {
            finalValue = String.valueOf(o);
        } else if (Date.class.isInstance(o)) {
            SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss", new Locale("en", "USA"));
            finalValue = sdf.format((Date)o);
        }
        else if (Collection.class.isInstance(o)) {
            Collection<?> col = (Collection<?>) o;
            JSONArray jarray = new JSONArray();
            for (Object item : col) {
                jarray.put(mapObject(item));
            }
            finalValue = jarray;
        } else {
            Map<String, Object> map = new HashMap<String, Object>();
            Method[] methods = o.getClass().getMethods();
            for (Method method : methods) {
                if (method.getDeclaringClass() == o.getClass()
                        && method.getModifiers() == Modifier.PUBLIC
                        && method.getName().startsWith("get")) {
                    String key = method.getName().substring(3);
                    try {
                        Object obj = method.invoke(o, null);
                        Object value = mapObject(obj);
                        map.put(key, value);
                        finalValue = new JSONObject(map);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

        }
        return finalValue;
    }

    public JSONObject CreateNewAccount(String Name,int phoneNumber,String password,String email) throws Exception {
        JSONObject result = null;
        JSONObject o = new JSONObject();
        JSONObject p = new JSONObject();
        o.put("interface","RestAPI");
        o.put("method", "CreateNewAccount");
        p.put("Name",mapObject(Name));
        p.put("phoneNumber",mapObject(phoneNumber));
        p.put("password",mapObject(password));
        p.put("email",mapObject(email));
        o.put("parameters", p);
        String s = o.toString();
        String r = load(s);
        result = new JSONObject(r);
        System.out.println("GOOD SO FAR, AFTER CREATE");
        return result;
    }

    public JSONObject UserAuthentication(String phoneNumber,String email) throws Exception {
        JSONObject result = null;
        JSONObject o = new JSONObject();
        JSONObject p = new JSONObject();
        o.put("interface","RestAPI");
        o.put("method", "UserAuthentication");
        p.put("phoneNumber",mapObject(phoneNumber));
        p.put("email",mapObject(email));
        o.put("parameters", p);
        String s = o.toString();
        String r = load(s);
        result = new JSONObject(r);
        return result;
    }

    public JSONObject CreateAppointment(String appointmentType,Date appointmentIssuedDate,Date appointmentDate,String licencePlate,String clientComment,String issuerName,String appointmentMethod,String lineName,Date reminderDate,int phoneNumber,String clientFirstName,String email,int vehicleModel,String vehicle_name,String clientLastName) throws Exception {
        JSONObject result = null;
        JSONObject o = new JSONObject();
        JSONObject p = new JSONObject();
        o.put("interface","RestAPI");
        o.put("method", "CreateAppointment");
        p.put("appointmentType",mapObject(appointmentType));
        p.put("appointmentIssuedDate",mapObject(appointmentIssuedDate));
        p.put("appointmentDate",mapObject(appointmentDate));
        p.put("licencePlate",mapObject(licencePlate));
        p.put("clientComment",mapObject(clientComment));
        p.put("issuerName",mapObject(issuerName));
        p.put("appointmentMethod",mapObject(appointmentMethod));
        p.put("lineName",mapObject(lineName));
        p.put("reminderDate",mapObject(reminderDate));
        p.put("phoneNumber",mapObject(phoneNumber));
        p.put("clientFirstName",mapObject(clientFirstName));
        p.put("email",mapObject(email));
        p.put("vehicleModel",mapObject(vehicleModel));
        p.put("vehicle_name",mapObject(vehicle_name));
        p.put("clientLastName",mapObject(clientLastName));
        o.put("parameters", p);
        String s = o.toString();
        String r = load(s);
        result = new JSONObject(r);
        return result;
    }

    public JSONObject deleteClient(int phone) throws Exception {
        JSONObject result = null;
        JSONObject o = new JSONObject();
        JSONObject p = new JSONObject();
        o.put("interface","RestAPI");
        o.put("method", "deleteClient");
        p.put("phone",mapObject(phone));
        o.put("parameters", p);
        String s = o.toString();
        String r = load(s);
        result = new JSONObject(r);
        return result;
    }

    public JSONObject checkAvailableLines(int service_type_ID,Date Appointment_Date) throws Exception {
        JSONObject result = null;
        JSONObject o = new JSONObject();
        JSONObject p = new JSONObject();
        o.put("interface","RestAPI");
        o.put("method", "checkAvailableLines");
        p.put("service_type_ID",mapObject(service_type_ID));
        p.put("Appointment_Date",mapObject(Appointment_Date));
        o.put("parameters", p);
        String s = o.toString();
        String r = load(s);
        result = new JSONObject(r);
        return result;
    }

}

UserDetailsTable.java

package hamadk.car_care;
public class UserDetailsTable {

String name, password, email;
int phonenumber;

public UserDetailsTable(String name, int phonenumber, String password,
                        String email) {
    super();
    this.name = name;
    this.phonenumber = phonenumber;
    this.password = password;
    this.email = email;
}

public UserDetailsTable() {
    super();
    this.name = null;
    this.phonenumber = 0;
    this.password = null;
    this.email = null;

}

public String getName() {
    return name;
}

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

public int getPhoneNumber() {
    return phonenumber;
}

public void setPhoneNumber(int phonenumber) {
    this.phonenumber = phonenumber;
}

public String getPassword() {
    return password;
}

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

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

}

ServiceAPI.cs

using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections;

namespace JSONWebAPI
{

    public class ServiceAPI : IServiceAPI
    {

        void main()
        {



        }

        SqlConnection dbConnection;

        public ServiceAPI()
        {
            dbConnection = DBConnect.getConnection();
        }

        public void CreateNewAccount(string Name, int phoneNumber, string password, string email)
        {
            if (dbConnection.State.ToString() == "Closed")
            {
                dbConnection.Open();
            }



            string query = "INSERT INTO Clients (client_firstName, client_phone_No, client_password, client_email_address) VALUES ('" + Name + "','" + phoneNumber + "','" + password + "','" + email + "');";

            SqlCommand command = new SqlCommand(query, dbConnection);
            command.ExecuteNonQuery();

            dbConnection.Close();
        }



        public bool UserAuthentication(string phoneNumber, string email)
        {
            bool auth = false;

            if (dbConnection.State.ToString() == "Closed")
            {
                dbConnection.Open();
            }

            string query = "SELECT client_ID FROM dbo.Clients WHERE client_phone_No='" + phoneNumber + "' AND client_email_address='" + email + "';";

            SqlCommand command = new SqlCommand(query, dbConnection);
            SqlDataReader reader = command.ExecuteReader();

            if (reader.HasRows)
            {
                auth = true;
            }

            reader.Close();
            dbConnection.Close();

            return auth;

        }


        public void CreateAppointment(string appointmentType, DateTime appointmentIssuedDate, DateTime appointmentDate, string licencePlate, string clientComment, String issuerName, String appointmentMethod, String lineName, DateTime reminderDate, int phoneNumber, String clientFirstName, String email, int vehicleModel, String vehicle_name, String clientLastName)
        {
            if (dbConnection.State.ToString() == "Closed")
            {
                dbConnection.Open();
            }



            string query = "INSERT INTO dbo.Appointment_Types (appointment_type_name) VALUES ('" + appointmentType + "'); INSERT INTO Appointments (appointment_issued_date, appointment_date, licence_plate, client_comment, issuer_name, appointment_method, line_name, reminder_date, mobile_No, client_firstName, email_address, vehicle_model, vehicle_name, client_lastName) VALUES ('" + appointmentIssuedDate + "','" + appointmentDate + "','" + licencePlate + "','" + clientComment + "','" + issuerName + "','" + appointmentMethod + "','" + lineName + "','" + reminderDate + "','" + phoneNumber + "','" + clientFirstName + "','" + email + "','" + vehicleModel + "','" + vehicle_name + "','" + clientLastName + "');";

            SqlCommand command = new SqlCommand(query, dbConnection);
            command.ExecuteNonQuery();

            dbConnection.Close();
        }


        public void deleteAppointment(int ID)
        {
            if (dbConnection.State.ToString() == "Closed")
            {
                dbConnection.Open();
            }



            string query = "DELETE FROM dbo.Appointments WHERE appointment_ID='" + ID + "' ; ";

            SqlCommand command = new SqlCommand(query, dbConnection);
            command.ExecuteNonQuery();

            dbConnection.Close();
        }

        public DataTable displayAppointment(int ID)
        {

            DataTable appointmentTable = new DataTable();
            appointmentTable.Columns.Add("Appointment Date", typeof(DateTime));
            /* appointmentTable.Columns.Add("Service Name", typeof(String)); this is from Appointment Types */
            appointmentTable.Columns.Add("Vehicle Name", typeof(String)); // this is from Appointments
            appointmentTable.Columns.Add("Maintenance Status", typeof(String));
            appointmentTable.Columns.Add("Engineer Comment", typeof(String));

            if (dbConnection.State.ToString() == "Closed")
            {
                dbConnection.Open();
            }


            string query = "SELECT appointment_date,vehicle_name,Maintenance_progress_status,engineer_comment FROM dbo.Appointments WHERE client_ID='" + ID + "'; ";

            SqlCommand command = new SqlCommand(query, dbConnection);
            SqlDataReader reader = command.ExecuteReader();

            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    appointmentTable.Rows.Add(reader["Appointment Date"], reader["Vehicle Name"], reader["Maintenance Status"], reader["Eningeer Comment"]);
                }
            }

            reader.Close();
            dbConnection.Close();

            return appointmentTable;
        }

        public DataTable displayUserProfile(int ID)
        {

            DataTable clientTable = new DataTable();
            clientTable.Columns.Add("First Name", typeof(String));
            clientTable.Columns.Add("Last Name", typeof(String));
            clientTable.Columns.Add("Phone Number", typeof(int));
            clientTable.Columns.Add("Email ", typeof(String));
            clientTable.Columns.Add("Points ", typeof(int));

            if (dbConnection.State.ToString() == "Closed")
            {
                dbConnection.Open();
            }


            string query = "SELECT client_firstName,client_lastName,client_phone_No,client_email_address,clientpoints FROM dbo.Clients WHERE client_ID='" + ID + "'; ";

            SqlCommand command = new SqlCommand(query, dbConnection);
            SqlDataReader reader = command.ExecuteReader();

            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    clientTable.Rows.Add(reader["First Name"], reader["Last Name"], reader["Phone Number"], reader["Email"], reader["Points"]);
                }
            }

            reader.Close();
            dbConnection.Close();

            return clientTable;
        }



        public void deleteClient(int phone)
        {
            if (dbConnection.State.ToString() == "Closed")
            {
                dbConnection.Open();
            }



            string query = "DELETE FROM dbo.Clients WHERE client_phone_No='" + phone + "' ; ";

            SqlCommand command = new SqlCommand(query, dbConnection);
            command.ExecuteNonQuery();

            dbConnection.Close();
        }

        public DataTable checkAvailableLines(int service_type_ID, DateTime Appointment_Date)
        {



            DataTable availableReservationTime = new DataTable(); 
            DataTable availableLinesTable = new DataTable();
            availableLinesTable.Columns.Add("Line Name", typeof(String));

            if (dbConnection.State.ToString() == "Closed")
            {
                dbConnection.Open();
            }


            string query = "SELECT line_name FROM dbo.Lines WHERE appointment_type_ID='" + service_type_ID + "'; ";

            SqlCommand command = new SqlCommand(query, dbConnection);
            SqlDataReader reader = command.ExecuteReader();
        if (reader.HasRows)
        {
            while (reader.Read())
            {
                availableLinesTable.Rows.Add(reader["Line Name"]);
            }
        }

        reader.Close();
        dbConnection.Close();

        availableReservationTime=checkAvailableTime(availableLinesTable);
        return availableReservationTime;
    }

    public DataTable checkAvailableTime(DataTable availableLinesTable)
    {

        DataTable availableLinesTable2 = availableLinesTable;
        DataTable availableReservationTime=new DataTable();

        availableLinesTable.Columns.Add("Reservation Time", typeof(DateTime));

        if (dbConnection.State.ToString() == "Closed")
        {
            dbConnection.Open();
        }

        Array  availableTimes = availableLinesTable2.Select();

        for (int i = 0; i <= availableTimes.Length;i++ )
        {
            string query = "SELECT reservation_time FROM dbo.VW_Connected_Reservations WHERE line_name='" + availableTimes.GetValue(i) + "'; ";

            SqlCommand command = new SqlCommand(query, dbConnection);
            SqlDataReader reader = command.ExecuteReader();

            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    availableReservationTime.Rows.Add(reader["Reservation Time"]);
                }
            } 

            reader.Close();
        }


        dbConnection.Close();

        return availableReservationTime;
    }


}

}

DBConnect.cs

using System.Configuration;
using System.Data.SqlClient;

namespace JSONWebAPI
{
    ///
    /// This class is used to connect to sql server database
    ///
    public class DBConnect
    {

        private static SqlConnection NewCon;
        private static string conStr = ConfigurationManager.ConnectionStrings["HondaDB"].ConnectionString;

        public static SqlConnection getConnection()
        {
            NewCon = new SqlConnection(conStr);
            return NewCon;

        }
        public DBConnect()
        {

        }

    }
}

Web.config

<!--
  For more information on how to configure your ASP.NET application, please visit
  http://ift.tt/1eW0XAj
  -->

<configuration> 
    <system.web>
      <compilation debug="true" targetFramework="4.5.1" />
      <httpRuntime targetFramework="4.5.1" />
    </system.web>

<connectionStrings>
  <add name="HondaDB" connectionString="Data Source=HAMAD; Initial Catalog=Honda_DB;Integrated Security=True " providerName="System.Data.SqlClient" />

</connectionStrings>
</configuration>


Set Dropdown List Selected Value with jQuery


I have created a dropdown list in an ASP.NET MVC view using AJAX:

Url="/Channel/GetChannels";
$.ajax({
    url:Url,
    dataType: 'json',
    data: '',
    success: function (data) {
        $("#ddlChannel").empty();
        $("#ddlChannel").append("<option value='0'>All</option>");
        $.each(data, function (index, optiondata) {
            $("#ddlChannel").append("<option value='" + optiondata.Id + "'>" + optiondata.Name + "</option>");
        });
    }
});
$("#ddlChannel option[value='1']").attr("selected", "selected");

This produces the following markup:

<select id="ddlChannel">
<option value="0">All</option>
<option value="1">New Homes</option>
<option value="2">Sales</option>
<option value="3">Lettings</option>
</select>

Would someone please tell me how I can select an option value using jQuery.

I have tried:

$("#ddlChannel option[value='1']").attr("selected", "selected");

which doesn't work.

Thanks.


Search gridview asp.net


I get the following error when I do a date range search in my asp.net program.

Conversion failed when converting date and/or time from character string

here is the code for the search . Please help. I also want to display only date and not date and time in my grid view.

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True"
        AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="SqlDataSource2">
        <Columns>
            <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True"
                SortExpression="ID" />
            <asp:BoundField DataField="Story_number" HeaderText="Story_number" SortExpression="Story_number" />
            <asp:BoundField DataField="Date" HeaderText="Date" SortExpression="Date" />
            <asp:BoundField DataField="Memory_card" HeaderText="Memory_card" SortExpression="Memory_card" />
            <asp:BoundField DataField="Story_Name" HeaderText="Story_Name" SortExpression="Story_Name" />
        </Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:IngestConnectionString %>"
        SelectCommand="SELECT ID, Story_number, Date, Memory_card, Story_Name FROM Library WHERE (Story_Name LIKE '%' + @Story_Name + '%') AND (Story_number LIKE '%' + @Story_number + '%')   AND (@startDate IS NULL OR Date >= @startdate) AND (@enddate IS NULL or Date <= @enddate)">
        <SelectParameters>
            <asp:ControlParameter ControlID="TextBox1" Name="Story_Name" PropertyName="Text"
                DefaultValue="%" />
            <asp:ControlParameter ControlID="TextBox2" DefaultValue="%" Name="Story_number" PropertyName="Text" />
            <asp:ControlParameter ControlID="TextBox3" DefaultValue="" Name="startdate" PropertyName="Text" />
            <asp:ControlParameter ControlID="TextBox4" Name="enddate" DefaultValue="" PropertyName="Text" />
 </asp:SqlDataSource>


Adding a new column with buttons in gridview


I have added a button for Print in my gridview table as follows

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
                    AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="ID" 
                    DataSourceID="SqlDataSource2" 
                    onselectedindexchanged="GridView1_SelectedIndexChanged" Width="522px">
                    <Columns>
                        <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" 
                            ReadOnly="True" SortExpression="ID" />
                        <asp:BoundField DataField="Story_number" HeaderText="Story_number" 
                            SortExpression="Story_number" />
                        <asp:BoundField DataField="Date" HeaderText="Date" SortExpression="Date" />
                        <asp:BoundField DataField="Memory_card" HeaderText="Memory_card" 
                            SortExpression="Memory_card" />
                        <asp:BoundField DataField="Story_Name" HeaderText="Story_Name" 
                            SortExpression="Story_Name" />
                        <asp:ButtonField ButtonType="Button" Text="print" />
                    </Columns>
                </asp:GridView>

Please help me with the c# code for this button. When the button is pressed I need it to redirect to a page (print.aspx) something like this. I have been trying the following code but it does not work . Please advise I need to create a new class etc . Thanks in advance for your help.

Session["id"] = GridView1.SelectedRow.Cells[0].Text;
Response.Redirect("Print.aspx");


Issues with creating unit tests - ASP C#


Hi all I'm trying to create a test class and I'm having 2 issues.

  1. It's taking forever to run

  2. When I debug the test class method I keep getting this error

Warning 25/04/2015 12:20:18 Warning: Test Run deployment issue: The assembly or module 'App_Code' directly or indirectly referenced by the test container 'c:\users\tunde\documents\visual studio 2010\projects\carfindertesting\bin\debug\carfindertesting.dll' was not found. TUNDS Error 25/04/2015 12:20:29 Test host process exited unexpectedly. TUNDS

I have no idea why this is happening could anyone offer any help on how I can get this issue fixed thanks.


How do I get the textbox value to the database within a repeater?


I have a repeater that I populate from a database:

using (SqlConnection conn = new SqlConnection(connString))
{
   SqlCommand cmd = new SqlCommand(@"SELECT CommunityName, CID, Budget FROM Donation WHERE Year = year(getdate()) ORDER BY CommunityName", conn);
   conn.Open();
   SqlDataAdapter adp = new SqlDataAdapter(cmd);
   DataSet myDataSet = new DataSet();
   adp.Fill(myDataSet);
   myRep.ItemDataBound += new RepeaterItemEventHandler(myRep_ItemDataBound);
   myRep.DataSource = myDataSet;
   myRep.DataBind();
}
void myRep_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
   var textbox = e.Item.FindControl("community");
   textbox.ClientIDMode = ClientIDMode.Static;
   textbox.ID = "community" + (e.Item.ItemIndex + 1);
 }

Repeater:

<asp:UpdatePanel ID="UpdatePanel" runat="server" UpdateMode="Always">
    <ContentTemplate>
       <asp:Repeater ID="myRep" runat="server">
          <ItemTemplate>
             <div class="form-group">
                <asp:Label ID='thisLbl' runat="server" Text='<%# Eval("CommunityName") %>' />
                <asp:TextBox runat="server" ID="community" Text='<%# Eval("Budget") %>' CssClass="form-control" />
             </div>
          </ItemTemplate>
       </asp:Repeater>
    </ContentTemplate>
</asp:UpdatePanel>

This creates 6 textboxes with labels and values, now my question is how do I detect which of these boxes belongs to the record it was initially pulled from in the database? I want to be able to modify the value in these boxes and hit a button to save them back to the database but I can't seem to wrap my head around getting them to the proper records.

Should I set the ID of the textbox to something I can parse through and match with the proper record? In the ItemDataBound?


log4net not logging to event viewer from IIS


I have a web service set up in my IIS, the appender that logs to a text file is working fine (the text file is in the same directory as where the web service is running from). The appender that writes to the Event Viewer isn't working, I'm currently connected to the web service as administrator so I should in theory be able to do this, what else should I check/see if I'm missing?

log4net.config:

<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date{ABSOLUTE} [%thread] %level %logger - %message%newlineExtra Info: %property{testProperty}%newline%exception"/>
  </layout>
  <filter type="log4net.Filter.LevelRangeFilter">
    <levelMin value="INFO"/>
    <levelMax value="FATAL"/>
  </filter>
</appender>

<appender name="EventLogAppender" type="log4net.Appender.EventLogAppender">
  <param name="ApplicationName" value="Lending Service" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message %newline %exception"  />
  </layout>
  <filter type="log4net.Filter.LevelRangeFilter">
    <levelMin value="INFO"/>
    <levelMax value="FATAL"/>
  </filter> 
</appender>

<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">

  <threshold value="DEBUG"/> 
  <file value="webLog.log"/>
  <appendToFile value="true"/>
  <rollingStyle value="Size"/>
  <maxSizeRollBackups value="5"/>
  <maximumFileSize value="10MB"/>
  <staticLogFileName value="true"/>

  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date [%thread] %level %logger - %message%newline%exception"/>
  </layout>

</appender>


<root>
  <appender-ref ref="RollingFileAppender"/>
  <appender-ref ref="EventLogAppender" />
</root>

<logger name="LendingService.Global_asax">
  <appender-ref ref="RollingFileAppender"/>
  <appender-ref ref="EventLogAppender" />
</logger>

<logger name="LendingService.LendingService">
  <appender-ref ref="RollingFileAppender"/>
  <appender-ref ref="EventLogAppender" />    
</logger>  

</log4net>
<startup>
  <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>


Store asp WebAPI bearer tokens in the database


I have a desperate need to store the bearer access_tokens in the database immediately they are produced before they are sent to the user...I am using an example from http://ift.tt/1gUyYFU to implement the authorization... How do I catch the token immediately it is created within the method "public override async Task GrantResourceOwnerCrede ntials ( OAuthGrantResourceOwne rCredentialsContext context )"

It's important to note that I implicitly understand the downfalls of doing things, but it's necessary


want to show the file uplded by User on admin,Files uplded directed to 'Files' foldr in proj. Only Admin be able to download or read the File (.Doc)


![Only Admin download or open file, snippet shows file saved in File directory of project][1 http://ift.tt/1QsTXyg]


Connect to SQL Server from ASP.NET MVC application


I am entirely new to ASP.NET MVC. I have one ASP.NET 2.0 Framework Web application with below architecture

  • Web Based Application 3 - Tier Architecture
  • Data Access Layer C#, ADO.NET
  • Database – SQL Server 2008 R2
  • Authentication - Forms

I am moving the application to an ASP.NET MVC 4 architecture; can anybody suggest the best practices to go with for data access layer, assume the connection string will be in web.config?

Code-first? Or data-first approach? What is the difference with the above approach and Entity Framework?

Also while adding a controller for a model, amongst the below template which I need to choose?

  1. Empty ASP.NET MVC controller
  2. ASP.NET MVC controller with read/write actions using Entity Framework
  3. ASP.NET MVC controller with empty read/write actions
  4. Empty API controller
  5. API controller with read/write actions using Entity Framework
  6. API controller with empty read/write actions

What is the difference between the above templates?


Browsing to home page generates 404 error


I deployed my ASP.NET application that works within VS Express for Web 2013 to a newly-created server (Windows Server 2008 R2, IIS 7.5). Browsing to the home page generates a 404 error. Detailed error information:

Module: IIS Web Core
Notification: MapRequestHandler
Handler: StaticFile
Error Code: 0x80070002
Requested URL: http://ift.tt/1DvyNq9
Physical Path: C:\example\Account\Login
Logon Method: Anonymous
Logon User: Anonymous

Of course, physical path C:\example\Account\Login does not exist; it is really c:\example\Account\Login.aspx.

My guess would be that the problem is that the handler is StaticFile, but how do I fix it?