gtk#: remove a column by its column name - mono

I have a TreeView in GTK# and want to remove specific columns.
How can I achieve this?
TreeView.RemoveColumn() sounds good, but I've got no idea how to find the desired columns by their names.
Thinking of something like
TreeView.RemoveColumn( TreeView.FindColumn("address"));
I really have no idea... :'-(

You can do a sequential search over the columns, this way:
/// <summary>
/// Finds a column by its title.
/// </summary>
/// <returns>The first <see cref="Gtk.TreeViewColumn"/> with that title.</returns>
/// <param name="tv">The given <see cref="Gtk.TreeView"/>.</param>
/// <param name="title">The title to look for.</param>
static Gtk.TreeViewColumn FindColumnByTitle(Gtk.TreeView tv, string title)
{
Gtk.TreeViewColumn toret = null;
title = title.ToLower();
foreach(Gtk.TreeViewColumn column in tv.Columns) {
if ( column.Title.ToLower() == title ) {
toret = column;
break;
}
}
return toret;
}
Hope this helps.

Related

Is either of these VB.NET methods faster: SaveSetting() or SetValue()?

I update my app's metrics a lot in registry, and want to know which method of writing to system registry is significantly faster.
If you use a .NET decompiler to peek into the source code of the Interaction class/module under the Microsoft.VisualBasic namespace, you'll find that the SaveSetting() method actually uses SetValue() under the hood:*
/// <summary>Saves or creates an application entry in the Windows registry. The My feature gives you greater productivity and performance in registry operations than SaveSetting. For more information, see <see cref="P:Microsoft.VisualBasic.Devices.ServerComputer.Registry" />.</summary>
/// <param name="AppName">Required. String expression containing the name of the application or project to which the setting applies.</param>
/// <param name="Section">Required. String expression containing the name of the section in which the key setting is being saved.</param>
/// <param name="Key">Required. String expression containing the name of the key setting being saved.</param>
/// <param name="Setting">Required. Expression containing the value to which <paramref name="Key" /> is being set.</param>
/// <exception cref="T:System.ArgumentException">Key registry could not be created, or user is not logged in.</exception>
/// <filterpriority>1</filterpriority>
/// <PermissionSet>
/// <IPermission class="System.Security.Permissions.RegistryPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
/// </PermissionSet>
public static void SaveSetting(string AppName, string Section, string Key, string Setting)
{
Interaction.CheckPathComponent(AppName);
Interaction.CheckPathComponent(Section);
Interaction.CheckPathComponent(Key);
string text = Interaction.FormRegKey(AppName, Section);
RegistryKey registryKey = Registry.CurrentUser.CreateSubKey(text);
if (registryKey == null)
{
throw new ArgumentException(Utils.GetResourceString("Interaction_ResKeyNotCreated1", new string[]
{
text
}));
}
try
{
registryKey.SetValue(Key, Setting);
}
catch (Exception ex)
{
throw ex;
}
finally
{
registryKey.Close();
}
}
Or in VB, if you prefer:
''' <summary>Saves or creates an application entry in the Windows registry. The My feature gives you greater productivity and performance in registry operations than SaveSetting. For more information, see <see cref="P:Microsoft.VisualBasic.Devices.ServerComputer.Registry" />.</summary>
''' <param name="AppName">Required. String expression containing the name of the application or project to which the setting applies.</param>
''' <param name="Section">Required. String expression containing the name of the section in which the key setting is being saved.</param>
''' <param name="Key">Required. String expression containing the name of the key setting being saved.</param>
''' <param name="Setting">Required. Expression containing the value to which <paramref name="Key" /> is being set.</param>
''' <exception cref="T:System.ArgumentException">Key registry could not be created, or user is not logged in.</exception>
''' <filterpriority>1</filterpriority>
''' <PermissionSet>
''' <IPermission class="System.Security.Permissions.RegistryPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
''' </PermissionSet>
Public Sub SaveSetting(AppName As String, Section As String, Key As String, Setting As String)
Interaction.CheckPathComponent(AppName)
Interaction.CheckPathComponent(Section)
Interaction.CheckPathComponent(Key)
Dim text As String = Interaction.FormRegKey(AppName, Section)
Dim registryKey As RegistryKey = Registry.CurrentUser.CreateSubKey(text)
If registryKey Is Nothing Then
Throw New ArgumentException(Utils.GetResourceString("Interaction_ResKeyNotCreated1", New String() { text }))
End If
Try
registryKey.SetValue(Key, Setting)
Catch ex As Exception
Throw ex
Finally
registryKey.Close()
End Try
End Sub
Therefore, I would expect them to have the same performance in this particular case (assuming you will be basically replicating the same behavior). However, the Microsoft.Win32.Registry class (or the My.Computer.Registry property, which is just a wrapper for the said class) is going to be more flexible and provides more options as noted in the documentation (thanks, Jimi!) and in the XML comments shown above.
As to the performance, to be 100% certain (assuming you actually need to), then you should always measure.
* This code was extracted using ILSpy.

Share a document with specified user in Google Drive

I want to share a file that exists in Google Drive with a specified user. The file is not public.
Firstly, I want to show a file in a WebBrowser control.
Secondly, I want that when I share an URL to a different user, they can then show the file in their Google Drive.
Here is my code, I already can do the first step but for the second step, I don't know how I can do it.
Public Sub A(fichier As String)
CreateService()
Dim url As String = ""
Dim list = Service.Files.List()
Dim count = list.Execute()
For Each fich In count.Items
If (fich.Title) = fichier Then
url = fich.WebContentLink
Exit For
End If
Next
affich_image.img.Navigate(url)
affich_image.Show()
You can use the permissions.insert method.
Inserts a permission for a file or Team Drive.
To see the parameters and further details, try to visit the documentation.
Here, I provide you the sample code for .NET that was introduced in the said documentation.
using Google.Apis.Drive.v2;
using Google.Apis.Drive.v2.Data;
using System.Net;
// ...
public class MyClass {
// ...
/// <summary>
/// Insert a new permission.
/// </summary>
/// <param name="service">Drive API service instance.</param>
/// <param name="fileId">ID of the file to insert permission for.</param>
/// <param name="value">
/// User or group e-mail address, domain name or null for "default" type.
/// </param>
/// <param name="type">The value "user", "group", "domain" or "default".</param>
/// <param name="role">The value "owner", "writer" or "reader".</param>
/// <returns>The inserted permission, null is returned if an API error occurred</returns>
public static Permission InsertPermission(DriveService service, String fileId, String value,
String type, String role) {
Permission newPermission = new Permission();
newPermission.Value = value;
newPermission.Type = type;
newPermission.Role = role;
try {
return service.Permissions.Insert(newPermission, fileId).Execute();
} catch (Exception e) {
Console.WriteLine("An error occurred: " + e.Message);
}
return null;
}
// ...
}
You may also visit this SO post for further discussion.

Merging PDF and Compressing files .net

i am trying merge and compress PDF files using bitmiracle.docotic.pdf library(trial version) and for a merged file of size 700MB i am facing "out of memory exception", below is my code
/// <summary>
/// Open file for copy.
/// </summary>
/// <param name="file">File name.</param>
/// <param name="outputDocument">Output pdf document.</param>
private void OpenFileForCopy(string file, PdfDocument outputDocument)
{
if (isFirstFile)
{
outputDocument.Open(file);
}
else {
outputDocument.Append(file);
}
}
/// <summary>
/// Saves PDF merged pdf file to location specified.
/// </summary>
/// <param name="outputDocument">Merged pdf document.</param>
/// <param name="path">Path to be stored.</param>
/// <param name="source">Source of file.</param>
/// <param name="Number">Number.</param>
private string[] SavePDF(PdfDocument outputDocument, string path, string source, string Number)
{
string[] result = new string[2];
outputDocument.PageLayout = PdfPageLayout.SinglePage;
string newPath = path + "_" + "Merged";
string nor= Number.Substring(1);
Directory.CreateDirectory(newPath);
newPath += "\\Stmt" + source + nor+ ".pdf";
outputDocument.SaveOptions.Compression = BitMiracle.Docotic.Pdf.PdfCompression.Flate;
outputDocument.SaveOptions.UseObjectStreams = true;
outputDocument.SaveOptions.RemoveUnusedObjects = true;
outputDocument.SaveOptions.OptimizeIndirectObjects = false;
outputDocument.SaveOptions.WriteWithoutFormatting = true;
outputDocument.Save(newPath);
outputDocument.Dispose();
isFirstFile = true;
result[0] = source ;
result[1] = Convert.ToString(fileCount);
fileCount = 0;
return result;
}
The instance of PdfDocument happens to be used across methods
Kindly let me know if anything needs to modified
Thanks,
Kirankumar
Your code is ok. Jut please note that amount of memory the library consumes is proportional to total size and number of appended documents.
I would recommend you to save and re-open documents once in a while to reduce amount of memory consumed by the library. You can also use the following setting for intermediate saves.
outputDocument.SaveOptions.UseObjectStreams = false;
So, I propose you to try the following process:
Open document
Append no more than 10 (or other number) documents
Save document (intermediate save)
Open the document you just saved
Append next batch of documents
...
Please note that current version of the library can lead to out of memory exceptions even when the proposed process is used.

sitecore search synonyms file location

I've changed my DefaultIndexConfiguration config file to search based on synonyms (http://firebreaksice.com/sitecore-synonym-search-with-lucene/) and it works fine. However this is based in a xml file in the filesystem
<param hint="engine" type="Sitecore.ContentSearch.LuceneProvider.Analyzers.XmlSynonymEngine, Sitecore.ContentSearch.LuceneProvider">
<param hint="xmlSynonymFilePath">C:\inetpub\wwwroot\website\Data\synonyms.xml</param>
</param>
What I'd like to do is to have this data manageable in the CMS.
Does anyone know how can I set this xmlSynonymFilePath parameter to achieve what I want? Or am I missing something?
The simplest solution would be to create an item in Sitecore (e.g. /sitecore/system/synonyms) using the template with only one multi-line field called Synonyms and keep xml in this field instead of reading it from file.
Then create your custom implementation of ISynonymEngine like that (this is just simplest example - it's NOT production ready code):
public class CustomSynonymEngine : Sitecore.ContentSearch.LuceneProvider.Analyzers.ISynonymEngine
{
private readonly List<ReadOnlyCollection<string>> _synonymGroups = new List<ReadOnlyCollection<string>>();
public CustomSynonymEngine()
{
Database database = Sitecore.Context.ContentDatabase ?? Sitecore.Context.Database ?? Database.GetDatabase("web");
Item item = database.GetItem("/sitecore/system/synonyms"); // or whatever is the path
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(item["synonyms"]);
XmlNodeList xmlNodeList = xmlDocument.SelectNodes("/synonyms/group");
if (xmlNodeList == null)
throw new InvalidOperationException("There are no synonym groups in the file.");
foreach (IEnumerable source in xmlNodeList)
_synonymGroups.Add(
new ReadOnlyCollection<string>(
source.Cast<XmlNode>().Select(synNode => synNode.InnerText.Trim().ToLower()).ToList()));
}
public IEnumerable<string> GetSynonyms(string word)
{
Assert.ArgumentNotNull(word, "word");
foreach (ReadOnlyCollection<string> readOnlyCollection in _synonymGroups)
{
if (readOnlyCollection.Contains(word))
return readOnlyCollection;
}
return null;
}
}
And register your engine in Sitecore configuration instead of default engine:
<analyzer type="Sitecore.ContentSearch.LuceneProvider.Analyzers.PerExecutionContextAnalyzer, Sitecore.ContentSearch.LuceneProvider">
<param desc="defaultAnalyzer" type="Sitecore.ContentSearch.LuceneProvider.Analyzers.DefaultPerFieldAnalyzer, Sitecore.ContentSearch.LuceneProvider">
<param desc="defaultAnalyzer" type="Sitecore.ContentSearch.LuceneProvider.Analyzers.SynonymAnalyzer, Sitecore.ContentSearch.LuceneProvider">
<param hint="engine" type="My.Assembly.Namespace.CustomSynonymEngine, My.Assembly">
</param>
</param>
</param>
</analyzer>
This is NOT production ready code - it only reads the list of synonyms once when the CustomSynonymsEngine class is instantiated (I don't know if Sitecore keeps the instance or creates new instance multiple times).
You should extend this code to cache the synonyms and clear the cache every time a synonyms list is changed.
Also you should think about having a nice synonyms structure in the Sitecore tree instead of having a one item and xml blob which will be really hard to maintain.

MVC 4.0 - sign in using Google

I know there's a lot of information about this subject, but I just can't seem to find an answer suitable to my specific needs:
I opened a new MVC 4.0 basic application (meaning, no "AuthConfig.cs" file exist).
I have already successfully implemented Facebook sign-in.
I can't seem to find any way to do the same with Google.
I already have a custom "Connect with google" button. I need a very simple code to authenticate using google. Please bare in mind, that after authentication, I need to get user information, and also get a hold of the user's calendar.
Please help
Thank you.
Some Code to help you get started
In AuthConfig file
OAuthWebSecurity.RegisterClient(new Mvc.GoogleCustomClient(), "Google", null);
In GoogleCustomClient.cs
public class GoogleCustomClient : OpenIdClient
{
public GoogleCustomClient()
: base("google", WellKnownProviders.Google) { }
/// <summary>
/// Gets the extra data obtained from the response message when authentication is successful.
/// </summary>
/// <param name="response">
/// The response message.
/// </param>
/// <returns>A dictionary of profile data; or null if no data is available.</returns>
protected override Dictionary<string, string> GetExtraData(IAuthenticationResponse response)
{
FetchResponse fetchResponse = response.GetExtension<FetchResponse>();
if (fetchResponse != null)
{
var extraData = new Dictionary<string, string>();
extraData.Add("email", fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.Email));
extraData.Add("country", fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.HomeAddress.Country));
extraData.Add("firstName", fetchResponse.GetAttributeValue(WellKnownAttributes.Name.First));
extraData.Add("lastName", fetchResponse.GetAttributeValue(WellKnownAttributes.Name.Last));
return extraData;
}
return null;
}
/// <summary>
/// Called just before the authentication request is sent to service provider.
/// </summary>
/// <param name="request">
/// The request.
/// </param>
protected override void OnBeforeSendingAuthenticationRequest(IAuthenticationRequest request)
{
// Attribute Exchange extensions
var fetchRequest = new FetchRequest();
fetchRequest.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
fetchRequest.Attributes.AddRequired(WellKnownAttributes.Contact.HomeAddress.Country);
fetchRequest.Attributes.AddRequired(WellKnownAttributes.Name.First);
fetchRequest.Attributes.AddRequired(WellKnownAttributes.Name.Last);
request.AddExtension(fetchRequest);
}
}
You can Use this Code to retrieve the User Information from google.