Wednesday, November 27, 2013

Getting All Responses From TWILIO API

Hi Friends,

I got a requirement where I have to retrieve all the messages I sent using Twilio number in one day. This was like any other simple requirement and can be easily achieved through exporting the records in .CSV format as given in Twilio Dashboard. The twist is that Twilio dashboard supports only to fetch 10000 records(however in my case it was not exporting more than 5000 records out of some odd 8000 records and putting error message "Could not finish exporting all records." in the exported .CSV file).


This is the story about when you have to fetch within 10000 records. In case you want to fetch records more than that then following is the code for your rescue which I figured out after hit and trial as Twilio support was also much not helpful:

This is how I got it working:

For Collecting Responses to Twilio Numbers
TwilioRestClient client = new TwilioRestClient(accountSID, authToken);
for (int count = 0; count <= 3; count++)
{
     var smss = client.ListSmsMessages("Your number to which you received messages", null, null, count, 1000);
     foreach (var sms in smss.SMSMessages)
     {
         //Saving in DB
         SaveToDB(sms.Sid, sms.From, sms.To, sms.DateSent, sms.Body);
     }
}


For Collecting Sent Message From Twilio Numbers
TwilioRestClient client = new TwilioRestClient(accountSID, authToken);
for (int count = 0; count <= 3; count++)
{
     var smss = client.ListSmsMessages(null, "Your number through which you sent messages", null, count, 1000);
     foreach (var sms in smss.SMSMessages)
     {
         //Saving in DB
         SaveToDB(sms.Sid, sms.From, sms.To, sms.DateSent, sms.Body);
     }
}
*count is the number of pages you are expecting which can be calculated by dividing the no. of messages by 1000(max records supported by API in one request)

Monday, October 28, 2013

Listing all tables in PostGreSQL DB

You should be able to just run
select * from information_schema.tables
to get a listing of every table being managed by Postgres for a particular database.

You can also add a where table_schema = 'information_schema' to see just the tables in the information schema.

This is another version to get the specific results:

SELECT *
FROM information_schema.tables
WHERE table_schema='public'
AND table_type='BASE TABLE';

Wednesday, August 21, 2013

Dynamically adding or removing items from a C# collection in a loop.

Strictly speaking, there is no way to dynamically add or remove items from a Collection in a C# Foreach loop. There are at least three ways I know of that this can be faked though, do you know any others?

The "Right" Way
for(i = list.Count()-1;i>=0;i--)
{
item=list[i];
if (item.Delete) list.Remove(item);
}
This way cycles through the list backwards with a plain old For loop. Doing this forwards could be problematic if the size of the collection changes, but backwards should always be safe.

The "Easy" Way
foreach(var item in list.ToList())
{
if(item.Delete) list.Remove(item);
}
Simply create an entirely new list from the first one. I say "Easy" rather than "Right" as creating an entirely new list probably comes at a performance premium over the previous method (I haven't bothered with any benchmarking.) I generally prefer this pattern, it can also be useful in overcoming Linq-To-Entities limitations.

The "Strange" Way
var outList = new List(CustomObject);
foreach(var item in list)
{
if(!item.Delete) outList.Add(item);
}
list = outList;
I encountered this particular pattern in early versions of the Monkey programming language. Monkey originally had no way of removing items from a collection (No longer an issue), so the only way you could do it is to create a smaller list to supplant the larger one. This is probably the clumsiest and slowest of the three methods, but it has the unusual (but probably useless) advantage of not needing a remove method.

The Linq Way
list.RemoveAll(p=>p.Delete);

Monday, August 12, 2013

The namespace 'global namespace' already contains a definition for 'xxxxx'

While troubleshooting a handler in ASP.NET suddenly, I encountered with following error. I started looking around and reverted the changes however error didn't go and then I found the reason for that :)

Server Error in '/' Application.
--------------------------------------------------------------------------------

Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS0101: The namespace 'global namespace' already contains a definition for 'xxxx'




I had renamed and kept the versions of the same .cs file for the handler in the same directory. You should also check whether you have a copy of the file with different name but using the same class thus having duplicate file. I took the files out of the directory and kept them somewhere else as backup, hence solved the problem. You can also save your precious time either by deleting the file or excluding it from the project.

Wednesday, June 5, 2013

NHibernate: Returning extra properties from stored procedure not in model

I was working on getting the data from two tables using a stored procedure in which resultset was a combination of fields coming from multiple tables. I created the domain model for one of the tables involved in the query in stored procedure and introduced the other fields pertaining to the other table in the same domain model class. I did provide the return property tag in the .hbm mapping file too, as shown below.  

After doing all this I got an error for the fields which were part of the other table for which only properties were added to the domain model class.
Solution:

 
UserData Class
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Reflection;
using NameSpace.DAL.Base;
using NameSpace.DomainModel.Base;
using NameSpace.DomainModel.User;
using NHibernate;
using NHibernate.Criterion;

namespace NameSpace.DAL.User
{
    ///
    /// UserData class for doing DB operations related to User
    ///

    public partial class UserData : DataManagerBase
    {
        #region Constructors

        internal UserData()
            : base()
        {
        }

        ///
        /// Initializes a new instance of the class.
        ///

        /// The session.
        public UserData (INHibernateSession session)
            : base(session)
        {
        }
        #endregion Constructors

        #region Get Methods
        ///
        /// Method to get the User Info.
        ///

        ///
        ///
        public IList GetUserInfo()
        {
            IList lstUserInfo = null;
         
            try
            {
                IQuery Q = GetNamedQuery("User.GetUsers");
                lstUserInfo = Q.List();
             }
            catch (Exception ex)
            {
                 Your Exception Handling Code here.
            }

            return lstUserInfo ;
        }

 #endregion Get Methods
    }
}


User DomainModel Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Namespace.DomainModel.User
{
    ///
    /// Represents a User entity
    ///

    /// XYZ
    /// ABC
    /// TRT
    /// 05 June 2013

    public class User : EntityBase
    {
        #region Constructors

        ///
        /// Class constructor...
        ///

        public User()
        {
            //TODO:Write constructor stuff here..
        }

        #endregion Constructors

        #region Property Declarations

        public virtual int UserId
        {
            get
            {
                return base.Id;
            }
            set
            {
                base.Id = value;
            }
        }

        public virtual string FirstName { set; get; }

        public virtual string LastName { set; get; }

        public virtual string SearchCriterion { set; get; }
      
        #endregion Property Declarations

        #region ToString() Implementation

        ///
        /// This methods returns a string representation of this class.
        ///

        /// A string representation of this class.
        public virtual new string ToString()
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder(6);

            sb.AppendLine("------------User dump starts---------------");
            sb.AppendLine("UserId: " + (this.Id.ToString()));
            sb.AppendLine("FirstName: " + (this. FirstName != null ? this. FirstName: "").ToString());
            sb.AppendLine("LastName: " + (this. LastName!= null ? this. LastName: "").ToString());
            sb.AppendLine("SearchCriterion: " + (this. SearchCriterion!= null ? this. SearchCriterion : "").ToString());
sb.AppendLine("------------User dump ends---------------");
            return sb.ToString();
        }

        public override bool Equals(object obj)
        {
            //Same reference check !
            if (object.ReferenceEquals(this, obj)) return true;

            //Type check !
            User other = obj as User;
            if (other == null) return false;

            if ((Id == 0))
                //Do a per-property search
                return
                (FirstName == other.FirstName) &&
                (FirstName == other.FirstName) &&
                (SearchCriterion == other.SearchCriterion) ;
            else
                return Id == other.Id;
        }

        public override int GetHashCode()
        {
            return (this.GetType().FullName + Id.ToString()).GetHashCode();
        }

        #endregion ToString() Implementation
    }
}