How do I create a program that details files and their sub directories? - visual-c#-express-2010

There is a program that I am working on and Im absolutly lost even at how to begin this. I am using Visual Studio C# Windows App Form.
What I need to do is allow the user to enter any path location they want and the program will return the Name of the file/folder; Path; date and size, and this will also be done for sub directories.
I found some code in the MSDN site and I am trying to use it and modify it for the first part of this project, but keep receiving error messages. Some of the messages indicate that there is more than one entry ie (static void Main() and using namespace Detailed).
This is what I have so far, a form with rich text box and the FolderBrowserDialog and it seems as I can't get beyond this point without so many errors.
This is under Form1.Designer.cs:
<i>namespace Detailed
{
partial class Form1
{
///
/// Required designer variable.
///
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog();
this.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.SuspendLayout();
//
// folderBrowserDialog1
//
this.folderBrowserDialog1.HelpRequest += new System.EventHandler(this.folderBrowserDialog1_HelpRequest);
//
// richTextBox1
//
this.richTextBox1.Location = new System.Drawing.Point(12, 32);
this.richTextBox1.Name = "richTextBox1";
this.richTextBox1.Size = new System.Drawing.Size(167, 23);
this.richTextBox1.TabIndex = 0;
this.richTextBox1.Text = "";
//
// openFileDialog1
//
this.openFileDialog1.FileName = "openFileDialog1";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 262);
this.Controls.Add(this.richTextBox1);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog1;
private System.Windows.Forms.RichTextBox richTextBox1;
private System.Windows.Forms.OpenFileDialog openFileDialog1;
}
}
For the For1.cs this is what I have so far:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
public class FolderBrowserDialogExampleForm : System.Windows.Forms.Form
{
private FolderBrowserDialog folderBrowserDialog1;
private OpenFileDialog openFileDialog1;
private RichTextBox richTextBox1;
private MainMenu mainMenu1;
private MenuItem fileMenuItem, openMenuItem;
private MenuItem folderMenuItem, closeMenuItem;
private string openFileName, folderName;
private bool fileOpened = false;
public partial class Form1 : Form
{
public Form1()
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void folderBrowserDialog1_HelpRequest(object sender, EventArgs e)
{
}
}
private void InitializeComponent()
{
this.SuspendLayout();
//
// FolderBrowserDialogExampleForm
//
this.ClientSize = new System.Drawing.Size(284, 262);
this.Name = "FolderBrowserDialogExampleForm";
this.ResumeLayout(false);
}
}
I'm still new to programing and hope I can get this figured out asap as I was requested to have this no later than Thursday morning est. I had the Rich TextBox in the Form, but removed it because of too many errors.
This is the code I found. I know this is just part of what I need to do, but when reading through the code I noticed that maybe I can apply what is needed to the form and then break up the code and put the pieces of code where I need them. This is the code I am following
Here is an error message I am receiving with Form1.Designer.cs - there are 14 of these same errors:
‘Detailed.form1’ does not contain a definition for ‘Form1_Load’ and no extension method ‘Form1_Load’ accepting a first argument of type ‘Detailed.Form1’ could be found (are you missing a using directive or an assembly reference?)

The first thing you want is a dialog prompting the user for a directory.
So get rid of all that code, start a new project win form and place a textbox in your form and a button in your form.
Simple enough one text box and one button. Now in the click event of your button "Browse", have you, you write code to open an instance of the FolderBrowserDialog class and you .ShowDialog().
To get this path:
Here is a sample screen output:
The code is fairly straightforward, look at my picture and how much code i have to do this.

Related

error : is a field but used as a type

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication5
{
public class ClientContext
{
private string p;
public ClientContext(string p)
{
// TODO: Complete member initialization
this.p = p;
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//First construct client context, the object which will be responsible for
//communication with SharePoint:
private ClientContext context = new ClientContext("#url");
//then get a hold of the list item you want to download, for example
public List list;
public ClientContext
{
list = context.Web.Lists.GetByTitle("001_CFR_DPV_COST_REV_SHARING");
}
//note that data has not been loaded yet. In order to load the data
//you need to tell SharePoint client what you want to download:
context.Load(result, items=>items.Include(
item => item["Title"],
item => item["FileRef"]
));
//now you get the data
context.ExecuteQuery();
//here you have list items, but not their content (files). To download file
//you'll have to do something like this:
var item = items.First();
//get the URL of the file you want:
var fileRef = item["FileRef"];
//get the file contents:
FileInformation fileInfo = File.OpenBinaryDirect(context, fileRef.ToString());
using (var memory = new MemoryStream())
{
byte[] buffer = new byte[1024 * 64];
int nread = 0;
while ((nread = fileInfo.Stream.Read(buffer, 0, buffer.Length)) > 0)
{
memory.Write(buffer, 0, nread);
}
memory.Seek(0, SeekOrigin.Begin);
// ... here you have the contents of your file in memory,
// do whatever you want
}
}
}
this is the complete code.
I don't know why it is showing error. I searched for the error "is a field but used as a type" and I tried that but it didn't help. Please help with a solution Code to this since I am new to this. Thank you in advance.
What are you trying to achieve by this lines of code?
public partial class Form1 : Form
{
...
public ClientContext
{
list = context.Web.Lists.GetByTitle("001_CFR_DPV_COST_REV_SHARING");
}
}
What is public ClientContext {} inside class Form1 ?
It seems that you intended to create constructor to a class in another class and for compiler it looks more like a property but without accessors (get, set) as if it is a Type or smth like this.
Try to put get; set; accessors inside if you intended to create property:
public List Context
{
get
{
list = context.Web.Lists.GetByTitle("001_CFR_DPV_COST_REV_SHARING");
return list;
}
}
Or change it to method instead :
public void GetClientContext()
{
list = context.Web.Lists.GetByTitle("001_CFR_DPV_COST_REV_SHARING");
}

Debugging Package Manager Console Update-Database Seed Method

I wanted to debug the Seed() method in my Entity Framework database configuration class when I run Update-Database from the Package Manager Console but didn't know how to do it. I wanted to share the solution with others in case they have the same issue.
Here is similar question with a solution that works really well.
It does NOT require Thread.Sleep.
Just Launches the debugger using this code.
Clipped from the answer
if (!System.Diagnostics.Debugger.IsAttached)
System.Diagnostics.Debugger.Launch();
The way I solved this was to open a new instance of Visual Studio and then open the same solution in this new instance of Visual Studio. I then attached the debugger in this new instance to the old instance (devenv.exe) while running the update-database command. This allowed me to debug the Seed method.
Just to make sure I didn't miss the breakpoint by not attaching in time I added a Thread.Sleep before the breakpoint.
I hope this helps someone.
If you need to get a specific variable's value, a quick hack is to throw an exception:
throw new Exception(variable);
A cleaner solution (I guess this requires EF 6) would IMHO be to call update-database from code:
var configuration = new DbMigrationsConfiguration<TContext>();
var databaseMigrator = new DbMigrator(configuration);
databaseMigrator.Update();
This allows you to debug the Seed method.
You may take this one step further and construct a unit test (or, more precisely, an integration test) that creates an empty test database, applies all EF migrations, runs the Seed method, and drops the test database again:
var configuration = new DbMigrationsConfiguration<TContext>();
Database.Delete("TestDatabaseNameOrConnectionString");
var databaseMigrator = new DbMigrator(configuration);
databaseMigrator.Update();
Database.Delete("TestDatabaseNameOrConnectionString");
But be careful not to run this against your development database!
I know this is an old question, but if all you want is messages, and you don't care to include references to WinForms in your project, I made some simple debug window where I can send Trace events.
For more serious and step-by-step debugging, I'll open another Visual Studio instance, but it's not necessary for simple stuff.
This is the whole code:
SeedApplicationContext.cs
using System;
using System.Data.Entity;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
namespace Data.Persistence.Migrations.SeedDebug
{
public class SeedApplicationContext<T> : ApplicationContext
where T : DbContext
{
private class SeedTraceListener : TraceListener
{
private readonly SeedApplicationContext<T> _appContext;
public SeedTraceListener(SeedApplicationContext<T> appContext)
{
_appContext = appContext;
}
public override void Write(string message)
{
_appContext.WriteDebugText(message);
}
public override void WriteLine(string message)
{
_appContext.WriteDebugLine(message);
}
}
private Form _debugForm;
private TextBox _debugTextBox;
private TraceListener _traceListener;
private readonly Action<T> _seedAction;
private readonly T _dbcontext;
public Exception Exception { get; private set; }
public bool WaitBeforeExit { get; private set; }
public SeedApplicationContext(Action<T> seedAction, T dbcontext, bool waitBeforeExit = false)
{
_dbcontext = dbcontext;
_seedAction = seedAction;
WaitBeforeExit = waitBeforeExit;
_traceListener = new SeedTraceListener(this);
CreateDebugForm();
MainForm = _debugForm;
Trace.Listeners.Add(_traceListener);
}
private void CreateDebugForm()
{
var textbox = new TextBox {Multiline = true, Dock = DockStyle.Fill, ScrollBars = ScrollBars.Both, WordWrap = false};
var form = new Form {Font = new Font(#"Lucida Console", 8), Text = "Seed Trace"};
form.Controls.Add(tb);
form.Shown += OnFormShown;
_debugForm = form;
_debugTextBox = textbox;
}
private void OnFormShown(object sender, EventArgs eventArgs)
{
WriteDebugLine("Initializing seed...");
try
{
_seedAction(_dbcontext);
if(!WaitBeforeExit)
_debugForm.Close();
else
WriteDebugLine("Finished seed. Close this window to continue");
}
catch (Exception e)
{
Exception = e;
var einner = e;
while (einner != null)
{
WriteDebugLine(string.Format("[Exception {0}] {1}", einner.GetType(), einner.Message));
WriteDebugLine(einner.StackTrace);
einner = einner.InnerException;
if (einner != null)
WriteDebugLine("------- Inner Exception -------");
}
}
}
protected override void Dispose(bool disposing)
{
if (disposing && _traceListener != null)
{
Trace.Listeners.Remove(_traceListener);
_traceListener.Dispose();
_traceListener = null;
}
base.Dispose(disposing);
}
private void WriteDebugText(string message)
{
_debugTextBox.Text += message;
Application.DoEvents();
}
private void WriteDebugLine(string message)
{
WriteDebugText(message + Environment.NewLine);
}
}
}
And on your standard Configuration.cs
// ...
using System.Windows.Forms;
using Data.Persistence.Migrations.SeedDebug;
// ...
namespace Data.Persistence.Migrations
{
internal sealed class Configuration : DbMigrationsConfiguration<MyContext>
{
public Configuration()
{
// Migrations configuration here
}
protected override void Seed(MyContext context)
{
// Create our application context which will host our debug window and message loop
var appContext = new SeedApplicationContext<MyContext>(SeedInternal, context, false);
Application.Run(appContext);
var e = appContext.Exception;
Application.Exit();
// Rethrow the exception to the package manager console
if (e != null)
throw e;
}
// Our original Seed method, now with Trace support!
private void SeedInternal(MyContext context)
{
// ...
Trace.WriteLine("I'm seeding!")
// ...
}
}
}
Uh Debugging is one thing but don't forget to call:
context.Update()
Also don't wrap in try catch without a good inner exceptions spill to the console.
https://coderwall.com/p/fbcyaw/debug-into-entity-framework-code-first
with catch (DbEntityValidationException ex)
I have 2 workarounds (without Debugger.Launch() since it doesn't work for me):
To print message in Package Manager Console use exception:
throw new Exception("Your message");
Another way is to print message in file by creating a cmd process:
// Logs to file {solution folder}\seed.log data from Seed method (for DEBUG only)
private void Log(string msg)
{
string echoCmd = $"/C echo {DateTime.Now} - {msg} >> seed.log";
System.Diagnostics.Process.Start("cmd.exe", echoCmd);
}

how to add emoticons to richtextbox

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace abc
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
EmoticonRender ab = new EmoticonRender();
private void button1_Click(object sender, EventArgs e)
{
string textie = ab.Parse(textBox1.Text);
richTextBox1.Text += textie+"\n";
}
}
public class EmoticonRender
{
private List<KeyValuePair<string, string>> _dictionary = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>(":-)", "a.png"),
new KeyValuePair<string, string>(";-(", "a.png"),
};
public string Parse(string text)
{
foreach(KeyValuePair<string, string> kvp in _dictionary)
{
text = text.Replace(kvp.Key, #"C:\Users\Buddiez\Documents\Visual Studio 2010\Projects\abc\abc\a.png");
}
return text;
}
}
}
im using these line of codes to insert smilyes into richtextbox but instead of showing smileye it is showing the path of the png imgae ie. C:\Users\Buddiez\Documents\Visual Studio 2010\Projects\abc\abc\a.png
Copy all the images which you have and navigate to >> visual studio select Project>>Properties.There select Resources and paste all copied images on the right side pane.
Hashtable emotions;
void CreateEmotions()
{
emotions= new Hashtable(6);
emotions.Add(":-)", Project.Properties.Resources.regular_smile);
emotions.Add(":)", Project.Properties.Resources.regular_smile);
}
void AddEmotions()
{
foreach (string emote in emotions.Keys)
{
while(richTextBox1.Text.Contains(emote))
{
int ind = richTextBox1.Text.IndexOf(emote);
richTextBox1.Select(ind, emote.Length);
Clipboard.SetImage((Image)emotions[emote]);
richTextBox1.Paste();
}
}
}
A good (and relatively new) solution could be using the open-source EmojiBox project.
There's not much code there so it's quite easy to follow, just note that in order to insert an emoji into the custom RichTextBox there, the text you type has to follow the template of :emoji_name:
Of course, if you don't want to use the whole list of unicode emojis, you could also replace the image files or their names/descriptions within the json file.

XNA 4.0 Graphics Device Error

I know that the way the declaration of the graphics device is suppose to look in the main Game1() constructor is:
GraphicsDeviceManager graphics;
graphics = new GraphicsDeviceManager(this);
then you can use stuff like:
graphics.PreferredBackBufferWidth = 1366;
But if I declare the same inside a separate class, what do I fill in for "this"?
GraphicsDeviceManager graphics;
graphics = new GraphicsDeviceManager(?);
EDIT:
After modifying everything as you said, I now get a error that sends me to this line of code:
/// <summary>
/// Event handler for when the Play Game menu entry is selected.
/// </summary>
void PlayGameMenuEntrySelected(object sender, PlayerIndexEventArgs e, Game game)
{
LoadingScreen.Load(ScreenManager, true, e.PlayerIndex,
new GameplayScreen(game));
}
This program is the menu sample you can get from Microsoft, heavily modified of course, this is the code that executes when you hit enter on the main menu screen with "Play Game" highlighted. I guess the problem is passing the variable.
Edit 2:
I fixed the code I think but now it sent me to this line and I don't know how to edit it.
playGameMenuEntry.Selected += PlayGameMenuEntrySelected;
You need a reference to your Game instance. I'd just pass it to your new class constructor.
For example, if you want to move the GraphicsDeviceManager instance into a separate class, Foo,
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
private Foo _foo;
public Game1()
{
_foo = new Foo(this);
}
protected override void Dispose(bool disposing)
{
if (_foo != null)
{
_foo.Dispose();
_foo = null;
}
base.Dispose(disposing);
}
}
public class Foo : IDisposable
{
private Game _game;
private GraphicsDeviceManager _graphics;
private SpriteBatch _spriteBatch;
public Foo(Game game)
{
_game = game;
_game.Content.RootDirectory = "Content";
_graphics = new GraphicsDeviceManager(_game);
_spriteBatch = new SpriteBatch(_game.GraphicsDevice);
}
public void Dispose()
{
if (!_spriteBatch.IsDisposed)
{
_spriteBatch.Dispose();
_spriteBatch = null;
}
}
}
Update
It's important to properly dispose of a lot of XNA objects (otherwise, you get memory leaks). See Foo.Dispose() and the Game1.Dispose() override above.

How To Make UserControl In MasterPage Public For All Child Pages

I have a UserControl which I have added to my web.config
<add tagPrefix="BCF" src="~/controls/MyMessageBox.ascx" tagName="error"/>
and added to my master page
<BCF:error ID="BCError" runat="server" Visible="false" />
Now I need to be able to reference this control AND its public properties from all child pages that use that masterpage. I did this is my BasePage OnLoad event
public UserControl BCError;
BCError = (UserControl)Master.FindControl("BCError");
Problem is, although I can do this in the .aspx page
BCError.Visible = true;
I cannot reference any of the Controls properties I have put in? Such as ShowError .. If I do
BCError.ShowError = "Error Message";
I just get an error saying
'System.Web.UI.UserControl' does not contain a definition for 'ShowInfo' and no extension method 'ShowInfo'
Can you please point me in the right direction!
This is the code for the user control... I can use the properties in the masterpage code behind (And in a page if I put the control directly into it) but cannot use them in the child page code behind?? It doesn't even show the properties or wrapper methods in the intellisense?
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class MyMessageBox : System.Web.UI.UserControl
{
#region Properties
public bool ShowCloseButton { get; set; }
#endregion
#region Load
protected void Page_Load(object sender, EventArgs e)
{
if (ShowCloseButton)
CloseButton.Attributes.Add("onclick", "document.getElementById('" + MessageBox.ClientID + "').style.display = 'none'");
}
#endregion
#region Wrapper methods
public void ShowError(string message)
{
Show(MessageType.Error, message);
}
public void ShowInfo(string message)
{
Show(MessageType.Info, message);
}
public void ShowSuccess(string message)
{
Show(MessageType.Success, message);
}
public void ShowWarning(string message)
{
Show(MessageType.Warning, message);
}
#endregion
#region Show control
public void Show(MessageType messageType, string message)
{
CloseButton.Visible = ShowCloseButton;
litMessage.Text = message;
MessageBox.CssClass = messageType.ToString().ToLower();
this.Visible = true;
}
#endregion
#region Enum
public enum MessageType
{
Error = 1,
Info = 2,
Success = 3,
Warning = 4
}
#endregion
}
Ok I think I reproduced roughly what your describing and I deleted my original answer cause it was way off.
What I found is that when you want a content page to reference a user control being used in a master page and the control is accesible and what not, you will get an error indicating that you need to reference a specific assembly, and then you get errors indicating that no Method exists of type such and such.
By adding the Register page directive on the child page to the user control resolved this issue. I reproduced this even with the control defined in the web.config or on the page. In both cases I still had to explicitly add a Register on the content page.
This doesn't make sense to me but it allowed my code to compile and work. Give it a shot let me know.
Once you do this you can reference the control like
this.Master.MessageBox.ShowInfo();
This assumes that you have a public property called MessageBox on the Master Page.
Edit
I've also found that this works much better if you register the control on both the master and the content page and not use the web.config.
Edit
If you don't want your child page to reference the user control your other option is expose methods on the master page like ShowInfo() which would delegate to the user control.
You need to declare it as your control type to access it's properties.
public MyMessageBox BCError;
BCError = (MyMessageBox )Master.FindControl("BCError");
Try using this in the pages that inherit from your master page:
<%# MasterType VirtualPath="~/MasterPageName.Master" %>

Resources