vendredi 31 juillet 2015

An expression of non-boolean type specified in a context where a condition is expected, near 'AdmissionID'

Server Error in '/' Application.

An expression of non-boolean type specified in a context where a condition is expected, near 'AdmissionID'.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: An expression of non-boolean type specified in a context where a condition is expected, near 'AdmissionID'.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[SqlException (0x80131904): An expression of non-boolean type specified in a context where a condition is expected, near 'AdmissionID'.]
   System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +1767866
   System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +5352418
   System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +244
   System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +1691
   System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() +61
   System.Data.SqlClient.SqlDataReader.get_MetaData() +90
   System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +365
   System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds) +1406
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) +177
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +53
   System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +134
   System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +41
   System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior) +10
   System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +140
   System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +316
   System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, String srcTable) +86
   System.Web.UI.WebControls.SqlDataSourceView.ExecuteSelect(DataSourceSelectArguments arguments) +1481
   System.Web.UI.WebControls.ListControl.OnDataBinding(EventArgs e) +101
   System.Web.UI.WebControls.ListControl.PerformSelect() +34
   System.Web.UI.WebControls.BaseDataBoundControl.DataBind() +30
   System.Web.UI.WebControls.BaseDataBoundControl.EnsureDataBound() +105
   System.Web.UI.WebControls.BaseDataBoundControl.set_RequiresDataBinding(Boolean value) +9844021
   System.Web.UI.WebControls.DataBoundControl.OnDataSourceViewChanged(Object sender, EventArgs e) +15
   System.Web.UI.DataSourceView.OnDataSourceViewChanged(EventArgs e) +105
   System.Web.UI.WebControls.SqlDataSourceView.SelectParametersChangedEventHandler(Object o, EventArgs e) +31
   System.Web.UI.WebControls.ParameterCollection.OnParametersChanged(EventArgs e) +20
   System.Web.UI.WebControls.Parameter.UpdateValue(HttpContext context, Control control) +142
   System.Web.UI.WebControls.ParameterCollection.UpdateValues(HttpContext context, Control control) +101
   System.Web.UI.WebControls.ParameterCollection.GetValues(HttpContext context, Control control) +36
   System.Web.UI.WebControls.SqlDataSourceView.InitializeParameters(DbCommand command, ParameterCollection parameters, IDictionary exclusionList) +257
   System.Web.UI.WebControls.SqlDataSourceView.ExecuteSelect(DataSourceSelectArguments arguments) +589
   System.Web.UI.WebControls.ListControl.OnDataBinding(EventArgs e) +101
   System.Web.UI.WebControls.ListControl.PerformSelect() +34
   System.Web.UI.WebControls.BaseDataBoundControl.DataBind() +30
   System.Web.UI.WebControls.BaseDataBoundControl.EnsureDataBound() +105
   System.Web.UI.WebControls.ListControl.OnPreRender(EventArgs e) +23
   System.Web.UI.Control.PreRenderRecursiveInternal() +83
   System.Web.UI.Control.PreRenderRecursiveInternal() +155
   System.Web.UI.Control.PreRenderRecursiveInternal() +155
   System.Web.UI.Control.PreRenderRecursiveInternal() +155
   System.Web.UI.Control.PreRenderRecursiveInternal() +155
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +974

My SQL Command is like this >> SELECT * FROM [Bed] WHERE WardID = @WardID AND BedStatus = 'Available' AND BedNo NOT IN (SELECT BedNo FROM [AdmissionDetail], [Admission] WHERE ([AdmissionDate] <= @AdmissionDate AND [DischargeDate] >= @DischargeDate AND AdmissionStatus <> 'Discharged' AND [AdmissionDetail]AdmissionID = [Admission]AdmissionID))

I'm using Visual Studio 2013 and using asp:DropDownList and asp:SqlDataSource to do this. I have 4 table which is Admission, AdmissionDetail, Ward and Bed.

GridView with Template Column and Image Inside

I have a GridView with one template column which contains a user control (an Image and a Label). I use the code below to get list of images in a directory:

string[] filePaths = Directory.GetFiles(Server.MapPath("~/Resources/Pictures"),"*.jpg");
        GridView1.DataSource = filePaths;
        GridView1.DataBind();

It will create an extra column which contains the image's path. for example if we have 5 files in the folder, then we have 5 rows in our gridview. But in first column which is a template column with user control, you can see raw image and raw label. It means in every row we have a template column with raw controls and a column which contains image's path getting from code above. I need to access the user control's image and label control and update them in each row.

For example if in first row image's path is "~/pics/.jpg" I need to update the image control's imageurl to this path so we can see the image and then I need to update the label's text into another text.

How Can I do this and access to template column's controls in each row?

mvc rout and get string

im begginer in asp.net mvc

i write this rout code

    routes.MapRoute(
        name: "test",
        url: "test/{name}",
        defaults: new { controller = "Home", action = "test"}
    );

and this controller

public ActionResult test(string data)
{                   

    switch (data)
    {
        case "test1":
            return View("test1");
        case "test2":
            return View("test2");
        case "test3":
            return View("test3");
        default:
            return View("test1");
    }

}

and in my url http://localhost:3598/test/test1

but i get null data in parameter in controller

how i can get 'test1' in switch (data) ?

thank you for your help

annoying temporary files often while building project in Visual Studio 2012?

"hi, Many time, the following error occurs while running the asp.net project in Visual Studio 2012

[![> Error 24 The file name 'C:\Users\hr\AppData\Local\Temp\Temporary

ASP.NET Files\online invoice\7c64e6a9\cbf90bd2\qkrvpnfc.res' was already in the collection. Parameter name: fileName]1]1

Even though temporary files deleted, the above error occurring repeatedly.

Please help, thanks a lot"

RadAjaxManager OnRequestStart is not fired when press for the second time on a button?

RadAjaxManager OnRequestStart is not fired when press for the second time on a button.

1. Button post back working good. 2. No javascript error.

Code Here:

Rad code block

    <telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
        <script type="text/javascript">
            var currentLoadingPanel = null;
            var currentUpdatedControl = null;
            var btn1 = $find("<%= btnsave.ClientID%>");
            function requestStart(sender, args) {
                currentLoadingPanel = $find("<%= RadAjaxLoadingPanel1.ClientID%>");
                btn1 = $find("<%= btnsave.ClientID%>");
                if (args.get_eventTarget() == "<%= btnsave.UniqueID %>") {
                    currentUpdatedControl = "<%= importprocess.ClientID %>";
                    //show the loading panel over the updated control   
                    currentLoadingPanel.show(currentUpdatedControl);
                }
            }

            function responseEnd() {

                //hide the loading panel and clean up the global variables               
                if (currentLoadingPanel != null) {
                    currentLoadingPanel.hide(currentUpdatedControl);
                }
                currentUpdatedControl = null;
                currentLoadingPanel = null;

            }

        </script>
    </telerik:RadCodeBlock>
    <telerik:RadAjaxManager ID="RadAjaxManager1"  runat="server">
        <AjaxSettings>
            <telerik:AjaxSetting AjaxControlID="btnstart">
                <UpdatedControls>
                    <telerik:AjaxUpdatedControl ControlID="importprocess" />
                </UpdatedControls>
            </telerik:AjaxSetting>
              <telerik:AjaxSetting AjaxControlID="btnsave">
                <UpdatedControls>
                    <telerik:AjaxUpdatedControl ControlID="btnsave" ></telerik:AjaxUpdatedControl>
                </UpdatedControls>
            </telerik:AjaxSetting>
        </AjaxSettings>
         <ClientEvents OnRequestStart="requestStart" OnResponseEnd="responseEnd"></ClientEvents>
    </telerik:RadAjaxManager>

RadAjaxLoadingPanel

When I selecting the combobox items its deleting or refreshing the attachments the file

I developed the compose message from email,

I attaching the files then i have selecting the combo box item its deleting the attachment files.

Here my ASP Code:

<asp:UpdatePanel ID="updatepanel" runat="server">
                                            <ContentTemplate>
                                                <tr>
                                                    <td valign="top">
                                                        <asp:Label ID="lblfile_name" runat="server" CssClass="labels">Upload File</asp:Label>
                                                    </td>
                                                    <td>
                                                        <div style="overflow-y: scroll; z-index: auto; height: 60px;">
                                                            <asp:FileUpload ID="FileUpload1" runat="server" CssClass="multi" Visible="true" />
                                                        </div>
                                                    </td>
                                                </tr>
                                            </ContentTemplate>
                                        </asp:UpdatePanel>


                                           <tr>
                                            <td>
                                                <telerik:RadComboBox EmptyMessage="----- Select -----" ID="cboTemplate" runat="server" Skin="WebBlue" AutoPostBack="true">
                                                </telerik:RadComboBox>
                                            </td>

                                        </tr>

Here VB. NET CODE

   Private Sub cboTemplate_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboTemplate.SelectedIndexChanged
    If cboTemplate.SelectedValue = "--Select--" Then
        lblErrMsg.Text = objcmnfunctions.GetErrMsg("B2B_WAR_110")
        SetFocus(anc_err)
        Exit Sub
    End If
    objdbconn.OpenConn()
    msSQL = " Select mailtemplate_gid, template_name, template_content " & _
            " from crm_trn_tmailtemplates " & _
            " where mailtemplate_gid = '" & cboTemplate.SelectedValue & "'"
    objOdbcDataReader = objdbconn.GetDataReader(msSQL)
    If objOdbcDataReader.HasRows = True Then
        objOdbcDataReader.Read()
        radmailcontent.Content = objOdbcDataReader.Item("template_content").ToString
    End If
    objOdbcDataReader.Close()
    objdbconn.CloseConn()
End Sub

Error in Importing data from excel file to database using c#.net

Here is my code...

constr = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""", FilePath);

    Econ = new OleDbConnection(constr); ExcelConn(FilePath);
    Econ.Open();

    Query = string.Format("Select [Emp ID],[Emp Name],[Log Date],[LogTime],[Type] FROM [{0}]", "One Month Report$");
    OleDbCommand Ecom = new OleDbCommand(Query, Econ);

    DataSet ds = new DataSet();
    OleDbDataAdapter oda = new OleDbDataAdapter(Query, Econ);
    Econ.Close();
    oda.Fill(ds);
    DataTable Exceldt = ds.Tables[0];

    //creating object of SqlBulkCopy    
    SqlBulkCopy objbulk = new SqlBulkCopy(conn);
    //assigning Destination table name    
    objbulk.DestinationTableName = " Attendancetable";
    //Mapping Table column
    objbulk.ColumnMappings.Add("Emp ID", "Emp ID");
    objbulk.ColumnMappings.Add("Emp Name", "Emp Name");
    objbulk.ColumnMappings.Add("Log Date", "Log Date");
    objbulk.ColumnMappings.Add("LogTime", "LogTime");
    objbulk.ColumnMappings.Add("Type", "Type");
    //inserting Datatable Records to DataBase    
    conn.Open();
    objbulk.WriteToServer(Exceldt);
    conn.Close();

Using this code am getting "External table is not in expected formt" this error. opened excel sheet uploading is successfull but in closed excel sheet file uploading process showing this error. please anyone help me out.

how to call button's click event from click of linkbutton of another page without post back in c# ASP.NET

i have a LinkButton in masterpage and on click of LinkButton , i am redirecting to, say, Page1.aspx . On Page1.aspx , i have a button1. On click of that button1, i am opening new window, not affecting data of the Page1.aspx.

but when i click on LinkButton of masterpage, redirecting to Page1.aspx and from code behind,clicking button1 , Page1.aspx 's data gets changed.

how to prevent this. i am providing my code..

LinkButton on Masterpage :

<asp:LinkButton ID="lnkAppointMent" runat="server" OnClick="lnkAppointMent_Click"><span>Appointment Scheduler </span></asp:LinkButton>

click Event of LinkButton :

protected void lnkAppointMent_Click(object sender, EventArgs e)
        {
            Session["PhoneCenter"] = "Appointment";
            Response.Redirect("PhoneMessage.aspx");
        }

PageLoad of redirecting page(PhoneMessage.aspx) :

    protected void Page_Load(object sender, EventArgs e)
                {
                    fillCustomTypeMessages();            
                    if (!Page.IsPostBack)
                    {
                        .

    .

    .
                        else if (Session["PhoneCenter"].ToString() == "Appointment")
                        {
                            btnScheduleAppointments_Click(btnScheduleAppointments, null);
                        }

.

.

.

RaisPostBack method on PhoneMessage.aspx :

protected override void RaisePostBackEvent(IPostBackEventHandler source, string eventArgument)
        {
            try
            {
                base.RaisePostBackEvent(source, eventArgument);
            }
            catch (Exception ex)
            {


            }

.

.

Click event of button :

protected void btnScheduleAppointments_Click(object sender, EventArgs e)
        {
            if (!Permissions.checkPermissions(Session["employeeloggedin"].ToString(), "PHMSGVMD"))
            {
                ScriptManager.RegisterStartupScript(this, Page.GetType(), "OnLoad", "alert('You must have the Phone Messages: View and Modify permission to schedule appointments!')", true);
            }
            else
            {
                string script = String.Format("openNewWin('" + "phonescheduler.aspx" + "')");
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "openNewWin", script, true);
            }

        }

Script :

function openNewWin(url)
        {
            alert(url);
            var open_link = window.open('', '_blank');
            open_link.location = url;
        }

Any clarification needed. please comment..

I want to create a custom function in jquery with few controls as parameters. How can I achieve this?

Have a checkbox and want to enable disable many ddl according to its onchecked >functionality. I have atleast 14 checkboxes I need to accomplish this in.. Is >it possible to do this using jquery?


enter code here

");" Checked="false" />

enter code here $(function enablecheck(chk,ddl) { $('[id$=chk]').on('click', function () { if ($(this).is(":checked")) {

               ddl.prop("disabled", false);

            } else {
                ddl.prop("disabled", true);

            }
        })
    });

user account specific connectionstrings

I am a novice in C# MVC and I have a MVC5 project, where each specific user will be connected to a specific mssql db. So is it possible to set a user-specific connectionstrings in the web.config. My second question is, as the number of users will grow, will this kind of set up (one project with many user-specific connection strings) will affect the speed?

how do i get purchased items to a gridview in a shopping cart?

Hey I recently created a shopping cart but I'm having problems sorting the purchased items into a gridview. this is my cart class:

Public Class Cart
    Private dt As DataTable = New DataTable()

    Public Sub New()
        dt.Columns.Add(New DataColumn("Product ID"))
        dt.Columns.Add(New DataColumn("Quantity"))
        dt.PrimaryKey = New DataColumn() {dt.Columns("Product ID")}
    End Sub

    Public Sub AddToCart(ByVal prd_id As Integer, ByVal quantity As Integer)
        Dim dr As DataRow = dt.NewRow()
        dr("Product ID") = prd_id
        dr("Quantity") = quantity
        dt.Rows.Add(dr)
    End Sub

    Public Sub RemoveFromCart(ByVal prd_id As Integer)
        Dim dr As DataRow = dt.Rows.Find(prd_id)
        dt.Rows.Remove(dr)
    End Sub

    Public Function GetCart() As DataTable
        Return dt
    End Function
End Class

this is the button function:

If Session("Customer_ID") <> Nothing Then
Dim userCart As Cart = CType(Session("shoppingCart"), Cart)
Dim qty As Integer = txtqty.text
Dim pid As Integer = lblid.text
userCart.AddToCart(pID, qty)
Else 
Response.Redirect("User_Login.aspx")
End If

when I try to run the code I get an error saying that ("Object reference not set to an instance of an object.") please help I've completely ran out of ideas. how can i fix this?

IIS 8.5 Web.config for named SQL instance on alternate port

I recently upgraded to Windows Server 2012 from 2003. It was a big IIS jump from 6 to 8.5. I cannot seem to get a named SQL instance on an alternate port to work in my ASP.net 4.0 website. The connection string I am using is as follows:

<add name="MyConn" connectionString="Server=192.168.12.5\stage,7839;Database=mydb;uid=myun;pwd=mypw;" />

When the website tries to load in the browser, I get the following error:

[HttpException (0x80004005): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 0 - No connection could be made because the target machine actively refused it.)]

We've checked firewall settings to no avail. Is the syntax correct in the above example? I've done numerous searches and found examples of people using

192.168.12.5:7839\stage

or

192.168.12.5\stage;port=7839;

but both of those give syntax errors.

I need some confirmation on the correct syntax for the Web.config file. Any help is greatly appreciated, thanks!

displaying data in a rdlc report using a method

My project uses a repository pattern so I have already written a method in my business logic layer that gets the information I need from the database to display an invoice for a customer. Can I use this method to display data in the report I created? If so, how?

All of the examples I've seen query the database directly.

Detailed documentation about mapping a web templete inside Orchard CMS

I found a web template on the net link and I want to allow end-users to edit the website using CMS. I found Orchad CMS, which is based on ASP.Net MVC. But the problem I'm facing is that I didn't find the full documentation on how I can map a web template similar to the one I provide to be managed inside a CMS such as Orchard so that end-users (non-technical users) can add new images, change the home page message, add new projects, etc.

How can I execute some Javascript after all ASP.NET startup scripts have been executed?

I have an ASP.NET page with a variety of client-side controls being initialized via ClientScriptManager.RegisterStartupScript. I have another script that I need to ensure runs only after all of the registered startup scripts have executed, without having control over the order they're registered in.

Is there any way I can make my script execute only after the start up scripts have been run?

FBA Providers, .NET Roles, .NET Users, missing in IIS if App Pool is in v2.0 version

I am migrating a WSS 3.0 database to a new SharePoint 2010 farm. It is a FBA Web Application and when I go to configure the Providers, .NET Roles and Users are missing. If I change the Web Application app pool to v4.0, this options appear. If it stays in v2.0, the options are gone. It need to stay in v2.0 since this is SharePoint related.

I am doing this operation in a Windows Server 2012, SQL Server 2014 and IIS 6.2

What am I missing here?

MVC : PHP Laravel Vs Asp.NET

I am starting to build an E learning platform, Application will be expected to cater whole amount of user , there would be some automated jobs, and the vast range of learning material to be stored on server. moreover i will also be dealing with APIs & third party Library.

I am a bit confuse in selection of framework, to build, with having two different Options i.e. PHP Laravel & ASP.NET MVC. I also had research on internet regarding the pros and cons of Both but the major Criteria are :

  • Performance
  • License. (Open Source or PAID)
  • flexibility (easily maintainable)
  • -

Would Laravel make a better choice given the nature of our workflow in the circumstances?

Thanks in Advance

Getting AdWords customerId without a refresh token

I'm working on a Web Application that allows user to connect AdWords account. 1) So once user connected their AW account I am getting token from AW API that includes an access token and a refresh token. So far so good, it's just a typical OAuth2 process.

2) Next time another user connects same AW account, AW would not provide me with a refresh token, assuming I have it stored somewhere, which is expected.

So here is the problem, there doesn't seem to be a way to get user information without the refresh token, meaning I can't identify the user to retrieve the refresh token.

I'm using .NET library (Google.Apis.Analytics.v3) and it doesn't allow me to request customer information without providing the refresh token...

Here is the sample code:

var tokenResponse = await adWordsService.ExchangeCodeForTokenAsync(code, redirectUri);
var adWordsUser = adWordsService.GetAdWordsUser();
var customerService = (CustomerService)adWordsUser.GetService(AdWordsService.v201502.CustomerService);
var customer = customerService.get();

adWordsService is just a wrapper around the API. so when I execute this line var customer = customerService.get() I get a following error:

ArgumentNullException: Value cannot be null.

Parameter name: AdWords API requires a developer token. If you don't have one, you can refer to the instructions at http://ift.tt/RTUfQb to get one.

Google.Api.Ads.AdWords.Lib.AdWordsSoapClient.InitForCall(String methodName, Object[] parameters)

Developer token is there and so are all the client IDs.

If I add this line adWordsUser.Config.AuthToken = tokenResponse.AccessToken; before making the call, it complains about the refresh token.

ArgumentNullException: Value cannot be null.

Parameter name: Looks like your application is not configured to use OAuth2 properly. Required OAuth2 parameter RefreshToken is missing. You may run Common\Utils\OAuth2TokenGenerator.cs to generate a default OAuth2 configuration.

Google.Api.Ads.Common.Lib.OAuth2ProviderBase.ValidateOAuth2Parameter(String propertyName, String propertyValue)

So the question is, how does one acquire user information (in this case customerId, according to this article http://ift.tt/1Ie2Uou) during authentication for the purpose of storing the refresh token?

How to restrict external javascript load to one time. Sitecore implementation

I have a view layout (main.cshtml) where I am calling an external javascript file. I have renderings (another cshtml files) which are included as placeholders to this layout(main.cshtml). example: two pages: 1) http://localhost/home/ has two renderings for Body placeholder 2)http://localhost/about/ has two renderings for Body placeholder

both home and about pages uses same main.cshtml, I don't want to load externalJS.js every time I navigate from home to about or vice versa. i.e;the externalJS.js should load once for entire application. Can I achieve it?

    <!DOCTYPE html>
<html>
<head>
    <title>Main</title>
</head>
<body>
    <div data-role="page" class="pageWrapper">
        <header data-role="header" class="header">
            @Html.Sitecore().Placeholder("Header")
        </header>
            <div class="wrapper" data-role="main">
            @Html.Sitecore().Placeholder("Body")
        </div>
        <div data-role="footer" role="contentinfo" class="ui-footer ui-bar-inherit">
            @Html.Sitecore().Placeholder("Footer")
        </div>
    </div>
  <script src="../../js/externalJS.js"></script>
 </body>
</html>

How to transfer Session text to Microsoft Access Database

I am using a program from class to make an application that takes a user's input from text boxes and drop-down lists, stores the session, and redirects the user to a verification page that shows that the info was saved or NOT saved.

I put it all together and, for the life of me, can't wrap my head around why I can't get this program to store the info into the database. Here is some of the code:

A copy of the application can be downloaded here:Program Files

// Code that saves the session information and transfers it to the frmPersonnelVerified.aspx
Session["txtInvoice"] = txtInvoice.Text;
Session["DropDownList1"] = DropDownList1.Text;
Session["DropDownList3"] = DropDownList3.Text;
Session["txtPrice"] = txtPrice.Text;
Session["txtYear"] = txtYear.Text;
Session["DropDownList4"] = DropDownList4.Text;
Session["txtModel"] = txtModel.Text;
Session["txtVin"] = txtVin.Text;
Session["txtLastName"] = txtLastName.Text;
Session["DropDownList2"] = DropDownList2.Text;
Session["DropDownList5"] = DropDownList5.Text;
Session["txtSystemNum"] = txtSystemNum.Text;
Session["DropDownList6"] = DropDownList6.Text;
Session["DropDownList8"] = DropDownList8.Text;
Session["txtPayout"] = txtPayout.Text;

Response.Redirect("frmPersonnelVerified.aspx");

From the redirect page:

// Output displayed from Invoice form
txtVerifiedInfo.Text = "ALSCO Invoice: " + (string)Session["txtInvoice"];
txtVerifiedInfo.Text += "\nType: " + (string)Session["DropDownList1"];
txtVerifiedInfo.Text += "\nVendor: " + (string)Session["DropDownList3"];
txtVerifiedInfo.Text += "\nPrice: " + (string)Session["txtPrice"];
txtVerifiedInfo.Text += "\nYear: " + (string)Session["txtYear"];
txtVerifiedInfo.Text += "\nMake: " + (string)Session["DropDownList4"];
txtVerifiedInfo.Text += "\nModel: " + (string)Session["txtModel"];
txtVerifiedInfo.Text += "\nVIN: " + (string)Session["txtVin"];
txtVerifiedInfo.Text += "\nDebtor Last Name: " + (string)Session["txtLastName"];
txtVerifiedInfo.Text += "\nPayment Status: " + (string)Session["DropDownList2"];
txtVerifiedInfo.Text += "\nSystem: " + (string)Session["DropDownList5"];
txtVerifiedInfo.Text += "\nSystem Invoice #: " + (string)Session["txtSystemNum"];
txtVerifiedInfo.Text += "\nSales Rep: " + (string)Session["DropDownList6"];
txtVerifiedInfo.Text += "\nRepo Agent: " + (string)Session["DropDownList8"];
txtVerifiedInfo.Text += "\nEmployee Pay Out: " + (string)Session["txtPayout"];

// Verifies the information from the DB and strings a save line if all is good
if (clsDataLayer.SavePersonnel(Server.MapPath("PayrollSystem_DB.mdb"),
     Session["txtInvoice"].ToString(),
     Session["DropDownList1"].ToString(),
     Session["DropDownList3"].ToString(),
     Session["txtPrice"].ToString(),
     Session["txtYear"].ToString(),
     Session["DropDownList4"].ToString(),
     Session["txtModel"].ToString(),
     Session["txtVin"].ToString(),
     Session["txtLastName"].ToString(),
     Session["DropDownList2"].ToString(),
     Session["DropDownList5"].ToString(),
     Session["txtSystemNum"].ToString(),
     Session["DropDownList6"].ToString(),
     Session["DropDownList8"].ToString(),
     Session["txtPayout"].ToString()))
{
     txtVerifiedInfo.Text = txtVerifiedInfo.Text +
         "\n\nThe information was successfully saved!";
}
else
{
     txtVerifiedInfo.Text = txtVerifiedInfo.Text +
         "\n\nThe information was NOT saved.";
}

Heres the DB code:

// This function saves the  data
    public static bool SavePersonnel(string Database, string AlscoInvoice, string Type,
                                     string Vendor, string Price, 
                                     string Year, string Make, string Model, string VIN, string Debtor, string Payment, 
                                     string System, string SysInvoice, string SalesRep, string RepoAgent, string Payout)
    {

        bool recordSaved;


        OleDbTransaction myTransaction = null;

        try
        {

            OleDbConnection conn = new OleDbConnection(clsDataLayer.GetDataConnection());
            conn.Open();
            OleDbCommand command = conn.CreateCommand();
            string strSQL;


            myTransaction = conn.BeginTransaction();
            command.Transaction = myTransaction;

            // Inserts into table
            strSQL = "Insert into tblPersonnel " +
                     "(ALSCO Invoice, Job Type) values ('" +
                     AlscoInvoice + "', '" + Type + "')";


            command.CommandType = CommandType.Text;
            command.CommandText = strSQL;


            command.ExecuteNonQuery();

            // Updates DB
            strSQL = "Update tblPersonnel " +
                     "Vendor Name=" + Vendor + ", " +
                     "Price='" + Price + "', " +
                     "Vehicle Year='" + Year + "', " +
                     "Vehicle Make='" + Make + "', " +
                     "Vehicle Model='" + Model + "', " +
                     "VIN Number='" + VIN + "', " +
                     "Debtor Last Name='" + Debtor + "', " +
                     "Payment Status='" +Payment + "', " +
                     "System='" + System + "', " +
                     "System Invoice='" + SysInvoice + "', " +
                     "Sales Rep='" + SalesRep + "', " +
                     "Repo Agent='" + RepoAgent + "', " +
                     "Employee Payout='" + Payout + "', " +

                     "Where ID=(Select Max(ID) From tblPersonnel)";


            command.CommandType = CommandType.Text;
            command.CommandText = strSQL;


            command.ExecuteNonQuery();

            myTransaction.Commit();

            conn.Close();
            recordSaved = true;
        }
        catch (Exception )
        {

            myTransaction.Rollback();
            recordSaved = false;

        }

        return recordSaved;

How to run ASP.NET MVC app in IIS 10 on Windows 10

I installed IIS 10 through windows features and published MVC app into the IIS folder, then executed "dism /online /enable-feature /featurename:IIS-ASPNET45" command but still getting error:

HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents of this directory

I've done this in windows 7 with "aspnet_regiis -I" command instead of "dism /online /enable-feature /featurename:IIS-ASPNET45" and web app loaded just fine from localhost, but I can't seem to get this to work on Windows 10.

How do i differentiate auto generated links with JavaScript?

(Hi Dr.Nick)

I am pretty new to JavaScript and still i'm trying to build a website with asp.net EF JavaScript and so on...

I have genereated links from the information I have in my database and I want the name of that link to appear in my textbox but as you can see from this picture, no matter what link I press I will get entity... (if i press alfk i get entity).

link and stuff

My links get generated like this (for each entry in database):

<span>
  <a id="myLink" title="tagLink" value = @i.ID
    href="PleaseEnableJavascript.html" onclick="MyFunction();return false;">@i.Name</a>
</span>

and my JavaScript looks like this:

$( '#myLink' ).click(function () { MyFunction(); return false; });
function MyFunction() {
    document.getElementById( 'textTemp' ).value += document.getElementById( 'myLink' ).text + " ";
}

We can all see the problem... All my links have the same ID thus javascript will take the first one... But how do I solve this problem?

ASP.Net Using A Respsone.Redirect Depending On If The Email Has Been Sent Or Not

I have a 4pg process and the 3rd page is my confirmation page. This page has a button which sends and email. Then once the email has been sent or not, I have a response.redirect. What I want to do though is if the email has been sent then go to next page but if it fails to send, then display and error on the page and not redirect.

Not to sure how to do this. My code for the is

protected void pg3button_Click(object sender, EventArgs e)
        {
            try
            {
                //Create the msg object to be sent
                MailMessage msg = new MailMessage();

                //Add your email address to the recipients
                msg.To.Add("test@test.com");

                //Configure the address we are sending the mail from
                MailAddress address = new MailAddress("test@test.com");
                msg.From = address;

                //Append their name in the beginning of the subject
                msg.Subject = "Enquiry";

                msg.Body = Label1.Text + " " + Session["pg1input"].ToString()
                            + Environment.NewLine.ToString() +
                            Label2.Text + " " + Session["pg1dd"].ToString()
                            + Environment.NewLine.ToString() +
                            Label3.Text + " " + Session["pg2"].ToString();

                //Configure an SmtpClient to send the mail.
                SmtpClient client = new SmtpClient("smtp.live.com", 587);
                client.EnableSsl = true; //only enable this if your provider requires it

                //Setup credentials to login to our sender email address ("UserName", "Password")
                NetworkCredential credentials = new NetworkCredential("test@test.com", "Password");
                client.Credentials = credentials;

                //Send the msg
                client.Send(msg);

                //Display some feedback to the user to let them know it was sent
                lblResult.Text = "Your message was sent!";

                //Clear the form
                //txtName.Text = "";
                //txtMessage.Text = "";
            }
            catch
            {
                //If the message failed at some point, let the user know
                lblResult.Text = "Your message failed to send, please try again.";
            }
                Response.Redirect("/Session/Pg4.aspx");                
        }

Refresh Listview after delete a row into table

Into my asp.net application there is a Listview called ( pendingorderLV ) shown the pending orders of the customer and it include a delete button to delete the orders, what i am looking for is how i can make the listview refresh it self when the user click on each delete button and show the remain orders.

the listview behind code where user can reach it from a button into my application called: gotovieworder

 protected void gotovieworder_Click(object sender, EventArgs e)
    {


        MultiView1.ActiveViewIndex = 7;

        if (Session["UsrNme"] != null)
        {
            var user = Session["UsrNme"];
            using (var UsOrderCon = new SqlConnection(sc))
            {
                UsOrderCon.Open();

                string chksUsOrderstring = "Select count (*) from ShoppingCart where UID=@chkUID";

                SqlCommand ChkUsOrderCMD = new SqlCommand(chksUsOrderstring, UsOrderCon);

                ChkUsOrderCMD.Parameters.AddWithValue("@chkUID", user);

                var orderExists = (Int32)ChkUsOrderCMD.ExecuteScalar() > 0;

                if (orderExists)
                {

                    pendingorderpanel.Visible = true;
                    SqlDataAdapter UsOrderADPA = new SqlDataAdapter("SELECT [UID], [Product], [DateAdded], [PayMeth], [ProdDesc], [CartID] FROM [ShoppingCart] WHERE  [UID] = @uSer ", sc);

                    UsOrderADPA.SelectCommand.Parameters.AddWithValue("@uSer", Convert.ToString(Session["UsrNme"]));

                    DataSet UsOrderDST = new DataSet();
                    UsOrderADPA.Fill(UsOrderDST);
                    pendingorderLV.DataSource = UsOrderDST.Tables[0];
                    pendingorderLV.DataBind();
                    pendingorderpanel.Visible = true;


                }
                else
                {
                    UsexcOrderpanel.Visible = true;
                    UsOrderlbl.Text = "You dont have any orders, if you would like to become a premium user";
                }
            }
        }
    }

And the delete button inside the listview behind code is:

protected void deltPendOrder_Command(object sender, CommandEventArgs e)
    {
        using (SqlConnection DeltPndOrdSQLCon = new SqlConnection(sc))
        {
            int OrdPendID = Convert.ToInt32(e.CommandArgument);

            System.Data.SqlClient.SqlCommand DeltPendOrdcmd = new System.Data.SqlClient.SqlCommand();
            DeltPendOrdcmd.CommandType = System.Data.CommandType.Text;

            DeltPendOrdcmd.CommandText = "DELETE FROM ShoppingCart WHERE CartID = @CartID";

            DeltPendOrdcmd.Parameters.AddWithValue("@CartID", OrdPendID);
            DeltPendOrdcmd.Connection = DeltPndOrdSQLCon;
            DeltPndOrdSQLCon.Open();

            DeltPendOrdcmd.ExecuteNonQuery();
            DeltPndOrdSQLCon.Close();
            viewmsgView.Visible = true;
        }


    }

How to know if current culture in ASP.Net Webforms app is based on English alphabets

I have a regular expression validator in an ASP.Net Webforms app that makes sure the input in a textbox is a combination of these characters alphabets, digits, period, hyphen and single quote as in code below. Since this ASP.Net is multi-lingual i.e. both English and non-English cultures are allowed, the regex validator will need to b disabled when its being accessed from a non-English culture.

Question

Is the code-behind mentioned below going to satisfy this requirement of disabling the regex validator when being accessed from a non-English culture, Or is the code lacking something?

Regex Validator

<asp:RegularExpressionValidator 
ID="revProdName" runat="server" 
ErrorMessage="RegularExpressionValidator" ControlToValidate="ctxtProductName" 
ValidationExpression="^[(a-z)(A-Z) .'-(0-9)]+$"></asp:RegularExpressionValidator>

Code-behind of page

 If System.Globalization.CultureInfo.CurrentUICulture.DisplayName.StartsWith("en-") Then
            revProdName.Enabled = True
        Else
            revProdName.Enabled = False
        End If

Converting a piece of code written for Socket.IO to SignalR

I am trying to implement a video conferencing with SignalR.

I found this sample promising: http://ift.tt/1KqzQ17

The issue I am facing is to implement it with SignalR.

There are two samples given in the same link there.

One with Firebase and other one Sockets:

Want to use Firebase for signaling?

var config = {
    openSocket: function (config) {
        var channel = config.channel || location.href.replace(/\/|:|#|%|\.|\[|\]/g, '');
        var socket = new Firebase('http://ift.tt/1guTL4i' + channel);
        socket.channel = channel;
        socket.on('child_added', function (data) {
            config.onmessage(data.val());
        });
        socket.send = function (data) {
            this.push(data);
        }
        config.onopen && setTimeout(config.onopen, 1);
        socket.onDisconnect().remove();
        return socket;
    }
}
Want to use PubNub for signaling?

var config = {
    openSocket: function (config) {
        var channel = config.channel || location.href.replace(/\/|:|#|%|\.|\[|\]/g, '');
        var socket = io.connect('http://ift.tt/1OTEMMl' + channel, {
            publish_key: 'demo',
            subscribe_key: 'demo',
            channel: config.channel || channel,
            ssl: true
        });
        if (config.onopen) socket.on('connect', config.onopen);
        socket.on('message', config.onmessage);
        return socket;
    }
}

Can you help me writing that piece of code using SignalR?

Passing value to a user control from asp.net Page

I have following user control my .ascx Page. (Test.ascx)

<uc:Addresses runat="server" itemId='<%# StringId %>'></uc:SNETAddresses>

In the code behind of Test.ascx I have

protected string StringId = "{2A06199B-ED96-42F0-AB9A-602139E58BFB}";

In the code behind of user control Addresses.cs I have:

 public string itemId { get; set; }

So basically I want to pass a string to the variable itemId. But Somehow its not getting the value of variable "StringId". This simple thing is taking my so much time. I checked this post asp.net passing string variable to a user control but I am so sorry I could not get the answer. The reply is:

You may need to call DataBind on your Page in CreateChildControls or some other method 

I am new to Asp.Net and I didn't get what the user mean here.

ASP.net MVC framework and caching and executing javascript

First of all, excuse my terminology as I'm not an ASP.net MVC framework developer. My company is using an ASP.net MVC 5 framework. I'm developing the analytics code using Adobe DTM for this new framework. The issue I'm having is I recently worked on an Angular/Node.js implementation where my JavaScript files were only loaded initially and then ran on every view without being reloaded allowing me to keep track of states etc. I'm now working at a new company and they are using a ASP.net MVC 5 framework, but the JavaScripts are being reloaded every view. From what the developers are telling me, it is a hybrid where some pages use a controller and other pages don't. Is there a way to load JavaScript one time (initial load) and keep the JavaScript running (not destroying objects/variables)?

Thanks!

Linq Query Nested select + distinct

I'm having a really hard time converting this query to LINQ.

select fk, count(*)
from (
    select distinct fk, attribute1, attribute2
    from table
) a
group by fk
having count(*) > X

I need each distinct combination of fk, attr1, attr2 grouped by fk only where count is bigger than x (parameter).

Any ideas?

problems with data format string

well, i have this .aspx code:

<asp:GridView ID="GridView3" DataSourceID="test" runat="server" AutoGenerateColumns="False">
       <Columns>
               <asp:BoundField DataField="deuda" 
              HeaderText="deuda" ReadOnly="True"
              SortExpression="deuda" DataFormatString="{0:#,##0}" HtmlEncode="False" />
       </Columns>
</asp:GridView>

and its data source has this query:

set @lvl = 0;
set @saldo = 0;
WHILE @saldo &lt; (SELECT (80 * (sum(CASE WHEN a1.c11 &lt;&gt; 0 AND DATEADD(DAY, CONVERT(FLOAT(10), KDUD.C16), A1.C7) &lt; DATEADD(day, - 90, GETDATE())
 THEN ((a1.C17 / a1.C11) * a1.C20) END)) / 100) 
 FROM kdue a1 
 LEFT JOIN KDMM ON KDMM.C1 = 'U' AND A1.C3 = KDMM.C2 AND A1.C4 = KDMM.C3 AND A1.C5 = KDMM.C4 
 LEFT JOIN KDMS ON A1.C1 = KDMS.C1 
 LEFT JOIN KDUD ON A1.C2 = KDUD.C2 
 LEFT JOIN KDUV ON A1.C18 = KDUV.C2
  WHERE a1.c1 = '02-01') 
  BEGIN SET
   @saldo = @saldo + 
   (SELECT 
   sum(CASE WHEN a1.c11 &lt;&gt; 0 AND DATEADD(DAY, CONVERT(FLOAT(10), KDUD.C16), A1.C7) &lt; DATEADD(day, - 90, GETDATE()) THEN ((a1.C17 / a1.C11) * a1.C20) END) AS x
    FROM KDUE A1 
    LEFT JOIN KDMM ON KDMM.C1 = 'U' AND A1.C3 = KDMM.C2 AND A1.C4 = KDMM.C3 AND A1.C5 = KDMM.C4
     LEFT JOIN KDMS ON A1.C1 = KDMS.C1
      LEFT JOIN KDUD ON A1.C2 = KDUD.C2 
      LEFT JOIN KDUV ON A1.C18 = KDUV.C2
       WHERE a1.c1 = '02-01' GROUP BY kdud.c3 ORDER BY x DESC OFFSET @lvl ROWS FETCH NEXT 1 ROWS ONLY);
        SET @lvl = @lvl + 1 END 
        select replace(cliente,' ','')as cliente,replace(convert(varchar,round(p,0)),'.000000000','')as deuda from
(
SELECT TOP (@lvl) kdud.c3 as cliente, 
        (sum(CASE WHEN a1.c11 &lt;&gt; 0 THEN ((a1.C17 / a1.C11) * a1.C20) END)) AS p 
        FROM KDUE A1 
        LEFT JOIN KDMM ON KDMM.C1 = 'U' AND A1.C3 = KDMM.C2 AND A1.C4 = KDMM.C3 AND A1.C5 = KDMM.C4 
        LEFT JOIN KDMS ON A1.C1 = KDMS.C1 LEFT JOIN KDUD ON A1.C2 = KDUD.C2 
        LEFT JOIN KDUV ON A1.C18 = KDUV.C2 
        WHERE a1.c1 = '02-01' AND DATEADD(DAY, CONVERT(FLOAT(10), KDUD.C16), A1.C7) &lt; DATEADD(day, - 90, GETDATE()) 
        GROUP BY kdud.c3 ORDER BY p DESC)as x

which returns 2 columns called deuda and cliente, on my asp.net project on visual basic 2013 i tried to add the query to the data source with the wizard but since it adds parameters and they will mess up my query i added the asp columns manually and tried to apply the data format string but it just ignores it...

jquery mobile 1.4.5 single-page template href querystring ajax

I am a newbie to JQM (I use 1.4.5) and my webapp (asp.net C# apache Cordova) contains many separate pages of .cshtml (single-page template) only. I am testing my webapp on a Samsung Galaxy Grand using Android 4.2.2

A. I am not sure about my understanding of 'linking pages', even after reading all the JQM docs on this and also after reading up many, many posts on this topic about passing querystring values to another page; mainly because I find that ALMOST ALL the examples are directed towards providing answers for internal pages (Multi-Page template) within a single html page.

So I request some of you JQM experts to confirm or correct the following understanding of mine....

From the JQM docs I understood that

  1. I could use in any link (e.g button), href="page2.cshtml?par1=1&par2=2"; and JQM will automatically use Ajax for this link to work.

  2. I also understood that use of querystring is always allowed in such cases of different html pages of the same domain and it will work via Ajax automatically ; so long as the attr such as rel="external", data-ajax="false" etc. are not used in the same link.

  3. but querystrings are not allowed in case of the internal pages (multi-page template) only....;

  4. and if I need to use the above href to link to a page in another domain e.g. http://ift.tt/1OET0Qv, then I need to use rel="external".

Are all my above points (that reflect my understanding) CORRECT? KIndly confirm ro please correct me ...

B. In my app, I find that most of the links work according to my understanding as above, to connect to different pages in the same domain; and I assume it happens via Ajax. Is it correct? I am also able to use the querystring params in page2 ( i.e. To-Page).

  1. But in one case, though it works, in the To-Page the Panel features do not operate correctly, unless I introduce rel="external' in the href link !!! I suppose it means it IS NOT AJAX anymore? Also I am unable to find the reason..

  2. Further independent of the above topic, I face another issue. The loading time (i.e. Time taken to display the To-Page) varies.

Mostly it is OK, but at times the loading-circle goes on forever.... and I presume it has crashed....??? then If I go back using the back button and come forward again, many times it loads immediately...!!!!! Any thoughts or suggestions.....?

Thanks in anticipation... Ratna

Windows 10 IIS redirecting external IP to index html

I created default ASP.NET MVC 4 project in VS 2015 Community and tried to setup IIS to work with it. I just added this project to Sites List and bound it to port 80 (forwarding enabled). It's ok if I try to load localhost. But when I try to load my external IP, it suddenly redirects me to /index.html (that is 404 not found). Nevertheless if I go to my external IP with /Home, it redirects me to /Home/Index view as needed. It is also ok if I create an index.html page in the root of my project. But I just want to setup default project to work with IIS on my external IP. Could somebody help, please?

It is completely default project. Route config:

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }

From time to time we have System.OutOfMemoryException error on our asp.net web application

From time to time, our web application will cause this error:

System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.

The application is C# ASP.NET 4.5 Web Forms application, running on Windows 2008 R2 server with 6G memory. We have increased memory several times, but it still happens. So I am wondering if its application's problem? What could be the reason?

edit

I have this stack, don't know if it helps at all:

System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.

Generated: Wed, 29 Jul 2015 08:49:24 GMT

System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
   at ASP.popups_downloadtrendpdf_aspx.__BuildControlTree(popups_downloadtrendpdf_aspx __ctrl)
   at ASP.popups_downloadtrendpdf_aspx.FrameworkInitialize()
   at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
   at System.Web.UI.Page.ProcessRequest()
   at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context)
   at System.Web.UI.Page.ProcessRequest(HttpContext context)
   at ASP.popups_downloadtrendpdf_aspx.ProcessRequest(HttpContext context)
   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

How do I apply bootstrap in asp dropdownlist getting data from an objectdatasource?

How do I apply bootstrap in asp dropdownlist getting data from an objectdatasource?

The old code is running perfectly. Here's the old code

<asp:DropDownList ID="uxLocations" runat="server" 
                  DataSourceID="ObjectDataSource1" DataTextField="Name" DataValueField="ID" 
                  Height="24px" Width="200px" AutoPostBack="True" 
                  onselectedindexchanged="uxLocations_SelectedIndexChanged">
</asp:DropDownList>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" 
                      SelectMethod="GetLocations" 
                      TypeName="Domain.LocationManager">
</asp:ObjectDataSource>

I tried to apply bootstrap but the list is not showing properly, unlike when you hardcode the list using "ul and li" tags, just as shown in http://ift.tt/1G6FijP

Here's what i did: [not good]

<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="menu1" 
 data-toggle="dropdown">Locations
<span class="caret"></span></button>

<asp:DropDownList ID="uxLocations" runat="server" AutoPostBack="True" 
 CssClass="dropdown-menu" DataSourceID="ObjectDataSource1" 
 DataTextField="Name" DataValueField="ID" Height="24px" Width="200px">
</asp:DropDownList>

<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" 
    SelectMethod="GetLocations" 
    TypeName="Domain.LocationManager">
</asp:ObjectDataSource>

</div>

Help.

Thread was being aborted after response.redirect("Default.aspx")

Good afternoon, I get this error:

_message = "Thread was being aborted."

after a Response.Redirect("Default.aspx") sentence Anyeone can helpme?

Drop Down List appears twice if user double-clicks selection?

This page is dynamically created and the control is just a generic HTML drop down control. Sometimes if you double click certain items in the list (usually the middle options are more problematic than the others) it'll display the list of items twice, like so:

enter image description here

I've tried to Google around to see if this was a known issue with either .NET, IE or what but I cannot find a single relevant result.

Has anyone seen anything like this before? I'm completely at a loss as to what might be causing it. Using IE11 in Compatability Mode.

Looking at the ASPX page that gets generated in Visual Studio the control looks like this:

<div id="dlRepOpt_ctl02_DynControl">
    <SELECT NAME='Aedates' Class='clsComboBox110' onchange='mDataChanged=1;'>
        <option value='Previous Month'>Previous Month</option>
        <option value='Current Month'>Current Month</option>
        <option value='Previous Quarter'>Previous Quarter</option>
        <option value='Current Quarter'>Current Quarter</option>
        <option value='Previous Calendar Year'>Previous Calendar Year</option>
        <option value='Current Calendar Year'>Current Calendar Year</option>
        <option value='Last 12 Months'>Last 12 Months</option>
        <option value='User-defined Date Range' Selected>User-defined Date Range</option>
    </SELECT>
</div>

Nothing crazy.

ASP sqlDataSource racle.DataAccess.Client.OracleException: ORA-00911: invalid character

I'm using an sqlDataSource for a grid control. But i'm having issues when executing the insert command. I'm using Oracle.DataAccess.Client as the provider.

This is the code sqlDataSource generated

<asp:SqlDataSource ID="SqlDataSource3" runat="server" 
                ConnectionString="<%$ ConnectionStrings:ConnectionString1 %>" 
                InsertCommand="INSERT INTO &quot;EE_AP_KPIS&quot; (&quot;ID&quot;, &quot;TITLE&quot;, &quot;SECTION_ID&quot;, &quot;DISPLAY_TITLE&quot;, &quot;SORT&quot;) VALUES (?, ?, ?, ?, ?)" 
                ProviderName="<%$ ConnectionStrings:ConnectionString1.ProviderName %>" 
                SelectCommand="SELECT * FROM &quot;EE_AP_KPIS&quot;">
                                   <InsertParameters>
                                       <asp:Parameter Name="ID" Type="Decimal" />
                                       <asp:Parameter Name="TITLE" Type="String" />
                                       <asp:Parameter Name="SECTION_ID" Type="Decimal" />
                                       <asp:Parameter Name="DISPLAY_TITLE" Type="String" />
                                       <asp:Parameter Name="SORT" Type="Decimal" />
                                   </InsertParameters>                                       
            </asp:SqlDataSource>

I get the following error Oracle.DataAccess.Client.OracleException: ORA-00911: invalid character

I realise it could be a value in my data but I want to confirm if the code above looks OK? I'm not sure if the sqlDataSource has generated the sql correctly. Is VALUES (?, ?, ?, ?, ?) the correct way to bind variables? If not, any idea why it generated it like this?

Overide Connection for RedisSessionStateProvider on Azure

i am using i am using RedisSessionStateProvider with asp.net mvc 4.5 for session management. i am using azure web app for my hosting. how do i override this connection info on azure portal during prod deployment. is there any other way than using web.release.config transform file?

  <sessionState mode="Custom" timeout="2000" customProvider="MySessionStateStore">
    <providers>
      <add name="MySessionStateStore" type="Microsoft.Web.Redis.RedisSessionStateProvider" host="server.cloudapp.net" port="6379" accessKey="password" ssl="false" databaseId="1" applicationName="pWeb" />
    </providers>
  </sessionState>

EntityDataSource Iterates over result

I am using EntityDataSource to query data from database. I can read data normally through e.Result

 protected void My_OnSelected(object _sender, EntityDataSourceSelectedEventArgs _e)
{
    ...

    from result in _e.Results.Cast<DataType>() ....
    ....
}

I can see that my query works. The result from query should fill a gridview. In my case, before to bind this data to gridView, I need to do some processing and create an anonymous with some files calculated from variables result like

from result in _e.Results.Cast<DataType>() 
select new{
    z = result.x + result.y
}

the problem is that I can set this result to e.Result and then to bind the data. Is there a way to accomplish this behavior?

Programmatically adding a Panel control adds "body" to its ID

So I have this code:

var pnl = new Panel() {
    CssClass = "tab-pane",
    ID = "tab_content_" + gymTypes.Rows[0]["stars"].ToString()
};
tab_content.Controls.Add(pnl);

The gymTypes.Rows[0]["stars"] returns 1 so the ID should be tab_content_1 however when I run the website and inspect element the ID is somehow body_tab_content_1.

Is there a reason for this?

Can't run asp.net app on os x with dnx . kestrel

I followed this tutorial to install tools to run asp.net on os x. I scaffolded the asp.net web application successfully, but and run all the commands the application isn't running.

macbook$ cd '/Users/macbook/Documents/Leisure/asp/webapp' ; /Users/macbook/.dnx/runtimes/dnx-mono.1.0.0-beta6/bin/dnx . kestrel
info    : [Microsoft.Framework.DependencyInjection.DataProtectionServices] User profile is available. Using '/Users/macbook/.local/share/http://ift.tt/1KG10ju' as key repository; keys will not be encrypted at rest.
Started

Everything seems fine, but when I go to localhost:5000 I get ERR_CONNECTION_REFUSED, even though kestrel is set at this url.

What's not right? how do I get my asp.net app working?

Troubleshoot IIS authentication

Is there a reason why Forms authentication works fine using project debuging but not with IIS 7.5 ? In my IIS auhtentication I only got Anonymous and Forms enabled. check my authentication part of my web.config file, the logon page should redirect to FramePage.svc after validation. FramePage.svc permision is set to everyone. it seems like its not happening, any reason for this ? I'm getting error "Unknown exception occurs while logon to system, check with your admin. And this is if enter the right credentials. If enter wrong username, I will get invalid credential which is normal. Appreciated.

<authentication mode="Forms">
        <forms name=".Global" defaultUrl="FramePage.svc" loginUrl="LogOn.aspx" slidingExpiration="true" timeout="60" />
    </authentication>

QueryString obfuscation

I am wondering if the following is possible... I want to essentially accept a URL but hide the URL parameters. (have an existing ASP.NET web forms app - 4.0 on IIS 7 that I want to modify)

The effect that I am looking for is to accept a URL such as the following

http:/mysite/page.aspx?param1=100

But then have the what shows in the address bar not be something that could be copied and pasted into another browser session as a valid URL. Perhaps something like (assumes that the param1 is required)

http:/mysite/page.aspx

I have looked at a number of resources on SO and elsewhere, such as: Code Project How to Hide Params, Hide a QueryString parameters, how?, hide parameters passing to controller in address bar (URL rewrite or something else), ScottGu Rewriting URL

I know this is not the greatest idea, is not secure, etc, etc. I have a sense that it is not really possible either. The reason I want to do this is to provide a very thin layer of security. This is an internal only web app. Again, I know that it's not real security. I have considered all of the following techniques but don't see how any could work.

  • Session with redirect
  • URL rewrite
  • POST
  • Server.Transfer

I'd really rather not recreate my pages as posts. Am I correct: this is not possible? No way to just accept a valid URL with parameters but then what is left showing in the address bar of browser is not valid, or at least has parameters stripped out?

Updating date in SQL/VB/Asp.Net

I'm pretty much a novice at all this.. I know bits. Just trying to store a date in an SQL database.. I've set it to "06/06/2015" temporarily in code below to see if I can get it to update but it updates it as 01/01/0001. When I suss it, The value I actually want to store is todays date plus 6 months. EG: if its 31/07/2015 today, I want it to store 31/01/2016. Can anyone help ? Much appreciated...

ASPX.VB

Protected Sub imgBtnDatechange_Click(sender As Object, e As ImageClickEventArgs) Handles imgBtn.Click
Dim acc As New accounts(Membership.GetUser().ProviderUserKey)
Dim adjustedDate as Date = "06/06/2015"
acc.UpdateVipEndDate(acc.accountID, acc.adjustedDate)
End Sub

ACCOUNTS.VB

Public Property adjustedDate As Date

Public Sub UpdateVipEndDate(ByVal accountID As Guid, ByVal adjustedDate As Date)
Dim DBConnect As New DBConn
Using db As DbConnection = DBConnect.Conn("DBConnectionString")
    Dim cmd As SqlCommand = DBConnect.Command(db, "UpdateVipEndDate")
    cmd.Parameters.Add(New SqlParameter("accountID", SqlDbType.UniqueIdentifier,       ParameterDirection.Input)).Value = accountID
    cmd.Parameters.Add(New SqlParameter("newadjustedDate", SqlDbType.Date,     ParameterDirection.Input)).Value = adjustedDate
    db.Open()
    cmd.ExecuteNonQuery()
    cmd.Dispose()
    cmd = Nothing
    db.Dispose()
    db.Close()
End Using

End Sub

STORED PROCEDURE

CREATE PROCEDURE [UpdateVipEndDate]
@accountID          uniqueidentifier,
@newadjustedDate    date
AS
BEGIN

UPDATE tblAccounts SET [vipEndDate] = @newadjustedDate WHERE [accountID] = @accountID

END

Ajax.BeginForm that can redirect to a new page without submit

I have something like this:

@using (Ajax.BeginForm("Validate", "Basket", new AjaxOptions
    {
        UpdateTargetId = "panelId", 
        HttpMethod = "Post", 
        InsertionMode = InsertionMode.Replace,
        OnSuccess = "SuccessMethod" 
    }))
{
    @if(Model != null)
    {
       my action...
    }
    else
    {
     Response.Redirect(Url.Action("Index", "Home"))
    }
}

It works perfect when I use submit button, because partial is refreshing, and layout stay the same.

I have a problem, when my Model became null, because user make a remove action on my page. Then I want to make redirect to my home page (different layout), but when I do that (like in my code), I get two layounts on my page, because of InsertionMode.Replace mode.

How can I omit the Ajax.BeginForm in my view?