working on it ...

Filters

Explore Public Snippets

Sort by

Found 3,427 snippets matching: .net

    public by sTiLL-iLL @ SniPitz-KND  550000  5  8  16

    Async Queue in C#

    using System;
    using System.Net;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    
    public class ParalyzKue
    {
    	readonly object _locker = new object();
    	Task _tail = Task.FromResult (true);
    	
    	public Task Enqueue (Action action)
    	{
    		lock (_locker)
    			return _tail = _tail.ContinueWith (ant => action());
    	}
    
    	public Task<TResult> Enqueue<TResult> (Func<TResult> func)
    	{
    		lock (_locker)
    			return (Task<TResult>) (_tail = _tail.ContinueWith (ant => func()));
    	}
    
    	public Task Enqueue (Func<Task> action)
    	{
    		lock (_locker)
    			return _tail = _tail.Catch().Then (action);
    	}	
    
    	public Task<TResult> Enqueue<TResult> (Func<Task<TResult>> func)
    	{
    		lock (_locker)
    			return (Task<TResult>) (_tail = _tail.Catch().Then (func));
    	}
    }
    
    
    public static class Extensions
    {
    	public static Task<T> Catch<T,TError> (this Task<T> task, Func<TError,T> onError) where TError : Exception
    	{
    		var tcs = new TaskCompletionSource<T> ();
    		task.ContinueWith (ant => {
    			if (task.IsFaulted && task.Exception.InnerException is TError)
    			{
    				tcs.SetResult (onError ((TError) task.Exception.InnerException));
    			}
    			else if (ant.IsCanceled)
    			{
    				tcs.SetCanceled ();
    			}
    			else if (task.IsFaulted)
    			{
    				tcs.SetException (ant.Exception.InnerException);
    			}
    			else
    			{
    				tcs.SetResult (ant.Result);
    			}
    		});
    		return tcs.Task;
    	}		
    	public static Task<T> Catch<T,TError> (this Task<T> task, T onError) where TError : Exception
    	{
    		return task.Catch<T,TError> (ex => onError);
    	}
    	
    	public static Task<T> Catch<T,TError> (this Task task, T onError) where TError : Exception
    	{
    		return task.ToTaskOfT<T>().Catch<T,TError> (onError);
    	}
    
    	public static Task Catch (this Task task)
    	{
    		return task.Catch<object,Exception> (null);
    	}
    	
    	public static Task<T> Catch<T> (this Task<T> task, T valueIfError = default(T))
    	{
    		return task.Catch<T,Exception> (valueIfError);
    	}
    
    	public async static Task<T> ToTaskOfT<T> (this Task t)
    	{
    		await t;
    		return default(T);
    	}
    	
    	public static async Task Then(this Task task, Func<Task> continuation)
    	{
    		await task;
    		await continuation();
    	}
    	
    	public static async Task<TNewResult> Then<TNewResult>(this Task task, Func<Task<TNewResult>> continuation)
    	{
    		await task;
    		return await continuation();
    	}
    	
    	public static async Task Then<TResult>(this Task<TResult> task, Func<TResult,Task> continuation)
    	{
    		await continuation(await task);
    	}
    	
    	public static async Task<TNewResult> Then<TResult, TNewResult>(this Task<TResult> task, Func<TResult, Task<TNewResult>> continuation)
    	{
    		return await continuation(await task);
    	}
    }
    
    /*
    public void doKue()
    {
    	var pcQ = new ParaKue();
    	
      pcQ.Enqueue (() => AsyncMethod1 ("http://www.rotten.com/")).Dump ("Task 1");
    	pcQ.Enqueue (() => AsyncMethod1 ("https://youtube.com/")).Dump ("Task 2");
    	pcQ.Enqueue (() => AsyncMethod1 ("https://yahoo.com/search?q=the cube")).Dump ("Task 3");
      pcQ.Enqueue (() => AsyncMethod1 ("http://www.rotten.com/")).Dump ("Task 4");
    	pcQ.Enqueue (() => AsyncMethod1 ("https://youtube.com/")).Dump ("Task 5");
    	pcQ.Enqueue (() => AsyncMethod1 ("https://www.google.com/search?q=web scrapers")).Dump ("Task 6");
      pcQ.Enqueue (() => AsyncMethod1 ("http://www.rotten.com/")).Dump ("Task 7");
    	pcQ.Enqueue (() => AsyncMethod1 ("https://youtube.com/")).Dump ("Task 8");
    	pcQ.Enqueue (() => AsyncMethod1 ("https://youtube.com/search?q=aliens gods")).Dump ("Task 9");
      pcQ.Enqueue (() => AsyncMethod ("http://www.rotten.com/")).Dump ("Task 10");
    	pcQ.Enqueue (() => AsyncMethod ("https://youtube.com/")).Dump ("Task 11");
    	pcQ.Enqueue (() => AsyncMethod ("https://www.google.com/search?q=javascript")).Dump ("Task 12");
      pcQ.Enqueue (() => AsyncMethod ("http://www.rotten.com/")).Dump ("Task 13");
    	pcQ.Enqueue (() => AsyncMethod ("https://youtube.com/search?q=aliens")).Dump ("Task 14");
      pcQ.Enqueue (() => AsyncMethod ("https://www.yahoo.com/")).Dump ("Task 15");
    	pcQ.Enqueue (() => AsyncMethod ("https://youtube.com/")).Dump ("Task 16");
    	pcQ.Enqueue (() => AsyncMethod ("https://www.google.com/search?q=aliens disclosure")).Dump ("Task 17");
    }
    
    string SyncMethod (string uri)
    {
        var x = new System.Net.WebClient();
        var y = x.DownloadString(uri);
        return y;
    }
    
    async Task<string> AsyncMethod (string uri)
    {
       return await Task.Run(() => new System.Net.WebClient().DownloadStringTaskAsync(uri).Dump());
    }
    
    
    async Task<string> AsyncMethod1 (string uri)
    {
       var x = await new System.Net.WebClient().DownloadStringTaskAsync(uri);
       return x;
    }
    
    */

    public by sherazam  228310  0  5  0

    How to Insert Check Boxes or HTML into Word Docs during Mail Merge inside .NET Apps

    How to Insert Check Boxes or HTML into Word Docs during Mail Merge inside .NET Apps
    // Enter here the actual content of the snippet.            
    //[C# Code Sample]
     
    using System;
    using System.IO;
    using System.Reflection;
    using Aspose.Words;
    using Aspose.Words.Fields;
    using Aspose.Words.MailMerging;
    
    namespace MailMergeFormFields
    {
        /// <summary>
        /// This sample shows how to insert check boxes and text input form fields during mail merge into a document.
        /// </summary>
        class Program
        {
            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            public static void Main(string[] args)
            {
                Program program = new Program();
                program.Execute();
            }
    
            private void Execute()
            {
                string exeDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar;
                string dataDir = new Uri(new Uri(exeDir), @"../../Data/").LocalPath;
    
                // Load the template document.
                Document doc = new Document(dataDir + "Template.doc");
    
                // Setup mail merge event handler to do the custom work.
                doc.MailMerge.FieldMergingCallback = new HandleMergeField();
    
                // This is the data for mail merge.
                String[] fieldNames = new String[] {"RecipientName", "SenderName", "FaxNumber", "PhoneNumber",
                    "Subject", "Body", "Urgent", "ForReview", "PleaseComment"};
                Object[] fieldValues = new Object[] {"Josh", "Jenny", "123456789", "", "Hello",
                    "<b>HTML Body Test message 1</b>", true, false, true};
    
                // Execute the mail merge.
                doc.MailMerge.Execute(fieldNames, fieldValues);
    
                // Save the finished document.
                doc.Save(dataDir + "Template Out.doc");
            }
    
            private class HandleMergeField : IFieldMergingCallback
            {
                /// <summary>
                /// This handler is called for every mail merge field found in the document,
                ///  for every record found in the data source.
                /// </summary>
                void IFieldMergingCallback.FieldMerging(FieldMergingArgs e)
                {
                    if (mBuilder == null)
                        mBuilder = new DocumentBuilder(e.Document);
    
                    // We decided that we want all boolean values to be output as check box form fields.
                    if (e.FieldValue is bool)
                    {
                        // Move the "cursor" to the current merge field.
                        mBuilder.MoveToMergeField(e.FieldName);
    
                        // It is nice to give names to check boxes. Lets generate a name such as MyField21 or so.
                        string checkBoxName = string.Format("{0}{1}", e.FieldName, e.RecordIndex);
    
                        // Insert a check box.
                        mBuilder.InsertCheckBox(checkBoxName, (bool)e.FieldValue, 0);
    
                        // Nothing else to do for this field.
                        return;
                    }
    
                    // We want to insert html during mail merge.
                    if (e.FieldName == "Body")
                    {
                        mBuilder.MoveToMergeField(e.FieldName);
                        mBuilder.InsertHtml((string)e.FieldValue);
                    }
    
                    // Another example, we want the Subject field to come out as text input form field.
                    if (e.FieldName == "Subject")
                    {
                        mBuilder.MoveToMergeField(e.FieldName);
                        string textInputName = string.Format("{0}{1}", e.FieldName, e.RecordIndex);
                        mBuilder.InsertTextInput(textInputName, TextFormFieldType.Regular, "", (string)e.FieldValue, 0);
                    }
                }
    
                void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
                {
                    // Do nothing.
                }
    
                private DocumentBuilder mBuilder;
            }
        }
    }
     
    //[VB.NET Code Sample]
     
    
    Imports Microsoft.VisualBasic
    Imports System
    Imports System.IO
    Imports System.Reflection
    Imports Aspose.Words
    Imports Aspose.Words.Fields
    Imports Aspose.Words.MailMerging
    
    Namespace MailMergeFormFields
        ''' <summary>
        ''' This sample shows how to insert check boxes and text input form fields during mail merge into a document.
        ''' </summary>
        Friend Class Program
            ''' <summary>
            ''' The main entry point for the application.
            ''' </summary>
            Public Shared Sub Main(ByVal args() As String)
                Dim program As New Program()
                program.Execute()
            End Sub
    
            Private Sub Execute()
                Dim exeDir As String = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar
                Dim dataDir As String = New Uri(New Uri(exeDir), "../../Data/").LocalPath
    
                ' Load the template document.
                Dim doc As New Document(dataDir & "Template.doc")
    
                ' Setup mail merge event handler to do the custom work.
                doc.MailMerge.FieldMergingCallback = New HandleMergeField()
    
                ' This is the data for mail merge.
                Dim fieldNames() As String = {"RecipientName", "SenderName", "FaxNumber", "PhoneNumber", "Subject", "Body", "Urgent", "ForReview", "PleaseComment"}
                Dim fieldValues() As Object = {"Josh", "Jenny", "123456789", "", "Hello", "<b>HTML Body Test message 1</b>", True, False, True}
    
                ' Execute the mail merge.
                doc.MailMerge.Execute(fieldNames, fieldValues)
    
                ' Save the finished document.
                doc.Save(dataDir & "Template Out.doc")
            End Sub
    
            Private Class HandleMergeField
                Implements IFieldMergingCallback
                ''' <summary>
                ''' This handler is called for every mail merge field found in the document,
                '''  for every record found in the data source.
                ''' </summary>
                Private Sub IFieldMergingCallback_FieldMerging(ByVal e As FieldMergingArgs) Implements IFieldMergingCallback.FieldMerging
                    If mBuilder Is Nothing Then
                        mBuilder = New DocumentBuilder(e.Document)
                    End If
    
                    ' We decided that we want all boolean values to be output as check box form fields.
                    If TypeOf e.FieldValue Is Boolean Then
                        ' Move the "cursor" to the current merge field.
                        mBuilder.MoveToMergeField(e.FieldName)
    
                        ' It is nice to give names to check boxes. Lets generate a name such as MyField21 or so.
                        Dim checkBoxName As String = String.Format("{0}{1}", e.FieldName, e.RecordIndex)
    
                        ' Insert a check box.
                        mBuilder.InsertCheckBox(checkBoxName, CBool(e.FieldValue), 0)
    
                        ' Nothing else to do for this field.
                        Return
                    End If
    
                    ' We want to insert html during mail merge.
                    If e.FieldName = "Body" Then
                        mBuilder.MoveToMergeField(e.FieldName)
                        mBuilder.InsertHtml(DirectCast(e.FieldValue, String))
                    End If
    
                    ' Another example, we want the Subject field to come out as text input form field.
                    If e.FieldName = "Subject" Then
                        mBuilder.MoveToMergeField(e.FieldName)
                        Dim textInputName As String = String.Format("{0}{1}", e.FieldName, e.RecordIndex)
                        mBuilder.InsertTextInput(textInputName, TextFormFieldType.Regular, "", CStr(e.FieldValue), 0)
                    End If
                End Sub
    
                Private Sub ImageFieldMerging(ByVal args As ImageFieldMergingArgs) Implements IFieldMergingCallback.ImageFieldMerging
                    ' Do nothing.
                End Sub
    
                Private mBuilder As DocumentBuilder
            End Class
        End Class
    End Namespace
    
    

    public by sherazam  184670  0  5  0

    How to Render an Image of 3D Model from the Camera inside .NET Application

    This Technical tip explains how .NET developers can render an image of 3D model from the camera inside their .NET applications. Using Aspose.3D for .NET, developers can render an image to view a realistic image of 3D model, with or without the enhanced background, textures, shadows and also adjust the image size. The Render method exposed by the Sc
    // Enter here the actual content of the snippet.            // this code example creates a camera in a 3D scene, sets its target and render an image.
    
    // [C# Code Sample]
    
    // For complete examples and data files, please go to https://github.com/aspose-3d/Aspose.3D-for-.NET
    // The path to the documents directory.
    string MyDir = RunExamples.GetDataDir();
    
    // Load scene from file
    Scene scene = new Scene(MyDir + "camera.3ds");
    // Create a camera at (10,10,10) and look at the origin point for rendering,
    // it must be attached to the scene before render
    Camera camera = new Camera();
    scene.RootNode.CreateChildNode("camera", camera);
    camera.ParentNode.Transform.Translation = new Vector3(10, 10, 10);
    camera.LookAt = Vector3.Origin;
    
    // Specify the image render option
    ImageRenderOptions opt = new ImageRenderOptions();
    // Set the background color
    opt.BackgroundColor = Color.AliceBlue;
    // Tells renderer where the it can find textures
    opt.AssetDirectories.Add(MyDir + "textures");
    // Turn on shadow
    opt.EnableShadows = true;
    // Render the scene in given camera's perspective into specified png file with size 1024x1024
    scene.Render(camera, MyDir + "Render3DModelImageFromCamera_out_.png", new Size(1024, 1024), ImageFormat.Png, opt);
    
    //[VB.NET Code Sample]
    
    ' For complete examples and data files, please go to https://github.com/aspose-3d/Aspose.3D-for-.NET
    ' The path to the documents directory.
    Dim MyDir As String = RunExamples.GetDataDir()
    
    ' Load scene from file
    Dim scene As New Scene(MyDir & Convert.ToString("camera.3ds"))
    ' Create a camera at (10,10,10) and look at the origin point for rendering,
    ' it must be attached to the scene before render
    Dim camera As New Camera()
    scene.RootNode.CreateChildNode("camera", camera)
    camera.ParentNode.Transform.Translation = New Vector3(10, 10, 10)
    camera.LookAt = Vector3.Origin
    
    ' Specify the image render option
    Dim opt As New ImageRenderOptions()
    ' Set the background color
    opt.BackgroundColor = Color.AliceBlue
    ' Tells renderer where the it can find textures
    opt.AssetDirectories.Add(MyDir & Convert.ToString("textures"))
    ' Turn on shadow
    opt.EnableShadows = True
    ' Render the scene in given camera's perspective into specified png file with size 1024x1024
    scene.Render(camera, MyDir & Convert.ToString("Render3DModelImageFromCamera_out_.png"), New Size(1024, 1024), ImageFormat.Png, opt)
    

    public by sherazam  182332  1  5  0

    How to Delete Messages in Bulk or One by One from Outlook PST in .NET Apps

    This technical tip explains how .NET developers can Delete Messages from outlook PST. Add Messages to PST Files showed how to add messages to PST files. It is, of course, also possible to delete items (contents) from a PST file and it may also be desirable to delete messages in bulk. Items from a PST file can be deleted using the FolderInfo.DeleteC
    // Enter here the actual content of the snippet.            
    //Deleting Messages from PST Files
    
    //The code snippets below delete messages from a PST file's Sent subfolder.
    
    //[C# Code Sample]
    
    // Get the Sent items folder
    FolderInfo folderInfo = pst.GetPredefinedFolder(StandardIpmFolder.SentItems);
    MessageInfoCollection msgInfoColl = folderInfo.GetContents();
    foreach (MessageInfo msgInfo in msgInfoColl)
    {
        Console.WriteLine(msgInfo.Subject + ": " + msgInfo.EntryIdString);
        if (msgInfo.Subject.Equals("some delete condition") == true)
        {
            // Delete this item
            folderInfo.DeleteChildItem(msgInfo.EntryId);
            Console.WriteLine("Deleted this message");
        }
    }
     
    //[VB.NET Code Sample]
    
    ' Get the Sent items folder
    Dim folderInfo As FolderInfo = pst.GetPredefinedFolder(StandardIpmFolder.SentItems)
    Dim msgInfoColl As MessageInfoCollection = folderInfo.GetContents()
    For Each msgInfo As MessageInfo In msgInfoColl
    	Console.WriteLine(msgInfo.Subject & ": " & msgInfo.EntryIdString)
    	If msgInfo.Subject.Equals("some delete condition") = True Then
    		' Delete this item
    		folderInfo.DeleteChildItem(msgInfo.EntryId)
    		Console.WriteLine("Deleted this message")
    	End If
    Next msgInfo
    
    //Delete Items in Bulk from PST File
    
    //Aspose.Email API can be used to delete items in bulk from a PST file. This is achieved using the DeleteChildItems method which accepts a list of Entry ID items referring to the items to be deleted.
    
    //[C# Code Sample]
    
    using (PersonalStorage pst = PersonalStorage.FromFile(@"test.pst"))
    {
        FolderInfo inbox = pst.RootFolder.GetSubFolder("Inbox");
        
        // find messages having From = "someuser@domain.com" 
        PersonalStorageQueryBuilder queryBuilder = new PersonalStorageQueryBuilder();
        queryBuilder.From.Contains("someuser@domain.com");
        MessageInfoCollection messages = inbox.GetContents(queryBuilder.GetQuery());
        IList<string> deleteList = new List<string>();
        foreach (MessageInfo messageInfo in messages)
        {
            deleteList.Add(messageInfo.EntryIdString);
        }
        
        // delete messages having From = "someuser@domain.com"
        inbox.DeleteChildItems(deleteList);
    }
    
    //[VB.NET Code Sample]
    
    Using pst As PersonalStorage = PersonalStorage.FromFile("test.pst")
    	Dim inbox As FolderInfo = pst.RootFolder.GetSubFolder("Inbox")
    
    	' find messages having From = "someuser@domain.com" 
    	Dim queryBuilder As New PersonalStorageQueryBuilder()
    	queryBuilder.From.Contains("someuser@domain.com")
    	Dim messages As MessageInfoCollection = inbox.GetContents(queryBuilder.GetQuery())
    	Dim deleteList As IList(Of String) = New List(Of String)()
    	For Each messageInfo As MessageInfo In messages
    		deleteList.Add(messageInfo.EntryIdString)
    	Next
    
    	' delete messages having From = "someuser@domain.com"
    	inbox.DeleteChildItems(deleteList)
    End Using
    
    

    public by zonaro  197150  0  8  0

    Sum (Excel port for VB.NET)

    Like in Excel, this method sum the numbers of a ParamArray
    Function Sum(ByVal ParamArray Nums As Decimal()) As Decimal
            Dim s = 0
            For Each i As Decimal In Nums
                s += i
            Next
            Return s
        End Function            

    public by sherazam  120634  0  5  0

    How to Set Line Spacing of a Paragraph in an Excel Shape or Textbox inside .NET Apps

    This technical tip shows how to Set Line Spacing of the Paragraph in a Shape or Textbox in .NET applications. You can set the line space of the paragraph, its space before and space after using the TextParagraph.LineSpace, TextParagraph.SpaceBefore and TextParagraph.SpaceAfter respectively. The following example shows how to Set Line Spacing of the
    // Enter here the actual content of the snippet.            
    
    //[C# Code]
     
    // For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
    // The path to the documents directory.
    string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    
    // Create a workbook
    Workbook wb = new Workbook();
    
    // Access first worksheet
    Worksheet ws = wb.Worksheets[0];
    
    // Add text box inside the sheet
    ws.Shapes.AddTextBox(2, 0, 2, 0, 100, 200);
    
    // Access first shape which is a text box and set is text
    Shape shape = ws.Shapes[0];
    shape.Text = "Sign up for your free phone number.\nCall and text online for free.";
    
    // Acccess the first paragraph
    TextParagraph p = shape.TextBody.TextParagraphs[1];
    
    // Set the line space
    p.LineSpaceSizeType = LineSpaceSizeType.Points;
    p.LineSpace = 20;
    
    // Set the space after
    p.SpaceAfterSizeType = LineSpaceSizeType.Points;
    p.SpaceAfter = 10;
    
    // Set the space before
    p.SpaceBeforeSizeType = LineSpaceSizeType.Points;
    p.SpaceBefore = 10;
    
    // Save the workbook in xlsx format
    wb.Save(dataDir + "output_out_.xlsx", SaveFormat.Xlsx); 
    
    //[VB.NET Code]
    
    ' For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
    ' The path to the documents directory.
    Dim dataDir As String = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
    
    ' Create a workbook
    Dim wb As New Workbook()
    
    ' Access first worksheet
    Dim ws As Worksheet = wb.Worksheets(0)
    
    ' Add text box inside the sheet
    ws.Shapes.AddTextBox(2, 0, 2, 0, 100, 200)
    
    ' Access first shape which is a text box and set is text
    Dim shape As Shape = ws.Shapes(0)
    shape.Text = "Sign up for your free phone number." & vbLf & "Call and text online for free."
    
    ' Acccess the first paragraph
    Dim p As TextParagraph = shape.TextBody.TextParagraphs(1)
    
    ' Set the line space
    p.LineSpaceSizeType = LineSpaceSizeType.Points
    p.LineSpace = 20
    
    ' Set the space after
    p.SpaceAfterSizeType = LineSpaceSizeType.Points
    p.SpaceAfter = 10
    
    ' Set the space before
    p.SpaceBeforeSizeType = LineSpaceSizeType.Points
    p.SpaceBefore = 10
    
    ' Save the workbook in xlsx format
    wb.Save(dataDir & Convert.ToString("output_out_.xlsx"), SaveFormat.Xlsx) 
    
    

    public by johansonkatherine  219711  1  6  2

    C# Code Sample to Replace Multiple Texts inside PDF File Using Cloud API

    The following code sample shows how developers can replace multiple texts in a single API call in a PDF file using Aspose.Pdf for Cloud API in their applications. Developers can use Aspose REST API with any language: .NET, Java, PHP, Ruby, Rails, Python, jQuery and many more.
    AsposeApp.AppSID  = "77***********************************";
    AsposeApp.AppKey = "9a*******************************";
    
    //build URI
    stringstrURI = "http://api.aspose.com/v1.1/pdf/test.pdf/replaceTextList";
    
    //sign URI
    stringsignedURI = Utils.Sign(strURI);
    
    //build JSON to post
    TextReplace textReplace1 = new TextReplace();
    textReplace1.OldValue = "[!firm!]";
    textReplace1.NewValue = "Aspose";
    textReplace1.Regex = "false";
    
    //build JSON to post
    TextReplace textReplace2 = new TextReplace();
    textReplace2.OldValue = "[!client!]";
    textReplace2.NewValue = "Mark";
    textReplace2.Regex = "false";
    
    MultipleTextReplacestextReplaces = new MultipleTextReplaces();
    textReplaces.TextReplaces = new TextReplace[] { textReplace1, textReplace2 };
    stringstrJSON = JsonConvert.SerializeObject(textReplaces);
    Console.Write(strJSON);
    Utils.ProcessCommand(signedURI, "POST", strJSON);
    
    //build URI
    strURI = "http://api.aspose.com/v1.1/storage/file/test.pdf";
    
    //sign URI
    signedURI = Utils.Sign(strURI);
    
    Stream responseStream = Utils.ProcessCommand(signedURI, "GET");
    using (Stream fileStream = System.IO.File.OpenWrite(@"test.pdf"))
    {
    Utils.CopyStream(responseStream, fileStream);
    }
    responseStream.Close();
    
    //Following are required classes
    public class MultipleTextReplaces
        {
    publicTextReplace[] TextReplaces { get; set; }
        }
    public class TextReplace
        {
    publicTextReplace() { }
    
    public string OldValue { get; set; }
    public string NewValue { get; set; }
    public string Regex { get; set; }
    
        }
    

    public by cghersi @ MailUp API DEV  206839  8  6  1

    MailUp REST API - How to subscribe to a particular list several contacts with the "Confirmed Optin" Procedure

    This snippet takes advantage of the MailUp .NET SDK to setup the secure communication towards the server through OAuth2 two leg authentication. You can start digging into the MailUP API world by reading this content: http://help.mailup.com/display/mailupapi/REST+API An instance of MailUpClient class is able to manage one user at a time. A MailU
    public static void SubcribeRecipientsWithDoubleOptin(string clientID, string clientSecret, string username, string password)
    {
        // 1) Setup the MailUp Client:
        MailUpClient client = new MailUpClient(clientID, clientSecret);
        try
        {
            client.RetrieveAccessToken(username, password);
        }
        catch (MailUpException ex)
        {
            Console.WriteLine("Unable to access the service due to " + ex.Message);
            return;
        }
    
        // 2) Subscribe recipients:
        int idList = 1;
        List<ConsoleRecipientItem> recipients = new List<ConsoleRecipientItem>();
        ConsoleRecipientItem recipient1 = new ConsoleRecipientItem()
        {
            Email = "test1@mailup.com",
            Name = "First New Recipient" + DateTime.Now.ToFileTimeUtc(),
            MobileNumber = "3331234567",
            MobilePrefix = "39",
            Fields = new List<ConsoleRecipientDynamicFieldItem>()
            {
                new ConsoleRecipientDynamicFieldItem() { Id = 1, Value = "Name1_" + DateTime.Now.ToFileTimeUtc() },
                new ConsoleRecipientDynamicFieldItem() { Id = 2, Value = "LastName1_" + DateTime.Now.ToFileTimeUtc() }
                //here you can add all the fields you want to add...
            }
        };
        ConsoleRecipientItem recipient2 = new ConsoleRecipientItem()
        {
            Email = "test2@mailup.com",
            Name = "Second New Recipient" + DateTime.Now.ToFileTimeUtc(),
            MobileNumber = "3337654321",
            MobilePrefix = "39",
            Fields = new List<ConsoleRecipientDynamicFieldItem>()
            {
                new ConsoleRecipientDynamicFieldItem() { Id = 1, Value = "Name2_" + DateTime.Now.ToFileTimeUtc() },
                new ConsoleRecipientDynamicFieldItem() { Id = 2, Value = "LastName2_" + DateTime.Now.ToFileTimeUtc() }
                //here you can add all the fields you want to add...
            }
        };
        recipients.Add(recipient1);
        recipients.Add(recipient2);
        int subscriptionResult = 0;
        try
        {
            subscriptionResult = client.AddRecipientsToList(idList, recipients, true);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Cannot perform the operation due to " + ex.Message);
            return;
        }
    
        // 2.1) wait for the end of import task:
        if (subscriptionResult > 0)
        {
            Console.WriteLine("Recipients Import started; import ID:" + subscriptionResult);
    
            //optionally we can check the import status:
            bool completed = false;
            do
            {
                ConsoleImportStatus importStatus = client.CheckImportStatus(subscriptionResult);
                if (importStatus == null)
                {
                    Console.WriteLine("Cannot check the import status for import task #" + subscriptionResult);
                    return;
                }
                completed = importStatus.Completed;
            } while (!completed);
            Console.WriteLine("Recipients Added!");
        }
        else
        {
            Console.WriteLine("An error occurred while adding the recipients.");
            return;
        }
    
        // 3) Retrieve the sendingID of the confirmation email related to the previous task:
        int sendingID = -1;
        try
        {
            sendingID = client.GetSendingIDForImport(subscriptionResult);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Cannot retrieve sending ID due to " + ex.Message);
            return;
        }
        if (sendingID <= 0)
        {
            Console.WriteLine("Cannot retrieve sending ID.");
            return;
        }
    
        // 4) Send the confirmation email:
        EmailSendingItem sendingResult = null;
        try
        {
            sendingResult = client.SendEmailMessage(sendingID);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Cannot send email due to " + ex.Message);
            return;
        }
        if (sendingResult == null)
            Console.WriteLine("Cannot send confirmation email.");
        else
            Console.WriteLine("Confirmation email sent!");
    }
                

    public by cghersi @ MailUp API DEV  113001  11  5  0

    How to Retrieve your personal information with MailUp .NET SDK

    This snippet takes advantage of the MailUp .NET SDK to setup the secure communication towards the server through OAuth2 two leg authentication. You can start digging into the MailUP API world by reading this content: http://help.mailup.com/display/mailupapi/REST+API An instance of MailUpClient class is able to manage one user at a time. A MailU
    public static void GetPersonalDataFields(string clientID, string clientSecret, string username, string password)
    {
        // 1) Setup the MailUp Client:
        MailUpClient client = new MailUpClient(clientID, clientSecret);
        try
        {
            client.RetrieveAccessToken(username, password);
        }
        catch (MailUpException ex)
        {
            Console.WriteLine("Unable to access the service due to " + ex.Message);
            return;
        }
    
        // 2) Prepare the input:
        //nothing to do here...
    
        // 3) Invoke the web method:
        CollectionOf<ConsoleDynamicFieldItem> result = null;
        try
        {
            result = client.GetPersonalDataFields();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Cannot perform the operation due to " + ex.Message);
            return;
        }
    
    
        if (result != null)
            Console.WriteLine("Personal Data Fields Retrieved: " + result.Count);
        else
            Console.WriteLine("Cannot retrieve Personal Data Fields.");
    }
    

    public by cghersi @ MailUp API DEV  69238  7  5  0

    How to Add a recipient to a group of recipients with MailUp .NET SDK

    This snippet takes advantage of the MailUp .NET SDK to setup the secure communication towards the server through OAuth2 two leg authentication. You can start digging into the MailUP API world by reading this content: http://help.mailup.com/display/mailupapi/REST+API An instance of MailUpClient class is able to manage one user at a time. A MailU
    public static void AddRecipientToGroup(string clientID, string clientSecret, string username, string password)
    {
        // 1) Setup the MailUp Client:
        MailUpClient client = new MailUpClient(clientID, clientSecret);
        try
        {
            client.RetrieveAccessToken(username, password);
        }
        catch (MailUpException ex)
        {
            Console.WriteLine("Unable to access the service due to " + ex.Message);
            return;
        }
    
        // 2) Prepare the input:
        int idGroup = 1;
        ConsoleRecipientItem recipient = new ConsoleRecipientItem()
        {
            Email = "testGroup@mailup.com",
            Name = "Group - New Recipient" + DateTime.Now.ToFileTimeUtc(),
            Fields = new List<ConsoleRecipientDynamicFieldItem>()
            {
                new ConsoleRecipientDynamicFieldItem() { Id = 1, Value = "NameGroup" + DateTime.Now.ToFileTimeUtc() },
                new ConsoleRecipientDynamicFieldItem() { Id = 2, Value = "LastNameGroup" + DateTime.Now.ToFileTimeUtc() }
                //here you can add all the fields you want to add...
            }
        };
    
        // 3) Invoke the web method:
        int result = 0;
        try
        {
            result = client.AddRecipientToGroup(idGroup, recipient);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Cannot perform the operation due to " + ex.Message);
            return;
        }
    
        // 4) Print results:
        if (result > 0)
            Console.WriteLine("Recipient Added!");
        else
            Console.WriteLine("An error occurred while adding the recipient.");
    }
    
    • Public Snippets
    • Channels Snippets