PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label asp.net. Show all posts
Showing posts with label asp.net. Show all posts

Saturday, December 10, 2022

[FIXED] How to use ? : if statements with Razor and inline code blocks

 December 10, 2022     asp.net, asp.net-mvc, asp.net-mvc-3, razor, syntax     No comments   

Issue

I'm updating my old .aspx views with the new Razore view engine. I have a bunch of places where I have code like this:

<span class="vote-up<%= puzzle.UserVote == VoteType.Up ? "-selected" : "" %>">Vote Up</span>

Ideally I'd like to do this:

<span class="vote-up@{puzzle.UserVote == VoteType.Up ? "-selected" : ""}">Vote Up</span>

However there's two problems here:

  1. vote-up@{puzzle.UserVote .... is not treating the @ symbol as a start of a code block
  2. @puzzle.UserVote == VoteType.Up looks at the first part @puzzle.UserVote as if it's supposed to render the value of the variable.

Anyone know how to address these issues?


Solution

This should work:

<span class="vote-up@(puzzle.UserVote == VoteType.Up ? "-selected" : "")">Vote Up</span>


Answered By - CD..
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, December 3, 2022

[FIXED] How can I access an IFRAME from the codebehind file in ASP.NET?

 December 03, 2022     asp.net, iframe     No comments   

Issue

I am trying to set attributes for an IFRAME html control from the code-behind aspx.cs file.

I came across a post that says you can use FindControl to find the non-asp controls using:

The aspx file contains:

<iframe id="contentPanel1" runat="server" />

and then the code-behind file contains:

protected void Page_Load(object sender, EventArgs e)
{
    HtmlControl contentPanel1 = (HtmlControl)this.FindControl("contentPanel1");
    if (contentPanel1 != null)
        contentPanel1.Attributes["src"] = "http://www.stackoverflow.com";

}

Except that it's not finding the control, contentPanel1 is null.


Update 1

Looking at the rendered html:

<iframe id="ctl00_ContentPlaceHolder1_contentPanel1"></iframe>

i tried changing the code-behind to:

HtmlControl contentPanel1 = (HtmlControl)this.FindControl("ctl00_ContentPlaceHolder1_contentPanel1");

if (contentPanel1 != null)
    contentPanel1.Attributes["src"] = "http://www.clis.com";

But it didn't help.

i am using a MasterPage.


Update 2

Changing the aspx file to:

<iframe id="contentPanel1" name="contentPanel1" runat="server" />

also didn't help


Answer

The answer is obvious, and unworthy of even asking the original question. If you have the aspx code:

<iframe id="contentPanel1" runat="server" />

and want to access the iframe from the code-behind file, you just access it:

this.contentPanel1.Attributes["src"] = "http://www.stackoverflow.com";

Solution

If the iframe is directly on the page where the code is running, you should be able to reference it directly:


contentPanel1.Attribute = value;

If not (it's in a child control, or the MasterPage), you'll need a good idea of the hierarchy of the page... Or use the brute-force method of writing a recursive version of FindControl().



Answered By - AaronSieb
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, November 21, 2022

[FIXED] How to open .sln project in winrar?

 November 21, 2022     .net, asp.net, c#, visual-studio, visual-studio-2019     No comments   

Issue

I have a project , If I open in winrar , This project didn't open . My code editor is visual studio 2019. My code file is inculiding vs 2019 items. is there anyone who can help ?

Error : One or more projects in the solution were not loaded correctly. Please see the Output Window for details.


Solution

It is better to extract the rar file to a folder and open the .sln from there.

Do all the editing in VS 2019 and compress the whole solution into a rar again when it is time to submit homework.



Answered By - Null
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to find the reason for a failed Build without any error or warning

 November 21, 2022     .net, asp.net, c#, visual-studio     No comments   

Issue

I have a WebApplication which contains reference to WCF services.

While building using Visual Studio 2010, Build fails without any error or warning. However building the .csproj using MsBuild is successful.

Can't figure out what should I try in Visual Studio, to resolve / diagnose the issue. Can you please help out?

I find out that the build has been failing,

  1. From text displayed in status Bar.
    enter image description here

  2. From output window:

     ========== Build: 0 succeeded or up-to-date, 1 failed, 0 skipped ==========
    

    The output tab includes configuration details.

    ------ Build started: Project: <projectName here> Configuration: Debug Any CPU
    

Solution

I just ran into a similar situation. In my case, a custom action (from the MSBuildVersioning package available on Nuget.org - http://www.nuget.org/packages/MSBuildVersioning/) which appeared in the csproj file's BeforeBuild target was failing without triggering any error message in the normal place.

I was able to determine this by setting the "MSBuild project build output verbosity" (in the latest Visual Studio's Tools tab [Path: Tools > Options > Build and Run]) to "Diagnostic" as shown below. This then showed that the custom action (in my case HgVersionFile) was what had failed.

Screen capture from Visual Studio showing the modified setting.



Answered By - Richard J Foster
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to drop all tables and reset an Azure SQL Database

 November 21, 2022     asp.net, azure, azure-sql-database, c#, visual-studio     No comments   

Issue

I have an ASP.NET MVC 5 project that works local and whenever I need to blow away the DB, I just open a new query on it, change the available database dropdown to master, then close the connection on my local db and run the query "drop database [name]". Then I build the project, go into the package manager console and run "Update-Database". This seems to rebuild a fresh local database and runs the seed method in my configuration.cs file.

The problem is when I need to test things in a live environment so I can test API's and such better, I will do a deploy to an Azure Website and the accompanying Azure DB, which is nice and easy to do. I check off the "Execute code first migrations" in the publish wizard and most of the time it works and I can run and debug my live version. Sometimes I need to blow away that db and start from scratch again, but the only way I've really found to do it is to go into the Azure portal, delete the database, and then re-create it with the same name. This takes some time for Azure to process, so this is a slow testing cycle.

Is there a quick way to just drop/reset a Azure SQL DB to it's fresh, empty, virgin state and then re-publish with "execute code first migrations" to have it re-create the tables and re-seed the data?

I've seen some talk of creating an initial migration after I create the db, and then trying to use the Powershell to do some sort of roll-back to that initial state, but I haven't had luck getting it to work, and I want to delete all the data at the same time. Maybe I've just got the wrong syntax or haven't found a good enough tutorial. While I can run a query on the Azure DB to "drop database [x]" it literally kills the SQL Azure DB instance as you'd expect and you need to go back into the portal to recreate it. Sometimes that initial state is no good as the model has since been updated, so this may not be useful anyway.

I feel like there should be some easier quicker way to test changes on a live environment as there all these great tools and shortcuts provided by MS, but did they just drop the ball here for this phase of development or am I missing something?


Solution

Since there is not an API way to do this that I am aware of, we have used this script to leverage a T-SQL query to clear the database.

To delete each table (and maintain your EF migration histories if you want)

while(exists(select 1 from INFORMATION_SCHEMA.TABLES 
             where TABLE_NAME != '__MigrationHistory' 
             AND TABLE_TYPE = 'BASE TABLE'))
begin
 declare @sql nvarchar(2000)
 SELECT TOP 1 @sql=('DROP TABLE ' + TABLE_SCHEMA + '.[' + TABLE_NAME
 + ']')
 FROM INFORMATION_SCHEMA.TABLES
 WHERE TABLE_NAME != '__MigrationHistory' AND TABLE_TYPE = 'BASE TABLE'
exec (@sql)
 /* you dont need this line, it just shows what was executed */
 PRINT @sql
end

To remove the foreign keys first if you need to

while(exists(select 1 from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where CONSTRAINT_TYPE='FOREIGN KEY'))
begin
 declare @sql nvarchar(2000)
 SELECT TOP 1 @sql=('ALTER TABLE ' + TABLE_SCHEMA + '.[' + TABLE_NAME
 + '] DROP CONSTRAINT [' + CONSTRAINT_NAME + ']')
 FROM information_schema.table_constraints
 WHERE CONSTRAINT_TYPE = 'FOREIGN KEY'
 exec (@sql)
 PRINT @sql
end

In my testing, this worked without issues (except I did not have the where clause in the DROP TABLE while query since I don't use Code First or EF migrations).



Answered By - Tommy
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to repeat rdlc full page

 November 21, 2022     .net, asp.net, visual-studio     No comments   

Issue

I'm using VS 2013, VB.Net, and web forms. I have an rdlc file that has a table with dynamic content. Above the table there are some text boxes, some of the text boxes have static content, but some have dynamic content as well.

red arrows - dynamic outside of table, green arrow - table

red arrows - dynamic outside of table, green arrow - table

I am feeding this report an IEnumerable(of T)(t is a custom object). My issue is that on the 2nd, 3rd, 4th.... etc. pages, the boxes that are not in the table do not render.

I have tried putting the boxes above the table into a report header, which does make them repeat. The problem with this is that the dynamic content from the first report is shown on every page.

Is there a setting I'm missing that will make the entire page render for each report, or is my best option now to move all the text boxes into the table?

A little background, this report has existed for years as it stands, but the client has only been able to run one at a time. The new requirement is to generate all the reports that meet a certain condition, one report per page. So staying as close to the original look as possible is critical. I'm hoping to avoid putting the other boxes in a table so as to not add the dark border around them.

Edit I just found a setting "repeat with". This setting is located by highligting an individual text box, then going to the properties menu. When I select "Repeat with table1", the text boxes are repeated, but they only show the value from the first object.

The report's data source is set up to mirror the custom object below. A collection of these objects is put into an IEnumerable like this:

Dim pendingPerformanceReviewReports As IEnumerable(Of PerformanceReviewReportScheme)

and then send it to the rdlc.

Custom object constructor:

Public Class PerformanceReviewReportScheme
    Public Property ConfNumber As String
    Public Property Appointment As String
    Public Property PerformancePlanStatus As String
    Public Property ProcessLevel As String
    Public Property Department As String
    Public Property PositionCode As String
    Public Property EmployeesName As String
    Public Property EmployeeID As Integer?
    Public Property PositionCodeDescriptionLevel As String
    Public Property CurrentPayRate As String
    Public Property ProposedPayRate As String
    Public Property ProposedEffectiveDate As String
    Public Property NextReviewDate As String
    Public Property PerformanceRating As String
    Public Property BasePayIncreaseDollars As String
    Public Property BasePayIncreasePercentage As String
    Public Property LumpSumBonusDollars As String
    Public Property LumpSumBonusPercentage As String
    Public Property RequestedBy As String
    Public Property RequestedOn As String
End Class

Solution

I ended up putting all my fields in the table and adding them to the existing group. You are able to select individual cells and remove their borders.

While this solution does work, it is not ideal. I do not have the flexibility that comes with being able to place text boxes on a blank sheet wherever I please.



Answered By - rogerdeuce
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to Migrate VB 8 code (VS 2005) to VB 16 (VS 2019)

 November 21, 2022     .net, asp.net, vb.net, visual-studio     No comments   

Issue

I have a VB code project developed using VS 2005, (Vb8) and wanted to migrate the project using Visual Studio 2019 (VB 16 version). Please suggest the best possible way to do it.


Solution

I would make sure the workflows and templates are installed (say vs2022), and then simple open the project.

You don't mention what version of .net the older project is based on, but in theory, you should with great success be able to open this project in vs 2019, or vs2022, and then be able to target framework 4.8 (the latest, or better stated last version of .net framework). You do not have a smooth upgrade to .net core, but you should be able to simple open the project. and set the framework to 4.8 and see if the project compiles/builds.

VERY but BEYOND very important?

You need to determine if this is a asp.net web site, or a asp.net web site application. (look for a sln file in the project folder - if it has one, then you can/should be able to open that project using file->open project.

If no sln file exists, then use file->open web site, and browse to that folder.

Other then above (and making a mess if you don't figure out what kind of project), then updating to latest .net 4.8, and using vs2022 should work fine.

The code and application for the most part should work and run without issues.

But, find out what kind of application this is

(asp.net web site)

or (asp.net web site application).

vs2019 is probably a "bit" better of a choice, since vs2019 is the LAST x32 bit version of VS. vs2022 is x64 bits now.

however, if your project works fine with vs2019, then you should be ok to upgrade to vs2022.

Since you ARE using vs2019, then I recommend you get the project working in vs2019, as it has better legacy x32 bit support.

However, I'm currently opening some rather old desktop, and some asp.net systems with vs2022, and they are working fine. Just remember to install all of the legacy templates and workflows in vs2019 BEFORE you try to open and start messing around.



Answered By - Albert D. Kallal
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do I resolve '@echo' is not a recognized command

 November 21, 2022     asp.net, visual-studio, visual-studio-2008     No comments   

Issue

I've implemented Scott Hanselman's method for keeping up with a dev/qa/prod version of web.config: http://www.hanselman.com/blog/CommentView.aspx?guid=93bfa4b3-44cd-4681-b70e-f4a2b0386466

For some reason when I compile my project I get this error message in my output window.
Any ideas?

------ Build started: Project: ABC.Flims.Web, Configuration: Development Any CPU ------
"C:\Projects\ballyhoo-trunk\src\ABC.Flims.Web\scripts/copyifnewer.bat" "C:\Projects\ballyhoo-trunk\src\ABC.Flims.Web\web.config.Development" "C:\Projects\ballyhoo-trunk\src\ABC.Flims.Web\web.config"
'@echo' is not recognized as an internal or external command,
operable program or batch file.  

Here is the script file:

@echo off
echo Comparing two files: %1 with %2

if not exist %1 goto File1NotFound
if not exist %2 goto File2NotFound

fc %1 %2 
if %ERRORLEVEL%==0 GOTO NoCopy

echo Files are not the same.  Copying %1 over %2
copy %1 %2 /y & goto END

:NoCopy
echo Files are the same.  Did nothing
goto END

:File1NotFound
echo %1 not found.
goto END

:File2NotFound
copy %1 %2 /y
goto END

:END
echo Done.

Solution

The file is probably Unicode encoded and has a Byte Order Mark (BOM) at the start that is throwing off the batch processor.

Save it as an ASCII file and you should be OK. You can do this in notepad - select Save As... from the File menu and ensure that the Encoding dropdown is set to ANSI.



Answered By - Oded
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to insert row at any desired position in datatable?

 November 21, 2022     .net, asp.net, c#, visual-studio, visual-studio-2008     No comments   

Issue

I have a datatable which contains 10 rows. I now need to insert 11th row at the position specified by some conditions.

I have tried the InsertAt method but that gives the error of "this row already belongs to another table".

I cannot use ImportRow method as that simply import the rows into datatable and inserts the row at the end of the existing rows.

What should i do? Kindly help!

Thanks

UPDATED CODE

        int iCount = 0;
        foreach (DataRow dr in dtWithBundle.Rows)
        {
            DataRow drClone = dtOppClone.NewRow();
            drClone.ItemArray = dr.ItemArray;
            dtOpps.Rows.InsertAt(drClone, iIndex + iCount);
            //dtOpps.ImportRow(drClone);
            //dtOpps.Rows.Add(drClone.ItemArray); // Commented on Aug-4 2011 1700HRS
            iCount++;
            dtOpps.AcceptChanges();
        }

Solution

Try this. I think the error you are getting is bcz you are not creating NewRow.

    DataTable dt = new DataTable();
    dt.Columns.Add("Name", typeof(string));

    DataRow dr;
    dr = dt.NewRow();
    dr[0] = "A";
    dt.Rows.Add(dr);

    dr = dt.NewRow();
    dr[0] = "C";
    dt.Rows.Add(dr);

    dr = dt.NewRow();
    dr[0] = "B";
    dt.Rows.InsertAt(dr,1);

    foreach (DataRow d in dt.Rows)
    {
        Console.WriteLine(d[0].ToString());

    }

    Console.Read();


Answered By - Asdfg
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, November 17, 2022

[FIXED] How do I get input tag text to align to the top?

 November 17, 2022     asp.net, asp.net-mvc, input, vertical-alignment     No comments   

Issue

I am building a Razor Pages web app and I added the CRUD features to it. On my Create page, there's a form to create entries which uses input tags. One of those fields is for comments so obviously it needs to be larger. So I added a width and height styles to it. However, the text only appears in the middle of the comment field and when the text reaches the end of the field, it doesn't wrap.

Create.cshtml.cs

@page
@model HSLogApp.Pages.HSLogs.CreateModel

@{
    ViewData["Title"] = "Create";
}

<h2>Create</h2>

<h4>Log</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form method="post">
            ....
            ....
            <div class="form-group">
                <label asp-for="Log.Comment" class="control-label"></label>
                <input asp-for="Log.Comment" class="form-control" style="height:250px; width:500px; vertical-align:top; white-space: pre-wrap;"/>
                <span asp-validation-for="Log.Comment" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-page="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

How can I get the cursor to flush to the top and how do I get it to wrap?


Solution

For multiline input use a textarea element.

There is an ASP.NET Core Tag Helper for it. The usage will be mostly the same as an input. Here is your example with a textarea.

<div class="form-group">
    <label asp-for="Log.Comment" class="control-label"></label>
    <textarea asp-for="Log.Comment" rows="3" class="form-control"></textarea>
    <span asp-validation-for="Log.Comment" class="text-danger"></span>
</div>

Now the use of the rows attributes in the textarea to specify the number of rows of text.



Answered By - Shaun Luttin
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, November 13, 2022

[FIXED] how to find out which version of asp my website is coded in

 November 13, 2022     asp.net, c#, plesk, server     No comments   

Issue

I have a website which is coded in asp. We have upgraded out plesk server from plesk 9 to 12 since then, I am getting a "Internal server error".

It could be that the new version of ASP installed on Plesk is not compatiable with the version of ASP that the website is coded in. Right now we do not have the website only the code, so is there a way to find out which version my ASP code is coded in just so that I can install an older version of ASP on my server to get the website back up and running?

Thanks.


Solution

Open your project in visual studio. once your project is loaded in visual studio click web config file in that you can find .Net framework version.



Answered By - Prasanna Murali
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to access the font programmatically

 November 13, 2022     asp.net, c#, fonts, gdi+, plesk     No comments   

Issue

I'm trying to access to a font programmatically, because i cant install fonts on the sharing hosting

I use this code

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load

    Dim collection As New PrivateFontCollection()
    collection.AddFontFile(Server.MapPath("~\ShadowsIntoLight.ttf"))

    Dim image As New Bitmap(500, 500)
    Dim g As Graphics = Graphics.FromImage(image)

    Dim RedBrush As New SolidBrush(Color.Black)
    Dim drawFont As New Font("Shadows Into Light", 36)

    g.DrawString("the lazy fox jumped over the brown log", drawFont, RedBrush, 0, 100)

    Dim path As String = Server.MapPath("~/image.png")
    image.Save(path, ImageFormat.Png)
    g.Dispose()
    image.Dispose()

    Response.Write("<img src=""image.png""/>")

End Sub

but it always displays the Arial font. How can I make it display the specific font

Thank you


Solution

Could you not use CSS in the background? Add the custom font to your solution in a 'Fonts folder' > add existing item to fonts folder in visual studio

Example: (Using a random font I downloaded)

@font-face{
font-family: myFont;
src: url(/Fonts/Belleza-Regular.ttf);

}

.MyClass{
color:green;
font-family: myFont;
 }

Then append this font anywhere within your code?

myControl.CssClass = "MyClass" etc..



Might be a slightly longer way than you wanted and would only work if you're appending to controls and such however might be a nice workaround.

Edit:

maybe something like this? Using custom TTF font for DrawString image rendering



Answered By - dan6657
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, November 12, 2022

[FIXED] Where can I get memcached for Windows 64Bit

 November 12, 2022     asp.net, c#, memcached, windows     No comments   

Issue

I have checked other answers on SO but they are all old. I just cannot find a place to get memcached for windows 64bit. Where can I find it. Also, where do I find the windows clients for memcached?


Solution

32 bit should run on windows 64 machines. Regardless, check Membase server, it has memcached bundeled, it can be run in memcached only mode (i.e. no persistence).

Below links should also be of interest:

Memcache on windows

http://allegiance.chi-town.com/MemCacheDManager.aspx

And this SO question: can I get Memcached running on a Windows (x64) 64bit environment?



Answered By - VinayC
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to implement a payment gateway in ASP.NET

 November 12, 2022     asp.net, c#, payment-gateway     No comments   

Issue

I need to know how to implement a payment gateway in ASP.NET for my billing based project.

Is there one gateway enough to access all the bank account?


Solution

I would look at some open source solutions that do the same thing. Nopcommerce comes to mind and implements the APIs for a large number of payment providers. Download the code and get digging....



Answered By - JP.
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, November 11, 2022

[FIXED] How to retrieve checkout information when using Stripe SDK

 November 11, 2022     asp.net, asp.net-mvc-5, payment-gateway, stripe-payments     No comments   

Issue

Here is my Cart and Checkout process in my web application

My purpose is after checkout, I retrieve the payment information like transaction Id or payment reference

In my ASP.NET MVC 5 application, I have following code in Cart View

<div>
@using (Html.BeginForm("", "Cart", FormMethod.Post))
{
     ... here I show products in cart ...

     ... NOTE that I don't have any action in my form ...

     <input type="submit" id="stripe-checkout-button" value="Checkout" />
}
</div>

<script type="text/javascript">
    var stripe = Stripe('@ViewBag.StripePublishKey');
    var checkoutButton = document.getElementById('stripe-checkout-button');

    checkoutButton.addEventListener('click', function () {
        fetch('https://localhost:44323/Cart/CreateCheckoutSession', {
            method: 'POST'
            })
            .then(function(response) {
                return response.json();
            })
            .then(function(session) {
                return stripe.redirectToCheckout({ sessionId: session.id });
            })
            .then(function(result) {
                if (result.error) {
                    alert(result.error.message);
                }
            })
            .catch(function(error) {
                console.error('Error:', error);
            });
    });
</script>

In Cart controller I have following actions

[HttpPost]
public ActionResult CreateCheckoutSession()
{
    var cart = (ShoppingCart)Session["cart"];
    var options = new SessionCreateOptions
    {
        PaymentMethodTypes = new List<string> { "card" },
        Mode = "payment",
        SuccessUrl = Url.Action("CheckoutSuccessful", "Cart", null, Request.Url.Scheme),
        CancelUrl = Url.Action("CheckoutCancelled", "Cart", null, Request.Url.Scheme),
        PaymentIntentData = new SessionPaymentIntentDataOptions
        {
            CaptureMethod = "manual"
        },
        LineItems = new List<SessionLineItemOptions>()
    };

    foreach (var item in cart.Items)
    {
        // here I add the purchased product. I remove the code for simplification
    }

    var service = new SessionService();
    Session session = service.Create(options);

    ViewBag.SessionId = session.Id;

    return Json(new { id = session.Id });
}

public ActionResult CheckoutSuccessful(string sessionId)
{
    // sessionId is null here. I'm even not sure if I need this parameter

    ShoppingCart cart = (ShoppingCart)Session["cart"];
    return RedirectToAction("Index", "Checkout");
}

public ActionResult CheckoutCancelled()
{
    return RedirectToAction("Index", "Cart");
}

When I click on Checkout button, the application redirects to Stripe payment page and I can enter email and billing information and click pay. It works well and payment goes through.

Based on my setting, the application redirects to CheckoutSuccessful action after that.

What I am missing here is, in CheckoutSuccessful action, I need to retrieve email address and billing address plus payment or transaction Id. I don't know how to do that. In CheckoutSuccessful, the parameter sessionId is null. I don't know what I've done wrong here or what I'm missing.

Thanks for help.


Solution

After a few days research and try out, I figured it out.

After creating session, I need to store the session.Id in Http Session and in CheckoutSuccessful method (which does not need any parameter), I need to call couple of APIs to retrieve session and payment information like below:

var service = new SessionService();
var session = service.Get(the stored session.Id);

var custService = new CustomerService();
var customer = custService.Get(session.CustomerId);

var paymentService = new PaymentIntentService();
var payment = paymentService.Get(session.PaymentIntentId);

Then, I will have all required infromation in session, customer and payment objects.



Answered By - FLICKER
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, November 10, 2022

[FIXED] How to authenticate emails to prevent gmail mark it as spam

 November 10, 2022     asp.net, dkim, email, nopcommerce     No comments   

Issue

We just open a new e-commerce website and recently noticed Gmail treat our e-mails as spam (notice the red question mark). Our website run behind CloudFlare so the email server IP address is different than the domain.

SPAM marked notice the question mark

We also did not send a bulk email at least not yet. There are some explanations in Google FAQ but not sure what it means or how I need to implement it. Can you please explain how to set these DKIM (preferred) or SPF.

Our website uses nopcommerce (3.70) and developed with ASP.Net.


Solution

Disclaimer: I'm not a "pro" at these things (more later):

  • IMHO, this is probably the simplest explanation of DKIM

  • SPF: in my own words: providing a DNS TXT record that identifies "where" all your emails (smtp/mta servers) can come from. The more complete/formal spec is here

  • You can implement both


Opinionated:

  • SPF is easier to implement

    • identify all the origins of your email, set them in your SPF record, which is a TXT record in DNS
  • DKIM: is more complex - your mail/smtp server/s must implement it.

    As a "web developer" one can see how this would be done in ASP.Net/C#/VB - e.g. sign some payload and using HttClient send some signature in an HTTP header in some outbound request.

    But this is done on an SMTP server, so unless you have one that already implements it, it's something you'll have to do...

IMHO, for DKIM, unless your SMTP/MTA implements it, I'd go for services that provide it. There are 2 types:

  • Transactional email services:

    Not for bulk email. These are the usual "order confirmation" emails, standard support/customer service, etc. emails. They will likely have APIs for you to implement (e.g. sending your MailMessage using thier servers and/or constructing something that equates to it and send that "object" to their API).

  • Bulk email services

    these providers will already have implementations because one of their core value propositions is "deliverability" of your bulk/marketing emails. They should (of course do your due diligence) have both implementations inherently. Will also have their own APIs for bulk email context.

Hth



Answered By - EdSF
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, November 9, 2022

[FIXED] how do I display data to a text area in html from any sort of input aka text box or database in asp.net core ( runat doesnt work or pop up)

 November 09, 2022     asp.net, asp.net-core, c#, html, visual-studio     No comments   

Issue

i can't find anything that tells me how to display data to a text area from a database or textbox


Solution

how to display data to a text area from a database

You can refer to the below demo.

Controller:

 public IActionResult Index()
        {
            TextInputModel model = new TextInputModel();
            model.list = new List<string> { "answer1", "answer2", "answer3" };
            model.Name = "aa";//you can get your data from batabase too...
            return View(model);
        }

TextInputModel:

public class TextInputModel
    {
        public List<string> list { get; set; }
        public string Name { get; set; }    
    }

Index view:

@model TextInputModel 


<div class="form-group">
            <label class="control-label">List</label>
            <textarea name="list" class="form-control" style="text-align:right">@string.Join("\n ", Model.list)</textarea>
        </div>
        
<div class="form-group">
            <label class="control-label">Name</label>
            <textarea name="Name" class="form-control" style="text-align:right">@Model.Name</textarea>
        </div>

result: enter image description here

I have text boxes and a submit button when the button is pressed it must display to the text area

I create a view to show text box and a view display data to a text area.

Controller:

        public IActionResult Show()
        {
            return View();
        }
        [HttpPost]
        public IActionResult Show(string Name)
        {           
            ViewBag.Name = Name;      
            return View("ShowText");
        }

Show view:

<form method="post"  asp-action="Show">
    <input type="text"  name="Name"/>
    <input type="submit" value="Submit"/>
</form>

ShowText view:

<textarea name="Name" class="form-control" style="text-align:right">@ViewBag.Name</textarea>

result: enter image description here



Answered By - Qing Guo
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, October 31, 2022

[FIXED] How to track IIS server performance

 October 31, 2022     asp.net, iis, performance     No comments   

Issue

I have a reoccurring issue where a customer calls up and complains that the web site is too slow. Specifically, if they are inactive for a short period of time, then go back to the site, there will be a minute-two minute delay before the user sees a response. (the standard browser is Firefox in this case)

I have Perfmon up and running, the cpu utilization is usually below 20% (single proc...don't ask). The database is humming along. And I'm pulling my hair out.

So, what metrics/tools do you find useful when evaluating IIS performance?


Solution

Hope this helps:
Best Practices for Speeding Up Your Web Site
Scaling Strategies for ASP.NET Applications
IIS Tuning
14 Rules for Faster-Loading Web Sites
Best practices for creating websites in IIS 6.0
Stanford Computer Cience - High Performance Web Sites
10 Tips for Writing High-Performance Web Applications
Writing High-Performance Managed Applications : A Primer
Nine tips for a healthy "in production" ASP.NET application
Speedy C#, Part 2: Optimizing Memory Allocations - Pooling and Reusing Objects
Memory Usage Auditing For .NET Applications
Troubleshooting HTTP Compression in IIS 6.0
Maximizing IIS Performance - 25 tips
Optimizing IIS 6.0 Performance
Page Speed - an open-source Firefox/Firebug Add-on
Performance Testing Guidance for Web Applications
Top 10 Performance Improvements in IIS 7.0
CHAPTER 6 Optimizing IIS 6.0 Performance
Performance Tuning Guidelines for Windows Server 2003 - Performance Tuning for IIS 6.0
ASP.NET Performance Tips
IIS 6.0 Tuning for Performance - by Peter A. Bromberg, Ph.D.
Improving .NET Application Performance and Scalability - by MS
Optimizing and Performance Tuning IIS 6.0
12 Steps To Faster Web Pages With Visual Round Trip Analyzer
Thread: IIS 6 performance tweak guide (draft)
CPU Settings for an Application Pool IIS6 e IIS7

Great improvements tips :
Running ASMX Web Services on STA Threads
Scale Net

Measure, measure, measure :
Load Test Your Site
Show Slow
Performance Monitor Wizard
Two Minute Drill: Introduction to XPerf
Suggested Performance Counters to Watch (IIS 6.0)

See what the best sites did :
Benchmarks
TOP 100

More resource :
Learn papers

My experience says:

  • Enable compression (GZIP/Deflate) in IIS, for Static data. Simple to implement and with excellent results.
  • if cpu is not your problem try to enable compression for dynamic data as well.


Answered By - lsalamon
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, October 25, 2022

[FIXED] How access to abstract property from abstract that inherits interface?

 October 25, 2022     access-modifiers, asp.net, c#, oop     No comments   

Issue

I am not able to access a virtual property (IsNameAPalindrome) of an abstract class (PetBase ) having interface(IPet) inherited.

public interface IPet
{
    string Name { get; set; }
}

public abstract class PetBase : IPet
{
    public abstract string Name { get; set; }

    public virtual bool IsNameAPalindrome
    {
        get
        {
            return (Name.Equals(string.Join("", Name.Reverse())));
        }
    }

}

The derived classes inherit the abstract class (PetBase)

public class Bird : PetBase
{
    public override string Name { get; set; }
}

public class Cat : PetBase
{
    public override string Name { get; set; }

}

public class Dog : PetBase
{
    public override string Name { get; set; }
}

public class House : List<IPet>
{        
}

Now when I try to access the property(IsNameAPalindrome) while looping through house object, it is not accessible

 class Program
{
    static void Main(string[] args)
    {
        House house = BuildHouse();
        Print(house);
    }


    static void Print(House house)
    {
        // TODO: Print the contents of the house similar to the below.
        // Feel free to change or improve upon the table as you see fit.

        //Name    Palindrome
        //Gracie  False     
        //Patches False     
        //Izzi    True      
        //Missy   False     
        
        Console.WriteLine("Name Palindrome");
        foreach (var item in house)
        {
            Console.WriteLine( item.Name);

        }
    }

    static House BuildHouse()
    {
        House house = new House();

        house.Add(new Cat()
        {
            Name = "Gracie"
        });

        house.Add(new Cat()
        {
            Name = "Patches"
        });

        house.Add(new Bird()
        {
            Name = "Izzi"
        });

        house.Add(new Dog()
        {
            Name = "Missy"
        });

        return house;
    }
}

Solution

You define House as List<IPet>, meaning the compiler will see each list element as the type IPet, which does not have a property IsNameAPalindrome.

If it makes logical sense for IsNameAPalindrome to be part of that interface contract, the simple solution is to add it:

public interface IPet
{
    string Name { get; set; }
    bool IsNameAPalindrome { get; }
}

If that does not make sense to you (and it may not, given that palendromes aren't closely linked to the concept of being a pet), you can:

  • Cast each IPet to PetBase to access that property
  • Implement a new interface e.g. IPalendrome, have PetBase also implement that interface, and cast to that interface to access the method.

Changes to the code for

First option

Console.WriteLine( ((PetBase)item).IsNameAPalindrome);

Second option

public interface IPalendrome
{
    bool IsNameAPalindrome { get; }
}

public abstract class PetBase : IPet, IPalendrome
{
    ...
}

Console.WriteLine( ((IPalendrome)item).IsNameAPalindrome);


Answered By - Eric J.
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to properly return a list item for editing?

 October 25, 2022     asp.net, builder, c#, design-patterns, oop     No comments   

Issue

I created a class for convenient creation of a list that consists of different types of objects with a single interface.

A list item is created by calling a class method, the result of the method is a newly created object in the list for EDIT.

While this code works, I'm not sure if it's safe to return a list item to edit properties?

If not, how can you safely return an element from the list so that you can edit it.


var builder = new ElementBuilder();
var item = builder.AddText("abc");

// Edit new reference element property, should be stored in "builder" variable
item.Bold = true;

.....

// Pass builder instance with added items to other place

// If we do something like this with added values on above
var x = builder.First() as TextElement; 
Console.WriteLine(x.Text);
Console.WriteLine(x.Bold);

// Should output:
abc
true
public class ElementBuilder
{

    private List<IElement> elements =  new List<IElement>();;

    public TextElement AddText (string text)
    {
        var item = new TextElement (text);
        elements.Add(item);
// RETURNING to edit properties, updates of returning should affect to list item
        return _elements.First(x => x == item);
    }

    public ImageElement AddImage (string imageUrl)
    {
        var item = new ImageElement (imageUrl);
        elements.Add(item);

// RETURNING to edit properties, updates of returning should affect to list item
        return _elements.First(x => x == item);
    }

    public IElement First() 
    {
        return elements.First();
    }

    .....
}

Solution

if it's safe to return a list item to edit properties?

yeah, it is safe because what code is doing is it returns the reference to newly created item:

var item = new TextElement (text);

There are really nice posts how reference types work:

  • Value and Reference types confusion
  • Reference type in C#

In addition, it is possible to avoid iteration of the whole collection by returning item, not using First() method:

public IElement AddText (string text)
{
    var item = new TextElement (text);
    elements.Add(item);
    
    return item;
}

Because when you Add item into collection, then newly created item will be added at the end of list. So, First() method will iterate the whole List<T> to find your item. It can be seen in source code of First() method.



Answered By - StepUp
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing