working on it ...

Filters

Explore Public Snippets

Sort by

Found 596k snippets

    public by marceloviana modified Nov 3, 2018  26  0  2  0

    Acessando sub linhas de um json

    String json_resultado = "{\"hasErrors\":true,\"errors\":[{\"reference\":\"AcordoApplication\",\"message\":\"18 - Não existem dívidas pendentes.\"}]}";
            
           var jObject = Newtonsoft.Json.Linq.JObject.Parse(json_resultado.ToString());
    
           foreach (var itens in jObject["errors"]) {
    
               String resultado = itens["message"].ToString();
    
           };
    

    public by cghersi modified Sep 7, 2018  159  1  3  0

    Retrieve BLOB From Azure Blob Storage

    Quick method to retrieve a set of BLOBs for Azure Blob Storage, given their names. Unfortunately the Azure REST APIs don't allow, yet, to BULK retrieve the content of several BLOBs in one single call, so we need to loop over each BLOB and retrieve the content one by one
    public static Dictionary<Guid, byte[]> GetBlobs(List<string> names)
    {
      Dictionary<string, byte[]> result = new Dictionary<string, byte[]>();
    
      // retrieve info about the interesting BLOBs:
      IEnumerable<CloudBlob> blobs = s_defaultContainer.ListBlobs().
        OfType<CloudBlob>().Where(c => names.Contains(c.Name));
      
      // loop over the retrieved BLOBs:
      foreach (CloudBlob b in blobs)
      {
      	b.FetchAttributes(); //otherwise we cannot query for Properties...
      	byte[] res = new byte[b.Properties.Length];
      	
      	// download the actual content:
      	b.DownloadToByteArray(res, 0); 
      	
      	result.Add(b.Name, res);
      }
      
      return result;
    }

    public by cghersi @ MailUp API DEV modified Aug 29, 2018  1647  44  5  0

    MailUp REST API - How to send a transactional email message

    This snippet takes advantage of the MailUp .NET SDK to setup the secure communication towards the server. The credentials of the SMTP+ user are passed as parameter in the body of the request. Explore the MessageDTO object in order to understand how you can customize the message you want to send.
    public static void SendMessage()
    {
      // 1) Required values
      string username = "<your_username>";
    	string password = "<your_password>";
    
    	string clientid = "<your_clientid>";
    	string clientsecret = "<your_clientsecret>";
    
    	string smtpplus_username = "<your_smtpplus_username>";
    	string smtpplus_password = "<your_smtpplus_password>";
      
      // 2) Setup the MailUp Client:
    	MailUpClient client = new MailUpClient(clientid, clientsecret);
    	client.RetrieveAccessToken( username, password );
    
      // 3) prepare the input:
      MessageDTO msg = new MessageDTO()
      {
        Html = new HtmlDTO()
        {
          Body = "<div>Hello Mr. [firstname][lastname] !!!</div><br><img width='600' height='397' src='cid:img001'>",
          BodyTag = "<body>"
        },
        Text = "Hello world!!!",
        Subject = "Hello friend!",
        From = new EmailAddressDTO() { Name = "Test User", Email = "test@mailup.it" },
        To = new List<EmailAddressDTO>() { new EmailAddressDTO() { Name = "Massimo", Email = "info@mailup.it" } },
        Cc = new List<EmailAddressDTO>(),
        Bcc = new List<EmailAddressDTO>(),
        ReplyTo = null,
        CharSet = "utf-8",
        ExtendedHeaders = null,
        Attachments = null,
        EmbeddedImages = new List<MessagePartDTO>() {
          new MessagePartDTO() {
            Filename = "Image.jpg",
            ContentId = "img001",
            Body = new byte[] { 0x01, 0x02, 0x03, 0x04 }
          }
        },
        XSmtpAPI = new XSmtpAPIDTO()
        {
          CampaignName = "Test Campaign",
          CampaignCode = "1001",
          Header = null,
          Footer = null,
          ClickTracking = null,
          ViewTracking = null,
          Priority = null,
          Schedule = null,
          DynamicFields = new List<NameValueDTO>() {
            new NameValueDTO() { N = "firstname", V = "Mario"},
            new NameValueDTO() { N = "lastname", V = "Rossi"}
          },
          CampaignReport = null,
          SkipDynamicFields = null
        },
        User = new SmtpUserDTO() { Username = smtpplus_username, Secret = smtpplus_password }
      };
    
      // 4) Invoke the web method:
      SendResponseDTO result = null;
      try
      {
        result = client.SendMessage(msg);
      }
      catch (Exception ex)
      {
        Console.WriteLine("Cannot perform the operation due to " + ex.Message);
        return;
      }
    
      // 5) Print results:
      if (result != null)
        Console.WriteLine("Result of sending task:" + result.Message);
      else
        Console.WriteLine("An error occurred while sending message.");
    }
    						

    public by cghersi @ MailUp API DEV modified Aug 29, 2018  2203  12  5  0

    MailUp REST API - How to send a transactional email message that follows a template

    This snippet takes advantage of the MailUp .NET SDK to setup the secure communication towards the server. The credentials of the SMTP+ user are passed as parameter in the body of the request. Explore the TemplateDTO object in order to understand how you can customize the message you want to send.
    public static void SendTemplate()
    {
      // 1) Required values
      string username = "<your_username>";
    	string password = "<your_password>";
    
    	string clientid = "<your_clientid>";
    	string clientsecret = "<your_clientsecret>";
    
    	string smtpplus_username = "<your_smtpplus_username>";
    	string smtpplus_password = "<your_smtpplus_password>";
      
      // 2) Setup the MailUp Client:
    	MailUpClient client = new MailUpClient(clientid, clientsecret);
    	client.RetrieveAccessToken( username, password );
    
      // 3) prepare the input:
      TemplateDTO msg = new TemplateDTO()
      {
        TemplateId = 694,
        Subject = "Test message from template",
        From = new EmailAddressDTO() { Name = "Test User", Email = "test@mailup.it" },
        To = new List<EmailAddressDTO>() { new EmailAddressDTO() { Name = "Massimo", Email = "info@mailup.it" } },
        Cc = new List<EmailAddressDTO>(),
        Bcc = new List<EmailAddressDTO>(),
        ReplyTo = null,
        CharSet = "utf-8",
        ExtendedHeaders = null,
        Attachments = null,
        EmbeddedImages = new List<MessagePartDTO>() {
          new MessagePartDTO() {
            Filename = "Image.jpg",
            ContentId = "img001",
            Body = new byte[] { 0x01, 0x02, 0x03, 0x04 }
          }
        },
        XSmtpAPI = null,
        User = new SmtpUserDTO() { Username = smtpplus_username, Secret = smtpplus_password }
      };
    
      // 4) Invoke the web method:
      SendResponseDTO result = null;
      try
      {
        result = client.SendTemplate(msg);
      }
      catch (Exception ex)
      {
        Console.WriteLine("Cannot perform the operation due to " + ex.Message);
        return;
      }
    
      // 5) Print results:
      if (result != null)
        Console.WriteLine("Result of sending task:" + result.Message);
      else
        Console.WriteLine("An error occurred while sending template.");
    }
    												

    public by cghersi @ MailUp API DEV modified Aug 29, 2018  1728  8  5  0

    MailUp REST API - How to retrieve information of SMTP+ Users

    This snippet takes advantage of the MailUp .NET SDK to setup the secure communication towards the server. The credentials of the SMTP+ user are passed as parameter in the body of the request. You can optionally specify a username as third parameter in order to filter the resulting list.
    public static void GetUserInfo()
    {
      // 1) Required values
      string username = "<your_username>";
    	string password = "<your_password>";
    
    	string clientid = "<your_clientid>";
    	string clientsecret = "<your_clientsecret>";
    
    	string smtpplus_username = "<your_smtpplus_username>";
    	string smtpplus_password = "<your_smtpplus_password>";
      
      // 2) Setup the MailUp Client:
    	MailUpClient client = new MailUpClient(clientid, clientsecret);
    	client.RetrieveAccessToken( username, password );
    
      // 3) Invoke the web method:
      List<UserInfoDTO> result = null;
      try
      {
        result = client.ListUserInfo(smtpplus_username, smtpplus_password);
      }
      catch (Exception ex)
      {
        Console.WriteLine("Cannot perform the operation due to " + ex.Message);
        return;
      }
    
      // 4) Print results:
      if (result != null)
        Console.WriteLine("Retrieved users total:" + result.Count);
      else
        Console.WriteLine("An error occurred while retrieving users.");
    }
    																		

    public by marceloviana modified Aug 4, 2018  439  1  4  0

    Percorrer json

    foreach (var keyvalue in context_id)
            {
    
                
                text = text + "</br><b>" + keyvalue.Name + "</b>  " + keyvalue.Value;
            }

    public by tciss modified Jan 23, 2018  1180  1  5  0

    Create SAML2 Assertion

    //-----------------------------------------------------------------------
    // <copyright file="SAML20Assertion.cs" company="CoverMyMeds">
    //  Copyright (c) 2012 CoverMyMeds.  All rights reserved.
    //  This code is presented as reference material only.
    // </copyright>
    //-----------------------------------------------------------------------
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Xml.Serialization;
    using System.Security.Cryptography.X509Certificates;
    using System.Security.Cryptography.Xml;
    using System.IO;
    using CoverMyMeds.SAML.Library.Schema;
    
    namespace CoverMyMeds.SAML.Library {
    
        /// <summary>
        /// Encapsulate functionality for building a SAML Response using the Schema object
        ///     created by xsd.exe from the OASIS spec
        /// </summary>
        /// <remarks>Lots of guidance from this CodeProject implementation
        ///     http://www.codeproject.com/Articles/56640/Performing-a-SAML-Post-with-C#xx0xx
        /// </remarks>
        public class SAML20Assertion {
    
            /// <summary>
            /// Build a signed XML SAML Response string to be inlcuded in an HTML Form
            /// for POSTing to a SAML Service Provider
            /// </summary>
            /// <param name="Issuer">Identity Provider - Used to match the certificate for verifying 
            ///     Response signing</param>
            /// <param name="AssertionExpirationMinutes">Assertion lifetime</param>
            /// <param name="Audience"></param>
            /// <param name="Subject"></param>
            /// <param name="Recipient"></param>
            /// <param name="Attributes">Dictionary of attributes to send through for user SSO</param>
            /// <param name="SigningCert">X509 Certificate used to sign Assertion</param>
            /// <returns></returns>
            public static string CreateSAML20Response(string Issuer, int AssertionExpirationMinutes, string Audience, string Subject, string Recipient, Dictionary<string, string> Attributes, X509Certificate2 SigningCert) {
                // Create SAML Response object with a unique ID and correct version
                ResponseType response = new ResponseType() {ID = "_" + System.Guid.NewGuid().ToString(), Version = "2.0", IssueInstant = System.DateTime.UtcNow, Destination = Recipient.Trim(), Issuer = new NameIDType() {Value = Issuer.Trim()}, Status = new StatusType() {StatusCode = new StatusCodeType() {Value = "urn:oasis:names:tc:SAML:2.0:status:Success"}}};
    
                // Put SAML 2.0 Assertion in Response
                response.Items = new AssertionType[] {CreateSAML20Assertion(Issuer, AssertionExpirationMinutes, Audience, Subject, Recipient, Attributes)};
    
                XmlDocument XMLResponse = SerializeAndSignSAMLResponse(response, SigningCert);
    
                return System.Convert.ToBase64String(Encoding.UTF8.GetBytes(XMLResponse.OuterXml));
            }
    
            /// <summary>
            /// Accepts SAML Response, serializes it to XML and signs using the supplied certificate
            /// </summary>
            /// <param name="Response">SAML 2.0 Response</param>
            /// <param name="SigningCert">X509 certificate</param>
            /// <returns>XML Document with computed signature</returns>
            private static XmlDocument SerializeAndSignSAMLResponse(ResponseType Response, X509Certificate2 SigningCert) {
                // Set serializer and writers for action
                XmlSerializer responseSerializer = new XmlSerializer(Response.GetType());
                StringWriter stringWriter = new StringWriter();
                XmlWriter responseWriter = XmlTextWriter.Create(stringWriter, new XmlWriterSettings() {OmitXmlDeclaration = true, Indent = true, Encoding = Encoding.UTF8});
                responseSerializer.Serialize(responseWriter, Response);
                responseWriter.Close();
                XmlDocument xmlResponse = new XmlDocument();
                xmlResponse.LoadXml(stringWriter.ToString());
    
                // Set the namespace for prettire and more consistent XML
                XmlNamespaceManager ns = new XmlNamespaceManager(xmlResponse.NameTable);
                ns.AddNamespace("saml", "urn:oasis:names:tc:SAML:2.0:assertion");
    
                CertificateUtility.AppendSignatureToXMLDocument(ref xmlResponse, "#" + ((AssertionType) Response.Items[0]).ID, SigningCert);
    
                return xmlResponse;
            }
    
            /// <summary>
            /// Creates a SAML 2.0 Assertion Segment for a Response
            /// Simple implmenetation assuming a list of string key and value pairs
            /// </summary>
            /// <param name="Issuer"></param>
            /// <param name="AssertionExpirationMinutes"></param>
            /// <param name="Audience"></param>
            /// <param name="Subject"></param>
            /// <param name="Recipient"></param>
            /// <param name="Attributes">Dictionary of string key, string value pairs</param>
            /// <returns>Assertion to sign and include in Response</returns>
            private static AssertionType CreateSAML20Assertion(string Issuer, int AssertionExpirationMinutes, string Audience, string Subject, string Recipient, Dictionary<string, string> Attributes) {
                AssertionType NewAssertion = new AssertionType() {Version = "2.0", IssueInstant = System.DateTime.UtcNow, ID = "_" + System.Guid.NewGuid().ToString()};
    
                // Create Issuer
                NewAssertion.Issuer = new NameIDType() {Value = Issuer.Trim()};
    
                // Create Assertion Subject
                SubjectType subject = new SubjectType();
                NameIDType subjectNameIdentifier = new NameIDType() {Value = Subject.Trim(), Format = "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified"};
                SubjectConfirmationType subjectConfirmation = new SubjectConfirmationType() {Method = "urn:oasis:names:tc:SAML:2.0:cm:bearer", SubjectConfirmationData = new SubjectConfirmationDataType() {NotOnOrAfter = DateTime.UtcNow.AddMinutes(AssertionExpirationMinutes), Recipient = Recipient}};
                subject.Items = new object[] {subjectNameIdentifier, subjectConfirmation};
                NewAssertion.Subject = subject;
    
                // Create Assertion Conditions
                ConditionsType conditions = new ConditionsType();
                conditions.NotBefore = DateTime.UtcNow;
                conditions.NotBeforeSpecified = true;
                conditions.NotOnOrAfter = DateTime.UtcNow.AddMinutes(AssertionExpirationMinutes);
                conditions.NotOnOrAfterSpecified = true;
                conditions.Items = new ConditionAbstractType[] {new AudienceRestrictionType() {Audience = new string[] {Audience.Trim()}}};
                NewAssertion.Conditions = conditions;
    
                // Add AuthnStatement and Attributes as Items
                AuthnStatementType authStatement = new AuthnStatementType() {AuthnInstant = DateTime.UtcNow, SessionIndex = NewAssertion.ID};
                AuthnContextType context = new AuthnContextType();
                context.ItemsElementName = new ItemsChoiceType5[] {ItemsChoiceType5.AuthnContextClassRef};
                context.Items = new object[] {"urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified"};
                authStatement.AuthnContext = context;
    
                AttributeStatementType attributeStatement = new AttributeStatementType();
                attributeStatement.Items = new AttributeType[Attributes.Count];
                int i = 0;
                foreach (KeyValuePair<string, string> attribute in Attributes) {
                    attributeStatement.Items[i] = new AttributeType() {Name = attribute.Key, AttributeValue = new object[] {attribute.Value}, NameFormat = "urn:oasis:names:tc:SAML:2.0:attrname-format:basic"};
                    i++;
                }
    
                NewAssertion.Items = new StatementAbstractType[] {authStatement, attributeStatement};
    
                return NewAssertion;
            }
    
        }
    
    }

    public by azazqadir modified Dec 15, 2017  440  1  5  -1

    Installing PHP Website on Linode Server

    Here is how you can easily host a PHP based website easily and quickly on Linode using Cloudways PaaS: https://www.cloudways.com/blog/host-php-on-linode/
    <?php
    echo rand() . "\n";
    echo rand() . "\n";
    
    echo rand(5, 15);
    ?>

    public by jitin modified Dec 9, 2017  379  5  5  1

    Basic HTML 5

    <!DOCTYPE html>
    
    <html lang="en">
    <head>
      <meta charset="UTF-8">
    
      <title>Untitled</title>
      <meta name="description" content="HTML5 Website Content">
      <meta name="author" content="Jitin">
    
      <link rel="stylesheet" href="css/styles.css">
    
      <!--[if lt IE 9]>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.js"></script>
      <![endif]-->
    </head>
    
    <body>
    
    </body>
    </html>																								

    public by pradithya modified Dec 9, 2017  416  0  4  0

    Creating Alert with Action

    let controller = UIAlertController()
    controller.title = "Hey!"
    controller.message = "Don't Worry Be Happy!"
            
    let okAction = UIAlertAction(title: "ok", style: UIAlertActionStyle.default) { (alert: UIAlertAction) in
        self.dismiss(animated:true)
    }
            
    controller.addAction(okAction)
    self.present(controller, animated: true, completion: nil)
    						
    • Public Snippets
    • Channels Snippets