How to programmatically sign a project in c sharp - envdte

I am creating projects from a template using DTE. I want the projects to be signed by a particular .snk file. How to do it programmatically??
please help..!!
Thanks,
Girish

What I did is add a new Addin project into my solution and by adding this code:
public void OnConnection(object application, ext_ConnectMode connectMode, objec addInInst, ref Array custom)
{
_applicationObject = (DTE2)application;
_addInInstance = (AddIn)addInInst;
SetSign(_applicationObject);
}
public void SetSign(DTE2 app)
{
Solution solution = app.Solution;
foreach (Project proj in solution.Projects)
{
if (null != proj.Properties && null != proj.Properties.Item("SignAssembly"))
{
Property projProperty = proj.Properties.Item("SignAssembly");
bool signed = (bool)projProperty.Value;
if (!signed)
{
proj.Properties.Item("AssemblyOriginatorKeyFile").Value = #"C:\Projects\ClassLibrary1\Addins\Tools\mykeyfile.pfx";
proj.Properties.Item("SignAssembly").Value = true;
}
proj.Save();
}
}
}

Related

Which package should I use to embed admob in xamarin-forms?

I was thinking to use the Xamarin.GooglePlayServices.Ads.Lite package https://www.youtube.com/watch?v=6teJvSCg6UA&t=661s
But I can't find up-to-date instruction for embedding admob in xamarin-forms.
I registered with admob but found instructions only for kotlin and java.
Which package is currently relevant for xamarin-forms? And is there an up-to-date implementation guide?
You could create a control and do that with custom renderer.
Custom control:
public class AdControlView : View
{
}
Custom renderer:
[assembly: ExportRenderer(typeof(AdControlView), typeof(AdViewRenderer))]
namespace App14.Droid
{
public class AdViewRenderer : ViewRenderer<AdControlView, AdView>
{
public AdViewRenderer(Context context) : base(context)
{
}
string adUnitId = string.Empty;
//Note you may want to adjust this, see further down.
AdSize adSize = AdSize.Banner;
AdView adView;
AdView CreateNativeAdControl()
{
if (adView != null)
return adView;
adUnitId = "ca-app-pub-3940256099942544/6300978111"; //you could create you own unit id.
adView = new AdView(Forms.Context);
adView.AdSize = adSize;
adView.AdUnitId = adUnitId;
var adParams = new LinearLayout.LayoutParams(LayoutParams.WrapContent, LayoutParams.WrapContent);
adView.LayoutParameters = adParams;
adView.LoadAd(new AdRequest
.Builder()
.Build());
return adView;
}
protected override void OnElementChanged(ElementChangedEventArgs<AdControlView> e)
{
base.OnElementChanged(e);
if (Control == null)
{
CreateNativeAdControl();
SetNativeControl(adView);
}
}
}
}
Create your own application id and unitid or you could get the test ads on Google Admob.
For more details, please refer to the case i done before.
How to use App ID in Xamarin Visual Studio

HERE sdk Lite edition for android autosuggest return PARSING_ERROR

I'm a user HERE sdk Lite edition for android, mainly using the autosuggest search place feature. My application is already running and functioning properly. To this day problems arise so that they don't work. After I checked it turns out that in the SuggestCallback class section it return PARSING_ERROR. Please help
here is SuggestCallback class:
private final SuggestCallback autosuggestCallback = new SuggestCallback() {
#Override
public void onSuggestCompleted(#Nullable SearchError searchError, #Nullable List<Suggestion> list) {
if (searchError != null) {
//Log.d(LOG_TAG, "Autosuggest Error: " + searchError.name());
Toast.makeText(HereMapsActivity.this, "" + searchError.name(), Toast.LENGTH_SHORT).show();
return;
}
for (Suggestion autosuggestResult : list) {
String addressText = "Not a place.";
Place place = autosuggestResult.getPlace();
if (place != null) {
addressText = place.getAddress().addressText;
datatmp.add(new DataListLocation(
addressText,
place.getCoordinates().latitude,
place.getCoordinates().longitude
));
}else{
datatmp = new ArrayList<>();
}
adapterListLocation = new AdapterListLocation(HereMapsActivity.this, datatmp);
lstview.setAdapter(adapterListLocation);
}
progressDialog.dismiss();
}
};

Xamarin.Forms Directory Picker

I would like to save a file in a user selected folder, thats why I would like to provide a directory list to user and user will be able to choose the directory where he wants to export the data. Unfortuntely I could not find any example for directory/folder picker, I just found a file picker which is not useful for me..
https://github.com/jfversluis/FilePicker-Plugin-for-Xamarin-and-Windows
Is there any component for picking a folder for Xamarin.Forms? Actually I am just doing for Android but we use Xamarin.forms
There is none I can think of.
With netstandard everything is way more simple as you can use the classic c# File api to get the folders.
You just have to know the mappings between special folders and android folders (per example):
System.Environment.SpecialFolder Path
ApplicationData INTERNAL_STORAGE/.config
Desktop INTERNAL_STORAGE/Desktop
LocalApplicationData INTERNAL_STORAGE/.local/share
MyDocuments INTERNAL_STORAGE
MyMusic INTERNAL_STORAGE/Music
MyPictures INTERNAL_STORAGE/Pictures
MyVideos INTERNAL_STORAGE/Videos
Personal INTERNAL_STORAGE
source: https://learn.microsoft.com/en-US/xamarin/android/platform/files/
same for ios:
https://learn.microsoft.com/en-US/xamarin/ios/app-fundamentals/file-system
But it's really easy to implement, just enumerate all folders and display them in a ListView.
EDIT: more details on implementation.
In fact you want to code a "directory explorer", it's easy, here is the concept.
You have a ListView in your Page
You have a Cancel button and a Select button in your Page
You have a CurrentPath in your ViewModel
You bind CurrentPath to the Title of your Page
You have an List<DirectoryViewModel> Directories in your ViewModel
Each time a user click on a item from the list:
You add the directory name in your current path
You get all the directories from the new path, and update your Directories property (don't forget RaisePropertyChange(nameof(Directories)))
The ListView will be updated accordingly
Each time you back:
You remove last part of your current path
same as before
If you arrive to root path "/", you do nothing when clicking on back.
Oh and you could use this Grid component to instead of the ListView, will be nicer ;)
https://github.com/roubachof/Sharpnado.Presentation.Forms#grid-Layout
You can edit this to make it work..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Java.IO;
using Java.Util;
namespace Android.Basic.IO
{
public class DirectoryPicker : ListActivity
{
public const String START_DIR = "startDir";
public const String ONLY_DIRS = "onlyDirs";
public const String SHOW_HIDDEN = "showHidden";
public const String CHOSEN_DIRECTORY = "chosenDir";
public const int PICK_DIRECTORY = 43522;
private File dir;
private Boolean showHidden = false;
private bool onlyDirs = true;
public override void OnCreate(Bundle savedInstanceState, PersistableBundle persistentState)
{
base.OnCreate(savedInstanceState, persistentState);
Bundle extras = Intent.Extras;
dir = OS.Environment.ExternalStorageDirectory;
if (extras != null)
{
String preferredStartDir = extras.GetString(START_DIR);
showHidden = extras.GetBoolean(SHOW_HIDDEN, false);
onlyDirs = extras.GetBoolean(ONLY_DIRS, true);
if (preferredStartDir != null)
{
File startDir = new File(preferredStartDir);
if (startDir.IsDirectory)
{
dir = startDir;
}
}
}
SetContentView(Resource.Layout.folder_chooser_activity);
var title = dir.AbsolutePath.ToString();
Title = (title);
Button btnChoose = (Button)FindViewById(Resource.Id.btnChoose);
String name = dir.Name;
if (name.Length == 0)
name = "/";
btnChoose.Text = ("Choose " + "'" + name + "'");
btnChoose.Click += delegate
{
returnDir(dir.AbsolutePath);
};
ListView lv = this.ListView;
lv.TextFilterEnabled = (true);
if (!dir.CanRead())
{
Context context = ApplicationContext;
String msg = "Could not read folder contents.";
Toast.MakeText(context, msg, ToastLength.Long).Show();
return;
}
var files = filter(dir.ListFiles(), onlyDirs, showHidden);
String[] names = Names(files);
ListAdapter = (new ArrayAdapter<String>(this, Resource.Layout.folder_chooser_item, names));
lv.ItemClick += (ff, gg) =>
{
var position = gg.Position;
if (!files[gg.Position].IsDirectory)
return;
String path = files[position].AbsolutePath;
var intent = new Intent(this, typeof(DirectoryPicker));
intent.PutExtra(DirectoryPicker.START_DIR, path);
intent.PutExtra(DirectoryPicker.SHOW_HIDDEN, showHidden);
intent.PutExtra(DirectoryPicker.ONLY_DIRS, onlyDirs);
StartActivityForResult(intent, PICK_DIRECTORY);
};
}
protected void OnActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == PICK_DIRECTORY && resultCode == (int)Result.Ok)
{
Bundle extras = data.Extras;
String path = (String)extras.Get(DirectoryPicker.CHOSEN_DIRECTORY);
returnDir(path);
}
}
private void returnDir(String path)
{
Intent result = new Intent();
result.PutExtra(CHOSEN_DIRECTORY, path);
SetResult(Result.Ok, result);
Finish();
}
public List<File> filter(File[] file_list, bool onlyDirs, bool showHidden)
{
var files = new List<File>();
foreach (var file in file_list)
{
if (onlyDirs && !file.IsDirectory)
continue;
if (!showHidden && file.IsHidden)
continue;
files.Add(file);
}
Collections.Sort(files);
return files;
}
public String[] Names(List<File> files)
{
String[] names = new String[files.Count];
int i = 0;
foreach (var file in files)
{
names[i] = file.Name;
i++;
}
return names;
}
}
}
Start activity as result then catch in OnActivityResult
if (requestCode == DirectoryPicker.PICK_DIRECTORY && resultCode == Result.Ok)
{
Bundle extras = data.Extras;
String path = (String)extras.Get(DirectoryPicker.CHOSEN_DIRECTORY);
// do stuff with path
}

ASP.NET Bundling and Minification removing license comments? [duplicate]

I have found this link:
http://giddyrobot.com/preserving-important-comments-in-mvc-4-bundles/
It shows how to do this same thing for JavaScript and I have used it to make an attempt for StyleBundles, but I'm unsure if it's doing things correctly on the backend.
Is the source code available? If not does anyone know if this seems right? All I want to keep is comments that start with /*! so that licenses for open source projects like normalize get included properly in production.
Here is what I have so far:
public static void RegisterBundles(BundleCollection bundles)
{
// Allows us to keep /*! comments for licensing purposes
var cssBundleSettings = new CssSettings
{
CommentMode = CssComment.Important
};
}
public class ConfigurableStyleBundle : Bundle
{
public ConfigurableStyleBundle(string virtualPath, CssSettings cssSettings) :
this(virtualPath, cssSettings, null) { }
public ConfigurableStyleBundle(string virtualPath, CssSettings cssSettings, string cdnPath) :
base(virtualPath, cdnPath, new[] { new ConfigurableCSSTransform(cssSettings) })
{
// commented out from js concatenation token not sure if this one should have one
//base.ConcatenationToken = ";";
}
}
[ExcludeFromCodeCoverage]
public class ConfigurableCSSTransform : IBundleTransform
{
private readonly CssSettings _cssSettings;
public ConfigurableCSSTransform(CssSettings cssSettings)
{
_cssSettings = cssSettings;
}
public void Process(BundleContext context, BundleResponse response)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (response == null)
{
throw new ArgumentNullException("response");
}
if (!context.EnableInstrumentation)
{
var minifier = new Minifier();
var content = minifier.MinifyStyleSheet(response.Content, _cssSettings);
if (minifier.ErrorList.Count > 0)
{
GenerateErrorResponse(response, minifier.ErrorList);
}
else
{
response.Content = content;
}
}
response.ContentType = "text/css";
}
internal static void GenerateErrorResponse(BundleResponse bundle, IEnumerable<object> errors)
{
var content = new StringBuilder();
content.Append("/* ");
content.Append("CSS MinifyError").Append("\r\n");
foreach (object current in errors)
{
content.Append(current.ToString()).Append("\r\n");
}
content.Append(" */\r\n");
content.Append(bundle.Content);
bundle.Content = content.ToString();
}
}
All of this is wrapped in public class BundleConfig and gets called from Global.asax.
I'm just wondering if CssComment.Important could have negative effects and remove too much and if this seems to be doing what I want it to? When I have tested it everything seems to look correct styling wise, but it doesn't hurt to get some eyes seeing as this is probably useful for a lot of other ASP.NET devs who use open source libraries.
I don't think you've done anything incorrectly. Though I would approach it using the IBundleBuilder interface, as this will also keep regular comments out of production from prying eyes who switch user agent, like specified in How to prevent User-Agent: Eureka/1 to return source code. I show some steps on how to test against this in this related blog post.
public class ConfigurableStyleBuilder : IBundleBuilder
{
public virtual string BuildBundleContent(Bundle bundle, BundleContext context, IEnumerable<BundleFile> files)
{
var content = new StringBuilder();
foreach (var file in files)
{
FileInfo f = new FileInfo(HttpContext.Current.Server.MapPath(file.VirtualFile.VirtualPath));
CssSettings settings = new CssSettings();
settings.CommentMode = Microsoft.Ajax.Utilities.CssComment.Important;
var minifier = new Microsoft.Ajax.Utilities.Minifier();
string readFile = Read(f);
string res = minifier.MinifyStyleSheet(readFile, settings);
if (minifier.ErrorList.Count > 0)
{
res = PrependErrors(readFile, minifier.ErrorList);
content.Insert(0, res);
}
else
{
content.Append(res);
}
}
return content.ToString();
}
private string PrependErrors(string file, ICollection<ContextError> errors )
{
var content = new StringBuilder();
content.Append("/* ");
content.Append("CSS MinifyError").Append("\r\n");
foreach (object current in errors)
{
content.Append(current.ToString()).Append("\r\n");
}
content.Append("Minify Error */\r\n");
content.Append(file);
return content.ToString();
}
private string Read(FileInfo file)
{
using (var r = file.OpenText())
{
return r.ReadToEnd();
}
}
}
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
var cssBundle = new ConfigurableStyleBundle("~/Content/css");
cssBundle.Include("~/Content/stylesheet1.css");
cssBundle.Include("~/Content/stylesheet2.css");
bundles.Add(cssBundle);
//etc
}
}
I made a NuGet package for this (including a version for scripts) - https://www.nuget.org/packages/LicensedBundler/

Downloading Multiple files from FTP Server using JSCH

I want to download all the files from FTP server using JSCH.
Below is the code snippet,
List<File> fileList = null;
Vector<ChannelSftp.LsEntry> list = sftpChannel.ls(remoteFolder);
for (ChannelSftp.LsEntry file : list) {
if( getLog().isDebugEnabled() ){
getLog().debug("Retrieved Files from the folder is"+file);
}
if (!(new File(file.getFilename())).isFile()) {
continue;
}
fileList.add(new File(remoteFolder,file.getFilename())) ;
return fileList;
The method will return List, for another method to download the files from the remote server using sftpChannel.get(src,dest) ;
Please let me know if the code is ok.
I don't have an environment to test, so can't confirm it.
But somewhat similar code i wrote for FTPClient and it works.
Appreciate your help.
You can use SftpATTRS to get the file information. You can declare a wrapper class to store file information. An example shown below.
private class SFTPFile
{
private SftpATTRS sftpAttributes;
public SFTPFile(LsEntry lsEntry)
{
this.sftpAttributes = lsEntry.getAttrs();
}
public boolean isFile()
{
return (!sftpAttributes.isDir() && !sftpAttributes.isLink());
}
}
Now you can use this class to test if the LsEntry is a file
private List<SFTPFile> getFiles(String path)
{
List<SFTPFile> files = null;
try
{
List<?> lsEntries = sftpChannel.ls(path);
if (lsEntries != null)
{
files = new ArrayList<SFTPFile>();
for (int i = 0; i < lsEntries.size(); i++)
{
Object next = lsEntries.get(i);
if (!(next instanceof LsEntry))
{
// throw exception
}
SFTPFile sftpFile = new SFTPFile((LsEntry) next);
if (sftpFile.isFile())
{
files.add(sftpFile);
}
}
}
}
catch (SftpException sftpException)
{
//
}
return files;
}
Now you can use sftpChannel.get(src,dest) ; to download files.

Resources