I have a test project which is a library. I want to write a console application to be able to reference the DLL of the test project and call the methods and classes from my test project.
Also while writing the console app, I want to how to execute the exe from command prompt with parameters. My console app code should take in the input I give and execute the tests.
I just need some example code, so that I can pick it up from there.
You have to follow these steps:
Add your DLL file as reference to your console project.
Project>>Add Reference>>Browse and select your dll file.
add usign myNamespaceOfMyDll;
Then in your code you can use the methods from your dll file.
Sample (Using the GMmap's dll):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GMap.NET;
usign myNamespace;
namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
//GPoint is a user data type declared in GMap.NET
//method is a method definied in myNamespace (your dll)
GPoint s=method(param1,param2);
}
}
}
Suppose that you have the next code, you have to add an array of strings as param in your main method.
using System;
class Program
{
static void Main(string[] args)
{
if (args == null)
{
Console.WriteLine("args is null"); // Check for null array
}
else
{
//Here you can to use then content of your args array.
}
Console.ReadLine();
}
}
Thus if you type:
c:\> myApp param1 param2
args[0]="param1", args[1]="param2", and the length of the array is 2.
Related
I have prepared a .net core console application (Framework version .Net Core 2.2) for sending email as a service. Right now its working completely fine with static html content being hardcoded into service method for generating email body string.
I am in seek of the code which provides me a solution to render a razor view to have a html string with the model data.
Tried to implement the RazorEngine dll in entity framework ver. 4.5. with below code
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GenerateEmailUsingRazor.Model;
using RazorEngine.Templating;
namespace GenerateEmailUsingRazor
{
class Program
{
static readonly string TemplateFolderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "EmailTemplates");
static void Main(string[] args)
{
var model = GetUserDetail();
var emailTemplatePath = Path.Combine(TemplateFolderPath, "InviteEmailTemplate.cshtml");
var templateService = new TemplateService();
var emailHtmlBody = templateService.Parse(File.ReadAllText(emailTemplatePath), model, null, null);
Console.WriteLine(emailHtmlBody);
Console.ReadLine();
}
private static UserDetail GetUserDetail()
{
var model = new UserDetail()
{
Id = 1,
Name = "Test User",
Address = "Dummy Address"
};
for (int i = 1; i <= 10; i++)
{
model.PurchasedItems.Add("Item No " + i);
}
return model;
}
}
}
Expected Result:
Console Application should render the razor view and provide me the resultant html string.
I've written a clean library Razor.Templating.Core that works with .NET Core 3.0, 3.1 on both web and console app.
It's available as NuGet package.
After installing, you can call like
var htmlString = await RazorTemplateEngine
.RenderAsync("/Views/ExampleView.cshtml", model, viewData);
Note: Above snippet won't work straight away. Please refer the below working guidance on how to apply it.
Complete Working Guidance: https://medium.com/#soundaranbu/render-razor-view-cshtml-to-string-in-net-core-7d125f32c79
Sample Projects: https://github.com/soundaranbu/RazorTemplating/tree/master/examples
I've noticed a Seed folder in MyProject.EntityFrameworkCore project with the code to seed initial data to the database.
If I add code to populate the database with my new entity, where and how will the code be called?
Do the .NET Core and the full .NET Framework versions work the same way?
It is run:
On application startup, called in the PostInitialize method of YourEntityFrameworkModule:
public override void PostInitialize()
{
if (!SkipDbSeed)
{
SeedHelper.SeedHostDb(IocManager);
}
}
If you build Migrator project and run the .exe, called in Run method of MultiTenantExecuter:
public void Run(bool skipConnVerification)
{
// ...
Log.Write("HOST database migration started...");
try
{
_migrator.CreateOrMigrateForHost(SeedHelper.SeedHostDb);
}
// ...
}
If you add new code to populate your custom entity, remember to check before adding, like this:
var defaultEdition = _context.Editions.IgnoreQueryFilters().FirstOrDefault(e => e.Name == EditionManager.DefaultEditionName);
if (defaultEdition == null)
{
// ...
/* Add desired features to the standard edition, if wanted... */
}
Yes, the .NET Core and full .NET Framework versions work the same way.
I'm trying to work on ASP.NET 5 application. Here is a class and it looks good (no red curly underlines). But when I try to build, it gives error - SymmetricAlgorithm' does not contain a definition for 'Create'
using System;
using System.IO;
using System.Security.Cryptography;
namespace SalesBook
{
public static class Encryptor
{
private static byte[] EncryptString(string data)
{
byte[] byteData = Common.GetByte(data);
SymmetricAlgorithm algo = SymmetricAlgorithm.Create();
}
}
}
I'm using .net 4.6.1.
Any help?
This method has not been ported to .NET Core. The recommended alternative is to use the specific Create method associated with the algorithm you need:
var algorithm = Aes.Create();
On CoreCLR, it will automatically determine and return the best implementation, depending on your OS environement.
If you don't need .NET Core support, you can remove the dnxcore50/dotnet5.4 from your project.json.
Have created a brand new Visual Studio 2012 Ultimate SP2 MVC4 project but unable to get CSS class selector intellisense to work?
When I type <p class="m" .... I should get the class "myClass" appearing in intellisense dropdown but nothing happens.
The file I have listed below is: \Views\Shared\_Layout.cshtml
Any Ideas ?
Edit: Have re-installed VS2012 on brand new windows 7 system (running on Mac OSX parallels 8) and still acting in the same way. Also seems the same for MVC 3 projects.
Extensions installed:
Try adding Web Essentials 2012 extension for Visual Studio 2012: http://visualstudiogallery.msdn.microsoft.com/07d54d12-7133-4e15-becb-6f451ea3bea6?SRC=VSIDE
And/Or
Try adding Microsoft Web Developer Tools extension.
I have both of these and using your same example the intellisense works like a charm.
I tried all the above mentioned remedies and suggestions. None of these worked in my environment. According to Microsoft (Under Microsoft connect's bug id 781048), they have not implemented CSS class intellisense for MVC/Razor files but are working on including this in a future release.
I have a 10 minute webcast example of extending VS2012 intellisense that adds one solution that will add intellisense to your VS2012 environment: a Visual Studio Intellisense Extension
The webcast uses MEF to extend Visual Studio to add an intellisense completion source that scans the currently loaded project for CSS class names to add as an intellisense completion set. Here is the css completion source class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Utilities;
using EnvDTE;
using System.Text.RegularExpressions;
using System.Configuration;
using System.Collections.Specialized;
namespace CssClassIntellisense
{
internal class cssClassList
{
public string cssFileName { get; set; } //Intellisense Statement Completion Tab Name
public HashSet<string> cssClasses { get; set; }
}
internal class CssClassCompletionSource : ICompletionSource
{
private CssClassCompletionSourceProvider m_sourceProvider;
private ITextBuffer m_textBuffer;
private List<Completion> m_compList;
private Project m_proj;
private string m_pattern = #"(?<=\.)[A-Za-z0-9_-]+(?=\ {|{|,|\ )";
private bool m_isDisposed;
//constructor
public CssClassCompletionSource(CssClassCompletionSourceProvider sourceProvider, ITextBuffer textBuffer, Project proj)
{
m_sourceProvider = sourceProvider;
m_textBuffer = textBuffer;
m_proj = proj;
}
public void AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets)
{
ITextSnapshot snapshot = session.TextView.TextSnapshot;
SnapshotPoint currentPoint = (SnapshotPoint)session.GetTriggerPoint(snapshot);
if (TargetAttribute.Inside(currentPoint))
{
var hash = new List<cssClassList>();
//read any .css project file to get a distinct list of class names
if (m_proj != null)
foreach (ProjectItem _item in m_proj.ProjectItems)
{
getCssFiles(_item, hash);
}
//Scan Current Editor's text buffer for any inline css class names
cssClassList cssclasslist = ScanTextForCssClassName(
"Inline", snapshot.GetText());
//If file had any css class names add to hash of files with css class names
if (cssclasslist != null)
hash.Add(cssclasslist);
var _tokenSpanAtPosition = FindTokenSpanAtPosition(session.GetTriggerPoint(m_textBuffer), session);
foreach (cssClassList _cssClassList in hash)
{
m_compList = new List<Completion>();
foreach (string str in _cssClassList.cssClasses.OrderBy(x => x)) //alphabetic sort
m_compList.Add(new Completion(str, str, str, null, null));
completionSets.Add(new CompletionSet(
_cssClassList.cssFileName, //the non-localized title of the tab
_cssClassList.cssFileName, //the display title of the tab
_tokenSpanAtPosition,
m_compList,
null));
}
}
}
private ITrackingSpan FindTokenSpanAtPosition(ITrackingPoint point, ICompletionSession session)
{
SnapshotPoint currentPoint = (session.TextView.Caret.Position.BufferPosition) - 1;
ITextStructureNavigator navigator = m_sourceProvider.NavigatorService.GetTextStructureNavigator(m_textBuffer);
TextExtent extent = navigator.GetExtentOfWord(currentPoint);
return currentPoint.Snapshot.CreateTrackingSpan(extent.Span, SpanTrackingMode.EdgeInclusive);
}
private void getCssFiles(ProjectItem proj, List<cssClassList> hash)
{
foreach (ProjectItem _item in proj.ProjectItems)
{
if (_item.Name.EndsWith(".css") &&
!_item.Name.EndsWith(".min.css"))
{
//Scan File's text contents for css class names
cssClassList cssclasslist = ScanTextForCssClassName(
_item.Name.Substring(0, _item.Name.IndexOf(".")),
System.IO.File.ReadAllText(_item.get_FileNames(0))
);
//If file had any css class names add to hash of files with css class names
if (cssclasslist != null)
hash.Add(cssclasslist);
}
//recursively scan any subdirectory project files
if (_item.ProjectItems.Count > 0)
getCssFiles(_item, hash);
}
}
private cssClassList ScanTextForCssClassName(string FileName, string TextToScan)
{
Regex rEx = new Regex(m_pattern);
MatchCollection matches = rEx.Matches(TextToScan);
cssClassList cssclasslist = null;
if (matches.Count > 0)
{
//create css class file object to hold the list css class name that exists in this file
cssclasslist = new cssClassList();
cssclasslist.cssFileName = FileName;
cssclasslist.cssClasses = new HashSet<string>();
}
foreach (Match match in matches)
{
//creat a unique list of css class names
if (!cssclasslist.cssClasses.Contains(match.Value))
cssclasslist.cssClasses.Add(match.Value);
}
return cssclasslist;
}
public void Dispose()
{
if (!m_isDisposed)
{
GC.SuppressFinalize(this);
m_isDisposed = true;
}
}
}
}
As an FYI, you can also address this issue using Resharper. But that is a 3rd party product that needs to be purchased for Visual Studio
Is it just CSS intellisense that's failed or has it completely stopped throughout Visual Studio?
I had a similar issue that effected the whole of my Visual Studio 2012. It was a while back but I remember deleting a folder from my appdata. Take a look at this link, hopefully it will help:
http://www.haneycodes.net/visual-studio-2012-intellisense-not-working-solved/
You are not going to get intellisense for CSS in VS2012 for Razor views. There is a workaround to use intellisense. Just create one test view(.aspx) using ASPX view engine and include your css file there. Now intellisense will work in new aspx view. All you have to do is copy paste the css class from aspx to Razor view(.cshtml or .vbhtml). I hope this helps.
I have searched high and low on RavenDB Put Trigger. However, I couldn't find a source where I can get the task completed. Here is my little dll code that I have stored inside Ravendb's Plugins folder - I am using build 960. My question is, how do I go from here.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Raven.Database.Plugins;
using System.Collections.Concurrent;
using Raven.Json.Linq;
using Raven.Abstractions.Data;
using System.Diagnostics;
namespace Raven.Tryouts
{
public class MyPutTrigger : AbstractPutTrigger
{
public override void OnPut(string key, Json.Linq.RavenJObject document, Json.Linq.RavenJObject metadata, Abstractions.Data.TransactionInformation transactionInformation)
{
base.OnPut(key, document, metadata, transactionInformation);
Debug.WriteLine("OnPut: " + key);
}
public override void AfterPut(string key, Json.Linq.RavenJObject document, Json.Linq.RavenJObject metadata, Guid etag, Abstractions.Data.TransactionInformation transactionInformation)
{
base.AfterPut(key, document, metadata, etag, transactionInformation);
Debug.WriteLine("AfterPut:" + key);
}
public override void AfterCommit(string key, Json.Linq.RavenJObject document, Json.Linq.RavenJObject metadata, Guid etag)
{
base.AfterCommit(key, document, metadata, etag);
Debug.WriteLine("AfterCommit:" + key);
}
}
}
Compile this code.
Take the resulting dll and place it in the Plugins directory (next to the .config file). If necessary, create the Plugins directory.
Restart Raven
Debug.WriteLine does not write to the RavenDB debug log. Start Sysinternals DebugView on the server where Raven is running to view the system debug output - there you'll see the diagnostic output from the example trigger.