Subscribe: Custom Server Controls
Added By: Feedage Forager Feedage Grade B rated
Language: English
cmd  code  convert  core  data  double  file  net core  net  new  return  string  text trim  text  time  timestamp  trim 
Rate this Feed
Rate this feedRate this feedRate this feedRate this feedRate this feed
Rate this feed 1 starRate this feed 2 starRate this feed 3 starRate this feed 4 starRate this feed 5 star

Comments (0)

Feed Details and Statistics Feed Statistics
Preview: Custom Server Controls

All Forums

All Forums

Last Build Date: Thu, 19 Oct 2017 11:43:20 -0700


Problems getting new DirectoryEntry prior to search of AD


Here is a sanitized version of the code I am trying to get working

The call in Main is to 

DirectoryEntry myLdapConnection = createDirectoryEntry();

static DirectoryEntry createDirectoryEntry()
// create and return new LDAP connection with desired settings

String myADSPath = "LDAPS://,DC=bozo,DC=clown,DC=com";
DirectoryEntry ldapConnection = new DirectoryEntry(myADSPath, @"", @"whatever12_Password", AuthenticationTypes.Secure);
return ldapConnection;

When I try to make the call for DirectoryEntry de =new DirectoryEntry(adsPath,username,
password,AuthenticationTypes.Secure) it returns a DirectoryEntry object, ldapConnection,
but many of the attributes in debugger for the value, ldapConnection, returned, show this type of thing:

'ldapConnection.AdsObject' threw an exception of type
'ldapConnection.ContainerObject' threw an exception of
type'ldapConnection.Guid' threw an exception of type
'ldapConnection.IsContainer' threw an exception of type

Same for Name, NativeObject, NativeGuid,Object Security....

Examining this object using VS2010....

Do anyone have any relevant references or advice on this problem and how to resolve it? (code snippets most welcome)

Very stange problem: The address wasn’t understood


I have a  hyperlink control that inside a GridView1. Its navigation URL is set to be C:\PdfDirectory\2014-0001-100.pdf . However, when I want click it, the file is not opened but instead a new tab opened with a message :The address wasn't understood. When I mouse over the hyperlink, it shows me the same path "C:\PdfDirectory\2014-0001-100.pdf". The file is available on the exact place and I can open it manually. So why I get this problem? Why it can't understand this local directory file?

The Hyperlink part of the aspx file is as following:



I will highly appreciate your help with thanks

Return Type to use in a method and launch attachment from the browser



I have a method that gets the file details and then I call that method in a WebAPI.  I want to launch a file in the browser when users click on a file image.  File could be .doc, xls, pdf etc so everything is dynamic.  I am having a hard time trying to understand how would I pass the file details to the WebAPI.

Here is the method:

public string GetFile(int fileId)
var listValues = GetFileList(fileId);
byte[] data = null;
string fileName = string.Empty;
string contentType = string.Empty;
for (var i = 0; i < listValues.Count; i++)
data = listValues[i].FileData;
fileName = listValues[i].FileName;
contentType = listValues[i].ContentType ;

return //Need to pass data, filename and contentType


Then in this WebAPI I would like to call the method listed above to use 3 file attributes(filename, bytes, contentType) to launch the attachment:

[HttpGet, Route("{fileId}/DLFile")]
public IHttpActionResult GetFile(int fileId)

var dFile = _Rep.GetFile(fileId)); // Received from the method above
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new ByteArrayContent(dFile.bytes);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentType = new MediaTypeHeaderValue(dFile.ConentType);
response.Content.Headers.ContentDisposition.FileName = dFile.FileName;

return Ok(response);


Is this is the right way to launch an attachment from a browser?


HasFlag in Unknown Enum


Hello Forum, 

I think I may have a bad design here, the problem is below - any suggestions would be a great help

I used to have code which did a check flag on a single enum - this was simple enough - did the binary values in the enum and it all all worked well

If Instance.HasFlag(PageType.AboutUs)

this works fine.

Now I have two possible Enums that are very different, but both have the name of 'AboutUs'. I have a way of knowing which enum to present in the code

      Dim Pages As Type = GetType(PageType)

So the now I am stuck. I can make a kind of EnumFactory to return the right Enum, and both with have the name 'AboutUs' - but I dont know if this is possible who how to write the code.

So the factory (if this is the right way to go) could return EnumA or EnumB both having a name of 'AboutUs' but not necessarily with the same flag value.

So if this is possible what do I put here - as the enum or the enum value is not known

If Instance.HasFlag(?????.AboutUs)

I used to do this by making my own custom flags classes - this worked well, but then I tryed to change to this, as moving forward it is less work and now am stuck on how to check for an unknown enum type..

I dont mind if any solution does not have intellisense as I know if it gets to this code it will have the flag as a possibility

Any help would be great and help me understand .NET a little bit more

Graham Mattingley

how to retrieve max date time record for each ID (oracle)


i have two column, 1st column store the "ID and date" format (IDXXX-YYYYMMDD) where IDXXX is the record ID and 2nd column store the time. how can i retrieve the record which is latest date and latest time for each ID in sql in oracle?

ID_DATE                           TIME 

ID001-20170930              1750

ID001-20170930               1830

ID001-20171001               1030

ID001-20171002               1230

ID002-20171101               1000

my expected result as below

ID001-2017002                 1230

ID002-20171101                1000

Get string between 2 strings in a list and use the values in a Dropdownlist


So I have a list of 'log' from database as below :

var listLog = dc.log
                .Where(o => o.descricao.Contains("Document was sent to sector "))
                .Select(s => new 
                    agrupamento_id = s.agrupamento_id,
                    created = s.created,
                    descricao = s.descricao,
                    evento_id = s.evento_id,
                    eventos = s.eventos,
                    id =,
                    tipo = s.tipo,
                    usuario_id = s.usuario_id,
                    usuarios = s.usuarios,
                    sector = ?????,
subsector = ??????
}) .ToList(); gvEncaminhamentos.DataSource = listaEncaminhamentos; gvEncaminhamentos.DataBind();

Rows in database in column description are like:

Document was sent to sector XXXXXXXXXX and subsector xxxxxxxxxxxxxxxx

How can I create those 2 new columns using LINQ or even ADO.NET ?


Leading Zero for Month


This is probably a simple request

DECLARE @JobDay AS CHAR (8) = CONVERT (CHAR (4), DATEPART(YEAR, @DateTimeStart)) + CONVERT (CHAR (2), DATEPART(MONTH, @DateTimeStart)) + CONVERT (CHAR (2), DATEPART(DAY, @DateTimeStart));

It returns 2017 218

what i would like is 20170218

Unknown username or bad password encountered in web application


My web application is using c#. The login page connects to active directory. The parent and child domain controller. The problem only encountered by users acessing the child domain controller. An error displayed is "unknown username or bad

The unexplained part is sometimes the login page is working okay. Sometimes its not.

I hope someone can help me on this or at least give me an idea why this happening.

PE format difference: .NET vs .NET Core


The idea of the code below is to extract build timestamp from PE-compatible EXE or DLL. The code works perfectly for .NET binaries (for >6 years by now, btw) and reports rubbish for .NET Core ones. For a freshly built .NET (not Core) assembly it (correctly) reports "Mon Oct  9 13:30:14 2017", for a freshly built .NET Core  v.2 assembly it reports "Tue Mar 29 05:14:00 2061" (?). It means that .NET Core assemblies do not follow PE file format _exactly_. In .NET Core case the timestamp field of IMAGE_FILE_HEADER does not contain "The low 32 bits of the number of seconds since 00:00 January 1, 1970 (a C run-time time_t value), that indicates when the file was created" (quote from pecoff.docx) as it should. I received an answer: "this is really a change by the roslyn compilers. see:".  Three questions in this regard: (1) Why would roslyn change PE format (that is, if it did, see next question)? (2) If roslyn did change PE format, why does the change show itself in .NET Core builds ONLY, but not in .NET builds (VS 2015 certainly uses roslyn for both .NET Core and .NET builds)? Are there two flavors of roslyn (a joke)? (3) Ok, let it be, but where _is_ the build timestamp in a binary built in .NET Core 2.0 environment? // per "Microsoft PE and COFF Specification" pecoff_v8.docx at (as of 06/18/11) // // or, as of Oct 9th, 2017, pecoff.docx available at // const long c_offsetOfOffsetOfPE = 0x3c; // per section 2 of pecoff_v8.docx const Int32 c_PE00 = 0x00004550; // = 50 45 00 00 = PE\0\0 /// /// Extracts build time from a PE executable (EXE or DLL) per "Microsoft PE and COFF Specification" pecoff_v8.docx /// static DateTime GetExeOrDll_EST_TimeStampDT() { DateTime timeStamp = new DateTime(); try { // This works OK for .NET but produces invalid timestamp for .NET Core assemblies(why ?) string path = MyAssembly.Location; using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (BinaryReader br = new BinaryReader(fs)) { fs.Position = c_offsetOfOffsetOfPE; byte OffsetOfPE = br.ReadByte(); // = 0x80 fs.Position = OffsetOfPE; Int32 PE00 = br.ReadInt32(); // = 0x00004550 [ = 50 45 00 00 = PE\0\0 ] if (PE00 != c_PE00) { return timeStamp; } // invalid file format, return "best guess" (last write time) fs.Position = OffsetOfPE + 8; UInt32 timeStampLower32Bits = br.ReadUInt32(); // .ReadInt32(); // = 0x4dfcd934 if (timeStampLower32Bits == 0 || timeStampLower32Bits == 0xFFFFFFFF) { return timeStamp; } // invalid date/time stamp, return "best guess" (last write time) timeStamp = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); // 00:00 January 1, 1970 (a C run-time time_t value) timeStamp = timeStamp.AddSeconds(timeStampLower32Bits); TimeZoneInfo easternStdTime = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"); timeStamp = TimeZoneInfo.ConvertTimeFromUtc(timeStamp, easternStdTime); } } } catch (Exception ex) { string qqq = ex.Message; } return timeStamp; } [...]

Upload automático de arquivo em um diretório


Boa tarde,

Gostaria de saber se é possível realizar o upload de todos os arquivos de um diretório? minha aplicação é web, instalado em um servidor externo.

Desde já agradeço,

Fábio Freitas

Passing data from view to controller with html checkbox


Hi I am using MVC.

I want to do Passing data from view to controller with html checkbox.

I try to when I click checkbox true get filter data. Other checkbox true get filter data.


  • Economy
  • Business


public ActionResult Talepler(int chkclass)
            var talep = (from v in shy.T_Talepler where v.KlasID == 1 select v).ToList();
            return View(talep);

Dynamic Scaffolding?


I've been reading the walkthoughs and watched various videos on how to get started with Dynamic Data Controls, and am pretty amazed at how quickly you can get a reasonably well featured UI together.  However everything I've seen so far assumes that you will use a designer build a LINQ to SQL (or use a predefined class structure).  Can I programmatically build these models on the fly?  I think I'm asking if I can use code to generate a dbml file for example.  Is this possible?  If so can anyone point me in the direction of some further reading.

Many thanks in advance, and apologies if I've asked a dumb question.

Question about PagedList, Webgrid, Grid.Mvc


My career in MVC development is kind of getting off the ground.  I inherited an MVC 5 project that uses PagedList.IPagedList(....) for displaying paged table data in an html table.  I have experimented a bit with Webgrid , and in my webform days I used the Gridview quite extensively. 

I am guessing that for MVC the gridview kinda came and went.  So I want to set my focus on a direction - but what direction to go in between PagedList, Webgrid, Grid.Mvc (and the rest like jqgrid, ....). 

For now I am mainly interested in hearing about the merits of PagedList, Webgrid, Grid.Mvc for displaying table data on my site (mainly in paged format)  Is any one of these three listed data display types overall more functionally complete than the others or is it a what flavor I prefer thing?

How do i parameterize this code below


Please i want to parameterize this code but dont know if i got it right, any help? protected void btnSave_Click(object sender, EventArgs e) { // string name = ddlcustomername.Text.Trim(); // string address = customeraddress.Text.Trim(); string productName = ddlProducts.SelectedItem.Text.Trim(); string name = ddlcustomername.SelectedItem.Text.Trim(); string address = ddlcustomeraddress.SelectedItem.Text.Trim(); decimal unitPrice = Convert.ToDecimal(lblProductPrice.Text.Trim()); int availableQuantity = Convert.ToInt32(lblQuantityAvailable.Text.Trim()); int quantity = Convert.ToInt32(txtQuantity.Text.Trim()); int inserted = 0; // int availableInventoryQty = AvailableInventoryQty(); if (lblProductPrice.Text.Length > 0 && txtQuantity.Text.Length > 0) { double stock = Convert.ToDouble(txtQuantity.Text); double customerqty = Convert.ToDouble(txtQuantity.Text); double tqty = stock - customerqty; double gqty = tqty; { if (lblProductPrice.Text.Length > 0 && txtQuantity.Text.Length > 0) { double unitprice2 = Convert.ToDouble(lblProductPrice.Text); double customerqty2 = Convert.ToDouble(txtQuantity.Text); double grandtotal = unitprice2 * customerqty; double total = grandtotal; { // if (txtunitprice.Text.Length > 0 && txtdiscount.Text.Length > 0) { // double unitprice = Convert.ToDouble(txtunitprice.Text); // double discount = Convert.ToDouble(txtdiscount.Text); // double sum = grandtotal - discount; // double sumb = sum; if ((availableQuantity != 0) && (quantity != 0) && (quantity < availableQuantity)) { using (SqlConnection con = new SqlConnection()) { con.ConnectionString = str; using (SqlCommand cmd = new SqlCommand()) { cmd.CommandType = CommandType.Text; cmd.Connection = con; cmd.CommandText = "INSERT INTO Sells VALUES('" + name + "','" + address + "','" + productName + "'," + unitPrice + "," + quantity + ")"; cmd.Parameters.AddWithValue("@UserName", Session["userName"]); cmd.Parameters.AddWithValue("@CustomerName", ddlcustomername.Text.Trim()); // cmd.Parameters.AddWithValue("@Location", ddlLocation.Text.Trim()); cmd.Parameters.AddWithValue("@ProductName", ddlProducts.Text.Trim()); // cmd.Parameters.AddWithValue("@Inches", ddlInches.Text.Trim()); //Name of rep // cmd.Parameters.AddWithValue("@Moul[...]

Not able to add items to dictionary



I am trying to add items to dictionary and then retrieve the values in it. I have declared and used the dictionary as below:

// Declaration

   private new Dictionary AttachmentNames
                if (ViewState["AttachmentNames"] != null)
                    return (Dictionary)ViewState["AttachmentNames"];
                    return new Dictionary();

                ViewState["AttachmentNames"] = value;

// When a file is browsed and upload button is clicked, I am adding the file name and file path to dictionary as below.

     AttachmentNames.Add(fileName, filepath);

// when submit button is clicked, I am retrieving the values and then saving to DB

 foreach (KeyValuePair pair in AttachmentNames)
 SaveAttachments(pair.Key, pair.Value);

However, when the file is brosed and upload button is clicked, the below line is hit, but AttachmentNames,count shows as 0 and no records are inserted

AttachmentNames.Add(fileName, filepath);

How to add items to Dictionary ? How to fix this?


why core with angular template still contains razor views?


Hi all,

I use VS2017 to create ASP.NET Core 2.0 web application, and I select Angular template, but the generated project still contains razor view, why? Any blog or articles can anylize the project's structure and how the client side and server side code organized?




setting Reply URL


I have Core Web app in a Service Fabric service running, single node.  It uses AzureAD for authentication. This works fine, the AzureApp has https://localhost:12345/signin-oidc  as reply Url defined and the app is running on that port. 

Now we modified this service, allowing it to run on multiple nodes and without a fixed port number. So it is running on 5 nodes under different port numbers. And we do not really know up front what portnumbers. We have another node that acts as a gateway and it is running on and https://localhost:12345 and forwards the requests to the other 5 nodes.

The problem is that after the user logged in in Azure we get an error like 

AADSTS50011: The reply address 'http://localhost:31001/signin-oidc' does not match the reply addresses configured for the application: xxxxxxxxxxxxxxxxxxx'. 

So how can we set the Reply URL to a fixed value? 

I was expecting I could do something with the OnRedirectToIdentityProvider event, but it is never reached. 

Surprising as the documentation states 'Invoked before redirecting to the identity provider to authenticate', I would expect to hit it BEFORE I go to the login page.




Sqlmembership provider PROFILE


Hello guys,

i'm trying to implement the Profile in my project, using Sql Membership Provider but i have some issues  :

The web.config part : 

   <profile enabled="true">
        <add name="username" type="String"/>
        <add name="codiceagenzia" type="string"/>
        <add name="codiceagente" type="string"/>

Now i expect to see something like this :


But the isn't possible, the property aren't aviable.

I already try to debug the web application and register new user but the situation keep no changes.

Last question, i will use profile for store user and i have a create user wizard but i need more information .

Wich is btter, custom the create user wizard with 10+ text box for additional information or make a web form with some text box and in back end an SQL Insert ? 

Thanks for any advice.

Cannot access a disposed object. Object name: 'System.Net.Sockets.NetworkStream'.



please help me, i see an eror. 

Cannot access a disposed object. Object name: 'System.Net.Sockets.NetworkStream'.

please help me to solve this eror..

submitting a form for product filters



I have a form which is for product filters, it has many checkbox's and all works well except for the url.

lets say I have multiple categories, the url will look for categories=something&categories=blah&categories=foo, but i would it to be categories=something,categories,foo

i know I can do this in in js, but i want to use both a standard form and js, i want the urls to be the same.

Any suggestions would be appriciated.