I'm trying to connect to Web service hosted over Https. I have this method:

ServicePointManager.ServerCertificateValidationCallback = delegate(object sender1, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, SslPolicyErrors sslPolicyErrors) 
{                    
     if (sslPolicyErrors != SslPolicyErrors.None)
     {
          return false;
     }                   
     return true;
}; 

The service is being called fine since the SSLPolicyErrors value is 'None' and hence the method returns true. But when I comment out this code, the call is throwing the error:

Message:System.ServiceModel.Security.SecurityNegotiationException: Could not establish secure channel for SSL/TLS with authority '******************'. ---> System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel. at System.Net.HttpWebRequest.GetResponse() at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)

I'm not sure what code I can write to detect this. I really need to catch all possible errors with the security certificate. Also, when I open the URL directly in IE and try to see details about the certificate, I cannot see any problems with the certificate and it looks valid.

Thanks for help.

I am facing issue with regards to treeview control. I have checkbox enabled for nodes of treeview control. It is working fine and showing properly.But when I deploy same to IIS, checkbox is not visible there. It is not rendered at all. Below is the treeview :

<asp:TreeView id="TreeTest"
        EnableClientScript="true"
        PopulateNodesFromClient="true"  
        ExpandDepth="0" 
        ShowLines="true" 
        ShowExpandCollapse="true"
        ShowCheckBoxes="Root"
        OnTreeNodePopulate="TreeTest_TreeNodePopulate"
        Width="1px"
        runat="server">

    <Nodes>
    </Nodes>

  </asp:TreeView> 

This code is working fine on my local machine. But not when deployed on IIS. Everything works except showing checkboxes for root nodes.

I need to display images on an ASP.NET website, using C# and SQL Server.

Currently, I am storing the images in a project folder, and storing/retrieving the image path in the database.

I tried to store the image in bits in the database table at the beginning but I was having trouble.

Is it better to store the image in bits rather than in a project folder? (Regarding storage space required, etc.)

Here's the relationship I am trying to create. I have a entity M and N. M has a collection of N, and N may be a parent to M m1 -> n1 -> m2

Below are the details of my entities and relationships, but The actual problem is

Problem

that all of the data is saved EXCEPT for the relationship between m2 and n1. Any tips on where I'm going wrong with the relationships or seeding of the data? Thank you.


Entities

[Table("M")]
public class M {

    public M() 
    {
        this.nCollection = new HashSet<N>();
    }

    [Key]
    public int ID {get;set;}

    //The optional parent N
    public virtual N parent {get; set;}
    public virtual int parentID {get;set;}

    //The collection of nodes
    public virtual ICollection<N> nCollection {get;set;}
}

[Table("N")]
public class N
{
    [Key]
    public int ID {get;set;}

    // The parent of N
    public virtual M parentM {get;set;}
    public virtual int parentMID {get;set;}

    // The optional child of N
    public virtual M childM {get; set;}
    public virtual int childMID {get; set;}
}

Context and Relationships

public class MNContext :DbContext 
{
    // modelBuilder is a DbModelBuilder
    public virtual DbSet<M> Ms { get; set; }
    public virtual DbSet<N> Ns { get; set; }
    .
    .
    .
    // Relationships
    modelBuilder.Entity<M>()
            .HasMany(m => m.nCollection)
            .WithRequired(n => n.parent)
            .HasForeignKey(n => n.parentID)
            .WillCascadeOnDelete(false);

    modelBuilder.Entity<M>()
            .HasOptional(m => m.parentN)
            .WithOptionalPrincipal(n => n.childM)
            .WillCascadeOnDelete(false);

    modelBuilder.Entity<N>()
            .HasRequired(n => n.parentM)
            .WithMany(pm => pm.nCollection)
            .WillCascadeOnDelete(false);

    modelBuilder.Entity<N>()
            .HasOptional(n => n.childM)
            .WithOptionalDependent(cM => cM.parentM);
}   

Seed

// Where context is MNContext

M m1 = new M();
N n1 = new N();
m1.nCollection.Add(n1);

M m2 = new M();

// Insert m1 into the datacontext
M persistedM1 = context.Ms.Add(m1);
// Save
context.SaveChanges();
// Pull the persisted N
N persistedN1 = context.N.FirstOrDefault();
// Set the relationship to m2
persistedN1.childM = m2;
m2.parentN = persistedN1;

//Add it back
context.N.Attach(persistedN1);
context.M.Add(m2);

context.SaveChanges();

I Have an Asp.Net web Application and at some point the user authenticate himself but i cannot track the end point to be detected by my OAuthAuthorizationServer. Here's my ConfigureOAuthTokenGeneration code :

private void ConfigureOAuthTokenGeneration(IAppBuilder app)
        {
            // Configure the db context and user manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

            //app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                //For Dev enviroment only (on production should be AllowInsecureHttp = false)
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/oauth/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new CustomOAuthProvider(),
                AccessTokenFormat = new CustomJwtFormat("http://localhost:55555/")
            };

            // OAuth 2.0 Bearer Access Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
        }

here's my javascript making the request to the server:

function Authenticate() {
    var self = {};

    Object.defineProperty(self, '_loginKey', {
        'get': function () { return "Key_Login" }
    });

    Object.defineProperty(self, 'storage', {
        'value': (function () {
            function getByKey(key) {
                return sessionStorage.getItem(key);
            }

            function setByKey(key, data) {
                sessionStorage.setItem(key, data);
            }

            function destroyByKey(key) {
                sessionStorage.removeItem(key);
            }
            return { set: setByKey, get: getByKey, destroy: destroyByKey };
        })()
    });


    function login(data,fnCallBack) {
        $.ajax({
            type: 'POST',
            cache: false,
            url: ConfirmationApplication.baseURL + '/oauth/token',
            data: data
        }).done(function (response) {
            sessionStorage.setItem(self._loginKey,response.access_token);
            fnCallBack(response);

        }).fail(function (response) {
            fnCallBack(response);
        });
    }

    function logout() {

    }

    function serialize(e) {
        return {
            grant_type: 'password',
            UserName: e.Email.value,
            Password: e.Password.value,
            __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val()
        };
    }

    function getToken() {
        var token = self.storage.get(self._loginKey);
        return token;
    }

    return {
        'serialize': serialize,
        'login': login,
        'logout': logout,
        'getToken': getToken
    }

}

Here's the error I get:

enter image description here

Currently I am using Unobtrusive validation on my site. So right now, when a form element is not valid, I display the error message (Configured from an attribute on the server) . What I want to do now is to also change the label and border of the text box so they go red when a form element is invalid, or green when valid.

Are there any extra attributes I can add to make this happen, or do I need to create my own validators that inherit from the standard ones, but add in the extra client side functionality?

Before I asked this question I looked into all the suggest made by SO and took a look into this to (What is a NullReferenceException, and how do I fix it?)

I have an function in my Usercontrol

User control:

Function MedewerkerNaam(Medewerker as integer, Meisjesnaam as boolean) 
    MedewerkerNaam = "Onbekend"
    If IIsNumeric(Medewerker) = True Then
        rs = Server.CreateObject("ADODB.Recordset")
        rs.open ("SELECT Medewerkers.Medewerkers_Voornaams_AchternaamVoorvoegsel, Medewerkers.Medewerkers_Achternaam, Medewerkers.Medewerkers_MeisjesnaamVoorvoegsel, Medewerkers.Medewerkers_Meisjesnaam FROM Medewerkers WHERE Medewerkers.Medewerkers_ID = 0" & int(Medewerker), strCon)
        If NOT rs.EOF Then
            MedewerkerNaam = rs("Medewerkers_Voornaam") & " " & rs("Medewerkers_AchternaamVoorvoegsel") & " " & rs("Medewerkers_Achternaam")
            If Meisjesnaam = True AND rs("Medewerkers_Meisjesnaam") <> "" Then MedewerkerNaam = MedewerkerNaam & " - " & rs("Medewerkers_MeisjesnaamVoorvoegsel") & " " & rs("Medewerkers_Meisjesnaam")
        End If
        rs.Close
         rs = nothing
    End If
End Function

In my webform.aspx:

    <%dim deneme as new basic%>

 this is a testttt : <%=deneme.MedewerkerNaam(10,false)%>

Why do I get the error:

system.nullreferenceexception object reference not set to an instance of an object

Sorry if it's something stupid it's just that I don't get it And how can I make sure I won't get this problem again ?

In my Edit Action I have this:

ViewBag.DropDownList2= new SelectList(ClassName.lstItems(), "Value", "Text", object.ItemID);

This is different from my Create Action, whereas I just have this:

ViewBag.DropDownList2= ClassName.lstItems();

The reason for that is because I need to keep the value that user originally picked when creating/editing the record.

ClassName.lstItems()

    public static List<SelectListItem> lstItems()
    {
        List<SelectListItem> lstAllItems = new List<SelectListItem>();

        using (var context = new ConnectionString())
        {
            List<Table1> lstTable1Items =
                context.Table1.Where(x => x.deleted == false).ToList();

            var groups =
                lstTable1Items .OrderBy(x => x.Table2.Property1).GroupBy(x => x.Table2.Property1);

            foreach (var group in groups)
            {
                var slg = new SelectListGroup() {Name = group.Key};
                foreach (Table1 table1Item in group)
                {
                    SelectListItem item = new SelectListItem() {Text = table1Item .PropertyText, Value = table1Item .ID.ToString(), Group = slg};
                    lstAllItems.Add(item);
                }
            }
        }

        return lstAllItems;
    }

Obviously I want a dropdownlist that is grouped. But in my Edit Action, it is not grouped. How do I keep my dropdownlist grouped while also having the original value as the selected value on page load?

Razor

    <div class="form-group">
        @Html.LabelFor(model => model.itemID, htmlAttributes: new { @class = "control-label col-md-4" })
        <div class="col-md-8">
            @Html.DropDownList("DropDownList2", null, "Select Item", htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.itemID, "", new { @class = "text-danger" })
        </div>
    </div>

I have a billing system that is supposed to send a gridview of the total cost and the item that was purchased.

I would like to export the gridview to pdf and I have done it through this.

  int columnsCount = GridView2.HeaderRow.Cells.Count;

        PdfPTable pdfTable = new PdfPTable(columnsCount);

        foreach (TableCell gridViewHeaderCell in GridView2.HeaderRow.Cells)
        {

            Font font = new Font();
            font.Color = new BaseColor(GridView2.HeaderStyle.ForeColor);
            PdfPCell pdfCell = new PdfPCell(new Phrase(gridViewHeaderCell.Text, font));
            pdfCell.BackgroundColor = new BaseColor(GridView2.HeaderStyle.BackColor);
            pdfTable.AddCell(pdfCell.Phrase.Content.ToString());
        }

        foreach (GridViewRow gridViewRow in GridView2.Rows)
        {
            if (gridViewRow.RowType == DataControlRowType.DataRow)
            {

                foreach (TableCell gridViewCell in gridViewRow.Cells)
                {
                    Font font = new Font();
                    font.Color = new BaseColor(GridView2.RowStyle.ForeColor);

                    PdfPCell pdfCell = new PdfPCell(new Phrase(gridViewCell.Text, font));

                    pdfCell.BackgroundColor = new BaseColor(GridView2.RowStyle.BackColor);

                    pdfTable.AddCell(pdfCell.Phrase.Content.ToString());
                }
            }
        }





        // Create the PDF document specifying page size and margins
        Document pdfDocument = new Document(PageSize.A4, 10f, 10f, 10f, 10f);

        PdfWriter.GetInstance(pdfDocument, Response.OutputStream);

        pdfDocument.Open();
        pdfDocument.Add(pdfTable);
        pdfDocument.Close();

        Response.ContentType = "application/pdf";
        Response.AppendHeader("content-disposition",
            "attachment;filename=Invoice_" + tbBillID.Text.ToString() + ".pdf");
        Response.Write(pdfDocument);
        Response.Flush();
        Response.End();

and the codes to send email is

  System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
        mail.To.Add("sendto@gmail.com");
        mail.From = new MailAddress("sendto@gmail.com", "Invoice", System.Text.Encoding.UTF8);
        mail.Subject = "subject";
        mail.SubjectEncoding = System.Text.Encoding.UTF8;
        mail.Body = "message body";
        mail.BodyEncoding = System.Text.Encoding.UTF8;
        mail.IsBodyHtml = true;


        System.Net.Mail.Attachment attachment;
        attachment = new System.Net.Mail.Attachment(Server.MapPath("~/Invoice_" +tbBillID.Text + ".pdf"));
        mail.Attachments.Add(attachment);

        mail.Priority = MailPriority.High;
        SmtpClient client = new SmtpClient();
        client.Credentials = new System.Net.NetworkCredential("email@gmail.com", "pw");
        client.Port = 587;
        client.Host = "smtp.gmail.com";
        client.EnableSsl = true;

        client.Send(mail);

Generating of PDF and sending of the email is done with one button click. I can save the pdf but it does not send the email. Any help would be appreciated.

Hi I have a certificate with a private key in the User1's Current User Store on windows . But now the thing is I want to log in as User2 and still access USer1's store for the certificate certificate's private key.

Ofcourse i would provide the user name and password for User1. Is there a way to do this cross user certificate loading in C#. I would not mind if I could get the certificate from User1 while logged in as User1 but have another password protection layer before accessing the certificate in C#.

//Want to be able to do this only after entering a passphrase    
var store = new X509Store(storeName, storeLocation);
                store.Open(OpenFlags.ReadOnly);
                var certCollection = store.Certificates;
                var myCertInStore =
                    certCollection.Cast<X509Certificate2>()
                        .FirstOrDefault(c => MyX509NameParser.GetCn(c.Subject) == MyX509NameParser.GetCn(subject));
                store.Close();
                var storeKey = (RSACryptoServiceProvider)myCertInStore?.PrivateKey;

The reason for the above is that my c# code will run in User1 and use certificates in User1's store to sign data. But User 1 is too easily accessible so if i had the certificate in another protected user that will be good. or if there is a way to add a password protection layer to the certificate so that i can only load it in my code with a password then that is okay too.

I want to explain my summary code flow.

I have Session["MainRule"] and I call a method to get selected item from this =>

var temprule=get_temp_rule_byid(Session["MainRule"],id);

I put this temprule to Session["temprule"].

Because when I update Session["temprule"],I don't want to update Main Session Session["MainRule"].

But When I was doing something update in Session["temprule"]. why Session["MainRule"] value automatically change?

Update

var temprule= RulesRepository.get_temp_rule_byid(Session["MainRule"], id);


public static RuleViewModel get_temp_rule_byid(object rulesFromSession, string id)
        {
            RuleViewModel ruleViewModel = null;
            var temp = rulesFromSession as Dictionary<string, RuleViewModel>;
            if (temp?.TryGetValue(id, out ruleViewModel) == true)
            {
                return ruleViewModel;
            }

            return null;
        }

I'm using Asp.Net MVC 5 (Code First), i'm trying to add a new user in AspNetUsers table manually using SQL Management,enter image description here

when i want to login with the new user it shows Invalid login attempt. thanks

I have a dictionary like below

Dictionary<Tuple<int, int>, bool> sampleDict= new Dictionary<Tuple<int, int>, bool>();

which I added in Session

if (!IsPostBack)
{
   HttpContext.Current.Session.Add("SessionsampleDict", sampleDict);
}

NOw I need to add values into Dictionary, so my code goes like.

sampleDict.Add(DictKey, true);

NOw issue is when I am coming back to my page using postback, I am loosing all my data in sampleDict.

What I am doing wrong here ? How to add values of dictionary on session ?

I wonder why my razor page output my html/css as string ? Example, the output in the browser is 1200 [span style=color:red]*[/span]

It suppose to be

1,200.00 *

My code in my vbhtml razor page is below


            result = 1,200 & "[span style=color:red]*[/span]"

I purposely use [] here instead of <> because if I use <> , my code is translated as html automatically.

I have configured SQL server to save ASP .net session state. And it was working fine in my local system but after hosting the application in web server, session returns null once it is created.

When i looked into the table. CreatedDate and Lockdate is same.

Note : i moved to Sql server session state because normal Session variables and cookies are not working in server so i am trying to save session variables with alternate ways.

I need to send attachment with email. I used following code which gives below exceptions.

System.NullReferenceException: Object variable or With block variable not set. at Microsoft.VisualBasic.CompilerServices.Symbols.Container..ctor(Object Instance) at Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet(Object Instance, Type Type, String MemberName, Object[] Arguments, String[] ArgumentNames, Type[] TypeArguments, Boolean[] CopyBack) at dynamicPage.makeCustom_Click(Object sender, EventArgs e)

try {
    generateRequestID();
    MailMessage mail = new MailMessage();
    SmtpClient SmtpServer = new SmtpClient();
    mail.To.Add("email.text");
    mail.From = new MailAddress(personEmail.Text);
    mail.Subject = "IDFC Bank BrandStore Product Customization Request";
    mail.Body = "Request ID : " + Session["requestID"].ToString + "<br>Name : " + personName.Text + "<br>Contact : " + personContact.Text + "<br>Email : " + personEmail.Text + "<br>Department : " + Department.Text + "<br>Quantity : " + quantity.Text + "<br>Description : " + customDescription.Text + "<br>Timeline : " + customTimeline.Text + "<br>Product Link : " + Request.Url.AbsoluteUri + "";
    if (artworkContainer.HasFile) {
        string FileName = Path.GetFileName(artworkContainer.PostedFile.FileName);
        mail.Attachments.Add(new Attachment(artworkContainer.PostedFile.InputStream, FileName));
    }
    mail.IsBodyHtml = true;
    SmtpServer.Port = 25;
    SmtpServer.Credentials = new System.Net.NetworkCredential("you@yourdomain.com", "mypassword");
    SmtpServer.Host = "relay-hosting.secureserver.net";
    SmtpServer.EnableSsl = false;
    SmtpServer.Send(mail);
    Response.Redirect("/customization-request-sent");
} catch (Exception ex) {
    Response.Write(ex);
}

I have a drop-down menu that selects user roles from Startup.cs file.

ViewBag.Name = new SelectList(context.Roles.Where(u => !u.Name.Contains("Admin")).ToList(), "Name", "Name");

The above code excludes the Admin role. I also want to exclude the Customer role. I am using the code below to do it. It doesn't give me any errors, but it results with all the roles being included in the drop-down menu:

ViewBag.Name = new SelectList(context.Roles.Where(u => !u.Name.Contains("Admin") || !u.Name.Contains("Customer")).ToList(), "Name", "Name");

How can I exclude more than one item from the SelectList?

I would like to replace js windows by bootstrap popover in few pages but I have two issues and I don't find any solutions.

First, if I click on the button to display the popover, required fields are fired directly. Even if I fill in it the message "xx is a required field" stay displayed.

Second, when I try to save my data. Every fields contain an extra character ",". So if I put 10 in the price field in code behind the value of my field is "10,"

Thanks for your help :)

My code:

<asp:Button ID="btnAdd" runat="server" Text="add" CssClass="btn btn-info"data-toggle="popover" data-placement="top" title="add something" ValidationGroup="vgAdd" />

<div id="testBox" class="hide">
   <asp:ValidationSummary ID="vsTest" runat="server" ValidationGroup="vgAdd" DisplayMode="BulletList" ShowMessageBox="false" ShowSummary="false" />
                                        <div class="row">
                                            <div class="form-group col-sm-6">
                                                <asp:Label ID="lblPrice" runat="server" Text="price" AssociatedControlID="txtPrice" CssClass="control-label"></asp:Label>
                                                <div class="input-group">
                                                    <span class="input-group-addon">$</span>
                                                    <asp:TextBox ID="txtPrice" runat="server" CssClass="form-control" MaxLength="12"></asp:TextBox>
                                                </div>
                                                <asp:CompareValidator ID="cvPrice1" runat="server" Display="None" ValidationGroup="vgAdd" ControlToValidate="txtPrice"
                                                    ErrorMessage="price is invalid." ValueToCompare="0" Type="Double" Operator="GreaterThan"></asp:CompareValidator>
                                                <asp:CompareValidator ID="cvPrice" runat="server" Display="None" ValidationGroup="vgAdd" ControlToValidate="txtPrice"
                                                    Type="Double" Operator="DataTypeCheck" ErrorMessage="price is invalid."></asp:CompareValidator>
                                                <asp:RequiredFieldValidator runat="server" ID="RequiredFieldValidator1" ValidationGroup="vgAdd" ControlToValidate="txtPrice"
                                                    ErrorMessage="Default price is a required field." SetFocusOnError="True" Display="Dynamic" />
                                            </div>
                                            <div class="form-group col-sm-6">
                                                    <asp:Label ID="lblDesc" runat="server" Text="Description" AssociatedControlID="txtDesc" CssClass="control-label"></asp:Label>
                                                    <asp:TextBox ID="txtDesc" runat="server" CssClass="form-control" TextMode="MultiLine" MaxLength="255"></asp:TextBox>
                                                </div>
                                        </div>
                                        <div class="clearfix">
                                            <asp:Button ID="btnSave" runat="server" ValidationGroup="vgAdd" CausesValidation="true"
                                                CssClass="btn btn-primary pull-right"
                                                OnClick="btnSaveTest_Click" Text="Save" />
                                        </div>
                                    </div>

$("[data-toggle=popover]").popover({
        html: true,
        content: function () {
            return $('#testBox').html();
        }
    });

If my web.config has this section:

  <system.webServer>
    ...
    <modules>
      <!--<remove name="WebDAVModule" />-->
    </modules>

I get this error on a 500.19 level error screen:

This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set explicitly by a location tag with overrideMode="Deny" or the legacy allowOverride="false".

And if I comment it out the whole modules section:

  <system.webServer>
    ...
    <!--<modules>
      <remove name="WebDAVModule" />
    </modules>-->

I get a dialog that says:

Unable to start debugging on the web server. The web server could not find the requested resource.

The first error seems to indicate I'm overriding something in an applicationhost.config file (which isn't in the User/Documents or .vs location), but if I try to not override it by commenting it out, it says it needs it.

IIS Express can't seem to determine if this section can appear in my web.config or not.

Good day!

I can not even publish a standard initial MVC application with x64 configuration. When i set the value of “Enable 32-bit Applications” to False in IIS AppPool settings everything works well, but when i set the value of “Enable 32-bit Applications” to True i get an error. here's a screencast (sorry that the IIS have russian interface): http://www.screencast.com/t/Kf0mpM9uFa

what am I doing wrong?

Thanks in Advance.

I have already had a look at some of the answers on here and tried google as well. I am not sure whether the question has been answered and I simply don't understand it or if I am doing something differently to create a similar error.

Where I am at. I have been learning C# and MVC for a few months slowly by working through tutorials, trying things and then going back to find another tutorial to try to understand the intricacies of the system. So beginner is where I sit solidly. So if I seem a bit simple this is why.

I am currently working through the tutorial on ASP.NET CLick Here for MVC Music Store on creating a shopping cart application. I am up to creating the StoreManagerController which is the first controller to be created using EF with views. The tutorial is for an older version of VS than I am using, however, so far everything else I have been able to work through.

To date we have created our models, created a few views and controllers. All fine and dandy.

To eliminate any potential issues I have:

-Built the project - Cleaned the project - Commented out the connection string in the web config file - commented out the entity framework in the web config file

None of the above seem to be working for me...or I am doing them wrong.

The not helpful error is:

Error and Controller

Sorry this forum doesn't allow me to enclose code properly with the two images. Will post follow on with code.