Quantcast
Channel: CodeProject Latest postings for ASP.NET
Viewing all 3938 articles
Browse latest View live

Histogram in Asp.net using canvas js

$
0
0
I want to create histogram with Machine names on X axis and observations on Y axis using canvas.js.
Thanks.

How do I change this code using Inheritance?

$
0
0
I have finally gotten my code to work, but there is one thing left that I want to do.
In my code I had made a Keycard class that had a name and a keynumber.
What I would like to do is to change the Keycard class to Person Class, which keeps the Name string, and then add the Keycard class as a child to the Person class, which keeps the Mykey int.

I have done inheritance before, but I have not tried doing it in a file that also uses Serialization.
How should the code look?

Also, a small bonus question. As you can see, my code gives a binary output. Like with XML, is there a way to show this binary output on a web application?

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Runtime.Serialization;using System.Runtime.Serialization.Formatters.Binary;namespace Keycard
{
    [Serializable()]publicclass Keycard : ISerializable
    {protectedstring name;protectedint mykey;public Keycard(string name, int mykey)
        {this.Name = name;this.Mykey = mykey;
        }publicstring Name
        {get { return name; }set { name = value; }
        }publicint Mykey
        {get { return mykey; }set { mykey = value; }
        }publicvoid GetObjectData(SerializationInfo info, StreamingContext context)
        {

            info.AddValue("Name", name);
            info.AddValue("Keynumber", mykey);

        }
        public Keycard(SerializationInfo info, StreamingContext context)
        {
            Name = (string)info.GetValue("Name", typeof(string));
            Mykey = (int)info.GetValue("Keynumber", typeof(int));
        }publicoverridestring ToString()
        {return"Name: " + name + " ---- " + " Keynumber: " + mykey;
        }
    }
}


using System;using System.Collections;using System.Collections.Generic;using System.Linq;using System.Xml.Serialization;using System.IO;using System.Runtime.Serialization.Formatters.Binary;namespace Keycard
{class Class1
    {publicstaticvoid Main(string[] args)
        {
            Keycard d1 = new Keycard("John", 102030);

            Stream stream = File.Open("KeycardData.dat",
                FileMode.Create);

            BinaryFormatter bf = new BinaryFormatter();

            bf.Serialize(stream, d1);
            stream.Close();

            d1 = null;

            stream = File.Open("KeycardData.dat", FileMode.Open);

            bf = new BinaryFormatter();

            d1 = (Keycard)bf.Deserialize(stream);
            stream.Close();
            Console.WriteLine(d1.ToString());
            Console.ReadLine();

        }
    }
}

ASP.Net MVC: How data is serialize into model when pass to client side from action

$
0
0
I am sending list of data from action to client side. in client side i am binding jquery data table with pass data. column name is extracted because column is dynamic in my case. i got a below code which is not very clear how it is working.

My question is very basic question. see how list of data is pass from action to client side.
[HttpGet]public ActionResult Index()
{

    List<UserData> data = new List<UserData>
    {new UserData
    {
    ID = 1,
    Name = "Simon"
    },new UserData
    {
    ID = 2,
    Name = "Alex"
    }
    };return View(data);
}


passed model data is captured like below way which is not clear to me
var keys = Object.keys(@Html.Raw(Json.Encode(Model[0])));var columns = keys.map(function (key) {return { title: key };
});var data = @Html.Raw(Json.Encode(Model));var dataSet = data.map(function (d) {returnObject.values(d);
});

console.log(columns);
console.log(dataSet);


see this code first
var keys = Object.keys(@Html.Raw(Json.Encode(Model[0])));var columns = keys.map(function (key) {return { title: key };
});


1) we know list is kind of array then why keys are extracted from zeroth position ? Model[0] why not Model[1]

i like to know in what form data is stored into model when pass from action to client side ?
see this code again
var data = @Html.Raw(Json.Encode(Model));var dataSet = data.map(function (d) {returnObject.values(d);
});


2) in above code no ordinal position mention during extracting data. why?

3) what is Model[0] ? how it comes? because in asp.net mvc we write model like @model not Model

4) is this Model is Asp.Net MVC related model or javascript Model object ?

During keys extraction ordinal position is mentioned but in case of data extraction no ordinal position mentioned. please explain if some one understand what i am trying to know.

My main question is i have only one question that what is Model[0] here in js? is it any JavaScript related object or server side object ? if it is javascript then how server side model data comes into js model ?

please explain how above code is working at client side. thanks

Scrape with htmlagilitypack problems

$
0
0
Searched and worked hours trying to pull off/identify when a work/project is available on a web page. Below is the source of the page and my code. I can pull the tables, which are 7, but rows comes up as nothing. Want to pull when table id="workorders" and then = Project Name/work order

Thanks
Jim




Current Work Orders




No assigned work orders found.



-------if present, want to identity/capture this


My code
Get all tables in the document
Dim k As Integer
'
' Get all tables in the document
Dim tables As HtmlAgilityPack.HtmlNodeCollection = main.DocumentNode.SelectNodes("//table").innertext
' Iterate all rows in the first table

Dim rows As HtmlAgilityPack.HtmlNodeCollection = main.DocumentNode.SelectNodes("th")
' Iterate all rows in the first table
For k = 0 To rows.Count - 1
' Iterate all columns in this row
Dim cols As HtmlAgilityPack.HtmlNodeCollection = rows(k).SelectNodes("th")
If cols IsNot Nothing Then
For j As Integer = 0 To cols.Count - 1
' Get the value of the column and print it
Dim value As String = cols(j).InnerText
Console.WriteLine(value)
Next
End If
Next
Project Name/Work OrderDateTimeLocationTechPay RatePay TypeActions

allowDefinition='MachineToApplication' beyond application level

$
0
0
I got Error when i use Machine key in web config file in asp.Net Project.

ASP.Net MVC: How to print raw model in razor view

$
0
0
Now in my razor view i am want to see what is stored in my raw Model ? So tell me how could i show raw model in razor view ?

or want to see what is stored in first element of Model ?

i tried this way but getting error
@model JQDataTable.Controllers.TestData

@Html.Raw(Json.Encode(@Model))

OR 

@Html.Raw(Model)


Getting error now for above code.

The model item passed into the dictionary is of type

'System.Collections.Generic.List`1[JQDataTable.Controllers.UserData]',
but this dictionary requires a model item of type 'JQDataTable.Controllers.TestData'.


please rectify my code as a result i will be able to print Model in razor page. thanks

ASP .NET list of text boxes not aligning properly

$
0
0
I am displaying a list of textboxes on top of an image on an ASP .NET Master/Content webpage. The image is the width of the page and has 6 even spaced white blocks. What I am trying to do is put a number in each image box white space using the CSS and HTML below. What is happening is all of the textboxes are being displayed in the same image box which is the first. In the first, the textboxes are only about 2px apart from each other and not spreading across the image 20px apart as defined it the left CSS tag. Why is my style is not correct?

Master:
// These style sheet classes match each textbox below<style>
        .floating_label1 {
            position: absolute;
            z-index: 200;
            top: 65px;
            **left: 115px;**
          //  border: hidden;
        }
        .floating_label2 {
            position: absolute;
            z-index: 200;
            top: 65px;
            **left: 130px;**
          //  border: hidden;
        }
        .floating_label3 {
            position: absolute;
            z-index: 200;
            top: 65px;
            **left: 150px;**
        //    border: hidden;
        }
        .floating_label4 {
            position: absolute;
            z-index: 200;
            top: 65px;
            **left: 170px;**
         //   border: hidden;
        }
        .floating_label5 {
            position: absolute;
            z-index: 200;
            top: 65px;
            **left: 190px;**
        //    border: hidden;
        }
        .floating_label6 {
            position: absolute;
            z-index: 200;
            top: 65px;
            **left: 210px;**
            border: hidden;
        }
}</style>
Content:<div style="position:relative;"><img src="Images/PAXSummary.jpg" /><asp:TextBox ID="TextBox1" runat="server" Text="1" style="height:25px; width:25px; vertical-align:central; text-align:center" CssClass="floating_label1" /> <asp:TextBox ID="TextBox2" runat="server" Text="2" style="height:25px; width:25px; vertical-align:central; text-align:center" CssClass="floating_label2" />             <asp:TextBox ID="TextBox3" runat="server" Text="3" style="height:25px; width:25px; vertical-align:central; text-align:center" CssClass="floating_label3" />             <asp:TextBox ID="TextBox4" runat="server" Text="4" style="height:25px; width:25px; vertical-align:central; text-align:center" CssClass="floating_label4" />             <asp:TextBox ID="TextBox5" runat="server" Text="5" style="height:25px; width:25px; vertical-align:central; text-align:center" CssClass="floating_label5" />             <asp:TextBox ID="TextBox6" runat="server" Text="6" style="height:25px; width:25px; vertical-align:central; text-align:center" CssClass="floating_label6" />             </div>

Error: Make sure that the class defined in this code file matches the 'inherits' attribute, and that it extends the correct base class (e.g. Page or UserControl)

$
0
0
The website is working fine now I added MenuLeft.ascx into the folder "C:\WebSite2010\WebMaster\Controls\" when pressing the Rebuild website button with the error "Error: C:\WebSite2010\WebMaster\Controls\MenuTop.ascx.cs(14): error ASPNET: Make sure that the class defined in this code file matches the 'inherits' attribute, and that it extends the correct base class (e.g. Page or UserControl)". Note that the folder "C:\WebSite2010\Controls\" already has a file with the same file name: MenuLeft.ascx now I copy the declaration of 2 files with the same name, how do I change the code ?
in the file: C:\WebSite2010\Controls\MenuLeft.ascx<%@ControlLanguage="C#"AutoEventWireup="true"CodeFile="MenuLeft.ascx.cs"Inherits="MenuLeft"%><%@ImportNamespace="webapp4U"%><%@RegisterSrc="~/Controls/ThuvienHinhAnh.ascx"TagPrefix="uc"TagName="ThuvienHinhAnh"%><%@RegisterSrc="~/Controls/QuangCaoLeft.ascx"TagPrefix="uc"TagName="QuangCaoLeft"%><%@RegisterSrc="~/Controls/WebURL.ascx"TagPrefix="uc"TagName="WebURL"%><%@RegisterSrc="~/Controls/Newsletter.ascx"TagPrefix="uc"TagName="Newsletter"%><%@Registersrc="DanhMucBDS.ascx"tagname="DanhMucBDS"tagprefix="uc"%><%@RegisterTagPrefix="webapp4U"Namespace="webapp4U.UI"%><tablecellspacing="0"cellpadding="0"width="180"border="0">
...</table>
in the file: C:\WebSite2010\WebMaster\Controls\MenuLeft.ascx<%@ControlLanguage="C#"AutoEventWireup="true"CodeFile="MenuLeft.ascx.cs"Inherits="MenuLeft"%><%@ImportNamespace="webapp4U"%><tablewidth="185px"border="0"cellpadding="0"cellspacing="0">
...</table>

How I can insert data into gridview without use data source???

$
0
0
Hi...

How I can insert data into gridview without use data source???

Trying to open a pdf file in a new Tab on Chrome browser - not happening

$
0
0
I have Get Method which I am expecting to open a pdf file in a new browser tab, but its not happening - below is the code
public void GetDoc(int id)
    {
        string fileInfo = "ID=[" + id + "] ";
        try
        {
            var file = this.DomainLogicUnitOfWork.UploadedDocumentManager.GetById(id);
            fileInfo = "FILENAME=[" + file.FileName + "]";

            Response.Clear();
            Response.ContentType = file.FileContentType;
            Response.AppendHeader("content-disposition", "attachment; filename=" + file.FileName);
            Response.OutputStream.Write(file.DocumentImage, 0, file.DocumentImage.Length);
            Response.Output.Flush();
            Response.End();
        }
        catch (Exception ex)
        {
            LogHandler.LogError(4617, "Error Downloading Document " + fileInfo, ex);
            throw ex;
        }
    }

My url is opening correctly: http://localhost:xcxcxcx/Upload/GetDoc?id=1088 and it gives a warning when click on the start of the browser address and one more thing is the Word and other documents are being downloaded fine - means they are working fine but problem is just with PDF files. Any suggestions or ideas -
thank you all friends.

Can i use timer control without use java sicrpt?

$
0
0
Hi every one...
Can i use timer control without use java sicrpt?

I want to use it directly by vb.net code only without anymore java sicrpt

Assigning data from sql database to a chart C# and entity framework

$
0
0
so I have the following code which I would like to adapt to take data straight from my sql database.

The code so far is:
@{
    Layout = "~/Views/Shared/_Layout.cshtml";

    var myChart = new Chart(width: 600, height: 400, theme: ChartTheme.Green)
.AddTitle("Product Life Cycle")
.AddSeries(
name: "Employee",
chartType: "Spline",
xValue: new[] { "2003", "2004", "2005", "2006", "2007", "2008", "2009", "20010", "2011", "2012", "2013", "2014", "2015", "2016", "2017", "2018", "2019", "2020", "2022", "2023", "2024", "2025", "2026" },
yValues: new[] { "5.40", "16.17", "109.46", "347.87", "791.62", "1865.88", "2899.26", "4083.32", "4693.27", "6442.52", "8053.77", "9388.84", "9964.89", "10776.18", "4931.34", "2582.54", "752.53", "150.83", "77.87", "31.21", "0.33", "0", "0" })
.Write();
}


I would like to assign xValue and yValue to a table example TBL_MYdata and with the fields ConDate and ConUnits. I am very new to C# and realy need to sort this soon. Many thanks for any help available

Scrape with htmlagilityapck question

$
0
0
I can seem to get to what I need. Below is a portion of my code. There happens to be 7 tables. My code is..
Dim tables As HtmlAgilityPack.HtmlNodeCollection = main.DocumentNode.SelectNodes("//table")
'
' Iterate all rows in the first table

Dim rows As HtmlAgilityPack.HtmlNodeCollection = Main.DocumentNode.SelectNodes("//table[@id='workorders']//tr")
<div class="panel panel-primary" style="margin-top: 10px"><div class="panel-heading">
        Work Opportunities Available</div><div class="panel-body"><p id="noWorkopportunities" class="text-info">
            No available work opportunities found.</p>

        
            I can get the table Id data but I need to get above the table and need <table id="workopportunities" class="table table-bordered"><tbody><tr><th>Project Name/Work Order</th><th>Date</th><th>Time</th><th>Location</th><th>Pay Rate</th><th>Pay Type</th><th>Tech</th><th>Actions</th></tr></tbody><tbody></tbody></table></div></div>

Name of the software that can package websites to install on smartphones: android and iphone ?

$
0
0
Suppose I have a website written in asp.net and the database is SQL Server, after I "Publish the web site" and I want to encode this code for smartphones (both android and Android operating systems) iphone) what software do I use? Note that I only packaged the code in "Publish web site" and the SQL Server data I still kept on the server (not packing the SQL Server data)

Text with Audio

$
0
0
Hello to everyone!

I need your support in coding that how should I add the speech audio to the paragraph texts/script in web-page by clicking on Read Button it should be played the audio and text should be appeared by type animation based on the audio.

Appreciate having your support in this regards!

How do I make my GetCasesButton_Click work?

$
0
0
I was asked to make a new web app based on a desktop client app which uses forms. My question today is, since some of the code I need help with is lengthy, is there a way to add code in my question by attaching a file?

How do I make my GetCasesButton_Click work?

$
0
0
The code below is from a desktop app that uses forms. I was asked to create a new web app to replace old desktop client app.
How can I change the following code to work in web app which does not have forms instead has aspx?
Please help.
private async void GetCasesButton_Click(object sender, EventArgs e)
       {
           if (CaseNumbersTextBox.Text.Length < 1)
           {
               MessageBox.Show("Casenumber textbox cannot be empty.", "Search Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
               return;
           }
           ComboboxItem requestorItem = new ComboboxItem();
           requestorItem = (ComboboxItem)RequestorComboBox.SelectedItem;
           ComboboxItem reasonItem = new ComboboxItem();
           reasonItem = (ComboboxItem)ReasonComboBox.SelectedItem;
           if (requestorItem.Value < 1)
           {
               MessageBox.Show("Please select a Requestor.", "Search Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
               return;
           }
           if (reasonItem.Value < 1)
           {
               MessageBox.Show("Please select a Reason.", "Search Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
               return;
           }
           string userEnteredCaseNumbers = CaseNumbersTextBox.Text;
           userEnteredCaseNumbers = userEnteredCaseNumbers.Replace("\r", ",");
           userEnteredCaseNumbers = userEnteredCaseNumbers.Replace("\n", ",");
           while (userEnteredCaseNumbers.Contains(",,"))
               userEnteredCaseNumbers = userEnteredCaseNumbers.Replace(",,", ",");
           List<string> userEnteredCaseNumberList = new List<string>();
           userEnteredCaseNumberList = userEnteredCaseNumbers.Split(',').Where(x => x.Length > 0).ToList();
           userEnteredCaseNumberList = userEnteredCaseNumberList.Select(s => s.Trim()).ToList();
           try
           {
               int newBatchNumber = await CandidateCaseController.GetNextBatchNumber();
               foreach (string caseNumber in userEnteredCaseNumberList)
               {
                   EditCandidateCaseModel newCandidate = new EditCandidateCaseModel();
                   newCandidate.CaseNbr = caseNumber;
                   newCandidate.RequestorInfoID = requestorItem.Value;
                   newCandidate.ReasonID = reasonItem.Value;
                   newCandidate.BatchNumber = newBatchNumber;
                   newCandidate.EntryStaffUserName = this._loggedInUserName;
                   await CandidateCaseController.PostCandidate(newCandidate);
               }
               List<GetCandidateCaseModel> candidateList = await CandidateCaseController.GetAllCandidates();
               candidateList = candidateList.Where(x => x.BatchNumber == newBatchNumber).ToList();
               string candidateCasesString = string.Empty;
               Regex rgxDash = new Regex("[^a-zA-Z0-9 ,]");
               candidateCasesString = string.Join(",", candidateList.Select(p => p.CaseNbr.ToString()));
               candidateCasesString = rgxDash.Replace(candidateCasesString, "").ToString();
               //Get MNCIS info on cases candidateCasesString
               List<string> smallEnoughStrings = new List<string>();
               while (candidateCasesString.Length > 0)
               {
                   int sendLength = 200;
                   bool isLastString = false;
                   if (candidateCasesString.Length < sendLength)
                   {
                       sendLength = candidateCasesString.Length;
                       isLastString = true;
                   }
                   string smallChunk = candidateCasesString.Substring(0, sendLength);
                   if (!isLastString)
                   {
                       int lastComma = smallChunk.LastIndexOf(',');
                       smallChunk = smallChunk.Substring(0, lastComma);
                       candidateCasesString = candidateCasesString.Remove(0, lastComma);
                       if (candidateCasesString[0] == ',')
                           candidateCasesString = candidateCasesString.Remove(0, 1);
                   }
                   else
                       candidateCasesString = candidateCasesString.Remove(0, sendLength);
                   smallEnoughStrings.Add(smallChunk);
               }
               List<AcceptCaseNumbersModel> mncisDetailList = new List<AcceptCaseNumbersModel>();
               List<AcceptCaseNumbersModel> smallEnoughMncisDetailList = new List<AcceptCaseNumbersModel>();
               foreach (string smallEnoughString in smallEnoughStrings)
               {
                   smallEnoughMncisDetailList = await FTACaseReset.Controllers.JusticeController.GetAllAcceptCaseNumbers(smallEnoughString);
                   mncisDetailList.AddRange(smallEnoughMncisDetailList);
               }
               //Parse data from MNCIS and add it to Candidate table
               //use candidateList to pull records out of mncisDetailList then update CandidateCase table
               foreach (GetCandidateCaseModel candidateCase in candidateList)
               {
                   string caseNbrWODash = rgxDash.Replace(candidateCase.CaseNbr, "").ToString();
                   AcceptCaseNumbersModel mncisDetail = mncisDetailList.Where(x => x.CaseNbrSrch.ToLower() == caseNbrWODash.ToLower()).FirstOrDefault();
                   if (mncisDetail != null)
                   {
                       //if it found a mncis record then edit Candidate details with MNCIS data
                       candidateCase.FirstPenalty = mncisDetail.FirstPenaltyFlag == 1 ? true : false;
                       candidateCase.SecondPenalty = mncisDetail.SecondPenaltyFlag == 1 ? true : false;
                       if (candidateCase.CaseNbr.ToLower().Contains("vb") == false)
                           candidateCase.RejectionReason = await FTACaseReset.Controllers.RejectionController.GetRejectionByDescription(Enumerations.Rejections.No_Records_To_Reset.ToString().Replace("_", " "));
                       else if (candidateCase.FirstPenalty == false && candidateCase.SecondPenalty == false)
                           candidateCase.RejectionReason = await FTACaseReset.Controllers.RejectionController.GetRejectionByDescription(Enumerations.Rejections.No_Records_To_Reset.ToString().Replace("_", " "));
                       if (candidateCase.RejectionReason == null)
                           candidateCase.RejectionReason = await FTACaseReset.Controllers.RejectionController.GetRejectionByDescription(Enumerations.Rejections.Valid.ToString());
                       candidateCase.Title = mncisDetail.Style;
                       await FTACaseReset.Controllers.CandidateCaseController.PutCandidate(candidateCase);
                   }
                   else
                   {
                       //if it didn't find a mncis record then change the rejection code on the Candidate
                       candidateCase.RejectionReason = await FTACaseReset.Controllers.RejectionController.GetRejectionByDescription(Enumerations.Rejections.Invalid_Case_Number.ToString().Replace("_", " "));
                       await FTACaseReset.Controllers.CandidateCaseController.PutCandidate(candidateCase);
                   }
               }
               GetCasesProgressBar.PerformStep();
               this.ClearForm();
               //Populate Results
               ValidTabPage.Controls.Clear();
               InvalidTabPage.Controls.Clear();
               ValidTabPage.Text = "Valid Cases";
               InvalidTabPage.Text = "Invalid Cases";
               //Repopulate Batch ComboBox
               this.PopulateBatchComboBox();
               List<GetCandidateCaseModel> thisBatchCasesList = new List<GetCandidateCaseModel>();
               thisBatchCasesList = await Controllers.CandidateCaseController.GetCandidateByBatchID(newBatchNumber);
               if (thisBatchCasesList.Count > 0)
                   this.EmailButton.Enabled = true;
               else
               {
                   this.EmailButton.Enabled = false;
                   return;
               }
               this.PopulateTabs(thisBatchCasesList, true);
               this.GetCasesPanel.Visible = false;
               this.UpdateExistingPanel.Visible = true;
               ComboboxItem batchItem = new ComboboxItem(thisBatchCasesList[0].BatchNumber);
               SelectBatch(batchItem);
               ComboboxItem requestorUpdateItem = new ComboboxItem(thisBatchCasesList[0].RequestorInfo);
               SelectRequestorUpdate(requestorUpdateItem);
               ComboboxItem reasonUpdateItem = new ComboboxItem(thisBatchCasesList[0].Reason);
               SelectReasonUpdate(reasonUpdateItem);
           }
           catch (Exception ex)
           {
               string errorMsg = string.Format("An error has occured in {0}. \nException:\n{1}", "GetCasesButton_Click()", ex.Message);
               MessageBox.Show(errorMsg, "Application Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
           }
       }

How to I make EmailButton_Click work?

$
0
0
My code for EmailButton_Click is not working. I am getting an error System.Net.Mail.SmtpException: 'SSL must not be enabled for pickup-directory delivery methods.' so email is not sent.

How can I fix this?

Here is the code
protectedvoid EmailButton_Click(object sender, EventArgs e)
        {//get selected emailstring requestor = RequestorDropDownList.SelectedValue.ToString();//string message = "The following records have been prepped for processing.  Valid cases will be processed.{0}{1}{2}";string message = "The following records have been prepped for processing.  Valid cases will be processed.";if (requestor.Length >0)
                message = string.Format(message);using (MailMessage mailMessage = new MailMessage())
                {
                    mailMessage.From = new MailAddress("NoReply_FTA@courts.state.mn.us");//MailAddress to = new MailAddress(requestorEmail);
                    MailAddress to = new MailAddress("okaymy1112@gmail.com");
                    mailMessage.To.Add(to);string ccEmailAddress = "okaymy1112@mail.com";if (ccEmailAddress.Length >0)
                    {
                        MailAddress ccto = new MailAddress(ccEmailAddress);
                        mailMessage.CC.Add(ccto);
                    }

                    mailMessage.Subject = "FTA Case Reset Notice";
                    mailMessage.Body = message;
                    mailMessage.IsBodyHtml = true;

                    SmtpClient smtpClient = new SmtpClient();
                    smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                    smtpClient.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
                    smtpClient.PickupDirectoryLocation = @"c:\smtp";
                    smtpClient.EnableSsl = true;
                    smtpClient.UseDefaultCredentials = true;
                    smtpClient.Timeout = 60000;

                    smtpClient.Send(mailMessage);//Error occurs on this line

                    ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('An email has been sent to '" + requestorName + "');", true);
        }

How do you have a DropDownList populated without default selected item?

$
0
0
I have a RequestorDropDownList which is populated with a list of names from a GetRequestorInfoModel.
I need help to make a change so that when this list is populated, the first name is not automatically selected until a user selects it.
How do I do this based on my code below?


ASP code for the dropdownlist
<asp:DropDownList ID="RequestorDropDownList" runat="server" Font-Size="8.25pt"
     Height="20px" ToolTip="Requestor" Width="160px" SelectMethod="GetRequestorEmail"
     DataTextField="DisplayName" DataValueField="Email"
     OnSelectedIndexChanged="RequestorDropDownList_SelectedIndexChanged"></asp:DropDownList>


Code behind that is populating the dropdownlist
#region Requestor dropdownlistpublicasync Task<IEnumerable<GetRequestorInfoModel>> GetRequestorEmail()
{                             try
   {var requestors = await FTACaseReseting.Controllers.RequestorInfoController.GetAllRequestorInfoes();//Show first name as selectedreturn requestors.OrderBy(x => x.DisplayName);
   }catch (Exception ex)
   {string errorMsg = string.Format("An error has occured in {0}. \nException:\n{1}", "PopulateRequestorComboBox()", ex.Message);
      Response.Write("<script>alert(" + HttpUtility.JavaScriptStringEncode(errorMsg, true) + ")</script>");return Enumerable.Empty<GetRequestorInfoModel>();
   }
}#endregion


Here is code for RequestorDropDownList_SelectedIndexChanged
protectedvoid RequestorDropDownList_SelectedIndexChanged(object sender, EventArgs e)
 {if (RequestorDropDownList.SelectedItem ==null)
     {
        ListItem requestorItem = new ListItem();
        requestorItem = (ListItem)RequestorDropDownList.SelectedItem;if (requestorItem.Text.Length <0)
        {string selectRequestor = "Please select a Requestor.";
           ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + selectRequestor + "');", true);
         }this.EmailButton.Enabled = false;
         RequestorDropDownList.SelectedValue = RequestorDropDownList.SelectedItem.Value;
     }

}

Why can't I login to the web even though the User and password are correct ?

$
0
0
I am writing a small example of Login webSite, there are two types of accounts and passwords, one is an account and password is stored in the Web.config file and the other two accounts and passwords are saved in SQL Server database, My problem is that in form 1, when logging in it opens Logon_Redirect.aspx file but cannot access, the following is my code
I am debugging and running to the code where this opens the Logon_Redirect.aspx file but nothing, but when I log in with another account and password (the user password of SQL Server) log in well.
In file Web.config<appSettings>
...<add key="SmtpServer"value="localhost"/><add key="EmailWebmaster"value="admin"/><add key="Password"value="123"/>
...</appSettings>

 In file Logon_Redirect.aspx
... 
<html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"><title>Untitled Page</title></head><body><form id="form1" runat="server"><div></div></form></body></html>

In file Logon_Redirect.aspx.cs
... 
publicpartialclass Logon_Redirect : System.Web.UI.Page
{protectedvoid Page_Load(object sender, EventArgs e)
    {// kiem tra va Redirect toi trang can thietif (Page.User.IsInRole(Globals.Settings.AppRoles.KhachHang))
          Response.Redirect(Globals.ApplicationPath);elseif (Page.User.IsInRole(Globals.Settings.AppRoles.Admin))
          Response.Redirect(Globals.ApplicationPath + "WebMaster/Contacts/Contact.aspx");
     }
}

In file Logon.aspx.cs  
protectedvoid btLogon_Click(object sender, EventArgs e)
{//I can't Login User/Pass in file Web.config, check User: admin and Pass: 123if (Membership.ValidateUser(txtEmail.Text, txtPassword.Text))
     {            if (Request.QueryString["ReturnUrl"] != null)
     {
      FormsAuthentication.RedirectFromLoginPage(txtEmail.Text, false);
     }else
    {
          FormsAuthentication.SetAuthCookie(txtEmail.Text, false);
          Session["username"] = txtEmail.Text.Trim();
          Response.Redirect(Globals.ApplicationPath + "Logon_Redirect.aspx");//I am debugging and running to the code here and opens the Logon_Redirect.aspx file but nothing 
    }
    }else//Login SQL Server very good
   {// check User/pass other on SQL Serverif (webapp4U.BOL.User.CheckUserName(txtEmail.Text) && txtPassword.Text ==             ConfigurationManager.AppSettings["Password"].ToString())
          {
                 FormsAuthentication.SetAuthCookie(txtEmail.Text, false);
                 Session["username"] = txtEmail.Text.Trim();
                 Response.Redirect(Globals.ApplicationPath + "Logon_Redirect.aspx");
         }else
                lblMsg.Text = ResourceManager.GetString("Logon_False");
     }
}
Viewing all 3938 articles
Browse latest View live