Quantcast
Channel: Visual C# forum
Viewing all 31927 articles
Browse latest View live

Run .NET 4.7 on a Mono Image

$
0
0

Hi,

what do I have to consider, if I want to execute a .NET 4.7 application on a Mono system?

Best regards,
Christian


Security issue needs to be resolved.

$
0
0

I have this code:

        public void GetRole ( )
        {
            StringBuilder sbld = new StringBuilder ( );
            System.AppDomain.CurrentDomain.SetPrincipalPolicy ( PrincipalPolicy.WindowsPrincipal );
            WindowsIdentity curIdentity = WindowsIdentity.GetCurrent ( );
            WindowsPrincipal myPrincipal = new WindowsPrincipal ( curIdentity );
            List<string> groups = new List<string> ( );
            foreach ( IdentityReference irc in curIdentity.Groups )
            {
                groups.Add ( ( ( NTAccount )irc.Translate ( typeof ( NTAccount ) ) ).Value );
            }

            sbld.Append ( "Name: " + curIdentity.Name + " System: curIdentity.IsSystem " + " Authenticated: " +
                                      curIdentity.IsAuthenticated + "  BuiltinAdmin: " + "Identiry: " +
                                      myPrincipal.IsInRole ( WindowsBuiltInRole.Administrator ).ToString ( ) +
                                      myPrincipal.Identity + string.Join ( string.Format ( ",{0}tt", Environment.NewLine ), groups.ToArray ( ) ) );
            Console.WriteLine ( @"Name: {0} System: {1} Authenticated: {2} BuiltinAdmin: {3} Identity: {4} Groups: {5}",
            curIdentity.Name, curIdentity.IsSystem, curIdentity.IsAuthenticated,
            myPrincipal.IsInRole ( WindowsBuiltInRole.Administrator ) ? "True" : "False",
            myPrincipal.Identity,
            string.Join ( string.Format ( ",{0}tt", Environment.NewLine ), groups.ToArray ( ) ) );
            try
            {
                Console.WriteLine ( Environment.NewLine );
            }
            catch ( System.Security.SecurityException scx )
            {
                Console.WriteLine ( scx.Message + " " + scx.FirstPermissionThatFailed.ToString ( ) );
            }
            Console.WriteLine(Environment.NewLine);
        }            // GetRole

I get this Exception at runtime:

System.Security.SecurityException
  HResult=0x8013150A
  Message=Request for principal permission failed.
  Source=mscorlib
  StackTrace:
   at System.Security.Permissions.PrincipalPermission.ThrowSecurityException()
   at System.Security.Permissions.PrincipalPermission.Demand()
   at System.Security.PermissionSet.DemandNonCAS()
   at ComeAndGet.SecurityAndDebug.GetRole() in C:\VCSharp_Projects\ComeAndGet\ComeAndGet\SecurityAndDebug.cs:line 23
   at ComeAndGet.Form1.comboSecurity_PG9_SelectedIndexChanged(Object sender, EventArgs e) in C:\VCSharp_Projects\ComeAndGet\ComeAndGet\Form1.cs:line 7625
   at System.Windows.Forms.ComboBox.OnSelectedIndexChanged(EventArgs e)
   at System.Windows.Forms.ComboBox.WmReflectCommand(Message& m)
   at System.Windows.Forms.ComboBox.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Forms.UnsafeNativeMethods.SendMessage(HandleRef hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at System.Windows.Forms.Control.SendMessage(Int32 msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Forms.Control.ReflectMessageInternal(IntPtr hWnd, Message& m)
   at System.Windows.Forms.Control.WmCommand(Message& m)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Forms.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at System.Windows.Forms.NativeWindow.DefWndProc(Message& m)
   at System.Windows.Forms.Control.WmCommand(Message& m)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ComboBox.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   at ComeAndGet.Program.Main() in C:\VCSharp_Projects\ComeAndGet\ComeAndGet\Program.cs:line 16

What is the reason. I am the administrator on this computer.

Thanks, - MyCatAlex

ManualResetEvent or AutoResetEvent

$
0
0

Hello,

When should I use ManualResetEvent and when should I use AutoResetEvent?

I mean ManualResetEvent is more correct. Can someone explain it well and in short?

If I call AutoResetEvent and check if the event is set with WaitOne, I have the impression that it is not set again.

With ManualResetEvent I get my use case better done. I just want to understand it.

Thanks for tips in advance.

Greetings Markus

How do I embed numbers in a defined string of numbers

$
0
0

Ok. I want to take a new Guid and embed a few numbers in it. I want to leave the dashes in it and put an "A"as a divider. So the number are like so
guid = {00000000-0000-0000-0000-000000000000}

Numbers I have
ID = 2345678
req# 234565

What I need
2345678A-2345-65A0-0000-000000000000

OR

Numbers I haveID = 84768899
req# 8654

What I need
84768899-A865-4A00-0000-000000000000


www.helixpoint.com

ASCII-to-EBCDIC or EBCDIC-to-ASCII

$
0
0

The question was 'how do you convert ASCII to EBCDIC?', but both of the programs told what to in the other situation of what to do to convert EBCDIC to ASCII.  But I don't need those, how would one convert ASCII to EBCDIC?

Process.Start fails (sometimes) with access denied

$
0
0

From a webservice i do a virusscan on uploaded file using a command line utility of the virus scanner in use.

It is possible to upload multiple files in one request and the files will be scanned one-by-one, sequentially.

The code i am using is the following:

using (Process process = new Process
{
  StartInfo = new ProcessStartInfo(SCANEXE)
  {
    Arguments = $"\"{filePath}\" /some-switch /another-switch",
    CreateNoWindow = true,
    ErrorDialog = false,
    WindowStyle = ProcessWindowStyle.Hidden,
    UseShellExecute = false
  }
})
{
  process.Start();
  if (process.WaitForExit(timeoutInMs))
    process.WaitForExit();

  if (process.HasExited)
  {
    switch (process.ExitCode)
    {
      case 0:
        return new ScanResult
        {
          ExitCode = process.ExitCode,
          State = ScanResult.States.FILEISCLEAN
	};
      case 1:
      case 50:
        return new ScanResult
        {
          ExitCode = process.ExitCode,
          State = ScanResult.States.FILEISDIRTY
        };
      case 10:
      case 100:
        return new ScanResult
        {
          ExitCode = process.ExitCode,
          State = ScanResult.States.SCANERROR
        };
      default:
        return new ScanResult
        {
          ExitCode = process.ExitCode,
          State = ScanResult.States.SCANERROR
        };
    }
  }
  process.Kill();
  return new ScanResult
  {
    State = ScanResult.States.SCANTIMEOUT
  };
}

What happens is that in approximately 5% of all scan attempts, Process.Start fails with an "Access Denied". The behavior is completely random, and has nothing to do with file beeing scanned. The same file will be scanned correctly in a subsequent try.

Wrapping the proces in a using statement as shown above (it was not, originally) improves the situation but does not completely fix the issue. (from 5% to approx. 1%)

It appeared to me like a timing issue so I did put in a Thread.Sleep(100) to get some time between process ending and next process starting. Without any success...

Does somebody have any clue ?

I am running out of ideas here...

Maybe worth noticing:

This problem magically started 1 day after a in-place-upgrade from the server from W2008 to W2012.


Parsing HTML and getting the value of an element based on its ID

$
0
0

I'm executing an HttpWebRequest that grabs the HTML from a given URL. I'm receiving the HTML as expected, but I'm not sure of the best way to get the value of an element based on its ID.

Here's the HTML I receive:

<HTML><HEAD><TITLE>Device Status</TITLE></HEAD><BODY><div id="deviceValue">00</div></BODY></HTML>

I'm wanting to get 00 from the element with the ID: "deviceValue"

I'm assuming there has to be a super simple way to do this since people have been parsing HTML for decades but I can't find a such a simple solution.

Any ideas?

Thanks!

Overwrite Json data toString() function to make www-form-urlencoded string

$
0
0

Hello:

I have to use HTTP client to post somex-www-form-urlencoded string to a web server.

The issue is the x-www-form-urlencoded formatted string is very very long, so I want to create a class to make it, and override the default toString() to build the string, so it can be posted to the web server.

For a short example of the x-www-form-urlencoded formatted string, it is something like this:

header0-A=1&header0-B=2&header0-C=3&timestamp=1579815039620

The header0 is something like this:

data-874969c24397b26ea55d9ec3e118096ea80a122e

What I want to do is something like this:

publicclassUrlencoded_Data

{

publicstringHeader0{get;set; }

publicdecimalData1{get;set; }

publicdecimalData2{get;set; }

publicdecimalData3{get;set; }

publiclongtimestamp{get;set; }

publicoverridestringToString()

{

returnJsonSerializer.Serialize(this);

}

}

I want to write one statement like this:

Urlencoded_Data pay_load1 =newUrlencoded_Data

{

Header0 =@"data-874969c24397b26ea55d9ec3e118096ea80a122e",

Data1 = 1m,

Data2 = 2m,

Data3 = 3m,

TimeStamp = 123456,

};

stringpost_data = pay_load1.ToString();

Comparing to the string I need for posting to web server, which is a string like this:

data-874969c24397b26ea55d9ec3e118096ea80a122e-A=1&data-874969c24397b26ea55d9ec3e118096ea80a122e-B=2&data-874969c24397b26ea55d9ec3e118096ea80a122e-C=3&timestamp=1579815039620

I got the Json string like this:

{"data-874969c24397b26ea55d9ec3e118096ea80a122e":"data-874969c24397b26ea55d9ec3e118096ea80a122e","Data1":1,"Data2":2,"Data3":3,"timestamp":123456}

They are totally different, I know I can use something like this:

string post_data =

string.Format("{0}-A={1}&{0}-B={2}&{0}-C={3}&timestamp={4}", @"data-874969c24397b26ea55d9ec3e118096ea80a122e", 1, 2, 3, 1579815039620);

Even the code works, but it looks ugly, I want to know if I can overwrite the toString() function, so it can do the job as the string.Format does.

Thanks,


DNS Resolution Failure only on Windows Server 2012 R2

$
0
0
I've encountered a very bizarre bug that I've narrowed down to a specific scenario but due to potential impact I need to try and find out why. 

Application A v 1.0 built for `.NET 4.7.2` runs fine on `Windows Server 2012 R2`
Application A v 2.0 also built for `.NET 4.7.2` but now using a `.Net Standard 2.0` shared library suddenly causes the tcp stack to fail (specifically all DNS resolution fails, even internal destinations) 

This bug only occurs on `2012 R2`. `2016` works just fine. 
This bug occurs even if only the assembly for the shared library is included, no actual instances declared or references made, not even a using statement, just having the shared library in the dependencies causes this. 

Outside of the application DNS resolution works fine. 
FusionLogs are functionally identical between what gets loaded on my `Windows 10 machine` and what gets loaded on `2012 R2`. Only difference being the encoded folder names for the native images loaded.

Here's a list of all relevant dependencies from the shared library
BouncyCastle.Crypto v 1.8.5:    Org.BouncyCastle.Crypto.Parameters;    
    Org.BouncyCastle.OpenSsl;    
    Org.BouncyCastle.Security;
Common.Logging v 3.4.1:
DnsClient v 1.2.0:
Microsoft.CSharp v 4.7.0:
Mimekit v 2.4.1:
NewtonSoft.Json v 12.0.1:
System v 4.0.0.0:    
    System.Collections.Generic;    
    System.Collections.Concurrent;    
    System.IO;    
    System.IO.Compression.FileSystem;    
    System.Drawing;    System.Numerics;    System.Runtime.Serialization;    System.Net;    System.Net.Http;    System.Net.Http.Headers;
    System.Security.Cryptography;    System.Text;    System.Threading;    System.Threading.Tasks;    System.Xml;

Exception:
17:16:21 [1] [Info] - DNS Query against 'google.com'
Unhandled Exception: System.Net.Sockets.SocketException: No such host is known   
   at System.Net.Dns.GetAddrInfo(String name)   
   at System.Net.Dns.InternalGetHostByName(String hostName, Boolean includeIPv6)   
   at System.Net.Dns.GetHostEntry(String hostNameOrAddress)   at DNSAPITestApp.Tester..ctor() in ...   at DNSAPITestApp.Program.Main(String[] args) in ...

I've searched extensively online however there's just too much white noise of similar DNS issues that still having nothing to do with this specific scenario or why this could be happening (and just as importantly how to confirm any theories).

Any help would be greatly appreciated. I can't post much of the code but if there are any specific areas where a particular dependency is used that anyone would like to see I can add snippets. 

Auto Complete Textbox that functions like gridview....

$
0
0

How can I make an auto complete textbox display data similar to a gridview?  I have a windows form application that has an order entry form.  I want to have the user see inventory quantities when he chooses the item location as part of the auto complete information.  How can I do this?

Example:

user types: Bin0103

autocomplete drops down: Bin0103, Qty 10

Thank you in advance!

Unable to download files with .db format from remote server to local server?

$
0
0

Hi all,

I developed an application that takes user input and store all the values in a structured .JSON file as shown below:

[
  {"Record": 1,"IPaddress": "192.168.6.67","Machinename": "naut","username": "net","password": "net","sourcefolder": "/home/root/data/completed","destfolder": "C:\\temp","filextension": ".db","removedownloaded": 0,"removecsv": 0,"removedb": 0,"eagleIOHost": "sftp.eagle.io","eagleIOUsername": "sftp.eagle.io","eagleIOpassword": "nautitech250","eagleIOdirectory": "/usr/share/tomcat8"
  }
]

these value are then used to connect to the local server and download data to the local server and then convert all the file to .csv which will then be visualized.

However, the file that are recorded seem to be empty and I am getting exception error. The code is below:

First read the .JSON file and deserialize it and convert it to a list

string text = File.ReadAllText(filePath);
var currentList = JsonConvert.DeserializeObject<List<Datalogger>>(text);

then read all the value on the JSON

string host = item.IPaddress;
string username = item.username;
string password = item.password;
string remoteDirectory = item.sourcefolder;
string localDirectory = item.destfolder;
string filextension = item.filextension;
string removedownloaded = item.removedownloaded.ToString();
string removecsv = item.removecsv.ToString();
string removedb = item.removedb.ToString();

string host_eagleio = item.eagleIOHost;
string username_eagleio = item.eagleIOUsername;
string password_eagleio = item.eagleIOpassword;
string eagleIOdirectoryDB = item.eagleIOdirectory;


Then connect to SFTP server then iterate through the files in the remote server and replace any occurrences of ':' by '_' (DADLoggerDB_2000-01-13T02:59:58 ==> DADLoggerDB_2000-01-13T02_59_58)

2 files should be created in the local server: one for the .db files and one for .csv files after conversion. Finally, the CSV file will be sent to the cloud server for data visualization. 

using (SftpClient sftp = new SftpClient(host, username, password))
                {
                    try
                    {
                        sftp.Connect();
                        var files = sftp.ListDirectory(remoteDirectory);

                        //Parallel.ForEach(files, file =>
                        foreach (var file in files)
                        {
                            try
                            {

                                string remoteFileName = file.Name;

                                string str = "";
                                str = remoteFileName.Replace(":", "_");
                                Console.WriteLine(str);
                                string Folder_path = item.destfolder;
                                var files_path = Directory.GetFiles(Folder_path, "*db", SearchOption.AllDirectories);
                                System.IO.DirectoryInfo local_directory = new DirectoryInfo(Folder_path);
                                System.IO.DirectoryInfo local_directory_csv = new DirectoryInfo(Folder_path);
                                string tablename = string.Empty;
                                //string path = remoteDirectory + "/" + remoteFileName;
                                string path = remoteDirectory + "/" + remoteFileName;
                                if ((file.Name.EndsWith(".db")))
                                {
                                    string subFolder_raw = Path.Combine(localDirectory, "Data");
                                    string subFolder = Path.Combine(localDirectory, "CSV");
                                    using (Stream file1 = File.OpenWrite(Path.Combine(subFolder_raw, remoteFileName)))
                                    {


                                        sftp.DownloadFile(path, file1);
                                        foreach (var item_db in files_path)
                                        {
                                            
                                            var result = item_db.Substring(item_db.Length - 3);
                                            for (var i = 1; i < files_path.Count() + 1; i++)
                                            {
                                                if (result == ".db")
                                                {
                                                    tablename = string.Format("DADLoggerTable{0}", i);
                                                    DataTable dt = ConverttoDatatable(item_db, tablename);
                                                    SaveCsv(dt, subFolder, tablename);
                                                }
                                            }
                                        }

                                        using (var sftp_eagleio = new SftpClient(host_eagleio, username_eagleio, password_eagleio))
                                        {
                                            sftp_eagleio.Connect();
                                            var files_eagleio = Directory.GetFiles(subFolder);
                                            foreach (var file_eagleio in files_eagleio)
                                            {
                                                string remoteFileName_eagleio = file_eagleio;
                                                using (Stream file1_eagleio = new FileStream(remoteFileName_eagleio, FileMode.Open))
                                                {
                                                    remoteFileName_eagleio = remoteFileName_eagleio.Substring(15);
                                                    sftp.UploadFile(file1_eagleio, eagleIOdirectoryDB + "/" + remoteFileName_eagleio, null);
                                                }
                                            }
                                        }

                                       
                                    }
                                    if (removedownloaded == "1")
                                    {
                                        sftp.Delete(path);

                                    }
                                   
                                    foreach (FileInfo filedb in local_directory.EnumerateFiles())
                                    {
                                        if (removedb == "1")
                                        {
                                            filedb.Delete();
                                        }
                                    }
                                    foreach (FileInfo filecsv in local_directory_csv.EnumerateFiles())
                                    {
                                        if (removecsv == "1")
                                        {
                                            filecsv.Delete();
                                        }
                                    }
                                }

                            }
                            catch (Exception er1)
                            {
                                MessageBox.Show("An exception has been caught " + er1.ToString());
                            }}
                        //});
                    }
                    catch (Exception entry)
                    {
                        MessageBox.Show(entry.Message);
                    }
                }


However, this bit of code is causing a problem

string remoteFileName = file.Name;
string str = "";
str = remoteFileName.Replace(":", "_");

when ":" is replaced by "_", I encountered this error after sftp.DownloadFile(path, file1); being executed:

A first chance exception of type 'Renci.SshNet.Common.SftpPathNotFoundException' occurred in Renci.SshNet.dll

and when I comment out this line and directly download the file without this replacement operation, I encounter this error after sftp.DownloadFile(path, file1); being executed::

A first chance exception of type 'System.NotSupportedException' occurred in mscorlib.dll

I tried different local repository rather than C drive, but still it is not working.

Any suggestion?

Thanks in advance

Sami


Sami Arja


How to Save word document in a folder which is created by Directory.CreateDirectory(docfile_path)?

$
0
0

I want to create a folder named as "test" inside this there will be another folder named as today's date "date" , i want to keep the the word document inside this date folder, please help.

This block of code throws an error called file name is invalid.

public string File_path; public string docfile_path; public string filename; private void button1_Click(object sender, EventArgs e) { string time = DateTime.Now.ToString("HH.mm.ss"); string date = DateTime.Today.ToShortDateString(); docfile_path = File_path+ "test" + date; Directory.CreateDirectory(docfile_path); filename = docfile_path + "worddoc"+"-" +".docx"; Word.Application app = new Word.Application(); Word.Document doc = new Word.Document(); try { doc = app.Documents.Open(filename); } catch { } Word.Paragraph oPara1; oPara1 = doc.Content.Paragraphs.Add(); oPara1.Range.Text = "Test Result"; oPara1.Range.Font.Bold = 1; oPara1.Format.SpaceAfter = 24; oPara1.Range.InsertParagraphAfter(); oPara1.Range.InsertParagraphAfter(); Word.Paragraph oPara2; oPara2 = doc.Content.Paragraphs.Add(); oPara2.Range.Text = "Test Name"; oPara2.Range.Font.Bold = 1; oPara2.Format.SpaceAfter = 24; oPara2.Range.InsertParagraphAfter(); doc.SaveAs2(filename); doc.Close(); doc = null; app.Quit(); app = null; }


Server Error in '/' Application

$
0
0

hi

datasource and datalist:

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:myCon %>" 

            SelectCommand="SELECT * FROM [news]" OnSelecting="SqlDataSource1_Selecting"></asp:SqlDataSource><br /><asp:DataList ID="DataList1" runat="server" DataKeyField="id" 
            DataSourceID="SqlDataSource1" Font-Bold="False" Font-Italic="False" 
            Font-Overline="False" Font-Strikeout="False" Font-Underline="False" 
            HorizontalAlign="Right" RepeatColumns="2" RepeatDirection="Horizontal" 
            Height="1103px" OnSelectedIndexChanged="DataList1_SelectedIndexChanged"><ItemTemplate><br /><asp:Image ID="Image1" runat="server" Width="250" Height="150"
                 ImageUrl='<%# "imageHandler/ImgHandler1.ashx?id=" + Eval("id") %>' /><br /><h6 style="color:Red">myTilte: </h6><asp:Label ID="titleLabel" runat="server" Text='<%# Eval("title") %>' /><br /><h6 style="color:Red"> myBody: </h6><asp:Label ID="bodyLabel" runat="server" Text='<%# Eval("body") %>' /><br /><asp:HyperLink ID="HyperLink1" 
                NavigateUrl='<%# FormatUrl( (int) Eval("id")) %>' runat="server" Font-Underline="False">continue</asp:HyperLink><br /><br /><br /><br /></ItemTemplate></asp:DataList>

i have this error ,while Execute :

Server Error in '/' Application.

DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'id'. 
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.Web.HttpException: DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'id'.

Source Error: 

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

Stack Trace: 


[HttpException (0x80004005): DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'id'.]
   System.Web.UI.DataBinder.GetPropertyValue(Object container, String propName) +2963837
   System.Web.UI.WebControls.DataList.CreateControlHierarchy(Boolean useDataSource) +582
   System.Web.UI.WebControls.BaseDataList.OnDataBinding(EventArgs e) +65
   System.Web.UI.WebControls.BaseDataList.DataBind() +84
   System.Web.UI.WebControls.BaseDataList.EnsureDataBound() +62
   System.Web.UI.WebControls.BaseDataList.CreateChildControls() +71
   System.Web.UI.Control.EnsureChildControls() +97
   System.Web.UI.Control.PreRenderRecursiveInternal() +42
   System.Web.UI.Control.PreRenderRecursiveInternal() +163
   System.Web.UI.Control.PreRenderRecursiveInternal() +163
   System.Web.UI.Control.PreRenderRecursiveInternal() +163
   System.Web.UI.Control.PreRenderRecursiveInternal() +163
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +906

many thanks

Howto get the list of files count and Created Date from folder group by Modified date?(C# 3.0 or ASP.Net)

$
0
0

I am trying to find count of all files in folder day wise showed in below image.(expected output)

Could you please help me how to loop all the files in a directory (Folder) to get the count of files and CreatedDate(Day wise).

Attempt : Below is the main method in C Sharp class

staticvoidMain(string[] args){Program p =newProgram();var directory =newDirectoryInfo(@"C:\Test\TestFileCount");var myFile =(from f in directory.GetFiles()orderby f.LastWriteTimedescendingselect f).First();List<FileInfo>FilesInNovember= p.GetFilesByDate(15,@"C:\Test\TestFileCount");Console.WriteLine("Number of files "+"\t"+FilesInNovember.Count+"\t"+"On"+"\t"+ myFile.LastWriteTime.ToString());Console.ReadLine();}

GetFilesByDate method defination

privateList<FileInfo>GetFilesByDate(intDayToGet,string directoryPath){DirectoryInfo dir =newDirectoryInfo(directoryPath);//  note use of the option to search sub-directoriesFileInfo[] theFiles = dir.GetFiles("*",SearchOption.AllDirectories);return theFiles.Where(fl => fl.CreationTime.Day==DayToGet).ToList();}

Some links with similar output requirement, but in VB.Net . Getting difficulty to understand it.http://www.codepal.co.uk/show/Show_file_count_and_filesizes_grouped_by_monthly_creation_date_in_ASPNET

Expected Output and Current out put with above code:


CPK

Handle data from DB directly into classes

$
0
0

Currently I'm very beginner in c# and I don't understand how can I get a data from DB (let's say using data table) and transform it into a object class. 

For example: 

public class Car    
{
  public string Name { get; set; }
  public string Brand { get; set; }
}

public class DataProccess
{
  var _dataTable = new DataTable(psfTable);
  var _dataAdapter = new DataAdapter("Select * FROM cars",_conn);

  _dataAdapter.Fill(_dataTable);
}

How can I map the datatable to the class without mapping each one of the fields? What is the right way to do it? 


Error connecting to SignalR from Android Xamarin

$
0
0

I have a problem that is really hard for me to find the fault, I looked for information on all sides I made two million changes and I can't make SignalR walk in the mobile application created with Xamarin Android. The theme is as follows: from VS using the Android emulator the connection to SignalR works fine but when I publish the Android application and use it from my cell phone it doesn't connect and I can see the following error message from Windows Events:

Event code: 3005 Event message: An unhandled exception has occurred. Event time: 21/1/2020 04:27:08 Event time (UTC): 21/1/2020 07:27:08 Event ID: 76845b1341fb48d3b71f05f2acc1f68f Event sequence: 4 Event occurrence: 1 Event detail code: 0

Application information: Application domain: /LM/W3SVC/6/ROOT-1-132240652228746740 Trust level: Full Application Virtual Path: / Application Path: C:\inetpub\wwwroot\MT001001\TESTING\WEB\PedidosMcd\ Machine name: IAVTECHVM

Process information: Process ID: 4740 Process name: w3wp.exe Account name: IIS APPPOOL\MT001001_TESTING

Exception information: Exception type: ArgumentNullException Exception message: Value cannot be null. Parameter name: key at System.Collections.Generic.Dictionary2.FindEntry(TKey key) at Microsoft.AspNet.SignalR.Hubs.HubDispatcher.AuthorizeRequest(IRequest request) in /_/src/Microsoft.AspNet.SignalR.Core/Hubs/HubDispatcher.cs:line 114 at Microsoft.AspNet.SignalR.PersistentConnection.ProcessRequest(IDictionary2 environment) in //src/Microsoft.AspNet.SignalR.Core/PersistentConnection.cs:line 159 at Microsoft.AspNet.SignalR.Owin.Middleware.HubDispatcherMiddleware.Invoke(IOwinContext context) in //src/Microsoft.AspNet.SignalR.Core/Owin/Middleware/HubDispatcherMiddleware.cs:line 38 at Microsoft.Owin.Infrastructure.OwinMiddlewareTransition.Invoke(IDictionary`2 environment) at Microsoft.Owin.Cors.CorsMiddleware.d__4.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Owin.Mapping.MapMiddleware.d__3.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContextStage.d__7.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.d__12.MoveNext() --- End of stack trace from previous location where exception was thrown --- at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult ar) at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar) at System.Web.HttpApplication.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

Request information: Request URL:...com:443/signalr/negotiate?clientProtocol=2.1&connectionData=[{}]  Request path: /signalr/negotiate User host address: 190.177.1.85 User:
Is authenticated: False Authentication Type:
Thread account name: IIS APPPOOL\MT001001_TESTING

Thread information: Thread ID: 16 Thread account name: IIS APPPOOL\MT001001_TESTING Is impersonating: False Stack trace: at System.Collections.Generic.Dictionary2.FindEntry(TKey key) at Microsoft.AspNet.SignalR.Hubs.HubDispatcher.AuthorizeRequest(IRequest request) in /_/src/Microsoft.AspNet.SignalR.Core/Hubs/HubDispatcher.cs:line 114 at Microsoft.AspNet.SignalR.PersistentConnection.ProcessRequest(IDictionary2 environment) in //src/Microsoft.AspNet.SignalR.Core/PersistentConnection.cs:line 159 at Microsoft.AspNet.SignalR.Owin.Middleware.HubDispatcherMiddleware.Invoke(IOwinContext context) in //src/Microsoft.AspNet.SignalR.Core/Owin/Middleware/HubDispatcherMiddleware.cs:line 38 at Microsoft.Owin.Infrastructure.OwinMiddlewareTransition.Invoke(IDictionary`2 environment) at Microsoft.Owin.Cors.CorsMiddleware.d__4.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Owin.Mapping.MapMiddleware.d__3.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContextStage.d__7.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.d__12.MoveNext() --- End of stack trace from previous location where exception was thrown --- at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult ar) at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar) at System.Web.HttpApplication.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

Custom event details:

And in IIS I have the transports.log.txt log:

SignalR.Transports.TransportHeartBeat Information: 0 : Connection 822d31dd-e4f6-4b08-9b65-c080b3ad2eb1 is New. SignalR.Transports.WebSocketTransport Verbose: 0 : Sending outgoing message. Connection id: 822d31dd-e4f6-4b08-9b65-c080b3ad2eb1, transport: WebSocketTransport, message: {"C":"d-5947C291-B,0|C,0|D,1","S":1,"M":[]} SignalR.Transports.WebSocketTransport Verbose: 0 : Sending outgoing message. Connection id: 822d31dd-e4f6-4b08-9b65-c080b3ad2eb1, transport: WebSocketTransport, message: {"R":{"id":"822d31dd-e4f6-4b08-9b65-c080b3ad2eb1","usuario":"TECNICO1","pass":"1234","iniciarauto":true},"I":"0"} SignalR.Transports.WebSocketTransport Error: 0 : OnError(822d31dd-e4f6-4b08-9b65-c080b3ad2eb1, System.Net.WebSockets.WebSocketException (0x80070026): Reached the end of the file at System.Web.WebSockets.WebSocketPipe.<>c__DisplayClass9_0.b__0(Int32 hrError, Int32 cbIO, Boolean fUtf8Encoded, Boolean fFinalFragment, Boolean fClose) --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.WebSockets.AspNetWebSocket.d__45`1.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.WebSockets.AspNetWebSocket.<>c__DisplayClass36_0.<b__0>d.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNet.SignalR.WebSockets.WebSocketMessageReader.d__3.MoveNext() in /_/src/Microsoft.AspNet.SignalR.Core/Owin/WebSockets/WebSocketMessageReader.cs:line 36 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNet.SignalR.WebSockets.WebSocketHandler.d__25.MoveNext() in /_/src/Microsoft.AspNet.SignalR.Core/Owin/WebSockets/WebSocketHandler.cs:line 170) SignalR.Transports.WebSocketTransport Information: 0 : CloseSocket(822d31dd-e4f6-4b08-9b65-c080b3ad2eb1)

I have an Azure VM but it does not have an Antivirus installed, only windows defender, I saw elsewhere that it could be the AV but I discard it.

The strange thing is that from the VS Android emulator I address the signalr path and it connects well. The webapp also connects and works well, it just does not work by running the application from the cell phone with Android (I tested it on several computers).

try to address with http and https and it works fine from the emulator but not from the Android app

Can you miss any permission from Xamarin Android?

I appreciate any help

Tks

Security issue needs to be resolved.

$
0
0

public void AddFileSecurity(string fileName, string account,
            FileSystemRights rights, AccessControlType controlType)
        {
            // Adds an ACL entry on the specified file for the specified account.
            FileSecurity fSecurity = File.GetAccessControl(fileName);
            fSecurity.AddAccessRule(new FileSystemAccessRule(account, rights, controlType));
            File.SetAccessControl(fileName, fSecurity);
        }         // AddFileSecurity

This is how it's called:

case "AddFileSecurity":
                    Console.Clear();
                    Console.WriteLine("AddFileSecurity\n\n");
                    OpenFileDialog openFileDialog1 = new OpenFileDialog();
                    openFileDialog1.InitialDirectory = "c:\\";
                    openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
                    openFileDialog1.FilterIndex = 2;
                    openFileDialog1.RestoreDirectory = true;
                    openFileDialog1.ShowDialog();
                    string fName = openFileDialog1.FileName;
                    sd.AddFileSecurity(fName, @"DomainName\AccountName",
                        FileSystemRights.FullControl, AccessControlType.Allow);
                    break;

RDLC Reports no longer working.

$
0
0

Waaaay back in VS 2010 I made a WINFORMS app that includes some reports.

My old VS2010 has gone on to it's reward, and now I have VS2015 and VS 2019.

Of course the client now wants a SIMPLE change to the report, only a text box changed, and...

1. 2019 and 2015 no longer have a report editor.  I downloaded one for 2019, but didn't find one for 2015.

2. change made, piece of cake, but when I attempt to run the report, I get this...

Microsoft.Reporting.WinForms.LocalProcessingException occurred
  HResult=-2146233088
  Message=An error occurred during local report processing.
  Source=Microsoft.ReportViewer.WinForms
  StackTrace:
       at Microsoft.Reporting.WinForms.LocalReport.EnsureExecutionSession()
       at Microsoft.Reporting.WinForms.LocalReport.SetParameters(IEnumerable`1 parameters)
       at Microsoft.Reporting.WinForms.Report.SetParameters(ReportParameter parameter)
       at Onesource.Reports.SalesInvoice.salesInvoiceForm.salesInvoiceForm_Load(Object sender, EventArgs e) in C:\Users\Bryan Valencia\Documents\Visual Studio 2015\Projects\OneViewBackOffice\OneView\Reports\SalesInvoice\salesInvoiceForm.cs:line 33
  InnerException: 
       ExceptionLevelHelpLink=http://go.microsoft.com/fwlink/?LinkId=20476&EvtSrc=Microsoft.ReportingServices.Diagnostics.Utilities.ErrorStrings&EvtID=pvInvalidDefinition&ProdName=Microsoft%20SQL%20Server%20Reporting%20Services&ProdVer=1.0
       HResult=-2146233088
       Message=The definition of the report '' is invalid.
       SkipTopLevelMessage=false
       Source=Microsoft.ReportViewer.Common
       StackTrace:
            at Microsoft.Reporting.ReportCompiler.CompileReport(ICatalogItemContext context, Byte[] reportDefinition, Boolean generateExpressionHostWithRefusedPermissions, ControlSnapshot& snapshot)
            at Microsoft.Reporting.LocalService.GetCompiledReport(PreviewItemContext itemContext, Boolean rebuild, ControlSnapshot& snapshot)
            at Microsoft.Reporting.LocalService.CompileReport()
            at Microsoft.Reporting.LocalService.Microsoft.Reporting.ILocalProcessingHost.CompileReport()
            at Microsoft.Reporting.WinForms.LocalReport.EnsureExecutionSession()
       InnerException: 
            ExceptionLevelHelpLink=http://go.microsoft.com/fwlink/?LinkId=20476&EvtSrc=Microsoft.ReportingServices.Diagnostics.Utilities.ErrorStrings&EvtID=rsProcessingError&ProdName=Microsoft%20SQL%20Server%20Reporting%20Services&ProdVer=1.0
            HResult=-2146233088
            Message=The definition of this report is not valid or supported by this version of Reporting Services. The report definition may have been created with a later version of Reporting Services, or contain content that is not well-formed or not valid based on Reporting Services schemas. Details: The report definition has an invalid target namespace 'http://schemas.microsoft.com/sqlserver/reporting/2016/01/reportdefinition' which cannot be upgraded.
            SkipTopLevelMessage=false
            Source=Microsoft.ReportViewer.Common
            StackTrace:
                 at Microsoft.ReportingServices.ReportPublishing.ReportPublishing.CreateInvalidReportDefinitionException(Exception e)
                 at Microsoft.ReportingServices.ReportPublishing.ReportPublishing.Phase1(Stream definitionStream, String& description, String& language, DataSourceInfoCollection& dataSources, DataSetInfoCollection& sharedDataSetReferences, Boolean& hasExternalImages, Boolean& hasHyperlinks)
                 at Microsoft.ReportingServices.ReportPublishing.ReportPublishing.InternalCreateIntermediateFormat(Stream definitionStream, String& description, String& language, ParameterInfoCollection& parameters, DataSourceInfoCollection& dataSources, DataSetInfoCollection& sharedDataSetReferences, UserLocationFlags& userReferenceLocation, ArrayList& dataSetsName, Boolean& hasExternalImages, Boolean& hasHyperlinks, Byte[]& dataSetsHash)
                 at Microsoft.ReportingServices.ReportPublishing.ReportPublishing.CreateIntermediateFormat(Byte[] definition, String& description, String& language, ParameterInfoCollection& parameters, DataSourceInfoCollection& dataSources, DataSetInfoCollection& sharedDataSetReferences, UserLocationFlags& userReferenceLocation, ArrayList& dataSetsName, Boolean& hasExternalImages, Boolean& hasHyperlinks, Byte[]& dataSetsHash)
                 at Microsoft.ReportingServices.ReportProcessing.ReportProcessing.CompileOdpReport(PublishingContext reportPublishingContext, IDataProtection dataProtection, PublishingErrorContext errorContext, String& reportDescription, String& reportLanguage, ParameterInfoCollection& parameters, DataSourceInfoCollection& dataSources, DataSetInfoCollection& sharedDataSetReferences, UserLocationFlags& userReferenceLocation, ArrayList& dataSetsName, Boolean& hasExternalImages, Boolean& hasHyperlinks, Byte[]& dataSetsHash)
                 at Microsoft.ReportingServices.ReportProcessing.ReportProcessing.CreateIntermediateFormat(PublishingContext reportPublishingContext, IDataProtection dataProtection)
                 at Microsoft.Reporting.ReportCompiler.CompileReport(ICatalogItemContext context, Byte[] reportDefinition, Boolean generateExpressionHostWithRefusedPermissions, ControlSnapshot& snapshot)
            InnerException: 

This error occurs on this line:

                ReportParameter InvNoParam = new ReportParameter("InvNo", this.InvoiceNumber);
                this.reportViewer1.LocalReport.SetParameters(InvNoParam);

OK, details: Winforms app.  The report is a local report, set to process locally.

Was originally designed in VS2010, and worked fine there.

I have been all over the site AND stack, without any resolution.


I'd rather live with false hope than with false despair.

How to input strings into a private List

$
0
0

Can somebody help me how to input strings in a private List<Book> in the main method??

Thank you so much in advance.

-Morena

public class Librarian { private List<Book> bookList; public void RegisterBook(List<Book> myRegisteredBook) { bookList = myRegisteredBook; } public List<Book> RegisteredBooks() { return bookList; } } class Program { static void Main(string[] args) { Bok myBook = new Book(); string bookTitle; string bookAuthor; int PublishingYear; Librarian newBook = new Libararian(); newBook.RegisterBook();//I need help here!!! List<Book> newBooks = newBook.RegisteredBooks();


How to check for time in the last Hour?

$
0
0

I have the following string for the Database: 2014-09-11 11:50:00.0000000

I want to check if the record was created in the last hour. (I would rather not do this in the DB).

So I created this method:

public static bool InLastHour()
{
string dbDateTime = "2014-09-11 11:50:00.0000000"; 
//The date time is actually a variable.
DateTime arrival = Convert.ToDateTime(dbDateTime); DateTime now = DateTime.Now; DateTime yesterday = now.AddDays(-23); return (arrival > yesterday && arrival <= now); } //Another version here: public static bool InLastHour() { string dbDateTime = "2014-09-11 01:51:46.2300000"; DateTime arrival = new DateTime(); arrival = Convert.ToDateTime(dbDateTime); return (arrival <= DateTime.Now.AddHours(-23)); }

I am getting mixed results.

Thanks



Viewing all 31927 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>